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": "\n # may do and undo a change. Ie: \"Star if from Ben, Unstar if subject is \"Bla\"\n return Promise.ea", "end": 4350, "score": 0.9989696741104126, "start": 4347, "tag": "NAME", "value": "Ben" } ]
packages/client-app/src/mail-rules-processor.coffee
cnheider/nylas-mail
24,369
_ = require 'underscore' Task = require('./flux/tasks/task').default Actions = require('./flux/actions').default Category = require('./flux/models/category').default Thread = require('./flux/models/thread').default Message = require('./flux/models/message').default AccountStore = require('./flux/stores/account-store').default DatabaseStore = require('./flux/stores/database-store').default TaskQueueStatusStore = require './flux/stores/task-queue-status-store' {ConditionMode, ConditionTemplates} = require './mail-rules-templates' ChangeUnreadTask = require('./flux/tasks/change-unread-task').default ChangeFolderTask = require('./flux/tasks/change-folder-task').default ChangeStarredTask = require('./flux/tasks/change-starred-task').default ChangeLabelsTask = require('./flux/tasks/change-labels-task').default MailRulesStore = null ### Note: At first glance, it seems like these task factory methods should use the TaskFactory. Unfortunately, the TaskFactory uses the CategoryStore and other information about the current view. Maybe after the unified inbox refactor... ### MailRulesActions = markAsImportant: (message, thread) -> DatabaseStore.findBy(Category, { name: 'important', accountId: thread.accountId }).then (important) -> return Promise.reject(new Error("Could not find `important` label")) unless important return new ChangeLabelsTask(labelsToAdd: [important], threads: [thread.id], source: "Mail Rules") moveToTrash: (message, thread) -> if AccountStore.accountForId(thread.accountId).usesLabels() return MailRulesActions.moveToLabel(message, thread, 'trash') else DatabaseStore.findBy(Category, { name: 'trash', accountId: thread.accountId }).then (folder) -> return Promise.reject(new Error("The folder could not be found.")) unless folder return new ChangeFolderTask(folder: folder, threads: [thread.id], source: "Mail Rules") markAsRead: (message, thread) -> new ChangeUnreadTask(unread: false, threads: [thread.id], source: "Mail Rules") star: (message, thread) -> new ChangeStarredTask(starred: true, threads: [thread.id], source: "Mail Rules") changeFolder: (message, thread, value) -> return Promise.reject(new Error("A folder is required.")) unless value DatabaseStore.findBy(Category, { id: value, accountId: thread.accountId }).then (folder) -> return Promise.reject(new Error("The folder could not be found.")) unless folder return new ChangeFolderTask(folder: folder, threads: [thread.id], source: "Mail Rules") applyLabel: (message, thread, value) -> return Promise.reject(new Error("A label is required.")) unless value DatabaseStore.findBy(Category, { id: value, accountId: thread.accountId }).then (label) -> return Promise.reject(new Error("The label could not be found.")) unless label return new ChangeLabelsTask(labelsToAdd: [label], threads: [thread.id], source: "Mail Rules") # Should really be moveToArchive but stuck with legacy name applyLabelArchive: (message, thread) -> return MailRulesActions.moveToLabel(message, thread, 'all') moveToLabel: (message, thread, nameOrId) -> return Promise.reject(new Error("A label is required.")) unless nameOrId Promise.props( withId: DatabaseStore.findBy(Category, { id: nameOrId, accountId: thread.accountId }) withName: DatabaseStore.findBy(Category, { name: nameOrId, accountId: thread.accountId }) ).then ({withId, withName}) -> label = withId || withName return Promise.reject(new Error("The label could not be found.")) unless label return new ChangeLabelsTask({ source: "Mail Rules" labelsToRemove: [].concat(thread.labels).filter((l) => !l.isLockedCategory() and l.id isnt label.id ), labelsToAdd: [label], threads: [thread.id] }) class MailRulesProcessor constructor: -> processMessages: (messages) => MailRulesStore ?= require './flux/stores/mail-rules-store' return Promise.resolve() unless messages.length > 0 enabledRules = MailRulesStore.rules().filter (r) -> not r.disabled # When messages arrive, we process all the messages in parallel, but one # rule at a time. This is important, because users can order rules which # may do and undo a change. Ie: "Star if from Ben, Unstar if subject is "Bla" return Promise.each enabledRules, (rule) => matching = messages.filter (message) => @_checkRuleForMessage(rule, message) # Rules are declared at the message level, but actions are applied to # threads. To ensure we don't apply the same action 50x on the same thread, # just process one match per thread. matching = _.uniq matching, false, (message) -> message.threadId return Promise.map matching, (message) => # We always pull the thread from the database, even though it may be in # `incoming.thread`, because rules may be modifying it as they run! DatabaseStore.find(Thread, message.threadId).then (thread) => return console.warn("Cannot find thread #{message.threadId} to process mail rules.") unless thread return @_applyRuleToMessage(rule, message, thread) _checkRuleForMessage: (rule, message) => if rule.conditionMode is ConditionMode.All fn = _.every else fn = _.any return false unless message.accountId is rule.accountId fn rule.conditions, (condition) => template = _.findWhere(ConditionTemplates, {key: condition.templateKey}) value = template.valueForMessage(message) template.evaluate(condition, value) _applyRuleToMessage: (rule, message, thread) => actionPromises = rule.actions.map (action) => actionFunction = MailRulesActions[action.templateKey] if not actionFunction return Promise.reject(new Error("#{action.templateKey} is not a supported action.")) return actionFunction(message, thread, action.value) Promise.all(actionPromises).then (actionResults) -> performLocalPromises = [] actionTasks = actionResults.filter (r) -> r instanceof Task actionTasks.forEach (task) -> performLocalPromises.push TaskQueueStatusStore.waitForPerformLocal(task) Actions.queueTask(task) return Promise.all(performLocalPromises) .catch (err) -> # Errors can occur if a mail rule specifies an invalid label or folder, etc. # Disable the rule. Disable the mail rule so the failure is reflected in the # interface. Actions.disableMailRule(rule.id, err.toString()) return Promise.resolve() module.exports = new MailRulesProcessor
79658
_ = require 'underscore' Task = require('./flux/tasks/task').default Actions = require('./flux/actions').default Category = require('./flux/models/category').default Thread = require('./flux/models/thread').default Message = require('./flux/models/message').default AccountStore = require('./flux/stores/account-store').default DatabaseStore = require('./flux/stores/database-store').default TaskQueueStatusStore = require './flux/stores/task-queue-status-store' {ConditionMode, ConditionTemplates} = require './mail-rules-templates' ChangeUnreadTask = require('./flux/tasks/change-unread-task').default ChangeFolderTask = require('./flux/tasks/change-folder-task').default ChangeStarredTask = require('./flux/tasks/change-starred-task').default ChangeLabelsTask = require('./flux/tasks/change-labels-task').default MailRulesStore = null ### Note: At first glance, it seems like these task factory methods should use the TaskFactory. Unfortunately, the TaskFactory uses the CategoryStore and other information about the current view. Maybe after the unified inbox refactor... ### MailRulesActions = markAsImportant: (message, thread) -> DatabaseStore.findBy(Category, { name: 'important', accountId: thread.accountId }).then (important) -> return Promise.reject(new Error("Could not find `important` label")) unless important return new ChangeLabelsTask(labelsToAdd: [important], threads: [thread.id], source: "Mail Rules") moveToTrash: (message, thread) -> if AccountStore.accountForId(thread.accountId).usesLabels() return MailRulesActions.moveToLabel(message, thread, 'trash') else DatabaseStore.findBy(Category, { name: 'trash', accountId: thread.accountId }).then (folder) -> return Promise.reject(new Error("The folder could not be found.")) unless folder return new ChangeFolderTask(folder: folder, threads: [thread.id], source: "Mail Rules") markAsRead: (message, thread) -> new ChangeUnreadTask(unread: false, threads: [thread.id], source: "Mail Rules") star: (message, thread) -> new ChangeStarredTask(starred: true, threads: [thread.id], source: "Mail Rules") changeFolder: (message, thread, value) -> return Promise.reject(new Error("A folder is required.")) unless value DatabaseStore.findBy(Category, { id: value, accountId: thread.accountId }).then (folder) -> return Promise.reject(new Error("The folder could not be found.")) unless folder return new ChangeFolderTask(folder: folder, threads: [thread.id], source: "Mail Rules") applyLabel: (message, thread, value) -> return Promise.reject(new Error("A label is required.")) unless value DatabaseStore.findBy(Category, { id: value, accountId: thread.accountId }).then (label) -> return Promise.reject(new Error("The label could not be found.")) unless label return new ChangeLabelsTask(labelsToAdd: [label], threads: [thread.id], source: "Mail Rules") # Should really be moveToArchive but stuck with legacy name applyLabelArchive: (message, thread) -> return MailRulesActions.moveToLabel(message, thread, 'all') moveToLabel: (message, thread, nameOrId) -> return Promise.reject(new Error("A label is required.")) unless nameOrId Promise.props( withId: DatabaseStore.findBy(Category, { id: nameOrId, accountId: thread.accountId }) withName: DatabaseStore.findBy(Category, { name: nameOrId, accountId: thread.accountId }) ).then ({withId, withName}) -> label = withId || withName return Promise.reject(new Error("The label could not be found.")) unless label return new ChangeLabelsTask({ source: "Mail Rules" labelsToRemove: [].concat(thread.labels).filter((l) => !l.isLockedCategory() and l.id isnt label.id ), labelsToAdd: [label], threads: [thread.id] }) class MailRulesProcessor constructor: -> processMessages: (messages) => MailRulesStore ?= require './flux/stores/mail-rules-store' return Promise.resolve() unless messages.length > 0 enabledRules = MailRulesStore.rules().filter (r) -> not r.disabled # When messages arrive, we process all the messages in parallel, but one # rule at a time. This is important, because users can order rules which # may do and undo a change. Ie: "Star if from <NAME>, Unstar if subject is "Bla" return Promise.each enabledRules, (rule) => matching = messages.filter (message) => @_checkRuleForMessage(rule, message) # Rules are declared at the message level, but actions are applied to # threads. To ensure we don't apply the same action 50x on the same thread, # just process one match per thread. matching = _.uniq matching, false, (message) -> message.threadId return Promise.map matching, (message) => # We always pull the thread from the database, even though it may be in # `incoming.thread`, because rules may be modifying it as they run! DatabaseStore.find(Thread, message.threadId).then (thread) => return console.warn("Cannot find thread #{message.threadId} to process mail rules.") unless thread return @_applyRuleToMessage(rule, message, thread) _checkRuleForMessage: (rule, message) => if rule.conditionMode is ConditionMode.All fn = _.every else fn = _.any return false unless message.accountId is rule.accountId fn rule.conditions, (condition) => template = _.findWhere(ConditionTemplates, {key: condition.templateKey}) value = template.valueForMessage(message) template.evaluate(condition, value) _applyRuleToMessage: (rule, message, thread) => actionPromises = rule.actions.map (action) => actionFunction = MailRulesActions[action.templateKey] if not actionFunction return Promise.reject(new Error("#{action.templateKey} is not a supported action.")) return actionFunction(message, thread, action.value) Promise.all(actionPromises).then (actionResults) -> performLocalPromises = [] actionTasks = actionResults.filter (r) -> r instanceof Task actionTasks.forEach (task) -> performLocalPromises.push TaskQueueStatusStore.waitForPerformLocal(task) Actions.queueTask(task) return Promise.all(performLocalPromises) .catch (err) -> # Errors can occur if a mail rule specifies an invalid label or folder, etc. # Disable the rule. Disable the mail rule so the failure is reflected in the # interface. Actions.disableMailRule(rule.id, err.toString()) return Promise.resolve() module.exports = new MailRulesProcessor
true
_ = require 'underscore' Task = require('./flux/tasks/task').default Actions = require('./flux/actions').default Category = require('./flux/models/category').default Thread = require('./flux/models/thread').default Message = require('./flux/models/message').default AccountStore = require('./flux/stores/account-store').default DatabaseStore = require('./flux/stores/database-store').default TaskQueueStatusStore = require './flux/stores/task-queue-status-store' {ConditionMode, ConditionTemplates} = require './mail-rules-templates' ChangeUnreadTask = require('./flux/tasks/change-unread-task').default ChangeFolderTask = require('./flux/tasks/change-folder-task').default ChangeStarredTask = require('./flux/tasks/change-starred-task').default ChangeLabelsTask = require('./flux/tasks/change-labels-task').default MailRulesStore = null ### Note: At first glance, it seems like these task factory methods should use the TaskFactory. Unfortunately, the TaskFactory uses the CategoryStore and other information about the current view. Maybe after the unified inbox refactor... ### MailRulesActions = markAsImportant: (message, thread) -> DatabaseStore.findBy(Category, { name: 'important', accountId: thread.accountId }).then (important) -> return Promise.reject(new Error("Could not find `important` label")) unless important return new ChangeLabelsTask(labelsToAdd: [important], threads: [thread.id], source: "Mail Rules") moveToTrash: (message, thread) -> if AccountStore.accountForId(thread.accountId).usesLabels() return MailRulesActions.moveToLabel(message, thread, 'trash') else DatabaseStore.findBy(Category, { name: 'trash', accountId: thread.accountId }).then (folder) -> return Promise.reject(new Error("The folder could not be found.")) unless folder return new ChangeFolderTask(folder: folder, threads: [thread.id], source: "Mail Rules") markAsRead: (message, thread) -> new ChangeUnreadTask(unread: false, threads: [thread.id], source: "Mail Rules") star: (message, thread) -> new ChangeStarredTask(starred: true, threads: [thread.id], source: "Mail Rules") changeFolder: (message, thread, value) -> return Promise.reject(new Error("A folder is required.")) unless value DatabaseStore.findBy(Category, { id: value, accountId: thread.accountId }).then (folder) -> return Promise.reject(new Error("The folder could not be found.")) unless folder return new ChangeFolderTask(folder: folder, threads: [thread.id], source: "Mail Rules") applyLabel: (message, thread, value) -> return Promise.reject(new Error("A label is required.")) unless value DatabaseStore.findBy(Category, { id: value, accountId: thread.accountId }).then (label) -> return Promise.reject(new Error("The label could not be found.")) unless label return new ChangeLabelsTask(labelsToAdd: [label], threads: [thread.id], source: "Mail Rules") # Should really be moveToArchive but stuck with legacy name applyLabelArchive: (message, thread) -> return MailRulesActions.moveToLabel(message, thread, 'all') moveToLabel: (message, thread, nameOrId) -> return Promise.reject(new Error("A label is required.")) unless nameOrId Promise.props( withId: DatabaseStore.findBy(Category, { id: nameOrId, accountId: thread.accountId }) withName: DatabaseStore.findBy(Category, { name: nameOrId, accountId: thread.accountId }) ).then ({withId, withName}) -> label = withId || withName return Promise.reject(new Error("The label could not be found.")) unless label return new ChangeLabelsTask({ source: "Mail Rules" labelsToRemove: [].concat(thread.labels).filter((l) => !l.isLockedCategory() and l.id isnt label.id ), labelsToAdd: [label], threads: [thread.id] }) class MailRulesProcessor constructor: -> processMessages: (messages) => MailRulesStore ?= require './flux/stores/mail-rules-store' return Promise.resolve() unless messages.length > 0 enabledRules = MailRulesStore.rules().filter (r) -> not r.disabled # When messages arrive, we process all the messages in parallel, but one # rule at a time. This is important, because users can order rules which # may do and undo a change. Ie: "Star if from PI:NAME:<NAME>END_PI, Unstar if subject is "Bla" return Promise.each enabledRules, (rule) => matching = messages.filter (message) => @_checkRuleForMessage(rule, message) # Rules are declared at the message level, but actions are applied to # threads. To ensure we don't apply the same action 50x on the same thread, # just process one match per thread. matching = _.uniq matching, false, (message) -> message.threadId return Promise.map matching, (message) => # We always pull the thread from the database, even though it may be in # `incoming.thread`, because rules may be modifying it as they run! DatabaseStore.find(Thread, message.threadId).then (thread) => return console.warn("Cannot find thread #{message.threadId} to process mail rules.") unless thread return @_applyRuleToMessage(rule, message, thread) _checkRuleForMessage: (rule, message) => if rule.conditionMode is ConditionMode.All fn = _.every else fn = _.any return false unless message.accountId is rule.accountId fn rule.conditions, (condition) => template = _.findWhere(ConditionTemplates, {key: condition.templateKey}) value = template.valueForMessage(message) template.evaluate(condition, value) _applyRuleToMessage: (rule, message, thread) => actionPromises = rule.actions.map (action) => actionFunction = MailRulesActions[action.templateKey] if not actionFunction return Promise.reject(new Error("#{action.templateKey} is not a supported action.")) return actionFunction(message, thread, action.value) Promise.all(actionPromises).then (actionResults) -> performLocalPromises = [] actionTasks = actionResults.filter (r) -> r instanceof Task actionTasks.forEach (task) -> performLocalPromises.push TaskQueueStatusStore.waitForPerformLocal(task) Actions.queueTask(task) return Promise.all(performLocalPromises) .catch (err) -> # Errors can occur if a mail rule specifies an invalid label or folder, etc. # Disable the rule. Disable the mail rule so the failure is reflected in the # interface. Actions.disableMailRule(rule.id, err.toString()) return Promise.resolve() module.exports = new MailRulesProcessor
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993605613708496, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "hile j--\n client = net.connect(common.PORT, \"127.0.0.1\")\n client.id = j\n client.on \"close\", ->", "end": 2754, "score": 0.9997779130935669, "start": 2745, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " = true\n return\n\n server.listen common.PORT, \"127.0.0.1\"\n process.on \"exit\", ->\n assert.equal sent, c", "end": 3029, "score": 0.9997742176055908, "start": 3020, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
test/simple/test-child-process-fork-getconnections.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. assert = require("assert") common = require("../common") fork = require("child_process").fork net = require("net") count = 12 if process.argv[2] is "child" sockets = [] id = process.argv[3] process.on "message", (m, socket) -> if m.cmd is "new" assert socket assert socket instanceof net.Socket, "should be a net.Socket" sockets.push socket socket.on "end", -> throw new Error("[c] closing by accident!") unless @closingOnPurpose return if m.cmd is "close" assert.equal socket, `undefined` sockets[m.id].once "close", -> process.send id: m.id status: "closed" return sockets[m.id].destroy() return else closeSockets = (i) -> if i is count childKilled = true server.close() child.kill() return sent++ child.send id: i cmd: "close" child.once "message", (m) -> assert m.status is "closed" server.getConnections (err, num) -> closeSockets i + 1 return return return child = fork(process.argv[1], ["child"]) child.on "exit", (code, signal) -> throw new Error("child died unexpectedly!") unless childKilled return server = net.createServer() sockets = [] sent = 0 server.on "connection", (socket) -> child.send cmd: "new" , socket, track: false sockets.push socket closeSockets 0 if sockets.length is count return disconnected = 0 clients = [] server.on "listening", -> j = count client = undefined while j-- client = net.connect(common.PORT, "127.0.0.1") client.id = j client.on "close", -> disconnected += 1 return clients.push client return childKilled = false closeEmitted = false server.on "close", -> closeEmitted = true return server.listen common.PORT, "127.0.0.1" process.on "exit", -> assert.equal sent, count assert.equal disconnected, count assert.ok closeEmitted console.log "ok" return
103301
# 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. assert = require("assert") common = require("../common") fork = require("child_process").fork net = require("net") count = 12 if process.argv[2] is "child" sockets = [] id = process.argv[3] process.on "message", (m, socket) -> if m.cmd is "new" assert socket assert socket instanceof net.Socket, "should be a net.Socket" sockets.push socket socket.on "end", -> throw new Error("[c] closing by accident!") unless @closingOnPurpose return if m.cmd is "close" assert.equal socket, `undefined` sockets[m.id].once "close", -> process.send id: m.id status: "closed" return sockets[m.id].destroy() return else closeSockets = (i) -> if i is count childKilled = true server.close() child.kill() return sent++ child.send id: i cmd: "close" child.once "message", (m) -> assert m.status is "closed" server.getConnections (err, num) -> closeSockets i + 1 return return return child = fork(process.argv[1], ["child"]) child.on "exit", (code, signal) -> throw new Error("child died unexpectedly!") unless childKilled return server = net.createServer() sockets = [] sent = 0 server.on "connection", (socket) -> child.send cmd: "new" , socket, track: false sockets.push socket closeSockets 0 if sockets.length is count return disconnected = 0 clients = [] server.on "listening", -> j = count client = undefined while j-- client = net.connect(common.PORT, "127.0.0.1") client.id = j client.on "close", -> disconnected += 1 return clients.push client return childKilled = false closeEmitted = false server.on "close", -> closeEmitted = true return server.listen common.PORT, "127.0.0.1" process.on "exit", -> assert.equal sent, count assert.equal disconnected, count assert.ok closeEmitted console.log "ok" 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. assert = require("assert") common = require("../common") fork = require("child_process").fork net = require("net") count = 12 if process.argv[2] is "child" sockets = [] id = process.argv[3] process.on "message", (m, socket) -> if m.cmd is "new" assert socket assert socket instanceof net.Socket, "should be a net.Socket" sockets.push socket socket.on "end", -> throw new Error("[c] closing by accident!") unless @closingOnPurpose return if m.cmd is "close" assert.equal socket, `undefined` sockets[m.id].once "close", -> process.send id: m.id status: "closed" return sockets[m.id].destroy() return else closeSockets = (i) -> if i is count childKilled = true server.close() child.kill() return sent++ child.send id: i cmd: "close" child.once "message", (m) -> assert m.status is "closed" server.getConnections (err, num) -> closeSockets i + 1 return return return child = fork(process.argv[1], ["child"]) child.on "exit", (code, signal) -> throw new Error("child died unexpectedly!") unless childKilled return server = net.createServer() sockets = [] sent = 0 server.on "connection", (socket) -> child.send cmd: "new" , socket, track: false sockets.push socket closeSockets 0 if sockets.length is count return disconnected = 0 clients = [] server.on "listening", -> j = count client = undefined while j-- client = net.connect(common.PORT, "127.0.0.1") client.id = j client.on "close", -> disconnected += 1 return clients.push client return childKilled = false closeEmitted = false server.on "close", -> closeEmitted = true return server.listen common.PORT, "127.0.0.1" process.on "exit", -> assert.equal sent, count assert.equal disconnected, count assert.ok closeEmitted console.log "ok" return
[ { "context": "#\n# Copyright (c) 2019 Alexander Sporn. All rights reserved.\n#\n\nEnocean = require './Eno", "end": 38, "score": 0.9998582601547241, "start": 23, "tag": "NAME", "value": "Alexander Sporn" } ]
index.coffee
alexsporn/homebridge-enocean
1
# # Copyright (c) 2019 Alexander Sporn. All rights reserved. # Enocean = require './Enocean' Accessory = undefined Service = undefined Characteristic = undefined UUIDGen = undefined module.exports = (homebridge) -> Accessory = homebridge.platformAccessory Service = homebridge.hap.Service Characteristic = homebridge.hap.Characteristic UUIDGen = homebridge.hap.uuid homebridge.registerPlatform 'homebridge-enocean', 'enocean', EnoceanPlatform, true return EnoceanPlatform = (@log, @config, @api) -> @accessories = {} @enocean = new Enocean(port: @config.port) # @enocean.on 'pressed', (sender, button) => # @log sender + ": " + button + " pressed" # @sendSwitchEvent(sender, button, 1) @enocean.on 'released', (sender, button) => @log sender + ": " + button + " released" @setSwitchEventValue(sender, button, Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS) @api.on 'didFinishLaunching', => # @log 'DidFinishLaunching' for accessory in @config.accessories @addAccessory(accessory) return return EnoceanPlatform::setSwitchEventValue = (sender, button, value) -> accessory = @accessories[sender] unless accessory? @log 'Unknown sender', sender for service in accessory.services if service.UUID == Service.StatelessProgrammableSwitch.UUID and service.subtype == button characteristic = service.getCharacteristic(Characteristic.ProgrammableSwitchEvent) characteristic.setValue(value) @log 'Set', accessory.displayName, button, 'value', value return @log 'Could not find button', button return EnoceanPlatform::configureAccessory = (accessory) -> @log 'Configure Accessory:', accessory.displayName accessory.reachable = true accessory.on 'identify', (paired, callback) => @log accessory.displayName, 'Identify!!!' callback() return serial = accessory.getService(Service.AccessoryInformation).getCharacteristic(Characteristic.SerialNumber).value unless serial? @api.unregisterPlatformAccessories 'homebridge-enocean', 'enocean', [ accessory ] return @accessories[serial] = accessory @setSwitchEventValue(serial, 'A0', -1) @setSwitchEventValue(serial, 'AI', -1) @setSwitchEventValue(serial, 'B0', -1) @setSwitchEventValue(serial, 'BI', -1) return EnoceanPlatform::createProgrammableSwitch = (name, model, serial) -> uuid = UUIDGen.generate(serial) accessory = new Accessory(name, uuid) accessory.on 'identify', (paired, callback) => @log accessory.displayName, 'Identify!!!' callback() return info = accessory.getService(Service.AccessoryInformation) info.updateCharacteristic(Characteristic.Manufacturer, "EnOcean") .updateCharacteristic(Characteristic.Model, model) .updateCharacteristic(Characteristic.SerialNumber, serial) .updateCharacteristic(Characteristic.FirmwareRevision, '1.0') label = new Service.ServiceLabel(accessory.displayName) label.getCharacteristic(Characteristic.ServiceLabelNamespace).updateValue(Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS) accessory.addService(label) buttonAI = @createProgrammableSwitchButton(accessory.displayName, 1, 'AI') buttonA0 = @createProgrammableSwitchButton(accessory.displayName, 2, 'A0') buttonBI = @createProgrammableSwitchButton(accessory.displayName, 3, 'BI') buttonB0 = @createProgrammableSwitchButton(accessory.displayName, 4, 'B0') accessory.addService(buttonAI) accessory.addService(buttonA0) accessory.addService(buttonBI) accessory.addService(buttonB0) return accessory EnoceanPlatform::createProgrammableSwitchButton = (accesoryName, buttonIndex, button) -> button = new Service.StatelessProgrammableSwitch(accesoryName + ' ' + button, button) singleButton = minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS maxValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS button.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps(singleButton) button.getCharacteristic(Characteristic.ServiceLabelIndex).setValue(buttonIndex) return button EnoceanPlatform::addAccessory = (config) -> if @accessories[config.id]? # @log 'Skip Accessory: ' + config.name return @log 'Add Accessory:', config.name accessory = @createProgrammableSwitch(config.name, config.eep, config.id) @accessories[config.id] = accessory @api.registerPlatformAccessories 'homebridge-enocean', 'enocean', [ accessory ] return
90807
# # Copyright (c) 2019 <NAME>. All rights reserved. # Enocean = require './Enocean' Accessory = undefined Service = undefined Characteristic = undefined UUIDGen = undefined module.exports = (homebridge) -> Accessory = homebridge.platformAccessory Service = homebridge.hap.Service Characteristic = homebridge.hap.Characteristic UUIDGen = homebridge.hap.uuid homebridge.registerPlatform 'homebridge-enocean', 'enocean', EnoceanPlatform, true return EnoceanPlatform = (@log, @config, @api) -> @accessories = {} @enocean = new Enocean(port: @config.port) # @enocean.on 'pressed', (sender, button) => # @log sender + ": " + button + " pressed" # @sendSwitchEvent(sender, button, 1) @enocean.on 'released', (sender, button) => @log sender + ": " + button + " released" @setSwitchEventValue(sender, button, Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS) @api.on 'didFinishLaunching', => # @log 'DidFinishLaunching' for accessory in @config.accessories @addAccessory(accessory) return return EnoceanPlatform::setSwitchEventValue = (sender, button, value) -> accessory = @accessories[sender] unless accessory? @log 'Unknown sender', sender for service in accessory.services if service.UUID == Service.StatelessProgrammableSwitch.UUID and service.subtype == button characteristic = service.getCharacteristic(Characteristic.ProgrammableSwitchEvent) characteristic.setValue(value) @log 'Set', accessory.displayName, button, 'value', value return @log 'Could not find button', button return EnoceanPlatform::configureAccessory = (accessory) -> @log 'Configure Accessory:', accessory.displayName accessory.reachable = true accessory.on 'identify', (paired, callback) => @log accessory.displayName, 'Identify!!!' callback() return serial = accessory.getService(Service.AccessoryInformation).getCharacteristic(Characteristic.SerialNumber).value unless serial? @api.unregisterPlatformAccessories 'homebridge-enocean', 'enocean', [ accessory ] return @accessories[serial] = accessory @setSwitchEventValue(serial, 'A0', -1) @setSwitchEventValue(serial, 'AI', -1) @setSwitchEventValue(serial, 'B0', -1) @setSwitchEventValue(serial, 'BI', -1) return EnoceanPlatform::createProgrammableSwitch = (name, model, serial) -> uuid = UUIDGen.generate(serial) accessory = new Accessory(name, uuid) accessory.on 'identify', (paired, callback) => @log accessory.displayName, 'Identify!!!' callback() return info = accessory.getService(Service.AccessoryInformation) info.updateCharacteristic(Characteristic.Manufacturer, "EnOcean") .updateCharacteristic(Characteristic.Model, model) .updateCharacteristic(Characteristic.SerialNumber, serial) .updateCharacteristic(Characteristic.FirmwareRevision, '1.0') label = new Service.ServiceLabel(accessory.displayName) label.getCharacteristic(Characteristic.ServiceLabelNamespace).updateValue(Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS) accessory.addService(label) buttonAI = @createProgrammableSwitchButton(accessory.displayName, 1, 'AI') buttonA0 = @createProgrammableSwitchButton(accessory.displayName, 2, 'A0') buttonBI = @createProgrammableSwitchButton(accessory.displayName, 3, 'BI') buttonB0 = @createProgrammableSwitchButton(accessory.displayName, 4, 'B0') accessory.addService(buttonAI) accessory.addService(buttonA0) accessory.addService(buttonBI) accessory.addService(buttonB0) return accessory EnoceanPlatform::createProgrammableSwitchButton = (accesoryName, buttonIndex, button) -> button = new Service.StatelessProgrammableSwitch(accesoryName + ' ' + button, button) singleButton = minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS maxValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS button.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps(singleButton) button.getCharacteristic(Characteristic.ServiceLabelIndex).setValue(buttonIndex) return button EnoceanPlatform::addAccessory = (config) -> if @accessories[config.id]? # @log 'Skip Accessory: ' + config.name return @log 'Add Accessory:', config.name accessory = @createProgrammableSwitch(config.name, config.eep, config.id) @accessories[config.id] = accessory @api.registerPlatformAccessories 'homebridge-enocean', 'enocean', [ accessory ] return
true
# # Copyright (c) 2019 PI:NAME:<NAME>END_PI. All rights reserved. # Enocean = require './Enocean' Accessory = undefined Service = undefined Characteristic = undefined UUIDGen = undefined module.exports = (homebridge) -> Accessory = homebridge.platformAccessory Service = homebridge.hap.Service Characteristic = homebridge.hap.Characteristic UUIDGen = homebridge.hap.uuid homebridge.registerPlatform 'homebridge-enocean', 'enocean', EnoceanPlatform, true return EnoceanPlatform = (@log, @config, @api) -> @accessories = {} @enocean = new Enocean(port: @config.port) # @enocean.on 'pressed', (sender, button) => # @log sender + ": " + button + " pressed" # @sendSwitchEvent(sender, button, 1) @enocean.on 'released', (sender, button) => @log sender + ": " + button + " released" @setSwitchEventValue(sender, button, Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS) @api.on 'didFinishLaunching', => # @log 'DidFinishLaunching' for accessory in @config.accessories @addAccessory(accessory) return return EnoceanPlatform::setSwitchEventValue = (sender, button, value) -> accessory = @accessories[sender] unless accessory? @log 'Unknown sender', sender for service in accessory.services if service.UUID == Service.StatelessProgrammableSwitch.UUID and service.subtype == button characteristic = service.getCharacteristic(Characteristic.ProgrammableSwitchEvent) characteristic.setValue(value) @log 'Set', accessory.displayName, button, 'value', value return @log 'Could not find button', button return EnoceanPlatform::configureAccessory = (accessory) -> @log 'Configure Accessory:', accessory.displayName accessory.reachable = true accessory.on 'identify', (paired, callback) => @log accessory.displayName, 'Identify!!!' callback() return serial = accessory.getService(Service.AccessoryInformation).getCharacteristic(Characteristic.SerialNumber).value unless serial? @api.unregisterPlatformAccessories 'homebridge-enocean', 'enocean', [ accessory ] return @accessories[serial] = accessory @setSwitchEventValue(serial, 'A0', -1) @setSwitchEventValue(serial, 'AI', -1) @setSwitchEventValue(serial, 'B0', -1) @setSwitchEventValue(serial, 'BI', -1) return EnoceanPlatform::createProgrammableSwitch = (name, model, serial) -> uuid = UUIDGen.generate(serial) accessory = new Accessory(name, uuid) accessory.on 'identify', (paired, callback) => @log accessory.displayName, 'Identify!!!' callback() return info = accessory.getService(Service.AccessoryInformation) info.updateCharacteristic(Characteristic.Manufacturer, "EnOcean") .updateCharacteristic(Characteristic.Model, model) .updateCharacteristic(Characteristic.SerialNumber, serial) .updateCharacteristic(Characteristic.FirmwareRevision, '1.0') label = new Service.ServiceLabel(accessory.displayName) label.getCharacteristic(Characteristic.ServiceLabelNamespace).updateValue(Characteristic.ServiceLabelNamespace.ARABIC_NUMERALS) accessory.addService(label) buttonAI = @createProgrammableSwitchButton(accessory.displayName, 1, 'AI') buttonA0 = @createProgrammableSwitchButton(accessory.displayName, 2, 'A0') buttonBI = @createProgrammableSwitchButton(accessory.displayName, 3, 'BI') buttonB0 = @createProgrammableSwitchButton(accessory.displayName, 4, 'B0') accessory.addService(buttonAI) accessory.addService(buttonA0) accessory.addService(buttonBI) accessory.addService(buttonB0) return accessory EnoceanPlatform::createProgrammableSwitchButton = (accesoryName, buttonIndex, button) -> button = new Service.StatelessProgrammableSwitch(accesoryName + ' ' + button, button) singleButton = minValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS maxValue: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS button.getCharacteristic(Characteristic.ProgrammableSwitchEvent).setProps(singleButton) button.getCharacteristic(Characteristic.ServiceLabelIndex).setValue(buttonIndex) return button EnoceanPlatform::addAccessory = (config) -> if @accessories[config.id]? # @log 'Skip Accessory: ' + config.name return @log 'Add Accessory:', config.name accessory = @createProgrammableSwitch(config.name, config.eep, config.id) @accessories[config.id] = accessory @api.registerPlatformAccessories 'homebridge-enocean', 'enocean', [ accessory ] return
[ { "context": "mobyDick = \"Call me Ishmael. Some years ago --\n never", "end": 4, "score": 0.474505215883255, "start": 2, "tag": "NAME", "value": "by" }, { "context": "mobyDick = \"Call me Ishmael. Some years ago --\n never min", "end": 8, "score": 0.6427341103553772, "start": 5, "tag": "NAME", "value": "ick" }, { "context": "mobyDick = \"Call me Ishmael. Some years ago --\n never mind how long precisel", "end": 27, "score": 0.9972695708274841, "start": 20, "tag": "NAME", "value": "Ishmael" } ]
documentation/examples/strings.coffee
Trott/coffeescript
8,728
mobyDick = "Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."
102917
mo<NAME>D<NAME> = "Call me <NAME>. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."
true
moPI:NAME:<NAME>END_PIDPI:NAME:<NAME>END_PI = "Call me PI:NAME:<NAME>END_PI. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."
[ { "context": " return next(err)\n rs['password'] = undefined\n res.json rs\n )\n\nrouter.post '/", "end": 869, "score": 0.9904025793075562, "start": 860, "tag": "PASSWORD", "value": "undefined" }, { "context": " return next(err)\n rs['password'] = undefined\n res.json rs\n )\n\nrouter.post '/", "end": 1582, "score": 0.9789642691612244, "start": 1573, "tag": "PASSWORD", "value": "undefined" }, { "context": " return next(err)\n rs['password'] = undefined\n res.json rs\n )\n\nrouter.post '/", "end": 2280, "score": 0.9915499687194824, "start": 2271, "tag": "PASSWORD", "value": "undefined" }, { "context": " return next(err)\n rs['password'] = undefined\n res.json rs\n )\n # User.", "end": 2972, "score": 0.9917674660682678, "start": 2963, "tag": "PASSWORD", "value": "undefined" } ]
src/routes/preference.coffee
ureport-web/ureport-s
3
express = require('express') router = express.Router() User = require('../models/user') AccessControl = require('../utils/ac_grants') component = 'preference' #create the login get and post routes router.post '/update/dashboard', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateDashboardSetting req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = undefined res.json rs ) router.post '/update/report', (req, res, next) -> if(!req.body.user) res.status(400) return res.json {error: "userID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateReportSetting req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = undefined res.json rs ) router.post '/update/language', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateLanguage req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = undefined res.json rs ) router.post '/update/theme', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateTheme req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = undefined res.json rs ) # User.update( {_id: user._id}, { settting.theme: user.settings.theme}, (err, rs) -> # if err # return next(err) # res.json rs # ) module.exports = router
199837
express = require('express') router = express.Router() User = require('../models/user') AccessControl = require('../utils/ac_grants') component = 'preference' #create the login get and post routes router.post '/update/dashboard', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateDashboardSetting req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = <PASSWORD> res.json rs ) router.post '/update/report', (req, res, next) -> if(!req.body.user) res.status(400) return res.json {error: "userID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateReportSetting req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = <PASSWORD> res.json rs ) router.post '/update/language', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateLanguage req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = <PASSWORD> res.json rs ) router.post '/update/theme', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateTheme req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = <PASSWORD> res.json rs ) # User.update( {_id: user._id}, { settting.theme: user.settings.theme}, (err, rs) -> # if err # return next(err) # res.json rs # ) module.exports = router
true
express = require('express') router = express.Router() User = require('../models/user') AccessControl = require('../utils/ac_grants') component = 'preference' #create the login get and post routes router.post '/update/dashboard', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateDashboardSetting req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = PI:PASSWORD:<PASSWORD>END_PI res.json rs ) router.post '/update/report', (req, res, next) -> if(!req.body.user) res.status(400) return res.json {error: "userID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateReportSetting req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = PI:PASSWORD:<PASSWORD>END_PI res.json rs ) router.post '/update/language', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateLanguage req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = PI:PASSWORD:<PASSWORD>END_PI res.json rs ) router.post '/update/theme', (req, res, next) -> if(!req.body.user) return res.status(400).json {error: "UserID is mandatory"} if (!AccessControl.canAccessUpdateAnyIfOwn(req.user, req.body.user, component)) return res.status(403).json({"error": "You don't have permission to perform this action"}) User.updateTheme req.body.user, req.body, (user) -> if (!user) res.status(404) res.json {"error": "Cannot find User with id " + req.body.user} else user.save({ validateBeforeSave: false }, (err, rs) -> if err return next(err) rs['password'] = PI:PASSWORD:<PASSWORD>END_PI res.json rs ) # User.update( {_id: user._id}, { settting.theme: user.settings.theme}, (err, rs) -> # if err # return next(err) # res.json rs # ) module.exports = router
[ { "context": "angular: [\n {\n key: 'metadata.responseId'\n }\n {\n key: 'metadata.endSession'\n }\n {\n ", "end": 44, "score": 0.7463879585266113, "start": 25, "tag": "KEY", "value": "metadata.responseId" }, { "context": "\n key: 'metadata.responseId'\n }\n {\n key: 'metadata.endSession'\n }\n {\n key: 'data.phrase'\n }\n]\n", "end": 83, "score": 0.7484428286552429, "start": 64, "tag": "KEY", "value": "metadata.endSession" }, { "context": "\n key: 'metadata.endSession'\n }\n {\n key: 'data.phrase'\n }\n]\n", "end": 114, "score": 0.9465643763542175, "start": 103, "tag": "KEY", "value": "data.phrase" } ]
src/schemas/message/reprompt-form.cson
octoblu/alexa-service
3
angular: [ { key: 'metadata.responseId' } { key: 'metadata.endSession' } { key: 'data.phrase' } ]
190126
angular: [ { key: '<KEY>' } { key: '<KEY>' } { key: '<KEY>' } ]
true
angular: [ { key: 'PI:KEY:<KEY>END_PI' } { key: 'PI:KEY:<KEY>END_PI' } { key: 'PI:KEY:<KEY>END_PI' } ]
[ { "context": " key\n keyRE = \"#{Const.TAGS_RE.RECALL_BEGIN}#{keyRE}#{Const.TAGS_RE.RECALL_END}\"\n keyRE =", "end": 1600, "score": 0.7014304399490356, "start": 1598, "tag": "KEY", "value": "#{" }, { "context": " keyRE = \"#{Const.TAGS_RE.RECALL_BEGIN}#{keyRE}#{Const.TAGS_RE.RECALL_END}\"\n keyRE = \"\\\"?#{k", "end": 1608, "score": 0.6398556232452393, "start": 1606, "tag": "KEY", "value": "#{" }, { "context": "RE.RECALL_BEGIN}#{keyRE}#{Const.TAGS_RE.RECALL_END}\"\n keyRE = \"\\\"?#{keyRE}\\\"?\" if scope is 'js", "end": 1632, "score": 0.5617549419403076, "start": 1632, "tag": "KEY", "value": "" }, { "context": "E}#{Const.TAGS_RE.RECALL_END}\"\n keyRE = \"\\\"?#{keyRE}\\\"?\" if scope is 'json' and not _.isString ", "end": 1657, "score": 0.7335788011550903, "start": 1655, "tag": "KEY", "value": "#{" }, { "context": "nst.TAGS_RE.RECALL_END}\"\n keyRE = \"\\\"?#{keyRE}\\\"?\" if scope is 'json' and not _.isString value\n ", "end": 1667, "score": 0.7551427483558655, "start": 1660, "tag": "KEY", "value": "RE}\\\"?\"" } ]
src/callbacks.coffee
klarna/katt-js
2
### Copyright 2013 Klarna AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### http = require 'http' https = require 'https' url = require 'url' _ = require 'lodash' utils = require './utils' Const = require './const' { validateStatusCode validateHeaders validateBody } = require './validate' exports.recall = ({scope, input, params, callbacks}) -> return input if not input? or _.isEmpty params scope ?= 'text' switch scope when 'url' return exports.recall {scope: 'text', input, params, callbacks} when 'headers' _.each input, (value, key) -> input[key] = exports.recall {scope: 'text', input: value, params, callbacks} return input when 'body' scope = 'text' {headers, body} = input contentType = headers['content-type'] scope = 'json' if contentType? and utils.isJsonCT contentType return {headers, body: exports.recall {scope, input: body, params, callbacks}} when 'text', 'json' for key, value of params keyRE = Const.regexEscape key keyRE = "#{Const.TAGS_RE.RECALL_BEGIN}#{keyRE}#{Const.TAGS_RE.RECALL_END}" keyRE = "\"?#{keyRE}\"?" if scope is 'json' and not _.isString value keyRE = new RegExp keyRE, 'g' input = input.replace keyRE, value return input exports.parse = ({headers, body, params, callbacks}) -> contentType = headers['content-type'] return JSON.parse body if contentType? and utils.isJsonCT contentType body exports.request = ({request, params, callbacks}, finalNext) -> next = (err, res) -> return finalNext err if err headers = utils.normalizeHeaders res.headers res.body = callbacks.parse {headers, body: res.body, params, callbacks} finalNext null, { status: res.statusCode headers: res.headers body: res.body } options = url.parse request.url options.method = request.method options.headers = request.headers switch options.protocol when 'http:' protocol = http when 'https:' protocol = https else throw new Error "Unknown protocol #{options.protocol}" req = protocol.request options, (res) -> res.setEncoding 'utf8' res.body = '' res.on 'data', (chunk) -> res.body += chunk res.on 'end', () -> next null, statusCode: res.statusCode headers: res.headers body: res.body or null res.on 'error', next req.on 'socket', (socket) -> socket.setTimeout params.requestTimeout, req.abort req.on 'error', next req.write request.body, 'utf8' if request.body? req.end() exports.validate = ({actual, expected, params, callbacks}, next) -> errors = [] validateStatusCode {actual: actual.status, expected: expected.status, params, errors} validateHeaders {actual: actual.headers, expected: expected.headers, params, errors} validateBody {actual: actual.body, expected: expected.body, params, errors} next null, errors
69263
### Copyright 2013 Klarna AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### http = require 'http' https = require 'https' url = require 'url' _ = require 'lodash' utils = require './utils' Const = require './const' { validateStatusCode validateHeaders validateBody } = require './validate' exports.recall = ({scope, input, params, callbacks}) -> return input if not input? or _.isEmpty params scope ?= 'text' switch scope when 'url' return exports.recall {scope: 'text', input, params, callbacks} when 'headers' _.each input, (value, key) -> input[key] = exports.recall {scope: 'text', input: value, params, callbacks} return input when 'body' scope = 'text' {headers, body} = input contentType = headers['content-type'] scope = 'json' if contentType? and utils.isJsonCT contentType return {headers, body: exports.recall {scope, input: body, params, callbacks}} when 'text', 'json' for key, value of params keyRE = Const.regexEscape key keyRE = "#{Const.TAGS_RE.RECALL_BEGIN}<KEY>keyRE}<KEY>Const.TAGS_RE.RECALL_END<KEY>}" keyRE = "\"?<KEY>key<KEY> if scope is 'json' and not _.isString value keyRE = new RegExp keyRE, 'g' input = input.replace keyRE, value return input exports.parse = ({headers, body, params, callbacks}) -> contentType = headers['content-type'] return JSON.parse body if contentType? and utils.isJsonCT contentType body exports.request = ({request, params, callbacks}, finalNext) -> next = (err, res) -> return finalNext err if err headers = utils.normalizeHeaders res.headers res.body = callbacks.parse {headers, body: res.body, params, callbacks} finalNext null, { status: res.statusCode headers: res.headers body: res.body } options = url.parse request.url options.method = request.method options.headers = request.headers switch options.protocol when 'http:' protocol = http when 'https:' protocol = https else throw new Error "Unknown protocol #{options.protocol}" req = protocol.request options, (res) -> res.setEncoding 'utf8' res.body = '' res.on 'data', (chunk) -> res.body += chunk res.on 'end', () -> next null, statusCode: res.statusCode headers: res.headers body: res.body or null res.on 'error', next req.on 'socket', (socket) -> socket.setTimeout params.requestTimeout, req.abort req.on 'error', next req.write request.body, 'utf8' if request.body? req.end() exports.validate = ({actual, expected, params, callbacks}, next) -> errors = [] validateStatusCode {actual: actual.status, expected: expected.status, params, errors} validateHeaders {actual: actual.headers, expected: expected.headers, params, errors} validateBody {actual: actual.body, expected: expected.body, params, errors} next null, errors
true
### Copyright 2013 Klarna AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### http = require 'http' https = require 'https' url = require 'url' _ = require 'lodash' utils = require './utils' Const = require './const' { validateStatusCode validateHeaders validateBody } = require './validate' exports.recall = ({scope, input, params, callbacks}) -> return input if not input? or _.isEmpty params scope ?= 'text' switch scope when 'url' return exports.recall {scope: 'text', input, params, callbacks} when 'headers' _.each input, (value, key) -> input[key] = exports.recall {scope: 'text', input: value, params, callbacks} return input when 'body' scope = 'text' {headers, body} = input contentType = headers['content-type'] scope = 'json' if contentType? and utils.isJsonCT contentType return {headers, body: exports.recall {scope, input: body, params, callbacks}} when 'text', 'json' for key, value of params keyRE = Const.regexEscape key keyRE = "#{Const.TAGS_RE.RECALL_BEGIN}PI:KEY:<KEY>END_PIkeyRE}PI:KEY:<KEY>END_PIConst.TAGS_RE.RECALL_ENDPI:KEY:<KEY>END_PI}" keyRE = "\"?PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI if scope is 'json' and not _.isString value keyRE = new RegExp keyRE, 'g' input = input.replace keyRE, value return input exports.parse = ({headers, body, params, callbacks}) -> contentType = headers['content-type'] return JSON.parse body if contentType? and utils.isJsonCT contentType body exports.request = ({request, params, callbacks}, finalNext) -> next = (err, res) -> return finalNext err if err headers = utils.normalizeHeaders res.headers res.body = callbacks.parse {headers, body: res.body, params, callbacks} finalNext null, { status: res.statusCode headers: res.headers body: res.body } options = url.parse request.url options.method = request.method options.headers = request.headers switch options.protocol when 'http:' protocol = http when 'https:' protocol = https else throw new Error "Unknown protocol #{options.protocol}" req = protocol.request options, (res) -> res.setEncoding 'utf8' res.body = '' res.on 'data', (chunk) -> res.body += chunk res.on 'end', () -> next null, statusCode: res.statusCode headers: res.headers body: res.body or null res.on 'error', next req.on 'socket', (socket) -> socket.setTimeout params.requestTimeout, req.abort req.on 'error', next req.write request.body, 'utf8' if request.body? req.end() exports.validate = ({actual, expected, params, callbacks}, next) -> errors = [] validateStatusCode {actual: actual.status, expected: expected.status, params, errors} validateHeaders {actual: actual.headers, expected: expected.headers, params, errors} validateBody {actual: actual.body, expected: expected.body, params, errors} next null, errors
[ { "context": ".TwitterBot = class TwitterBot\n\n constructor : ({@username, @password}) ->\n @jar = request.jar()\n\n #----", "end": 303, "score": 0.8542296886444092, "start": 294, "tag": "USERNAME", "value": "@username" }, { "context": "n \"\"\n body = null\n form.authenticity_token = @tok if form? and @tok?\n headers = \n \"User-Age", "end": 559, "score": 0.7628988027572632, "start": 555, "tag": "USERNAME", "value": "@tok" }, { "context": "->\n form =\n 'session[username_or_email]' : @username\n 'session[password]' : @password\n 'redi", "end": 1710, "score": 0.9967249631881714, "start": 1701, "tag": "USERNAME", "value": "@username" }, { "context": "or_email]' : @username\n 'session[password]' : @password\n 'redirect_after_login' : ''\n '", "end": 1738, "score": 0.9985584616661072, "start": 1738, "tag": "PASSWORD", "value": "" } ]
test/lib/twitter.iced
AngelKey/Angelkey.nodeclient
151
request = require 'request' cheerio = require 'cheerio' {a_json_parse,katch} = require('iced-utils').util {make_esc} = require('iced-error') util = require 'util' #===================================================================== exports.TwitterBot = class TwitterBot constructor : ({@username, @password}) -> @jar = request.jar() #--------------------------------- load_page : ({path, status, form, method }, cb) -> status or= [200] uri = [ "https://twitter.com" , path ].join "" body = null form.authenticity_token = @tok if form? and @tok? headers = "User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36" await request { uri, @jar, body, method, headers }, defer err, res, body if not err? and not((sc = res.statusCode) in status) err = new Error "HTTP status code #{sc}" cb err, body, res #--------------------------------- grab_auth_token : ($, cb) -> err = null if not (raw = $("#init-data").val())? or raw.length is 0 err = new Error "No #init-data form data found" else [err, json] = katch () -> JSON.parse(raw) if not err? and not (ret = json.formAuthenticityToken)? err = new Error "init-data didn't have a 'formAuthenticityToken'" cb err, ret #--------------------------------- load_login_page : (cb) -> esc = make_esc cb, "load_log_page" await @load_page {path : "/login" }, esc defer body $ = cheerio.load body await @grab_auth_token $, esc defer @tok cb null #--------------------------------- post_login : (cb) -> form = 'session[username_or_email]' : @username 'session[password]' : @password 'redirect_after_login' : '' 'remember_me' : 1 'scribe_log' : "" path = "/sessions" await @load_page { status : [302,200], path , form, method : "POST" }, defer err, body, res cb err #--------------------------------- get_home : (cb) -> path = "/" await @load_page { path , method : "GET" }, defer err, body $ = cheerio.load body await @grab_auth_token $, defer err, @tok cb err #--------------------------------- tweet : (txt, cb) -> esc = make_esc cb, "TwitterBot::tweet" await @load_page { path : "/i/tweet/create", method : "POST", form : {status : txt, place_id : "" }, }, esc defer body await a_json_parse body, esc defer json cb err, json.tweet_id #--------------------------------- run : (txt, cb) -> esc = make_esc cb, "TwitterBot:run" await @load_login_page esc defer() await @post_login esc defer() await @get_home esc defer() await @tweet txt, esc defer tweet_id cb null, tweet_id #===================================================================== exports.tweet_scrape = tweet_scrape = ({username,password}, txt, cb) -> bot = new TwitterBot { username, password } await bot.run txt, defer err, tweet_id cb err, tweet_id #===================================================================== exports.tweet_api = tweet_api = (d, status, cb) -> await request.post { url : "https://api.twitter.com/1.1/statuses/update.json", form : {status } oauth : d json : true }, defer err, res, body cb err, body.id_str #=====================================================================
64059
request = require 'request' cheerio = require 'cheerio' {a_json_parse,katch} = require('iced-utils').util {make_esc} = require('iced-error') util = require 'util' #===================================================================== exports.TwitterBot = class TwitterBot constructor : ({@username, @password}) -> @jar = request.jar() #--------------------------------- load_page : ({path, status, form, method }, cb) -> status or= [200] uri = [ "https://twitter.com" , path ].join "" body = null form.authenticity_token = @tok if form? and @tok? headers = "User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36" await request { uri, @jar, body, method, headers }, defer err, res, body if not err? and not((sc = res.statusCode) in status) err = new Error "HTTP status code #{sc}" cb err, body, res #--------------------------------- grab_auth_token : ($, cb) -> err = null if not (raw = $("#init-data").val())? or raw.length is 0 err = new Error "No #init-data form data found" else [err, json] = katch () -> JSON.parse(raw) if not err? and not (ret = json.formAuthenticityToken)? err = new Error "init-data didn't have a 'formAuthenticityToken'" cb err, ret #--------------------------------- load_login_page : (cb) -> esc = make_esc cb, "load_log_page" await @load_page {path : "/login" }, esc defer body $ = cheerio.load body await @grab_auth_token $, esc defer @tok cb null #--------------------------------- post_login : (cb) -> form = 'session[username_or_email]' : @username 'session[password]' :<PASSWORD> @password 'redirect_after_login' : '' 'remember_me' : 1 'scribe_log' : "" path = "/sessions" await @load_page { status : [302,200], path , form, method : "POST" }, defer err, body, res cb err #--------------------------------- get_home : (cb) -> path = "/" await @load_page { path , method : "GET" }, defer err, body $ = cheerio.load body await @grab_auth_token $, defer err, @tok cb err #--------------------------------- tweet : (txt, cb) -> esc = make_esc cb, "TwitterBot::tweet" await @load_page { path : "/i/tweet/create", method : "POST", form : {status : txt, place_id : "" }, }, esc defer body await a_json_parse body, esc defer json cb err, json.tweet_id #--------------------------------- run : (txt, cb) -> esc = make_esc cb, "TwitterBot:run" await @load_login_page esc defer() await @post_login esc defer() await @get_home esc defer() await @tweet txt, esc defer tweet_id cb null, tweet_id #===================================================================== exports.tweet_scrape = tweet_scrape = ({username,password}, txt, cb) -> bot = new TwitterBot { username, password } await bot.run txt, defer err, tweet_id cb err, tweet_id #===================================================================== exports.tweet_api = tweet_api = (d, status, cb) -> await request.post { url : "https://api.twitter.com/1.1/statuses/update.json", form : {status } oauth : d json : true }, defer err, res, body cb err, body.id_str #=====================================================================
true
request = require 'request' cheerio = require 'cheerio' {a_json_parse,katch} = require('iced-utils').util {make_esc} = require('iced-error') util = require 'util' #===================================================================== exports.TwitterBot = class TwitterBot constructor : ({@username, @password}) -> @jar = request.jar() #--------------------------------- load_page : ({path, status, form, method }, cb) -> status or= [200] uri = [ "https://twitter.com" , path ].join "" body = null form.authenticity_token = @tok if form? and @tok? headers = "User-Agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36" await request { uri, @jar, body, method, headers }, defer err, res, body if not err? and not((sc = res.statusCode) in status) err = new Error "HTTP status code #{sc}" cb err, body, res #--------------------------------- grab_auth_token : ($, cb) -> err = null if not (raw = $("#init-data").val())? or raw.length is 0 err = new Error "No #init-data form data found" else [err, json] = katch () -> JSON.parse(raw) if not err? and not (ret = json.formAuthenticityToken)? err = new Error "init-data didn't have a 'formAuthenticityToken'" cb err, ret #--------------------------------- load_login_page : (cb) -> esc = make_esc cb, "load_log_page" await @load_page {path : "/login" }, esc defer body $ = cheerio.load body await @grab_auth_token $, esc defer @tok cb null #--------------------------------- post_login : (cb) -> form = 'session[username_or_email]' : @username 'session[password]' :PI:PASSWORD:<PASSWORD>END_PI @password 'redirect_after_login' : '' 'remember_me' : 1 'scribe_log' : "" path = "/sessions" await @load_page { status : [302,200], path , form, method : "POST" }, defer err, body, res cb err #--------------------------------- get_home : (cb) -> path = "/" await @load_page { path , method : "GET" }, defer err, body $ = cheerio.load body await @grab_auth_token $, defer err, @tok cb err #--------------------------------- tweet : (txt, cb) -> esc = make_esc cb, "TwitterBot::tweet" await @load_page { path : "/i/tweet/create", method : "POST", form : {status : txt, place_id : "" }, }, esc defer body await a_json_parse body, esc defer json cb err, json.tweet_id #--------------------------------- run : (txt, cb) -> esc = make_esc cb, "TwitterBot:run" await @load_login_page esc defer() await @post_login esc defer() await @get_home esc defer() await @tweet txt, esc defer tweet_id cb null, tweet_id #===================================================================== exports.tweet_scrape = tweet_scrape = ({username,password}, txt, cb) -> bot = new TwitterBot { username, password } await bot.run txt, defer err, tweet_id cb err, tweet_id #===================================================================== exports.tweet_api = tweet_api = (d, status, cb) -> await request.post { url : "https://api.twitter.com/1.1/statuses/update.json", form : {status } oauth : d json : true }, defer err, res, body cb err, body.id_str #=====================================================================
[ { "context": "x.props.sshcmd =\n 'ssh -A -t '+g.user+'@users.isi.deterlab.net '+\n 'ssh -A '+x.props.name+'.'+", "end": 6381, "score": 0.5692400932312012, "start": 6378, "tag": "EMAIL", "value": "isi" }, { "context": "d.add(@shp.obj3d)\n @props = {\n name: \"computer0\",\n sys: \"root\",\n os: \"Ubuntu1404-64", "end": 7097, "score": 0.9944860935211182, "start": 7088, "tag": "USERNAME", "value": "computer0" }, { "context": " sshcmd: \"\"\n }\n @id = {\n name: \"computer0\"\n sys: \"root\"\n design: dsg\n }\n", "end": 7269, "score": 0.9837926626205444, "start": 7260, "tag": "USERNAME", "value": "computer0" }, { "context": " if @id.name != @props.name\n x.props[@props.name] = x.props[@id.name]\n delete(x.props[@id", "end": 11429, "score": 0.9621207118034363, "start": 11419, "tag": "USERNAME", "value": "props.name" }, { "context": "ps.name\n x.props[@props.name] = x.props[@id.name]\n delete(x.props[@id.name])\n\n\n #cyjs ", "end": 11449, "score": 0.8877943158149719, "start": 11442, "tag": "USERNAME", "value": "id.name" }, { "context": "me] = x.props[@id.name]\n delete(x.props[@id.name])\n\n\n #cyjs generates the json for this object\n", "end": 11484, "score": 0.9031193256378174, "start": 11477, "tag": "USERNAME", "value": "id.name" }, { "context": "d.add(@shp.obj3d)\n @props = {\n name: \"sax0\",\n sys: \"root\",\n design: dsg,\n ", "end": 11831, "score": 0.9949151277542114, "start": 11827, "tag": "USERNAME", "value": "sax0" }, { "context": " sshcmd: \"\"\n }\n @id = {\n name: \"sax0\",\n sys: \"root\",\n design: dsg\n ", "end": 11999, "score": 0.9990819692611694, "start": 11995, "tag": "USERNAME", "value": "sax0" }, { "context": "() and @id.name != @props.name\n x.props[@props.name] = x.props[@id.name]\n delete(x.props[@id", "end": 12198, "score": 0.9688477516174316, "start": 12188, "tag": "USERNAME", "value": "props.name" }, { "context": "ps.name\n x.props[@props.name] = x.props[@id.name]\n delete(x.props[@id.name])\n \n #cy", "end": 12218, "score": 0.9289371967315674, "start": 12211, "tag": "USERNAME", "value": "id.name" }, { "context": "me] = x.props[@id.name]\n delete(x.props[@id.name])\n \n #cyjs generates the json for this obje", "end": 12253, "score": 0.9452484250068665, "start": 12246, "tag": "USERNAME", "value": "id.name" }, { "context": "d.add(@shp.obj3d)\n @props = {\n name: \"router0\",\n sys: \"root\",\n capacity: 100,\n ", "end": 12606, "score": 0.6452915072441101, "start": 12600, "tag": "NAME", "value": "router" }, { "context": "@shp.obj3d)\n @props = {\n name: \"router0\",\n sys: \"root\",\n capacity: 100,\n ", "end": 12607, "score": 0.5263414978981018, "start": 12606, "tag": "USERNAME", "value": "0" }, { "context": "md: \"\"\n }\n @id = {\n name: \"router0\"\n sys: \"root\"\n design: dsg\n }\n", "end": 12761, "score": 0.924057126045227, "start": 12760, "tag": "USERNAME", "value": "0" }, { "context": "@shp.obj3d)\n @props = {\n name: \"switch0\",\n sys: \"root\",\n capacity: 1000,\n ", "end": 13331, "score": 0.4730069935321808, "start": 13330, "tag": "NAME", "value": "0" }, { "context": "d.userData = this\n @props = {\n name: \"link0\",\n sys: \"root\",\n design: dsg,\n ", "end": 14043, "score": 0.5711894035339355, "start": 14038, "tag": "NAME", "value": "link0" }, { "context": "cy: 0,\n endpoints: [\n {name: \"link0\", sys: \"root\", design: dsg, ifname: \"\"},\n ", "end": 14176, "score": 0.49975836277008057, "start": 14175, "tag": "NAME", "value": "0" }, { "context": "\"}\n ]\n }\n @id = {\n name: \"link0\"\n sys: \"root\"\n design: dsg\n }\n", "end": 14334, "score": 0.7298029065132141, "start": 14329, "tag": "NAME", "value": "link0" } ]
coffee/main.coffee
cycps/designer
0
root = exports ? this getParameterByName = (name) => name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]") regex = new RegExp("[\\?&]" + name + "=([^&#]*)") results = regex.exec(location.search) decodeURIComponent(results[1].replace(/\+/g, " ")) initViz = () => g.ve = new VisualEnvironment( document.getElementById("surface0"), document.getElementById("surface1"), document.getElementById("surface2"), document.getElementById("surface3"), document.getElementById("controlPanel") ) g.ve.ebox = new StaticElementBox(g.ve, 120, g.ve.cheight/2 - 65) mh = g.ve.cheight - 167 g.ve.mbox = new ModelBox(g.ve, mh, (g.ve.cheight - 140)/2 - mh/2.0 - 60) g.ve.datgui = null g.ve.render(g.ve) dsg = "" launchAddieInstance = () => ($.get "/gatekeeper/launchAddie?user="+g.user+"&design="+dsg, (data) => console.log("addie instance launched and ready!") g.ve.addie.init() ).fail () -> console.log("failed to launch addie instance") true #Entry point root.go = -> ($.get "/gatekeeper/thisUser", (data) => g.user = data console.log("the user is " + g.user) g.xp = getParameterByName("xp") dsg = g.xp console.log("the xp is " + g.xp) initViz() launchAddieInstance() true ).fail () -> console.log("fail to get current user, going back to login screen") window.location.href = location.origin true #Global event handlers root.vz_mousedown = (event, idx) -> g.ve.sview.mouseh.ondown(event) root.hsplit_mdown = (event) => g.ve.splitView.hdown(event) root.vsplit_mdown = (event) => g.ve.splitView.vdown(event) root.vz_keydown = (event) => g.ve.keyh.ondown(event) root.vz_keyup = (event) => g.ve.keyh.onup(event) root.vz_wheel = (event, idx) => g.ve.sview.mouseh.onwheel(event) root.run = (event) => g.ve.addie.run() root.materialize = (event) => g.ve.addie.materialize() root.newModel = (event) -> g.ve.mbox.newModel() root.compile = () => g.ve.addie.compile() root.showSimSettings = () => g.ve.showSimSettings() root.showDiagnostics = () => g.ve.showDiagnostics() #Global state holder g = {} #Shapes contains a collection of classes that comprise the basic shapes used to #represent Cypress CPS elements Shapes = { Rectangle : class Rectangle constructor: (color, x, y, z, width, height) -> @geom = new THREE.PlaneBufferGeometry(width, height) @material = new THREE.MeshBasicMaterial({color: color}) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Circle : class Circle constructor: (color, x, y, z, radius) -> @geom = new THREE.CircleGeometry(radius, 64) @material = new THREE.MeshBasicMaterial({color: color}) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Diamond: class Diamond constructor: (color, x, y, z, l) -> @shape = new THREE.Shape() @shape.moveTo(0,l) @shape.lineTo(l,0) @shape.lineTo(0,-l) @shape.lineTo(-l,0) @shape.lineTo(0,l) @material = new THREE.MeshBasicMaterial({color: color}) @geom = new THREE.ShapeGeometry(@shape) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Line: class Line constructor: (color, from, to, z) -> @material = new THREE.LineBasicMaterial( { color: color, linewidth: 3 } ) @geom = new THREE.Geometry() @geom.dynamic = true @geom.vertices.push(from, to) @obj3d = new THREE.Line(@geom, @material) @obj3d.position.x = 0 @obj3d.position.y = 0 @obj3d.position.z = z @obj3d.lines = [] select: -> Icon: class Icon constructor: (@texture, x, y, z) -> @material = new THREE.SpriteMaterial({ map: @texture, depthTest: false, depthWrite: false }) @obj3d= new THREE.Sprite(@material) @obj3d.position.set(x,y,z) @obj3d.scale.set(30, 30, 1.0) @obj3d.lines = [] @obj3d.linep = new THREE.Vector3(x, y, 5) select: -> SelectionCube: class SelectionCube constructor: () -> @geom = new THREE.Geometry() @geom.dynamic = true @aa = new THREE.Vector3(0, 0, 75) @ab = new THREE.Vector3(0, 0, 75) @ba = new THREE.Vector3(0, 0, 75) @bb = new THREE.Vector3(0, 0, 75) @geom.vertices.push( @aa, @ab, @ba, @bb, @ba, @ab ) @geom.faces.push( new THREE.Face3(0, 1, 2), new THREE.Face3(2, 1, 0), new THREE.Face3(3, 4, 5), new THREE.Face3(5, 4, 3) ) @geom.computeBoundingSphere() @material = new THREE.MeshBasicMaterial( { color: 0xFDBF3B, opacity: 0.2, transparent: true } ) @obj3d = new THREE.Mesh(@geom, @material) updateGFX: () -> @geom.verticesNeedUpdate = true @geom.lineDistancesNeedUpdate = true @geom.elementsNeedUpdate = true @geom.normalsNeedUpdate = true @geom.computeFaceNormals() @geom.computeVertexNormals() @geom.computeBoundingSphere() @geom.computeBoundingBox() init: (p) -> @aa.x = @ab.x = @ba.x = p.x @aa.y = @ba.y = @ab.y = p.y @bb.x = @aa.x @bb.y = @aa.y @updateGFX() update: (p) -> @bb.x = @ba.x = p.x @bb.y = @ab.y = p.y @updateGFX() reset: () -> @aa.x = @bb.x = @ba.x = @ab.x = 0 @aa.y = @bb.y = @ba.y = @ab.y = 0 @updateGFX() } #The BaseElements object holds classes which are Visual representations of the #objects that comprise a Cypress networked CPS system BaseElements = { updateId: (e) -> e.onIdUpdate() if e.onIdUpdate? e.id.name = e.props.name if e.id.sys? e.id.sys = e.props.sys currentId: (d) -> {name: d.props.name, sys: d.props.sys, design: dsg } setSshCmd: (x) => x.props.sshcmd = 'ssh -A -t '+g.user+'@users.isi.deterlab.net '+ 'ssh -A '+x.props.name+'.'+g.user+'-'+dsg+'.cypress' initName: (x, n) => x.props.name = g.ve.namemanager.getName(n) x.id.name = x.props.name addInterface: (x) => ifname = "" if x.props.interfaces? ifname = "ifx"+Object.keys(x.props.interfaces).length x.props.interfaces[ifname] = { name: ifname, latency: 0, capacity: 1000 } ifname #The Computer class is a representation of a computer Computer: class Computer constructor: (@parent, x, y, z) -> @shp = new Shapes.Diamond(0x2390ff, x, y, z, 15) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "computer0", sys: "root", os: "Ubuntu1404-64-STD", start_script: "", interfaces: {}, sshcmd: "" } @id = { name: "computer0" sys: "root" design: dsg } @links = [] showProps: (f) -> c = f.add(@props, 'name') c = f.add(@props, 'sys') c = f.add(@props, 'start_script') c = f.add(@props, 'os') #cyjs generates the json for this object cyjs: -> #The Model class is a represenation of a mathematical model of a physical object Model: class Model constructor: (@parent, x, y, z) -> @shp = new Shapes.Rectangle(0x239f5a, x, y, z, 25, 25) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @sprite = false @props = { name: "model0", params: "", equations: "", icon: "" } @funcs = { "Set Icon": () => console.log("setting sprite for " + @props.name) $("#upModelName").val(@props.name) $("#upModelIcon").change () => f = $("#upModelIcon")[0].files[0] console.log("sprite selected") mdl = $("#upModelName").val() console.log("model is " + mdl) console.log(f) $("#upModelIcon").off("change") fd = new FormData($("#uploadModelIconForm")[0]) xhr = new XMLHttpRequest() xhr.open("POST", "/addie/"+dsg+"/design/modelIco") xhr.onreadystatechange = () => if xhr.readyState == 4 && xhr.status == 200 g.ve.loadIcon(mdl, (tex) => @setIcon(tex) ) xhr.send(fd) true $("#upModelIcon").click() } @id = { name: "model0" } @instances = [] setIcon: (tex) => @parent.obj3d.remove(@shp.obj3d) _shp = new Shapes.Icon(tex, @shp.obj3d.position.x, @shp.obj3d.position.y, @shp.obj3d.position.z) @shp = _shp @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) g.ve.render() @tex = tex instantiate: (parent, x, y, z) -> if @tex? obj = new Phyo(parent, x, y, z, @tex.clone()) obj.tex.needsUpdate = true else obj = new Phyo(parent, x, y, z) obj.props.model = @props.name obj #cyjs generates the json for this object cyjs: -> Phyo: class Phyo constructor: (@parent, x, y, z, @tex = null) -> if @tex == null @shp = new Shapes.Rectangle(0x239f5a, x, y, z, 25, 25) @shp.obj3d.userData = this else @setIcon() @model = null if @parent? @parent.obj3d.add(@shp.obj3d) @props = { name: "model0", sys: "root", model: "", args: "", init: "", } @id = { name: "model0", sys: "root", design: dsg } @links = [] @args = [] setIcon: (x=0, y=0, z=50) => savelx = false if @shp? lp = @shp.obj3d.linep ls = @shp.obj3d.lines savelx = true if @parent? and @shp? @parent.obj3d.remove(@shp.obj3d) @shp = new Shapes.Icon(@tex, x, y, z) if savelx @shp.obj3d.linep = lp @shp.obj3d.lines = ls @shp.obj3d.userData = this if @parent? @parent.obj3d.add(@shp.obj3d) g.ve.render() addArgs: () -> _args = @model.props.params .replace(" ", "") .split(",") .map((x) -> x.replace(" ", "")) .filter((x) -> x.length != 0) for p in _args if !@props[p]? @props[p] = "" for p in @args if p not in _args delete @props[p] @args = _args true loadArgValues: () -> _args = @props.args .split(",") .filter((x) -> x.length != 0) .map((x) -> x.split("=").filter((y) -> y.length != 0)) for x in _args @props[x[0]] = x[1] @args.push(x[0]) sync: -> if @model? @props.model = @model.props.name @addArgs() @props.args = "" for p in @args @props.args += (p+"="+@props[p]+",") onIdUpdate: -> for x in @links if @id.name != @props.name x.props[@props.name] = x.props[@id.name] delete(x.props[@id.name]) #cyjs generates the json for this object cyjs: -> #The Sax class is a representation of a sensing and acutation unit Sax: class Sax constructor: (@parent, x, y, z) -> @shp = new Shapes.Circle(0x239f9c, x, y, z, 7) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "sax0", sys: "root", design: dsg, sense: "", actuate: "" interfaces: {}, sshcmd: "" } @id = { name: "sax0", sys: "root", design: dsg } @links = [] onIdUpdate: -> for x in @links if x.isPhysical() and @id.name != @props.name x.props[@props.name] = x.props[@id.name] delete(x.props[@id.name]) #cyjs generates the json for this object cyjs: -> #Router is a visual representation of an IP-network router Router: class Router constructor: (@parent, x, y, z) -> @shp = new Shapes.Circle(0x23549F, x, y, z, 15) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "router0", sys: "root", capacity: 100, latency: 0, interfaces: {}, sshcmd: "" } @id = { name: "router0" sys: "root" design: dsg } @links = [] showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> #Switch is a visual representation of an IP-network swtich Switch: class Switch constructor: (@parent, x, y, z) -> @shp = new Shapes.Rectangle(0x23549F, x, y, z, 25, 25) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "switch0", sys: "root", capacity: 1000, latency: 0, interfaces: {} } @id = { name: "switch0" sys: "root" design: dsg } @links = [] showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> Link: class Link constructor: (@parent, from, to, x, y, z, isIcon = false) -> @endpoint = [null, null] @ep_ifx = ["",""] #TODO: s/ln/shp/g for consistency @ln = new Shapes.Line(0xcacaca, from, to, z) @ln.obj3d.userData = this @props = { name: "link0", sys: "root", design: dsg, capacity: 1000, latency: 0, endpoints: [ {name: "link0", sys: "root", design: dsg, ifname: ""}, {name: "link0", sys: "root", design: dsg, ifname: ""} ] } @id = { name: "link0" sys: "root" design: dsg } if isIcon @shp = new Shapes.Rectangle(@parent.material.color, x, y, z, 25, 25) @shp.obj3d.userData = this @shp.obj3d.add(@ln.obj3d) @parent.obj3d.add(@shp.obj3d) else @parent.obj3d.add(@ln.obj3d) isInternet: -> @endpoint[0] instanceof Router and @endpoint[1] instanceof Router isPhysical: -> @endpoint[0] instanceof Phyo and @endpoint[1] instanceof Phyo or @endpoint[0] instanceof Phyo and @endpoint[1] instanceof Sax or @endpoint[1] instanceof Phyo and @endpoint[0] instanceof Sax isIfxPhysical: (i) -> @endpoint[i] instanceof Phyo applyWanProps: -> @props.capacity = 100 @props.latency = 7 applyPhysicalProps: -> @props = { name: @props.name, sys: @props.sys, design: @props.design, endpoints: [ {name: "link0", sys: "root", design: dsg}, {name: "link0", sys: "root", design: dsg} ], bindings: ["",""] } @props[@endpoint[0].props.name] = "" if @endpoint[0] #instanceof Phyo @props[@endpoint[1].props.name] = "" if @endpoint[1] #instanceof Phyo @ln.material.color = new THREE.Color(0x125634) @ln.geom.colorsNeedUpdate = true setColor: () -> if @isPhysical() @ln.material.color = new THREE.Color(0x125634) @ln.geom.colorsNeedUpdate = true else @ln.material.color = new THREE.Color(0x123456) @ln.geom.colorsNeedUpdate = true linkEndpoint: (i, x) -> ifname = BaseElements.addInterface(x) x.links.push(this) x.shp.obj3d.lines.push(@ln) @ln.geom.vertices[i] = x.shp.obj3d.linep @endpoint[i] = x @ep_ifx[i] = ifname setEndpointData: -> @props.endpoints[0].name = @endpoint[0].props.name @props.endpoints[0].sys = @endpoint[0].props.sys if !@isIfxPhysical(1) #yes, this is based on the other side of the connection @props.endpoints[0].ifname = @ep_ifx[0] if @isPhysical() @props.bindings[0] = @props[@endpoint[0].props.name] @props.endpoints[1].name = @endpoint[1].props.name @props.endpoints[1].sys = @endpoint[1].props.sys if !@isIfxPhysical(0) @props.endpoints[1].ifname = @ep_ifx[1] if @isPhysical() @props.bindings[1] = @props[@endpoint[1].props.name] unpackBindings: -> @props[@endpoint[0].props.name] = @props.bindings[0] @props[@endpoint[1].props.name] = @props.bindings[1] ifInternetToWanLink: -> @applyWanProps() if @isInternet() removePhantomEndpoint: (i) -> if @endpoint[i] instanceof Sax delete @endpoint[i].props.interfaces[@ep_ifx[i]] ifPhysicalToPlink: -> if @isPhysical() @removePhantomEndpoint(0) @removePhantomEndpoint(1) @applyPhysicalProps() else @ln.material.color = new THREE.Color(0x123456) @ln.geom.colorsNeedUpdate = true typeResolve: -> @ifInternetToWanLink() @ifPhysicalToPlink() @setEndpointData() showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') if @isInternet() f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> } #The ElementBox holds Element classes which may be added to a system, #aka the thing on the left side of the screen class ElementBox #Constructs an ElementBox object given a @ve visual environment constructor: (@ve, @height, @y) -> @width = 75 @x = -@ve.cwidth/2 + @width / 2 + 5 @z = 5 @box = new Shapes.Rectangle(0x404040, @x, @y, @z, @width, @height) @box.obj3d.userData = this @ve.sscene.add(@box.obj3d) @count = 0 @addBaseElements() #addElement adds a visual element to the ElementBox given an element #contruction lambda ef : (box, x, y) -> Object3D addElement: (ef) -> row = Math.floor(@count / 2) col = @count % 2 _x = if col == 0 then -18 else 18 _y = (@height / 2 - 25) - row * 35 e = ef(@box, _x, _y) @count++ e #addBaseElements adds the common base elements to the ElementBox addBaseElements: -> class StaticElementBox extends ElementBox addBaseElements: -> @addElement((box, x, y) -> new BaseElements.Computer(box, x, y, 5)) @addElement((box, x, y) -> new BaseElements.Router(box, x, y, 5)) @addElement((box, x, y) -> new BaseElements.Switch(box, x, y, 5)) @addElement((box, x, y) -> lnk = new BaseElements.Link(box, new THREE.Vector3(-12.5, 12.5, 5), new THREE.Vector3(12.5, -12.5, 5), x, y, 5, true ) lnk.ln.material.color = new THREE.Color(0xcacaca) lnk ) @addElement((box, x, y) -> new BaseElements.Sax(box, x, y, 5)) class ModelBox extends ElementBox newModel: ()-> m = @addElement((box, x, y) -> new BaseElements.Model(box, x, y, 5)) m.props.name = @ve.namemanager.getName("model") m.id.name = m.props.name @ve.render() @ve.addie.update([m]) addBaseElements: -> #The Surface holds visual representations of Systems and Elements #aka the majority of the screen class Surface #Constructs a Surface object given a @ve visual environment constructor: (@ve) -> @width = 5000 @height = 5000 @baseRect = new Shapes.Rectangle(0x262626, 0, 0, 0, @width, @height) @baseRect.obj3d.userData = this @ve.scene.add(@baseRect.obj3d) @selectGroup = new THREE.Group() @ve.scene.add(@selectGroup) @selectorGroup = new THREE.Group() @ve.scene.add(@selectorGroup) @elements = [] addElement: (ef, x, y) -> e = null if ef instanceof Phyo and ef.tex? e = new ef.constructor(@baseRect, x, y, 50, ef.tex) else e = new ef.constructor(@baseRect, x, y, 50) e.props.name = @ve.namemanager.getName(e.constructor.name.toLowerCase()) e.id.name = e.props.name e.props.design = dsg if e.props.sshcmd? BaseElements.setSshCmd(e) @elements.push(e) @ve.render() e removeElement: (e) => idx = @elements.indexOf(e) if idx > -1 @elements.splice(idx, 1) obj3d = null obj3d = e.shp.obj3d if e.shp? obj3d = e.ln.obj3d if e.ln? idx = @baseRect.obj3d.children.indexOf(obj3d) if idx > -1 @baseRect.obj3d.children.splice(idx, 1) if e.glowBubble? idx = @selectGroup.children.indexOf(e.glowBubble) if idx > -1 @selectGroup.children.splice(idx, 1) delete e.glowBubble @ve.render() getElement: (name, sys) -> e = null for x in @elements if x.props.name == name && x.props.sys == sys e = x break e addIfContains: (box, e, set) -> o3d = null if e.shp? o3d = e.shp.obj3d else if e.ln? o3d = e.ln.obj3d if o3d != null o3d.geometry.computeBoundingBox() bb = o3d.geometry.boundingBox bx = new THREE.Box2( o3d.localToWorld(bb.min), o3d.localToWorld(bb.max) ) set.push(e) if box.containsBox(bx) #for some reason computing the bounding box kills selection o3d.geometry.boundingBox = null true toBox2: (box) -> new THREE.Box2( new THREE.Vector2(box.min.x, box.min.y), new THREE.Vector2(box.max.x, box.max.y) ) getSelection: (box) -> xs = [] box2 = @toBox2(box) @addIfContains(box2, x, xs) for x in @elements xs getSelected: () -> xs = [] xs.push(x.userData) for x in @selectGroup.children xs updateLink: (ln) -> ln.geom.verticesNeedUpdate = true ln.geom.lineDistancesNeedUpdate = true ln.geom.elementsNeedUpdate = true ln.geom.normalsNeedUpdate = true ln.geom.computeFaceNormals() ln.geom.computeVertexNormals() ln.geom.computeBoundingSphere() ln.geom.computeBoundingBox() moveObject: (o, p) -> o.position.x = p.x o.position.y = p.y if o.linep? o.linep.x = p.x o.linep.y = p.y if o.userData.glowBubble? o.userData.glowBubble.position.x = p.x o.userData.glowBubble.position.y = p.y if o.lines? @updateLink(ln) for ln in o.lines true moveObjectRelative: (o, p) -> o.position.x += p.x o.position.y += p.y if o.linep? o.linep.x += p.x o.linep.y += p.y if o.lines? @updateLink(ln) for ln in o.lines true glowMaterial: () -> #cam = @ve.sview.camera new THREE.ShaderMaterial({ uniforms: { "c": { type: "f", value: 1.0 }, "p": { type: "f", value: 1.4 }, glowColor: { type: "c", value: new THREE.Color(0xFDBF3B) }, viewVector: { type: "v3", value: new THREE.Vector3(0, 0, 200) } }, vertexShader: document.getElementById("vertexShader").textContent, fragmentShader: document.getElementById("fragmentShader").textContent, side: THREE.FrontSide, blending: THREE.AdditiveBlending, transparent: true }) glowSphere: (radius, x, y, z) -> geom = new THREE.SphereGeometry(radius, 64, 64) mat = @glowMaterial() obj = new THREE.Mesh(geom, mat) obj.position.x = x obj.position.y = y obj.position.z = z obj glowCube: (width, height, depth, x, y, z) -> geom = new THREE.BoxGeometry(width, height, depth, 2, 2, 2) mat = @glowMaterial() obj = new THREE.Mesh(geom, mat) obj.position.x = x obj.position.y = y obj.position.z = z modifier = new THREE.SubdivisionModifier(2) modifier.modify(geom) obj glowDiamond: (w, h, d, x, y, z) -> obj = @glowCube(w, h, d, x, y, z) obj.rotateZ(Math.PI/4) obj clearPropsGUI: -> if @ve.datgui? @ve.datgui.destroy() @ve.datgui = null showPropsGUI: (s) -> @ve.datgui = new dat.GUI() addElem = (d, k, v) -> if !d[k]? d[k] = [v] else d[k].push(v) dict = new Array() addElem(dict, x.constructor.name, x) for x in s addGuiElems = (typ, xs) => f = @ve.datgui.addFolder(typ) x.showProps(f) for x in xs f.open() addGuiElems(k, v) for k,v of dict $(@ve.datgui.domElement).focusout () => @ve.addie.update([x]) for x in s true selectObj: (obj) -> doSelect = true if not obj.glowBubble? if obj.shp instanceof Shapes.Circle p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 gs = @glowSphere(s, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Rectangle p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 l = s*1.5 gs = @glowCube(l, l, l, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Icon p = obj.shp.obj3d.position obj.shp.obj3d.geometry.computeBoundingSphere() s = obj.shp.obj3d.geometry.boundingSphere.radius + 3 l = s*10.5 gs = @glowCube(l, l, l, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Diamond p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 l = s*1.5 gs = @glowDiamond(l, l, l, p.x, p.y, p.z) else if obj.ln instanceof Shapes.Line d = 10 h = 10 v0 = obj.ln.geom.vertices[0] v1 = obj.ln.geom.vertices[obj.ln.geom.vertices.length - 1] w = obj.ln.geom.boundingSphere.radius * 2 x = (v0.x + v1.x) / 2 y = (v0.y + v1.y) / 2 z = 5 gs = @glowCube(w, h, d, x, y, z) theta = Math.atan2(v0.y - v1.y, v0.x - v1.x) gs.rotateZ(theta) else console.log "unkown object to select" console.log obj doSelect = false if doSelect gs.userData = obj obj.glowBubble = gs @selectGroup.add(gs) @ve.render() true clearSelection: (clearProps = true) -> for x in @selectGroup.children if x.userData.glowBubble? delete x.userData.glowBubble @selectGroup.children = [] @clearPropsGUI() if clearProps @ve.render() clearSelector: -> @selectorGroup.children = [] @ve.render() deleteSelection: () => console.log("deleting selection") deletes = [] for x in @selectGroup.children deletes.push(x.userData) if x.userData.links? deletes.push.apply(deletes, x.userData.links) @ve.addie.delete(deletes) for d in deletes @removeElement(d) @ve.propsEditor.hide(false) @ve.equationEditor.hide() true class NameManager constructor: (@ve) -> @names = new Array() getName: (s, sys='root') -> n = "" if !@names[s]? @names[s] = 0 n = s + @names[s] else @names[s]++ n = s + @names[s] while @ve.surface.getElement(n, sys) != null @names[s]++ n = s + @names[s] n class SimSettings constructor: () -> @props = { begin: 0, end: 0, maxStep: 1e-3 } #VisualEnvironment holds the state associated with the Threejs objects used #to render Surfaces and the ElementBox. This class also contains methods #for controlling and interacting with this group of Threejs objects. class VisualEnvironment #Constructs a visual environment for the given @container. @container must #be a reference to a <div> dom element. The Threejs canvas the visual #environment renders onto will be appended as a child of the supplied #container constructor: (@sc0, @sc1, @sc2, @sc3, @scontainer) -> @scene = new THREE.Scene() @sscene = new THREE.Scene() @pscene = new THREE.Scene() @surface = new Surface(this) @cwidth = @scontainer.offsetWidth #200 @cheight = @scontainer.offsetHeight @iconCache = {} @scamera = new THREE.OrthographicCamera( @cwidth / -2, @cwidth / 2, @cheight / 2, @cheight / -2, 1, 1000) @keyh = new KeyHandler(this) @sview = new SurfaceView(this, @sc0) @srenderer = new THREE.WebGLRenderer({antialias: true, alpha: true}) @srenderer.setSize(@cwidth, @cheight) @clear = 0x262626 @alpha = 1 @srenderer.setClearColor(@clear, @alpha) @scontainer.appendChild(@srenderer.domElement) @scamera.position.z = 200 @scamera.zoom = 1 @namemanager = new NameManager(this) @addie = new Addie(this) @propsEditor = new PropsEditor(this) @equationEditor = new EquationEditor(this) @simSettings = new SimSettings() @splitView = new SplitView(this) loadIcon: (name, f = null) => if not @iconCache[name]? THREE.ImageUtils.loadTexture( "ico/"+g.user+"/"+name+".png", {}, (tex) => @iconCache[name] = tex if f? f(tex) true ) else f(@iconCache[name]) hsplit: () => console.log("hsplit") vsplit: () => console.log("vsplit") render: -> @sview.doRender() @srenderer.clear() @srenderer.clearDepth() @srenderer.render(@sscene, @scamera) showSimSettings: () -> @propsEditor.hide() @propsEditor.elements = [@simSettings] @propsEditor.show() showDiagnostics: () => console.log("Showing Diagnostics") h = window.innerHeight dh = parseInt($("#diagnosticsPanel").css("height").replace('px', '')) if dh > 0 $("#diagnosticsPanel").css("top", h+"px") $("#hsplitter").css("top", "auto") else $("#diagnosticsPanel").css("top", (h-200)+"px") $("#hsplitter").css("top", (h-205)+"px") $("#diagnosticsPanel").css("height", "auto") class SplitView constructor: (@ve) -> @c0 = window.innerWidth @c1 = @c0 splitRatio: () -> @c0 / window.innerWidth hdown: (event) => $("#metasurface").mouseup(@hup) $("#diagnosticsPanel").mouseup(@hup) $("#metasurface").mousemove(@hmove) $("#diagnosticsPanel").mousemove(@hmove) $("#diagnosticsPanel").css("height", "auto") hup: (event) => console.log("hup") $("#metasurface").off('mousemove') $("#metasurface").off('mouseup') $("#diagnosticsPanel").off('mousemove') $("#diagnosticsPanel").off('mouseup') hmove: (event) => $("#diagnosticsPanel").css("top", (event.clientY+5)+"px") $("#hsplitter").css("top", event.clientY+"px") vdown: (event) => $("#metasurface").mouseup(@vup) $("#metasurface").mousemove(@vmove) vup: (event) => console.log("vup") $("#metasurface").off('mousemove') $("#metasurface").off('mouseup') @ve.render() vmove: (event) => @c1 = event.clientX dc = @c1 - @c0 x = @c1+"px" r = ($("#metasurface").width() - @c1)+"px" $("#vsplitter").css("left", x) left = 0 center = event.clientX right = window.innerWidth @ve.sview.panes[0].viewport.width = center - left @ve.sview.panes[1].viewport.width = right - center @ve.sview.panes[1].viewport.left = center @ve.sview.panes[0].camera.right += dc @ve.sview.panes[1].camera.right -= dc @ve.sview.doRender() @c0 = @c1 class SurfaceView constructor: (@ve, @container) -> @scene = @ve.scene @surface = @ve.surface @cwidth = @container.offsetWidth @cheight = @container.offsetHeight @l = Math.max(window.innerWidth, window.innerHeight) @l = Math.max(@cwidth, @cheight) @clear = 0x262626 @alpha = 1 @renderer = new THREE.WebGLRenderer({antialias: true, alpha: true}) @renderer.setSize(@cwidth, @cheight) @renderer.setClearColor(@clear, @alpha) @mouseh = new MouseHandler(this) @raycaster = new THREE.Raycaster() @raycaster.linePrecision = 10 @container.appendChild(@renderer.domElement) @panes = [ { id: 1, zoomFactor: 1, background: 0x262626, viewport: { left: 0, bottom: 0, width: @cwidth, height: @cheight }, camera: new THREE.OrthographicCamera( 0, @cwidth, @cheight, 0, 1, 1000) } { id: 2, zoomFactor: 1, background: 0x464646, viewport: { left: @cwidth, bottom: 0, width: 0, height: @cheight }, camera: new THREE.OrthographicCamera( 0, 0, @cheight, 0, 1, 1000) } ] for p in @panes p.camera.position.z = 200 mouseHits: (eve) -> @mouseh.updateMouse(eve) @raycaster.setFromCamera(@mouseh.pos, @mouseh.icam) ixs = @raycaster.intersectObjects(@ve.surface.baseRect.obj3d.children) ixs baseRectIx: (eve) -> @mouseh.updateMouse(eve) @raycaster.setFromCamera(@mouseh.pos, @mouseh.icam) bix = @raycaster.intersectObject(@ve.surface.baseRect.obj3d) bix doRender: () -> for p in @panes vp = p.viewport @renderer.setViewport(vp.left, vp.bottom, vp.width, vp.height) @renderer.setScissor(vp.left, vp.bottom, vp.width, vp.height) @renderer.enableScissorTest(true) @renderer.setClearColor(p.background) p.camera.updateProjectionMatrix() @renderer.clear() @renderer.clearDepth() @renderer.render(@scene, p.camera) render: () -> @ve.render() getPane: (c) => result = {} for p in @panes if c.x > p.viewport.left and c.x < p.viewport.left + p.viewport.width and c.y > p.viewport.bottom and c.y < p.viewport.bottom + p.viewport.height result = p break p zoomin: (x = 3, p = new THREE.Vector2(0,0)) -> w = Math.abs(@mouseh.icam.right - @mouseh.icam.left) h = Math.abs(@mouseh.icam.top - @mouseh.icam.bottom) @mouseh.apane.zoomFactor -= x/(@mouseh.apane.viewport.width) @mouseh.icam.left += x * (p.x/w) @mouseh.icam.right -= x * (1 - p.x/w) @mouseh.icam.top -= x * (p.y/h) @mouseh.icam.bottom += x * (1 - p.y/h) @mouseh.icam.updateProjectionMatrix() @render() pan: (dx, dy) => @mouseh.icam.left += dx @mouseh.icam.right += dx @mouseh.icam.top += dy @mouseh.icam.bottom += dy @mouseh.icam.updateProjectionMatrix() @render() #This is the client side Addie, it talks to the Addie at cypress.deterlab.net #to manage a design class Addie constructor: (@ve) -> @mstate = { up: false } init: () => @load() @msync() update: (xs) => console.log("updating objects") console.log(xs) #build the update sets link_updates = {} node_updates = {} model_updates = {} settings_updates = [] for x in xs if x.links? #x is a node if it has links node_updates[JSON.stringify(x.id)] = x for l in x.links link_updates[JSON.stringify(l.id)] = l if x instanceof BaseElements.Link link_updates[JSON.stringify(x.id)] = x node_updates[JSON.stringify(x.endpoint[0].id)] = x.endpoint[0] node_updates[JSON.stringify(x.endpoint[1].id)] = x.endpoint[1] if x instanceof BaseElements.Model model_updates[x.id.name] = x for i in x.instances node_updates[JSON.stringify(i.id)] = i if x instanceof SimSettings settings_updates.push(x) true #build the update messages model_msg = { Elements: [] } node_msg = { Elements: [] } link_msg = { Elements: [] } settings_msg = { Elements: [] } for _, m of model_updates model_msg.Elements.push( { OID: { name: m.id.name, sys: "", design: dsg }, Type: "Model", Element: m.props } ) true for _, n of node_updates node_msg.Elements.push( { OID: n.id, Type: n.constructor.name, Element: n.props } ) true for _, l of link_updates type = "Link" type = "Plink" if l.isPhysical() link_msg.Elements.push( { OID: l.id, Type: type, Element: l.props } ) true for s in settings_updates settings_msg.Elements.push( { OID: { name: "", sys: "", design: dsg }, Type: "SimSettings", Element: s.props } ) true doLinkUpdate = () => console.log("link update") console.log(link_msg) if link_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(link_msg), (data) => for _, l of link_updates BaseElements.updateId(l) doNodeUpdate = () => console.log("node update") console.log(node_msg) if node_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(node_msg), (data) => for _, n of node_updates BaseElements.updateId(n) for _, l of link_updates l.setEndpointData() doLinkUpdate() doModelUpdate = () => console.log("model update") console.log(model_msg) if model_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(model_msg), (data) => for _, m of model_updates BaseElements.updateId(m) for _, n of node_updates n.sync() if n.sync? doNodeUpdate() doSettingsUpdate = () => console.log("settings update") console.log(settings_msg) if settings_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(settings_msg), (data) => console.log("settings update complete") #do the updates since this is a linked structure we have to be a bit careful #about update ordering, here we do models, then nodes then links. This is #because some nodes reference models, and all links reference nodes. At #each stage of the update we update the internals of the data structures at #synchronization points within the updates to ensure consistency if model_msg.Elements.length > 0 doModelUpdate() else if node_msg.Elements.length > 0 doNodeUpdate() else if link_msg.Elements.length > 0 doLinkUpdate() #settings update is independent of other updates so we can break out of the #above update structure doSettingsUpdate() delete: (xs) => console.log("addie deleting objects") console.log(xs) ds = [] for x in xs if x instanceof Phyo ds.push({type: "Phyo", element: x.props}) if x instanceof Computer ds.push({type: "Computer", element: x.props}) if x instanceof Router ds.push({type: "Router", element: x.props}) if x instanceof Switch ds.push({type: "Switch", element: x.props}) if x instanceof Sax ds.push({type: "Sax", element: x.props}) if x instanceof Link if x.isPhysical() ds.push({type: "Plink", element: x.props}) else ds.push({type: "Link", element: x.props}) delete_msg = { Elements: ds } $.post "/addie/"+dsg+"/design/delete", JSON.stringify(delete_msg), (data) => console.log("addie delete complete") console.log(data) load: () => ($.get "/addie/"+dsg+"/design/read", (data, status, jqXHR) => console.log("design read success") console.log(data) @doLoad(data) true ).fail (data) => console.log("design read fail " + data.status) loadedModels = {} loadElements: (elements) => links = [] plinks = [] for x in elements @ve.namemanager.getName(x.type.toLowerCase()) switch x.type when "Computer" @loadComputer(x.object) when "Router" @loadRouter(x.object) when "Switch" @loadSwitch(x.object) when "Phyo" @loadPhyo(x.object) when "Sax" @loadSax(x.object) when "Link" links.push(x.object) when "Plink" plinks.push(x.object) @ve.namemanager.getName("link") for x in links @loadLink(x) for x in plinks @loadPlink(x) for k, v of @ve.namemanager.names @ve.namemanager.names[k] = v + 10 @ve.render() true loadModels: (models) => for x in models m = @ve.mbox.addElement((box, x, y) -> new BaseElements.Model(box, x, y, 5)) m.props = x m.id.name = x.name loadedModels[m.props.name] = m if m.props.icon != '' do (m) => #capture m-ref before it gets clobbered by loop @ve.loadIcon(m.props.name, (tex) -> _tex = tex.clone() _tex.needsUpdate = true m.setIcon(_tex) for i in m.instances i.tex = tex.clone() i.tex.needsUpdate = true i.setIcon( i.shp.obj3d.position.x, i.shp.obj3d.position.y ) ) true loadSimSettings: (settings) => @ve.simSettings.props = settings doLoad: (m) => @loadModels(m.models) @loadElements(m.elements) @loadSimSettings(m.simSettings) true setProps: (x, p) => x.props = p x.id.name = p.name x.id.sys = p.sys x.id.design = p.design loadComputer: (x) => c = new BaseElements.Computer(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(c, x) BaseElements.setSshCmd(c) @ve.surface.elements.push(c) true loadPhyo: (x) => m = loadedModels[x.model] p = new BaseElements.Phyo(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(p, x) @ve.surface.elements.push(p) m.instances.push(p) p.model = m p.loadArgValues() true loadSax: (x) => s = new BaseElements.Sax(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(s, x) BaseElements.setSshCmd(s) @ve.surface.elements.push(s) true loadRouter: (x) => r = new BaseElements.Router(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(r, x) BaseElements.setSshCmd(r) @ve.surface.elements.push(r) true loadSwitch: (x) => s = new BaseElements.Switch(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(s, x) @ve.surface.elements.push(s) true loadLink: (x) => a = @ve.surface.getElement( x.endpoints[0].name, x.endpoints[0].sys ) if a == null console.log("bad endpoint detected") b = @ve.surface.getElement( x.endpoints[1].name, x.endpoints[1].sys ) if b == null console.log("bad endpoint detected") l = new BaseElements.Link(@ve.surface.baseRect, a.shp.obj3d.linep, b.shp.obj3d.linep, 0, 0, 5) a.links.push(l) a.shp.obj3d.lines.push(l.ln) b.links.push(l) b.shp.obj3d.lines.push(l.ln) l.endpoint[0] = a l.endpoint[1] = b l.ep_ifx[0] = x.endpoints[0].ifname l.ep_ifx[1] = x.endpoints[1].ifname @setProps(l, x) l.setEndpointData() @ve.surface.elements.push(l) l.setColor() true #grosspants loadPlink: (x) => a = @ve.surface.getElement( x.endpoints[0].name, x.endpoints[0].sys ) if a == null console.log("bad endpoint detected") b = @ve.surface.getElement( x.endpoints[1].name, x.endpoints[1].sys ) if b == null console.log("bad endpoint detected") l = new BaseElements.Link(@ve.surface.baseRect, a.shp.obj3d.linep, b.shp.obj3d.linep, 0, 0, 5) a.links.push(l) a.shp.obj3d.lines.push(l.ln) b.links.push(l) b.shp.obj3d.lines.push(l.ln) l.endpoint[0] = a l.endpoint[1] = b l.applyPhysicalProps() @setProps(l, x) l.unpackBindings() l.setEndpointData() @ve.surface.elements.push(l) true levelColor: (l) => switch l when "info" then "blue" when "warning" then "orange" when "error" then "red" when "success" then "green" else "gray" compile: () => console.log("asking addie to compile the design") $("#diagText").html("") $("#ajaxLoading").css("display", "block") $.get "/addie/"+dsg+"/design/compile", (data) => console.log("compilation result:") console.log(data) $("#ajaxLoading").css("display", "none") if data.elements? for d in data.elements $("#diagText").append( "<span style='color:"+@levelColor(d.level)+"'><b>"+ d.level+ "</b></span> - " + d.message + "<br />" ) run: () => console.log("asking addie to run the experiment") $.get "/addie/"+dsg+"/design/run", (data) => console.log("run result: ") console.log(data) materialize: () => if @mstate.up console.log("asking addie to dematerialize the experiment") $("#materialize").html("Materialize") $.get "/addie/"+dsg+"/design/dematerialize", (data) => console.log("dematerialize result: ") console.log(data) #TODO do an async call here and then grey out the materialization button #until the async call returns @mstate.up = false else console.log("asking addie to materialize the experiment") $("#materialize").html("Dematerialize") @mstate.up = true $.get "/addie/"+dsg+"/design/materialize", (data) => console.log("materialize result: ") console.log(data) #synchronize materialization status msync: () => console.log("synchronizing materialization state with addie") $.get "/addie/"+dsg+"/design/mstate", (data) => console.log("materialization state:") console.log(data) if data.Status? and data.Status == "Active" @mstate.up = true $("#materialize").html("Dematerialize") class EBoxSelectHandler constructor: (@mh) -> test: (ixs) -> ixs.length > 0 and ixs[ixs.length - 1].object.userData instanceof StaticElementBox handleDown: (ixs) -> @mh.sv.surface.clearSelection() if ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! ebox select -- " + e.constructor.name console.log e #TODO double click should lock linking until link icon clicked again # this way many things may be linked without going back to the icon if e instanceof Link console.log "! linking objects" @mh.sv.container.style.cursor = "crosshair" @mh.placingObject = null @mh.sv.container.onmousemove = (eve) => @mh.linkingH.handleMove0(eve) @mh.sv.container.onmousedown = (eve) => @mh.linkingH.handleDown0(eve) else console.log "! placing objects" @mh.makePlacingObject(e) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) @mh.sv.ve.scontainer.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) stillOnEBox: (event) => @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.spos, @mh.sv.ve.scamera) ixs = @mh.sv.raycaster.intersectObjects(@mh.sv.ve.sscene.children, true) result = false for x in ixs if x.object.userData instanceof StaticElementBox result = true break result handleUp: (event) -> if @stillOnEBox(event) @mh.sv.surface.removeElement(@mh.placingObject) false else @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position @mh.sv.ve.addie.update([@mh.placingObject]) @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) -> @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) if bix.length > 0 @mh.sv.surface.moveObject(@mh.placingObject.shp.obj3d, bix[0].point) @mh.sv.render() class MBoxSelectHandler constructor: (@mh) -> @model = null @instance = null test: (ixs) -> ixs.length > 0 and ixs[ixs.length - 1].object.userData instanceof ModelBox handleDown: (ixs) -> @mh.sv.surface.clearSelection() if ixs[0].object.userData.cyjs? e = ixs[0].object.userData @model = e console.log('mbox down') @mh.sv.container.onmousemove = (eve) => @handleMove0(eve) @mh.sv.ve.scontainer.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) stillOnMBox: (event) => @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.spos, @mh.sv.ve.scamera) ixs = @mh.sv.raycaster.intersectObjects(@mh.sv.ve.sscene.children, true) result = false for x in ixs if x.object.userData instanceof ModelBox result = true break result handleUp: (event) -> console.log('mbox up') if @instance? if @stillOnMBox(event) @mh.sv.surface.removeElement(@mh.placingObject) idx = @model.instances.indexOf(@instance) if idx > -1 @model.instances.splice(idx, 1) @instance = null @mh.placingObject = null false else @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position @mh.placingObject.sync() @mh.sv.ve.addie.update([@mh.placingObject]) @mh.sv.surface.clearSelection() else if !@instance? @mh.sv.ve.propsEditor.elements = [@model] @mh.sv.ve.propsEditor.show() @mh.sv.ve.equationEditor.show(@model) @mh.sv.container.onmousemove = null @mh.sv.container.onmouseup = null @mh.sv.ve.scontainer.onmouseup = (eve) => null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @instance = null handleMove0: (event) -> @instance = @mh.makePlacingObject(@model.instantiate(null, 0, 0, 0, 25, 25)) @instance.model = @model @instance.addArgs() @model.instances.push(@instance) @mh.sv.container.onmousemove = (eve) => @handleMove1(eve) handleMove1: (event) -> @mh.updateMouse(event) @mh.sv.ve.propsEditor.hide() @mh.sv.ve.equationEditor.hide() @mh.sv.surface.clearSelection() @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) if bix.length > 0 #ox = @mh.placingObject.shp.geom.boundingSphere.radius @mh.sv.surface.moveObject(@mh.placingObject.shp.obj3d, bix[0].point) @mh.sv.render() class SurfaceElementSelectHandler constructor: (@mh) -> @start = new THREE.Vector3(0,0,0) @end= new THREE.Vector3(0,0,0) @p0 = new THREE.Vector3(0,0,0) @p1 = new THREE.Vector3(0,0,0) test: (ixs) -> ixs.length > 1 and ixs[ixs.length - 1].object.userData instanceof Surface and ixs[0].object.userData.cyjs? handleDown: (ixs) -> @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) @p0.copy(bix[0].point) @p1.copy(@p0) @mh.updateMouse(event) @start.copy(@mh.pos) e = ixs[0].object.userData console.log "! surface select -- " + e.constructor.name console.log "current selection" console.log @mh.sv.surface.selectGroup console.log("multiselect: " + @mh.sv.ve.keyh.multiselect) if not ixs[0].object.userData.glowBubble? && not @mh.sv.ve.keyh.multiselect @mh.sv.surface.clearSelection() @mh.sv.surface.selectObj(e) if @mh.sv.surface.selectGroup.children.length == 1 @mh.sv.ve.propsEditor.elements = [e] @mh.sv.ve.propsEditor.show() else @mh.sv.ve.propsEditor.elements = @mh.sv.surface.getSelected() @mh.sv.ve.propsEditor.show() if e instanceof BaseElements.Phyo @mh.sv.ve.equationEditor.show(e.model) @mh.placingObject = e @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) applyGroupMove: () -> for x in @mh.sv.surface.selectGroup.children p = new THREE.Vector3(@p1.x - @p0.x , @p1.y - @p0.y, @p0.z) if x.userData.shp? @mh.sv.surface.moveObjectRelative(x.userData.shp.obj3d, p) @mh.sv.surface.moveObjectRelative(x, p) updateGroupMove: () -> updates = [] for x in @mh.sv.surface.selectGroup.children x.userData.props.position = x.position updates.push(x.userData) @mh.sv.ve.addie.update(updates) handleUp: (ixs) -> @mh.updateMouse(event) @end.copy(@mh.pos) if @mh.placingObject.shp? @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position if @start.distanceTo(@end) > 0 @updateGroupMove() #@applyGroupMove() @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) -> @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) @p1.copy(bix[0].point) if bix.length > 0 @applyGroupMove() @mh.sv.render() @p0.copy(@p1) #TODO, me thinks that react.js orangular.js is meant to deal with precisely #the problem we are tyring to solve with the props editor, in the future we #should look into replacing dat.gui (as nifty as it is) with an angular #based control that is a bit more intelligent class PropsEditor constructor: (@ve) -> @elements = [] @cprops = {} show: () -> for e in @elements e.sync() if e.sync? @commonProps() @datgui = new dat.GUI() for k, v of @cprops @datgui.add(@cprops, k) if @elements.length == 1 and @elements[0].funcs? for k, v of @elements[0].funcs @datgui.add(@elements[0].funcs, k) true save: () -> for k, v of @cprops for e in @elements e.props[k] = v if v != "..." e.sync() if e.sync? @ve.addie.update(@elements) hide: (doSave = true) -> if @datgui? @save() if doSave @datgui.destroy() @elements = [] @cprops = {} @datgui = null commonProps: () -> ps = {} cps = new Array() addProp = (d, k, v) -> if !d[k]? d[k] = [v] else d[k].push(v) addProps = (e) => for k, v of e.props continue if k == 'position' continue if k == 'design' continue if k == 'endpoints' continue if k == 'interfaces' continue if k == 'path' continue if k == 'args' continue if k == 'equations' continue if k == 'bindings' continue if k == 'icon' continue if k == 'name' and @elements.length > 1 addProp(ps, k, v) addProps(e) for e in @elements addCommon = (k, v, es) -> if v.length == es.length then cps[k] = v true addCommon(k, v, @elements) for k, v of ps isUniform = (xs) -> u = true i = xs[0] for x in xs u = (x == i) break if !u u setUniform = (k, v, e) -> if isUniform(v) e[k] = v[0] else e[k] = "..." true reduceUniform = (xps) -> setUniform(k, v, xps) for k, v of xps true reduceUniform(cps) @cprops = cps cps class EquationEditor constructor: (@ve) -> @model = null show: (m) -> @model = m console.log("showing equation editor") $("#eqtnSrc").val(@model.props.equations) if @ve.propsEditor.datgui? $("#eqtnEditor").css("display", "inline") $("#eqtnEditor").css("top", @ve.propsEditor.datgui.domElement.clientHeight + 30) hide: () -> console.log("hiding equation editor") if @model? @model.props.equations= $("#eqtnSrc").val() $("#eqtnEditor").css("display", "none") class PanHandler constructor: (@mh) -> @p0 = new THREE.Vector2(0,0) @p1 = new THREE.Vector2(0,0) handleDown: (event) => @mh.updateMouse(event) @p0.x = event.clientX @p0.y = event.clientY @p1.x = event.clientX @p1.y = event.clientY @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) handleUp: (event) => @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) => @p1.x = event.clientX @p1.y = event.clientY dx = -(@p1.x - @p0.x) dx *= @mh.apane.zoomFactor dy = @p1.y - @p0.y dy *= @mh.apane.zoomFactor @mh.sv.pan(dx, dy) @p0.x = @p1.x @p0.y = @p1.y class SurfaceSpaceSelectHandler constructor: (@mh) -> @selCube = new SelectionCube() test: (ixs) -> ixs.length > 0 and ixs[0].object.userData instanceof Surface handleDown: (ixs) -> @mh.sv.surface.clearSelection() console.log "! space select down" p = new THREE.Vector3( ixs[ixs.length - 1].point.x, ixs[ixs.length - 1].point.y, 75 ) @selCube.init(p) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.surface.selectorGroup.add(@selCube.obj3d) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) @mh.sv.surface.clearSelection() handleUp: (event) -> console.log "! space select up" sel = @mh.sv.surface.getSelection(@selCube.obj3d.geometry.boundingBox) @mh.sv.surface.selectObj(o) for o in sel @mh.sv.ve.propsEditor.elements = sel console.log('common props') @mh.sv.ve.propsEditor.show() @selCube.reset() @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null @mh.sv.render() handleMove: (event) -> bix = @mh.baseRectIx(event) if bix.length > 0 p = new THREE.Vector3( bix[bix.length - 1].point.x, bix[bix.length - 1].point.y, 75 ) @selCube.update(p) @mh.sv.render() class LinkingHandler constructor: (@mh) -> handleDown0: (event) -> ixs = @mh.sv.mouseHits(event) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! link0 " + e.constructor.name pos0 = ixs[0].object.linep pos1 = new THREE.Vector3( ixs[0].object.position.x, ixs[0].object.position.y, 5 ) @mh.placingLink = new BaseElements.Link(@mh.sv.surface.baseRect, pos0, pos1, 0, 0, 5 ) @mh.sv.surface.elements.push(@mh.placingLink) BaseElements.initName(@mh.placingLink, "link") @mh.placingLink.linkEndpoint(0, ixs[0].object.userData) @mh.sv.container.onmousemove = (eve) => @handleMove1(eve) @mh.sv.container.onmousedown = (eve) => @handleDown1(eve) else console.log "! link0 miss" handleDown1: (event) -> ixs = @mh.sv.mouseHits(event) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! link1 " + e.constructor.name @mh.placingLink.ln.geom.vertices[1] = ixs[0].object.linep @mh.placingLink.linkEndpoint(1, ixs[0].object.userData) @mh.sv.surface.updateLink(@mh.placingLink.ln) @mh.placingLink.typeResolve() @mh.sv.render() @mh.sv.ve.addie.update([@mh.placingLink]) @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.style.cursor = "default" else console.log "! link1 miss" handleMove0: (event) -> @mh.updateMouse(event) handleMove1: (event) -> bix = @mh.sv.baseRectIx(event) if bix.length > 0 @mh.sv.scene.updateMatrixWorld() @mh.placingLink.ln.geom.vertices[1].x = bix[bix.length - 1].point.x @mh.placingLink.ln.geom.vertices[1].y = bix[bix.length - 1].point.y @mh.placingLink.ln.geom.verticesNeedUpdate = true @mh.sv.render() #Mouse handler encapsulates the logic of dealing with mouse events class MouseHandler constructor: (@sv) -> @pos = new THREE.Vector3(0, 0, 1) @spos = new THREE.Vector3(0, 0, 1) @eboxSH = new EBoxSelectHandler(this) @mboxSH = new MBoxSelectHandler(this) @surfaceESH = new SurfaceElementSelectHandler(this) @surfaceSSH = new SurfaceSpaceSelectHandler(this) @linkingH = new LinkingHandler(this) @panHandler = new PanHandler(this) @icam = null ondown: (event) -> @baseDown(event) onwheel: (event) => @apane = @sv.getPane(new THREE.Vector2(event.layerX, event.layerY)) @icam = @apane.camera @sv.zoomin(-event.deltaY / 5, new THREE.Vector2(event.layerX, event.layerY)) updateMouse: (event) -> @apane = @sv.getPane(new THREE.Vector2(event.layerX, event.layerY)) @icam = @apane.camera if @apane.id == 1 sr = @sv.ve.splitView.splitRatio() else sr = 1 - @sv.ve.splitView.splitRatio() @pos.x = ((event.layerX - @apane.viewport.left) / (@sv.cwidth * sr) ) * 2 - 1 @pos.y = -((event.layerY - @apane.viewport.bottom) / @sv.cheight ) * 2 + 1 @spos.x = (event.layerX / @sv.ve.scontainer.offsetWidth ) * 2 - 1 @spos.y = -(event.layerY / @sv.ve.scontainer.offsetHeight) * 2 + 1 baseRectIx: (event) -> @updateMouse(event) @sv.raycaster.setFromCamera(@pos, @icam) @sv.raycaster.intersectObject(@sv.ve.surface.baseRect.obj3d) placingObject: null placingLink: null makePlacingObject: (obj) -> @sv.raycaster.setFromCamera(@pos, @icam) bix = @sv.raycaster.intersectObject(@sv.ve.surface.baseRect.obj3d) x = y = 0 if bix.length > 0 ix = bix[bix.length - 1] x = ix.point.x y = ix.point.y @placingObject = @sv.surface.addElement(obj, x, y) #onmousedown handlers baseDown: (event) -> #the order actually matters here, need to hide the equation editor first #so the equations get saved to the underlying object before the props #editor sends them to addie @sv.ve.equationEditor.hide() @sv.ve.propsEditor.hide() #get the list of objects the mouse click intersected @updateMouse(event) console.log(@pos) #delegate the handling of the event to one of the handlers #check the model boxes first if event.which == 1 @sv.raycaster.setFromCamera(@spos, @sv.ve.scamera) sixs = @sv.raycaster.intersectObjects(@sv.ve.sscene.children, true) if @eboxSH.test(sixs) then @eboxSH.handleDown(sixs) else if @mboxSH.test(sixs) then @mboxSH.handleDown(sixs) else @sv.raycaster.setFromCamera(@pos, @icam) ixs = @sv.raycaster.intersectObjects(@sv.scene.children, true) if @surfaceESH.test(ixs) then @surfaceESH.handleDown(ixs) else if @surfaceSSH.test(ixs) then @surfaceSSH.handleDown(ixs) else if event.which = 3 @panHandler.handleDown(event) true doMultiplink = (sel) => class MultiLinker constructor: (@ve, @sel) -> console.log("multiplink") console.log(@sel) @ve.sview.container.style.cursor = "crosshair" @ve.sview.container.onmousedown = (eve) => @handleDown(eve) @tgtP = new THREE.Vector3(0,0,0) @links = [] for s in @sel l = new BaseElements.Link(@ve.surface.baseRect, s.shp.obj3d.linep, @tgtP, 0, 0, 5) BaseElements.initName(l, "link") l.linkEndpoint(0, s) @links.push(l) true handleDown: (eve) => ixs = @ve.sview.mouseHits(eve) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! multilink1 " + e.constructor.name @tgtP = ixs[0].object.linep for l in @links l.linkEndpoint(1, ixs[0].object.userData) l.typeResolve() @ve.surface.updateLink(l.ln) @ve.sview.render() @ve.addie.update([l]) @ve.sview.container.style.cursor = "default" @ve.sview.container.onmousedown = (eve) => @ve.sview.mouseh.baseDown(eve) true else console.log "! multilink miss" true class KeyHandler constructor: (@ve) -> @multiselect = false ondown: (event) => keycode = window.event.keyCode || event.which if(keycode == 8 || keycode == 46) @ve.surface.deleteSelection() event.preventDefault() else if(keycode == 16) console.log("multiselect start") @multiselect = true true else if(keycode == 67) xs = @ve.surface.getSelected() if xs.length == 0 @ve.sview.container.style.cursor = "crosshair" @ve.sview.container.onmousemove = (eve) => @ve.sview.mouseh.linkingH.handleMove0(eve) @ve.sview.container.onmousedown = (eve) => @ve.sview.mouseh.linkingH.handleDown0(eve) else ml = new MultiLinker(@ve, xs) true onup: (event) => keycode = window.event.keyCode || event.which if(keycode == 16) console.log("multiselect end") @multiselect = false true
90935
root = exports ? this getParameterByName = (name) => name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]") regex = new RegExp("[\\?&]" + name + "=([^&#]*)") results = regex.exec(location.search) decodeURIComponent(results[1].replace(/\+/g, " ")) initViz = () => g.ve = new VisualEnvironment( document.getElementById("surface0"), document.getElementById("surface1"), document.getElementById("surface2"), document.getElementById("surface3"), document.getElementById("controlPanel") ) g.ve.ebox = new StaticElementBox(g.ve, 120, g.ve.cheight/2 - 65) mh = g.ve.cheight - 167 g.ve.mbox = new ModelBox(g.ve, mh, (g.ve.cheight - 140)/2 - mh/2.0 - 60) g.ve.datgui = null g.ve.render(g.ve) dsg = "" launchAddieInstance = () => ($.get "/gatekeeper/launchAddie?user="+g.user+"&design="+dsg, (data) => console.log("addie instance launched and ready!") g.ve.addie.init() ).fail () -> console.log("failed to launch addie instance") true #Entry point root.go = -> ($.get "/gatekeeper/thisUser", (data) => g.user = data console.log("the user is " + g.user) g.xp = getParameterByName("xp") dsg = g.xp console.log("the xp is " + g.xp) initViz() launchAddieInstance() true ).fail () -> console.log("fail to get current user, going back to login screen") window.location.href = location.origin true #Global event handlers root.vz_mousedown = (event, idx) -> g.ve.sview.mouseh.ondown(event) root.hsplit_mdown = (event) => g.ve.splitView.hdown(event) root.vsplit_mdown = (event) => g.ve.splitView.vdown(event) root.vz_keydown = (event) => g.ve.keyh.ondown(event) root.vz_keyup = (event) => g.ve.keyh.onup(event) root.vz_wheel = (event, idx) => g.ve.sview.mouseh.onwheel(event) root.run = (event) => g.ve.addie.run() root.materialize = (event) => g.ve.addie.materialize() root.newModel = (event) -> g.ve.mbox.newModel() root.compile = () => g.ve.addie.compile() root.showSimSettings = () => g.ve.showSimSettings() root.showDiagnostics = () => g.ve.showDiagnostics() #Global state holder g = {} #Shapes contains a collection of classes that comprise the basic shapes used to #represent Cypress CPS elements Shapes = { Rectangle : class Rectangle constructor: (color, x, y, z, width, height) -> @geom = new THREE.PlaneBufferGeometry(width, height) @material = new THREE.MeshBasicMaterial({color: color}) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Circle : class Circle constructor: (color, x, y, z, radius) -> @geom = new THREE.CircleGeometry(radius, 64) @material = new THREE.MeshBasicMaterial({color: color}) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Diamond: class Diamond constructor: (color, x, y, z, l) -> @shape = new THREE.Shape() @shape.moveTo(0,l) @shape.lineTo(l,0) @shape.lineTo(0,-l) @shape.lineTo(-l,0) @shape.lineTo(0,l) @material = new THREE.MeshBasicMaterial({color: color}) @geom = new THREE.ShapeGeometry(@shape) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Line: class Line constructor: (color, from, to, z) -> @material = new THREE.LineBasicMaterial( { color: color, linewidth: 3 } ) @geom = new THREE.Geometry() @geom.dynamic = true @geom.vertices.push(from, to) @obj3d = new THREE.Line(@geom, @material) @obj3d.position.x = 0 @obj3d.position.y = 0 @obj3d.position.z = z @obj3d.lines = [] select: -> Icon: class Icon constructor: (@texture, x, y, z) -> @material = new THREE.SpriteMaterial({ map: @texture, depthTest: false, depthWrite: false }) @obj3d= new THREE.Sprite(@material) @obj3d.position.set(x,y,z) @obj3d.scale.set(30, 30, 1.0) @obj3d.lines = [] @obj3d.linep = new THREE.Vector3(x, y, 5) select: -> SelectionCube: class SelectionCube constructor: () -> @geom = new THREE.Geometry() @geom.dynamic = true @aa = new THREE.Vector3(0, 0, 75) @ab = new THREE.Vector3(0, 0, 75) @ba = new THREE.Vector3(0, 0, 75) @bb = new THREE.Vector3(0, 0, 75) @geom.vertices.push( @aa, @ab, @ba, @bb, @ba, @ab ) @geom.faces.push( new THREE.Face3(0, 1, 2), new THREE.Face3(2, 1, 0), new THREE.Face3(3, 4, 5), new THREE.Face3(5, 4, 3) ) @geom.computeBoundingSphere() @material = new THREE.MeshBasicMaterial( { color: 0xFDBF3B, opacity: 0.2, transparent: true } ) @obj3d = new THREE.Mesh(@geom, @material) updateGFX: () -> @geom.verticesNeedUpdate = true @geom.lineDistancesNeedUpdate = true @geom.elementsNeedUpdate = true @geom.normalsNeedUpdate = true @geom.computeFaceNormals() @geom.computeVertexNormals() @geom.computeBoundingSphere() @geom.computeBoundingBox() init: (p) -> @aa.x = @ab.x = @ba.x = p.x @aa.y = @ba.y = @ab.y = p.y @bb.x = @aa.x @bb.y = @aa.y @updateGFX() update: (p) -> @bb.x = @ba.x = p.x @bb.y = @ab.y = p.y @updateGFX() reset: () -> @aa.x = @bb.x = @ba.x = @ab.x = 0 @aa.y = @bb.y = @ba.y = @ab.y = 0 @updateGFX() } #The BaseElements object holds classes which are Visual representations of the #objects that comprise a Cypress networked CPS system BaseElements = { updateId: (e) -> e.onIdUpdate() if e.onIdUpdate? e.id.name = e.props.name if e.id.sys? e.id.sys = e.props.sys currentId: (d) -> {name: d.props.name, sys: d.props.sys, design: dsg } setSshCmd: (x) => x.props.sshcmd = 'ssh -A -t '+g.user+'@users.<EMAIL>.deterlab.net '+ 'ssh -A '+x.props.name+'.'+g.user+'-'+dsg+'.cypress' initName: (x, n) => x.props.name = g.ve.namemanager.getName(n) x.id.name = x.props.name addInterface: (x) => ifname = "" if x.props.interfaces? ifname = "ifx"+Object.keys(x.props.interfaces).length x.props.interfaces[ifname] = { name: ifname, latency: 0, capacity: 1000 } ifname #The Computer class is a representation of a computer Computer: class Computer constructor: (@parent, x, y, z) -> @shp = new Shapes.Diamond(0x2390ff, x, y, z, 15) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "computer0", sys: "root", os: "Ubuntu1404-64-STD", start_script: "", interfaces: {}, sshcmd: "" } @id = { name: "computer0" sys: "root" design: dsg } @links = [] showProps: (f) -> c = f.add(@props, 'name') c = f.add(@props, 'sys') c = f.add(@props, 'start_script') c = f.add(@props, 'os') #cyjs generates the json for this object cyjs: -> #The Model class is a represenation of a mathematical model of a physical object Model: class Model constructor: (@parent, x, y, z) -> @shp = new Shapes.Rectangle(0x239f5a, x, y, z, 25, 25) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @sprite = false @props = { name: "model0", params: "", equations: "", icon: "" } @funcs = { "Set Icon": () => console.log("setting sprite for " + @props.name) $("#upModelName").val(@props.name) $("#upModelIcon").change () => f = $("#upModelIcon")[0].files[0] console.log("sprite selected") mdl = $("#upModelName").val() console.log("model is " + mdl) console.log(f) $("#upModelIcon").off("change") fd = new FormData($("#uploadModelIconForm")[0]) xhr = new XMLHttpRequest() xhr.open("POST", "/addie/"+dsg+"/design/modelIco") xhr.onreadystatechange = () => if xhr.readyState == 4 && xhr.status == 200 g.ve.loadIcon(mdl, (tex) => @setIcon(tex) ) xhr.send(fd) true $("#upModelIcon").click() } @id = { name: "model0" } @instances = [] setIcon: (tex) => @parent.obj3d.remove(@shp.obj3d) _shp = new Shapes.Icon(tex, @shp.obj3d.position.x, @shp.obj3d.position.y, @shp.obj3d.position.z) @shp = _shp @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) g.ve.render() @tex = tex instantiate: (parent, x, y, z) -> if @tex? obj = new Phyo(parent, x, y, z, @tex.clone()) obj.tex.needsUpdate = true else obj = new Phyo(parent, x, y, z) obj.props.model = @props.name obj #cyjs generates the json for this object cyjs: -> Phyo: class Phyo constructor: (@parent, x, y, z, @tex = null) -> if @tex == null @shp = new Shapes.Rectangle(0x239f5a, x, y, z, 25, 25) @shp.obj3d.userData = this else @setIcon() @model = null if @parent? @parent.obj3d.add(@shp.obj3d) @props = { name: "model0", sys: "root", model: "", args: "", init: "", } @id = { name: "model0", sys: "root", design: dsg } @links = [] @args = [] setIcon: (x=0, y=0, z=50) => savelx = false if @shp? lp = @shp.obj3d.linep ls = @shp.obj3d.lines savelx = true if @parent? and @shp? @parent.obj3d.remove(@shp.obj3d) @shp = new Shapes.Icon(@tex, x, y, z) if savelx @shp.obj3d.linep = lp @shp.obj3d.lines = ls @shp.obj3d.userData = this if @parent? @parent.obj3d.add(@shp.obj3d) g.ve.render() addArgs: () -> _args = @model.props.params .replace(" ", "") .split(",") .map((x) -> x.replace(" ", "")) .filter((x) -> x.length != 0) for p in _args if !@props[p]? @props[p] = "" for p in @args if p not in _args delete @props[p] @args = _args true loadArgValues: () -> _args = @props.args .split(",") .filter((x) -> x.length != 0) .map((x) -> x.split("=").filter((y) -> y.length != 0)) for x in _args @props[x[0]] = x[1] @args.push(x[0]) sync: -> if @model? @props.model = @model.props.name @addArgs() @props.args = "" for p in @args @props.args += (p+"="+@props[p]+",") onIdUpdate: -> for x in @links if @id.name != @props.name x.props[@props.name] = x.props[@id.name] delete(x.props[@id.name]) #cyjs generates the json for this object cyjs: -> #The Sax class is a representation of a sensing and acutation unit Sax: class Sax constructor: (@parent, x, y, z) -> @shp = new Shapes.Circle(0x239f9c, x, y, z, 7) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "sax0", sys: "root", design: dsg, sense: "", actuate: "" interfaces: {}, sshcmd: "" } @id = { name: "sax0", sys: "root", design: dsg } @links = [] onIdUpdate: -> for x in @links if x.isPhysical() and @id.name != @props.name x.props[@props.name] = x.props[@id.name] delete(x.props[@id.name]) #cyjs generates the json for this object cyjs: -> #Router is a visual representation of an IP-network router Router: class Router constructor: (@parent, x, y, z) -> @shp = new Shapes.Circle(0x23549F, x, y, z, 15) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "<NAME>0", sys: "root", capacity: 100, latency: 0, interfaces: {}, sshcmd: "" } @id = { name: "router0" sys: "root" design: dsg } @links = [] showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> #Switch is a visual representation of an IP-network swtich Switch: class Switch constructor: (@parent, x, y, z) -> @shp = new Shapes.Rectangle(0x23549F, x, y, z, 25, 25) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "switch<NAME>", sys: "root", capacity: 1000, latency: 0, interfaces: {} } @id = { name: "switch0" sys: "root" design: dsg } @links = [] showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> Link: class Link constructor: (@parent, from, to, x, y, z, isIcon = false) -> @endpoint = [null, null] @ep_ifx = ["",""] #TODO: s/ln/shp/g for consistency @ln = new Shapes.Line(0xcacaca, from, to, z) @ln.obj3d.userData = this @props = { name: "<NAME>", sys: "root", design: dsg, capacity: 1000, latency: 0, endpoints: [ {name: "link<NAME>", sys: "root", design: dsg, ifname: ""}, {name: "link0", sys: "root", design: dsg, ifname: ""} ] } @id = { name: "<NAME>" sys: "root" design: dsg } if isIcon @shp = new Shapes.Rectangle(@parent.material.color, x, y, z, 25, 25) @shp.obj3d.userData = this @shp.obj3d.add(@ln.obj3d) @parent.obj3d.add(@shp.obj3d) else @parent.obj3d.add(@ln.obj3d) isInternet: -> @endpoint[0] instanceof Router and @endpoint[1] instanceof Router isPhysical: -> @endpoint[0] instanceof Phyo and @endpoint[1] instanceof Phyo or @endpoint[0] instanceof Phyo and @endpoint[1] instanceof Sax or @endpoint[1] instanceof Phyo and @endpoint[0] instanceof Sax isIfxPhysical: (i) -> @endpoint[i] instanceof Phyo applyWanProps: -> @props.capacity = 100 @props.latency = 7 applyPhysicalProps: -> @props = { name: @props.name, sys: @props.sys, design: @props.design, endpoints: [ {name: "link0", sys: "root", design: dsg}, {name: "link0", sys: "root", design: dsg} ], bindings: ["",""] } @props[@endpoint[0].props.name] = "" if @endpoint[0] #instanceof Phyo @props[@endpoint[1].props.name] = "" if @endpoint[1] #instanceof Phyo @ln.material.color = new THREE.Color(0x125634) @ln.geom.colorsNeedUpdate = true setColor: () -> if @isPhysical() @ln.material.color = new THREE.Color(0x125634) @ln.geom.colorsNeedUpdate = true else @ln.material.color = new THREE.Color(0x123456) @ln.geom.colorsNeedUpdate = true linkEndpoint: (i, x) -> ifname = BaseElements.addInterface(x) x.links.push(this) x.shp.obj3d.lines.push(@ln) @ln.geom.vertices[i] = x.shp.obj3d.linep @endpoint[i] = x @ep_ifx[i] = ifname setEndpointData: -> @props.endpoints[0].name = @endpoint[0].props.name @props.endpoints[0].sys = @endpoint[0].props.sys if !@isIfxPhysical(1) #yes, this is based on the other side of the connection @props.endpoints[0].ifname = @ep_ifx[0] if @isPhysical() @props.bindings[0] = @props[@endpoint[0].props.name] @props.endpoints[1].name = @endpoint[1].props.name @props.endpoints[1].sys = @endpoint[1].props.sys if !@isIfxPhysical(0) @props.endpoints[1].ifname = @ep_ifx[1] if @isPhysical() @props.bindings[1] = @props[@endpoint[1].props.name] unpackBindings: -> @props[@endpoint[0].props.name] = @props.bindings[0] @props[@endpoint[1].props.name] = @props.bindings[1] ifInternetToWanLink: -> @applyWanProps() if @isInternet() removePhantomEndpoint: (i) -> if @endpoint[i] instanceof Sax delete @endpoint[i].props.interfaces[@ep_ifx[i]] ifPhysicalToPlink: -> if @isPhysical() @removePhantomEndpoint(0) @removePhantomEndpoint(1) @applyPhysicalProps() else @ln.material.color = new THREE.Color(0x123456) @ln.geom.colorsNeedUpdate = true typeResolve: -> @ifInternetToWanLink() @ifPhysicalToPlink() @setEndpointData() showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') if @isInternet() f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> } #The ElementBox holds Element classes which may be added to a system, #aka the thing on the left side of the screen class ElementBox #Constructs an ElementBox object given a @ve visual environment constructor: (@ve, @height, @y) -> @width = 75 @x = -@ve.cwidth/2 + @width / 2 + 5 @z = 5 @box = new Shapes.Rectangle(0x404040, @x, @y, @z, @width, @height) @box.obj3d.userData = this @ve.sscene.add(@box.obj3d) @count = 0 @addBaseElements() #addElement adds a visual element to the ElementBox given an element #contruction lambda ef : (box, x, y) -> Object3D addElement: (ef) -> row = Math.floor(@count / 2) col = @count % 2 _x = if col == 0 then -18 else 18 _y = (@height / 2 - 25) - row * 35 e = ef(@box, _x, _y) @count++ e #addBaseElements adds the common base elements to the ElementBox addBaseElements: -> class StaticElementBox extends ElementBox addBaseElements: -> @addElement((box, x, y) -> new BaseElements.Computer(box, x, y, 5)) @addElement((box, x, y) -> new BaseElements.Router(box, x, y, 5)) @addElement((box, x, y) -> new BaseElements.Switch(box, x, y, 5)) @addElement((box, x, y) -> lnk = new BaseElements.Link(box, new THREE.Vector3(-12.5, 12.5, 5), new THREE.Vector3(12.5, -12.5, 5), x, y, 5, true ) lnk.ln.material.color = new THREE.Color(0xcacaca) lnk ) @addElement((box, x, y) -> new BaseElements.Sax(box, x, y, 5)) class ModelBox extends ElementBox newModel: ()-> m = @addElement((box, x, y) -> new BaseElements.Model(box, x, y, 5)) m.props.name = @ve.namemanager.getName("model") m.id.name = m.props.name @ve.render() @ve.addie.update([m]) addBaseElements: -> #The Surface holds visual representations of Systems and Elements #aka the majority of the screen class Surface #Constructs a Surface object given a @ve visual environment constructor: (@ve) -> @width = 5000 @height = 5000 @baseRect = new Shapes.Rectangle(0x262626, 0, 0, 0, @width, @height) @baseRect.obj3d.userData = this @ve.scene.add(@baseRect.obj3d) @selectGroup = new THREE.Group() @ve.scene.add(@selectGroup) @selectorGroup = new THREE.Group() @ve.scene.add(@selectorGroup) @elements = [] addElement: (ef, x, y) -> e = null if ef instanceof Phyo and ef.tex? e = new ef.constructor(@baseRect, x, y, 50, ef.tex) else e = new ef.constructor(@baseRect, x, y, 50) e.props.name = @ve.namemanager.getName(e.constructor.name.toLowerCase()) e.id.name = e.props.name e.props.design = dsg if e.props.sshcmd? BaseElements.setSshCmd(e) @elements.push(e) @ve.render() e removeElement: (e) => idx = @elements.indexOf(e) if idx > -1 @elements.splice(idx, 1) obj3d = null obj3d = e.shp.obj3d if e.shp? obj3d = e.ln.obj3d if e.ln? idx = @baseRect.obj3d.children.indexOf(obj3d) if idx > -1 @baseRect.obj3d.children.splice(idx, 1) if e.glowBubble? idx = @selectGroup.children.indexOf(e.glowBubble) if idx > -1 @selectGroup.children.splice(idx, 1) delete e.glowBubble @ve.render() getElement: (name, sys) -> e = null for x in @elements if x.props.name == name && x.props.sys == sys e = x break e addIfContains: (box, e, set) -> o3d = null if e.shp? o3d = e.shp.obj3d else if e.ln? o3d = e.ln.obj3d if o3d != null o3d.geometry.computeBoundingBox() bb = o3d.geometry.boundingBox bx = new THREE.Box2( o3d.localToWorld(bb.min), o3d.localToWorld(bb.max) ) set.push(e) if box.containsBox(bx) #for some reason computing the bounding box kills selection o3d.geometry.boundingBox = null true toBox2: (box) -> new THREE.Box2( new THREE.Vector2(box.min.x, box.min.y), new THREE.Vector2(box.max.x, box.max.y) ) getSelection: (box) -> xs = [] box2 = @toBox2(box) @addIfContains(box2, x, xs) for x in @elements xs getSelected: () -> xs = [] xs.push(x.userData) for x in @selectGroup.children xs updateLink: (ln) -> ln.geom.verticesNeedUpdate = true ln.geom.lineDistancesNeedUpdate = true ln.geom.elementsNeedUpdate = true ln.geom.normalsNeedUpdate = true ln.geom.computeFaceNormals() ln.geom.computeVertexNormals() ln.geom.computeBoundingSphere() ln.geom.computeBoundingBox() moveObject: (o, p) -> o.position.x = p.x o.position.y = p.y if o.linep? o.linep.x = p.x o.linep.y = p.y if o.userData.glowBubble? o.userData.glowBubble.position.x = p.x o.userData.glowBubble.position.y = p.y if o.lines? @updateLink(ln) for ln in o.lines true moveObjectRelative: (o, p) -> o.position.x += p.x o.position.y += p.y if o.linep? o.linep.x += p.x o.linep.y += p.y if o.lines? @updateLink(ln) for ln in o.lines true glowMaterial: () -> #cam = @ve.sview.camera new THREE.ShaderMaterial({ uniforms: { "c": { type: "f", value: 1.0 }, "p": { type: "f", value: 1.4 }, glowColor: { type: "c", value: new THREE.Color(0xFDBF3B) }, viewVector: { type: "v3", value: new THREE.Vector3(0, 0, 200) } }, vertexShader: document.getElementById("vertexShader").textContent, fragmentShader: document.getElementById("fragmentShader").textContent, side: THREE.FrontSide, blending: THREE.AdditiveBlending, transparent: true }) glowSphere: (radius, x, y, z) -> geom = new THREE.SphereGeometry(radius, 64, 64) mat = @glowMaterial() obj = new THREE.Mesh(geom, mat) obj.position.x = x obj.position.y = y obj.position.z = z obj glowCube: (width, height, depth, x, y, z) -> geom = new THREE.BoxGeometry(width, height, depth, 2, 2, 2) mat = @glowMaterial() obj = new THREE.Mesh(geom, mat) obj.position.x = x obj.position.y = y obj.position.z = z modifier = new THREE.SubdivisionModifier(2) modifier.modify(geom) obj glowDiamond: (w, h, d, x, y, z) -> obj = @glowCube(w, h, d, x, y, z) obj.rotateZ(Math.PI/4) obj clearPropsGUI: -> if @ve.datgui? @ve.datgui.destroy() @ve.datgui = null showPropsGUI: (s) -> @ve.datgui = new dat.GUI() addElem = (d, k, v) -> if !d[k]? d[k] = [v] else d[k].push(v) dict = new Array() addElem(dict, x.constructor.name, x) for x in s addGuiElems = (typ, xs) => f = @ve.datgui.addFolder(typ) x.showProps(f) for x in xs f.open() addGuiElems(k, v) for k,v of dict $(@ve.datgui.domElement).focusout () => @ve.addie.update([x]) for x in s true selectObj: (obj) -> doSelect = true if not obj.glowBubble? if obj.shp instanceof Shapes.Circle p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 gs = @glowSphere(s, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Rectangle p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 l = s*1.5 gs = @glowCube(l, l, l, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Icon p = obj.shp.obj3d.position obj.shp.obj3d.geometry.computeBoundingSphere() s = obj.shp.obj3d.geometry.boundingSphere.radius + 3 l = s*10.5 gs = @glowCube(l, l, l, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Diamond p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 l = s*1.5 gs = @glowDiamond(l, l, l, p.x, p.y, p.z) else if obj.ln instanceof Shapes.Line d = 10 h = 10 v0 = obj.ln.geom.vertices[0] v1 = obj.ln.geom.vertices[obj.ln.geom.vertices.length - 1] w = obj.ln.geom.boundingSphere.radius * 2 x = (v0.x + v1.x) / 2 y = (v0.y + v1.y) / 2 z = 5 gs = @glowCube(w, h, d, x, y, z) theta = Math.atan2(v0.y - v1.y, v0.x - v1.x) gs.rotateZ(theta) else console.log "unkown object to select" console.log obj doSelect = false if doSelect gs.userData = obj obj.glowBubble = gs @selectGroup.add(gs) @ve.render() true clearSelection: (clearProps = true) -> for x in @selectGroup.children if x.userData.glowBubble? delete x.userData.glowBubble @selectGroup.children = [] @clearPropsGUI() if clearProps @ve.render() clearSelector: -> @selectorGroup.children = [] @ve.render() deleteSelection: () => console.log("deleting selection") deletes = [] for x in @selectGroup.children deletes.push(x.userData) if x.userData.links? deletes.push.apply(deletes, x.userData.links) @ve.addie.delete(deletes) for d in deletes @removeElement(d) @ve.propsEditor.hide(false) @ve.equationEditor.hide() true class NameManager constructor: (@ve) -> @names = new Array() getName: (s, sys='root') -> n = "" if !@names[s]? @names[s] = 0 n = s + @names[s] else @names[s]++ n = s + @names[s] while @ve.surface.getElement(n, sys) != null @names[s]++ n = s + @names[s] n class SimSettings constructor: () -> @props = { begin: 0, end: 0, maxStep: 1e-3 } #VisualEnvironment holds the state associated with the Threejs objects used #to render Surfaces and the ElementBox. This class also contains methods #for controlling and interacting with this group of Threejs objects. class VisualEnvironment #Constructs a visual environment for the given @container. @container must #be a reference to a <div> dom element. The Threejs canvas the visual #environment renders onto will be appended as a child of the supplied #container constructor: (@sc0, @sc1, @sc2, @sc3, @scontainer) -> @scene = new THREE.Scene() @sscene = new THREE.Scene() @pscene = new THREE.Scene() @surface = new Surface(this) @cwidth = @scontainer.offsetWidth #200 @cheight = @scontainer.offsetHeight @iconCache = {} @scamera = new THREE.OrthographicCamera( @cwidth / -2, @cwidth / 2, @cheight / 2, @cheight / -2, 1, 1000) @keyh = new KeyHandler(this) @sview = new SurfaceView(this, @sc0) @srenderer = new THREE.WebGLRenderer({antialias: true, alpha: true}) @srenderer.setSize(@cwidth, @cheight) @clear = 0x262626 @alpha = 1 @srenderer.setClearColor(@clear, @alpha) @scontainer.appendChild(@srenderer.domElement) @scamera.position.z = 200 @scamera.zoom = 1 @namemanager = new NameManager(this) @addie = new Addie(this) @propsEditor = new PropsEditor(this) @equationEditor = new EquationEditor(this) @simSettings = new SimSettings() @splitView = new SplitView(this) loadIcon: (name, f = null) => if not @iconCache[name]? THREE.ImageUtils.loadTexture( "ico/"+g.user+"/"+name+".png", {}, (tex) => @iconCache[name] = tex if f? f(tex) true ) else f(@iconCache[name]) hsplit: () => console.log("hsplit") vsplit: () => console.log("vsplit") render: -> @sview.doRender() @srenderer.clear() @srenderer.clearDepth() @srenderer.render(@sscene, @scamera) showSimSettings: () -> @propsEditor.hide() @propsEditor.elements = [@simSettings] @propsEditor.show() showDiagnostics: () => console.log("Showing Diagnostics") h = window.innerHeight dh = parseInt($("#diagnosticsPanel").css("height").replace('px', '')) if dh > 0 $("#diagnosticsPanel").css("top", h+"px") $("#hsplitter").css("top", "auto") else $("#diagnosticsPanel").css("top", (h-200)+"px") $("#hsplitter").css("top", (h-205)+"px") $("#diagnosticsPanel").css("height", "auto") class SplitView constructor: (@ve) -> @c0 = window.innerWidth @c1 = @c0 splitRatio: () -> @c0 / window.innerWidth hdown: (event) => $("#metasurface").mouseup(@hup) $("#diagnosticsPanel").mouseup(@hup) $("#metasurface").mousemove(@hmove) $("#diagnosticsPanel").mousemove(@hmove) $("#diagnosticsPanel").css("height", "auto") hup: (event) => console.log("hup") $("#metasurface").off('mousemove') $("#metasurface").off('mouseup') $("#diagnosticsPanel").off('mousemove') $("#diagnosticsPanel").off('mouseup') hmove: (event) => $("#diagnosticsPanel").css("top", (event.clientY+5)+"px") $("#hsplitter").css("top", event.clientY+"px") vdown: (event) => $("#metasurface").mouseup(@vup) $("#metasurface").mousemove(@vmove) vup: (event) => console.log("vup") $("#metasurface").off('mousemove') $("#metasurface").off('mouseup') @ve.render() vmove: (event) => @c1 = event.clientX dc = @c1 - @c0 x = @c1+"px" r = ($("#metasurface").width() - @c1)+"px" $("#vsplitter").css("left", x) left = 0 center = event.clientX right = window.innerWidth @ve.sview.panes[0].viewport.width = center - left @ve.sview.panes[1].viewport.width = right - center @ve.sview.panes[1].viewport.left = center @ve.sview.panes[0].camera.right += dc @ve.sview.panes[1].camera.right -= dc @ve.sview.doRender() @c0 = @c1 class SurfaceView constructor: (@ve, @container) -> @scene = @ve.scene @surface = @ve.surface @cwidth = @container.offsetWidth @cheight = @container.offsetHeight @l = Math.max(window.innerWidth, window.innerHeight) @l = Math.max(@cwidth, @cheight) @clear = 0x262626 @alpha = 1 @renderer = new THREE.WebGLRenderer({antialias: true, alpha: true}) @renderer.setSize(@cwidth, @cheight) @renderer.setClearColor(@clear, @alpha) @mouseh = new MouseHandler(this) @raycaster = new THREE.Raycaster() @raycaster.linePrecision = 10 @container.appendChild(@renderer.domElement) @panes = [ { id: 1, zoomFactor: 1, background: 0x262626, viewport: { left: 0, bottom: 0, width: @cwidth, height: @cheight }, camera: new THREE.OrthographicCamera( 0, @cwidth, @cheight, 0, 1, 1000) } { id: 2, zoomFactor: 1, background: 0x464646, viewport: { left: @cwidth, bottom: 0, width: 0, height: @cheight }, camera: new THREE.OrthographicCamera( 0, 0, @cheight, 0, 1, 1000) } ] for p in @panes p.camera.position.z = 200 mouseHits: (eve) -> @mouseh.updateMouse(eve) @raycaster.setFromCamera(@mouseh.pos, @mouseh.icam) ixs = @raycaster.intersectObjects(@ve.surface.baseRect.obj3d.children) ixs baseRectIx: (eve) -> @mouseh.updateMouse(eve) @raycaster.setFromCamera(@mouseh.pos, @mouseh.icam) bix = @raycaster.intersectObject(@ve.surface.baseRect.obj3d) bix doRender: () -> for p in @panes vp = p.viewport @renderer.setViewport(vp.left, vp.bottom, vp.width, vp.height) @renderer.setScissor(vp.left, vp.bottom, vp.width, vp.height) @renderer.enableScissorTest(true) @renderer.setClearColor(p.background) p.camera.updateProjectionMatrix() @renderer.clear() @renderer.clearDepth() @renderer.render(@scene, p.camera) render: () -> @ve.render() getPane: (c) => result = {} for p in @panes if c.x > p.viewport.left and c.x < p.viewport.left + p.viewport.width and c.y > p.viewport.bottom and c.y < p.viewport.bottom + p.viewport.height result = p break p zoomin: (x = 3, p = new THREE.Vector2(0,0)) -> w = Math.abs(@mouseh.icam.right - @mouseh.icam.left) h = Math.abs(@mouseh.icam.top - @mouseh.icam.bottom) @mouseh.apane.zoomFactor -= x/(@mouseh.apane.viewport.width) @mouseh.icam.left += x * (p.x/w) @mouseh.icam.right -= x * (1 - p.x/w) @mouseh.icam.top -= x * (p.y/h) @mouseh.icam.bottom += x * (1 - p.y/h) @mouseh.icam.updateProjectionMatrix() @render() pan: (dx, dy) => @mouseh.icam.left += dx @mouseh.icam.right += dx @mouseh.icam.top += dy @mouseh.icam.bottom += dy @mouseh.icam.updateProjectionMatrix() @render() #This is the client side Addie, it talks to the Addie at cypress.deterlab.net #to manage a design class Addie constructor: (@ve) -> @mstate = { up: false } init: () => @load() @msync() update: (xs) => console.log("updating objects") console.log(xs) #build the update sets link_updates = {} node_updates = {} model_updates = {} settings_updates = [] for x in xs if x.links? #x is a node if it has links node_updates[JSON.stringify(x.id)] = x for l in x.links link_updates[JSON.stringify(l.id)] = l if x instanceof BaseElements.Link link_updates[JSON.stringify(x.id)] = x node_updates[JSON.stringify(x.endpoint[0].id)] = x.endpoint[0] node_updates[JSON.stringify(x.endpoint[1].id)] = x.endpoint[1] if x instanceof BaseElements.Model model_updates[x.id.name] = x for i in x.instances node_updates[JSON.stringify(i.id)] = i if x instanceof SimSettings settings_updates.push(x) true #build the update messages model_msg = { Elements: [] } node_msg = { Elements: [] } link_msg = { Elements: [] } settings_msg = { Elements: [] } for _, m of model_updates model_msg.Elements.push( { OID: { name: m.id.name, sys: "", design: dsg }, Type: "Model", Element: m.props } ) true for _, n of node_updates node_msg.Elements.push( { OID: n.id, Type: n.constructor.name, Element: n.props } ) true for _, l of link_updates type = "Link" type = "Plink" if l.isPhysical() link_msg.Elements.push( { OID: l.id, Type: type, Element: l.props } ) true for s in settings_updates settings_msg.Elements.push( { OID: { name: "", sys: "", design: dsg }, Type: "SimSettings", Element: s.props } ) true doLinkUpdate = () => console.log("link update") console.log(link_msg) if link_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(link_msg), (data) => for _, l of link_updates BaseElements.updateId(l) doNodeUpdate = () => console.log("node update") console.log(node_msg) if node_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(node_msg), (data) => for _, n of node_updates BaseElements.updateId(n) for _, l of link_updates l.setEndpointData() doLinkUpdate() doModelUpdate = () => console.log("model update") console.log(model_msg) if model_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(model_msg), (data) => for _, m of model_updates BaseElements.updateId(m) for _, n of node_updates n.sync() if n.sync? doNodeUpdate() doSettingsUpdate = () => console.log("settings update") console.log(settings_msg) if settings_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(settings_msg), (data) => console.log("settings update complete") #do the updates since this is a linked structure we have to be a bit careful #about update ordering, here we do models, then nodes then links. This is #because some nodes reference models, and all links reference nodes. At #each stage of the update we update the internals of the data structures at #synchronization points within the updates to ensure consistency if model_msg.Elements.length > 0 doModelUpdate() else if node_msg.Elements.length > 0 doNodeUpdate() else if link_msg.Elements.length > 0 doLinkUpdate() #settings update is independent of other updates so we can break out of the #above update structure doSettingsUpdate() delete: (xs) => console.log("addie deleting objects") console.log(xs) ds = [] for x in xs if x instanceof Phyo ds.push({type: "Phyo", element: x.props}) if x instanceof Computer ds.push({type: "Computer", element: x.props}) if x instanceof Router ds.push({type: "Router", element: x.props}) if x instanceof Switch ds.push({type: "Switch", element: x.props}) if x instanceof Sax ds.push({type: "Sax", element: x.props}) if x instanceof Link if x.isPhysical() ds.push({type: "Plink", element: x.props}) else ds.push({type: "Link", element: x.props}) delete_msg = { Elements: ds } $.post "/addie/"+dsg+"/design/delete", JSON.stringify(delete_msg), (data) => console.log("addie delete complete") console.log(data) load: () => ($.get "/addie/"+dsg+"/design/read", (data, status, jqXHR) => console.log("design read success") console.log(data) @doLoad(data) true ).fail (data) => console.log("design read fail " + data.status) loadedModels = {} loadElements: (elements) => links = [] plinks = [] for x in elements @ve.namemanager.getName(x.type.toLowerCase()) switch x.type when "Computer" @loadComputer(x.object) when "Router" @loadRouter(x.object) when "Switch" @loadSwitch(x.object) when "Phyo" @loadPhyo(x.object) when "Sax" @loadSax(x.object) when "Link" links.push(x.object) when "Plink" plinks.push(x.object) @ve.namemanager.getName("link") for x in links @loadLink(x) for x in plinks @loadPlink(x) for k, v of @ve.namemanager.names @ve.namemanager.names[k] = v + 10 @ve.render() true loadModels: (models) => for x in models m = @ve.mbox.addElement((box, x, y) -> new BaseElements.Model(box, x, y, 5)) m.props = x m.id.name = x.name loadedModels[m.props.name] = m if m.props.icon != '' do (m) => #capture m-ref before it gets clobbered by loop @ve.loadIcon(m.props.name, (tex) -> _tex = tex.clone() _tex.needsUpdate = true m.setIcon(_tex) for i in m.instances i.tex = tex.clone() i.tex.needsUpdate = true i.setIcon( i.shp.obj3d.position.x, i.shp.obj3d.position.y ) ) true loadSimSettings: (settings) => @ve.simSettings.props = settings doLoad: (m) => @loadModels(m.models) @loadElements(m.elements) @loadSimSettings(m.simSettings) true setProps: (x, p) => x.props = p x.id.name = p.name x.id.sys = p.sys x.id.design = p.design loadComputer: (x) => c = new BaseElements.Computer(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(c, x) BaseElements.setSshCmd(c) @ve.surface.elements.push(c) true loadPhyo: (x) => m = loadedModels[x.model] p = new BaseElements.Phyo(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(p, x) @ve.surface.elements.push(p) m.instances.push(p) p.model = m p.loadArgValues() true loadSax: (x) => s = new BaseElements.Sax(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(s, x) BaseElements.setSshCmd(s) @ve.surface.elements.push(s) true loadRouter: (x) => r = new BaseElements.Router(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(r, x) BaseElements.setSshCmd(r) @ve.surface.elements.push(r) true loadSwitch: (x) => s = new BaseElements.Switch(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(s, x) @ve.surface.elements.push(s) true loadLink: (x) => a = @ve.surface.getElement( x.endpoints[0].name, x.endpoints[0].sys ) if a == null console.log("bad endpoint detected") b = @ve.surface.getElement( x.endpoints[1].name, x.endpoints[1].sys ) if b == null console.log("bad endpoint detected") l = new BaseElements.Link(@ve.surface.baseRect, a.shp.obj3d.linep, b.shp.obj3d.linep, 0, 0, 5) a.links.push(l) a.shp.obj3d.lines.push(l.ln) b.links.push(l) b.shp.obj3d.lines.push(l.ln) l.endpoint[0] = a l.endpoint[1] = b l.ep_ifx[0] = x.endpoints[0].ifname l.ep_ifx[1] = x.endpoints[1].ifname @setProps(l, x) l.setEndpointData() @ve.surface.elements.push(l) l.setColor() true #grosspants loadPlink: (x) => a = @ve.surface.getElement( x.endpoints[0].name, x.endpoints[0].sys ) if a == null console.log("bad endpoint detected") b = @ve.surface.getElement( x.endpoints[1].name, x.endpoints[1].sys ) if b == null console.log("bad endpoint detected") l = new BaseElements.Link(@ve.surface.baseRect, a.shp.obj3d.linep, b.shp.obj3d.linep, 0, 0, 5) a.links.push(l) a.shp.obj3d.lines.push(l.ln) b.links.push(l) b.shp.obj3d.lines.push(l.ln) l.endpoint[0] = a l.endpoint[1] = b l.applyPhysicalProps() @setProps(l, x) l.unpackBindings() l.setEndpointData() @ve.surface.elements.push(l) true levelColor: (l) => switch l when "info" then "blue" when "warning" then "orange" when "error" then "red" when "success" then "green" else "gray" compile: () => console.log("asking addie to compile the design") $("#diagText").html("") $("#ajaxLoading").css("display", "block") $.get "/addie/"+dsg+"/design/compile", (data) => console.log("compilation result:") console.log(data) $("#ajaxLoading").css("display", "none") if data.elements? for d in data.elements $("#diagText").append( "<span style='color:"+@levelColor(d.level)+"'><b>"+ d.level+ "</b></span> - " + d.message + "<br />" ) run: () => console.log("asking addie to run the experiment") $.get "/addie/"+dsg+"/design/run", (data) => console.log("run result: ") console.log(data) materialize: () => if @mstate.up console.log("asking addie to dematerialize the experiment") $("#materialize").html("Materialize") $.get "/addie/"+dsg+"/design/dematerialize", (data) => console.log("dematerialize result: ") console.log(data) #TODO do an async call here and then grey out the materialization button #until the async call returns @mstate.up = false else console.log("asking addie to materialize the experiment") $("#materialize").html("Dematerialize") @mstate.up = true $.get "/addie/"+dsg+"/design/materialize", (data) => console.log("materialize result: ") console.log(data) #synchronize materialization status msync: () => console.log("synchronizing materialization state with addie") $.get "/addie/"+dsg+"/design/mstate", (data) => console.log("materialization state:") console.log(data) if data.Status? and data.Status == "Active" @mstate.up = true $("#materialize").html("Dematerialize") class EBoxSelectHandler constructor: (@mh) -> test: (ixs) -> ixs.length > 0 and ixs[ixs.length - 1].object.userData instanceof StaticElementBox handleDown: (ixs) -> @mh.sv.surface.clearSelection() if ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! ebox select -- " + e.constructor.name console.log e #TODO double click should lock linking until link icon clicked again # this way many things may be linked without going back to the icon if e instanceof Link console.log "! linking objects" @mh.sv.container.style.cursor = "crosshair" @mh.placingObject = null @mh.sv.container.onmousemove = (eve) => @mh.linkingH.handleMove0(eve) @mh.sv.container.onmousedown = (eve) => @mh.linkingH.handleDown0(eve) else console.log "! placing objects" @mh.makePlacingObject(e) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) @mh.sv.ve.scontainer.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) stillOnEBox: (event) => @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.spos, @mh.sv.ve.scamera) ixs = @mh.sv.raycaster.intersectObjects(@mh.sv.ve.sscene.children, true) result = false for x in ixs if x.object.userData instanceof StaticElementBox result = true break result handleUp: (event) -> if @stillOnEBox(event) @mh.sv.surface.removeElement(@mh.placingObject) false else @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position @mh.sv.ve.addie.update([@mh.placingObject]) @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) -> @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) if bix.length > 0 @mh.sv.surface.moveObject(@mh.placingObject.shp.obj3d, bix[0].point) @mh.sv.render() class MBoxSelectHandler constructor: (@mh) -> @model = null @instance = null test: (ixs) -> ixs.length > 0 and ixs[ixs.length - 1].object.userData instanceof ModelBox handleDown: (ixs) -> @mh.sv.surface.clearSelection() if ixs[0].object.userData.cyjs? e = ixs[0].object.userData @model = e console.log('mbox down') @mh.sv.container.onmousemove = (eve) => @handleMove0(eve) @mh.sv.ve.scontainer.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) stillOnMBox: (event) => @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.spos, @mh.sv.ve.scamera) ixs = @mh.sv.raycaster.intersectObjects(@mh.sv.ve.sscene.children, true) result = false for x in ixs if x.object.userData instanceof ModelBox result = true break result handleUp: (event) -> console.log('mbox up') if @instance? if @stillOnMBox(event) @mh.sv.surface.removeElement(@mh.placingObject) idx = @model.instances.indexOf(@instance) if idx > -1 @model.instances.splice(idx, 1) @instance = null @mh.placingObject = null false else @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position @mh.placingObject.sync() @mh.sv.ve.addie.update([@mh.placingObject]) @mh.sv.surface.clearSelection() else if !@instance? @mh.sv.ve.propsEditor.elements = [@model] @mh.sv.ve.propsEditor.show() @mh.sv.ve.equationEditor.show(@model) @mh.sv.container.onmousemove = null @mh.sv.container.onmouseup = null @mh.sv.ve.scontainer.onmouseup = (eve) => null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @instance = null handleMove0: (event) -> @instance = @mh.makePlacingObject(@model.instantiate(null, 0, 0, 0, 25, 25)) @instance.model = @model @instance.addArgs() @model.instances.push(@instance) @mh.sv.container.onmousemove = (eve) => @handleMove1(eve) handleMove1: (event) -> @mh.updateMouse(event) @mh.sv.ve.propsEditor.hide() @mh.sv.ve.equationEditor.hide() @mh.sv.surface.clearSelection() @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) if bix.length > 0 #ox = @mh.placingObject.shp.geom.boundingSphere.radius @mh.sv.surface.moveObject(@mh.placingObject.shp.obj3d, bix[0].point) @mh.sv.render() class SurfaceElementSelectHandler constructor: (@mh) -> @start = new THREE.Vector3(0,0,0) @end= new THREE.Vector3(0,0,0) @p0 = new THREE.Vector3(0,0,0) @p1 = new THREE.Vector3(0,0,0) test: (ixs) -> ixs.length > 1 and ixs[ixs.length - 1].object.userData instanceof Surface and ixs[0].object.userData.cyjs? handleDown: (ixs) -> @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) @p0.copy(bix[0].point) @p1.copy(@p0) @mh.updateMouse(event) @start.copy(@mh.pos) e = ixs[0].object.userData console.log "! surface select -- " + e.constructor.name console.log "current selection" console.log @mh.sv.surface.selectGroup console.log("multiselect: " + @mh.sv.ve.keyh.multiselect) if not ixs[0].object.userData.glowBubble? && not @mh.sv.ve.keyh.multiselect @mh.sv.surface.clearSelection() @mh.sv.surface.selectObj(e) if @mh.sv.surface.selectGroup.children.length == 1 @mh.sv.ve.propsEditor.elements = [e] @mh.sv.ve.propsEditor.show() else @mh.sv.ve.propsEditor.elements = @mh.sv.surface.getSelected() @mh.sv.ve.propsEditor.show() if e instanceof BaseElements.Phyo @mh.sv.ve.equationEditor.show(e.model) @mh.placingObject = e @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) applyGroupMove: () -> for x in @mh.sv.surface.selectGroup.children p = new THREE.Vector3(@p1.x - @p0.x , @p1.y - @p0.y, @p0.z) if x.userData.shp? @mh.sv.surface.moveObjectRelative(x.userData.shp.obj3d, p) @mh.sv.surface.moveObjectRelative(x, p) updateGroupMove: () -> updates = [] for x in @mh.sv.surface.selectGroup.children x.userData.props.position = x.position updates.push(x.userData) @mh.sv.ve.addie.update(updates) handleUp: (ixs) -> @mh.updateMouse(event) @end.copy(@mh.pos) if @mh.placingObject.shp? @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position if @start.distanceTo(@end) > 0 @updateGroupMove() #@applyGroupMove() @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) -> @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) @p1.copy(bix[0].point) if bix.length > 0 @applyGroupMove() @mh.sv.render() @p0.copy(@p1) #TODO, me thinks that react.js orangular.js is meant to deal with precisely #the problem we are tyring to solve with the props editor, in the future we #should look into replacing dat.gui (as nifty as it is) with an angular #based control that is a bit more intelligent class PropsEditor constructor: (@ve) -> @elements = [] @cprops = {} show: () -> for e in @elements e.sync() if e.sync? @commonProps() @datgui = new dat.GUI() for k, v of @cprops @datgui.add(@cprops, k) if @elements.length == 1 and @elements[0].funcs? for k, v of @elements[0].funcs @datgui.add(@elements[0].funcs, k) true save: () -> for k, v of @cprops for e in @elements e.props[k] = v if v != "..." e.sync() if e.sync? @ve.addie.update(@elements) hide: (doSave = true) -> if @datgui? @save() if doSave @datgui.destroy() @elements = [] @cprops = {} @datgui = null commonProps: () -> ps = {} cps = new Array() addProp = (d, k, v) -> if !d[k]? d[k] = [v] else d[k].push(v) addProps = (e) => for k, v of e.props continue if k == 'position' continue if k == 'design' continue if k == 'endpoints' continue if k == 'interfaces' continue if k == 'path' continue if k == 'args' continue if k == 'equations' continue if k == 'bindings' continue if k == 'icon' continue if k == 'name' and @elements.length > 1 addProp(ps, k, v) addProps(e) for e in @elements addCommon = (k, v, es) -> if v.length == es.length then cps[k] = v true addCommon(k, v, @elements) for k, v of ps isUniform = (xs) -> u = true i = xs[0] for x in xs u = (x == i) break if !u u setUniform = (k, v, e) -> if isUniform(v) e[k] = v[0] else e[k] = "..." true reduceUniform = (xps) -> setUniform(k, v, xps) for k, v of xps true reduceUniform(cps) @cprops = cps cps class EquationEditor constructor: (@ve) -> @model = null show: (m) -> @model = m console.log("showing equation editor") $("#eqtnSrc").val(@model.props.equations) if @ve.propsEditor.datgui? $("#eqtnEditor").css("display", "inline") $("#eqtnEditor").css("top", @ve.propsEditor.datgui.domElement.clientHeight + 30) hide: () -> console.log("hiding equation editor") if @model? @model.props.equations= $("#eqtnSrc").val() $("#eqtnEditor").css("display", "none") class PanHandler constructor: (@mh) -> @p0 = new THREE.Vector2(0,0) @p1 = new THREE.Vector2(0,0) handleDown: (event) => @mh.updateMouse(event) @p0.x = event.clientX @p0.y = event.clientY @p1.x = event.clientX @p1.y = event.clientY @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) handleUp: (event) => @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) => @p1.x = event.clientX @p1.y = event.clientY dx = -(@p1.x - @p0.x) dx *= @mh.apane.zoomFactor dy = @p1.y - @p0.y dy *= @mh.apane.zoomFactor @mh.sv.pan(dx, dy) @p0.x = @p1.x @p0.y = @p1.y class SurfaceSpaceSelectHandler constructor: (@mh) -> @selCube = new SelectionCube() test: (ixs) -> ixs.length > 0 and ixs[0].object.userData instanceof Surface handleDown: (ixs) -> @mh.sv.surface.clearSelection() console.log "! space select down" p = new THREE.Vector3( ixs[ixs.length - 1].point.x, ixs[ixs.length - 1].point.y, 75 ) @selCube.init(p) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.surface.selectorGroup.add(@selCube.obj3d) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) @mh.sv.surface.clearSelection() handleUp: (event) -> console.log "! space select up" sel = @mh.sv.surface.getSelection(@selCube.obj3d.geometry.boundingBox) @mh.sv.surface.selectObj(o) for o in sel @mh.sv.ve.propsEditor.elements = sel console.log('common props') @mh.sv.ve.propsEditor.show() @selCube.reset() @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null @mh.sv.render() handleMove: (event) -> bix = @mh.baseRectIx(event) if bix.length > 0 p = new THREE.Vector3( bix[bix.length - 1].point.x, bix[bix.length - 1].point.y, 75 ) @selCube.update(p) @mh.sv.render() class LinkingHandler constructor: (@mh) -> handleDown0: (event) -> ixs = @mh.sv.mouseHits(event) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! link0 " + e.constructor.name pos0 = ixs[0].object.linep pos1 = new THREE.Vector3( ixs[0].object.position.x, ixs[0].object.position.y, 5 ) @mh.placingLink = new BaseElements.Link(@mh.sv.surface.baseRect, pos0, pos1, 0, 0, 5 ) @mh.sv.surface.elements.push(@mh.placingLink) BaseElements.initName(@mh.placingLink, "link") @mh.placingLink.linkEndpoint(0, ixs[0].object.userData) @mh.sv.container.onmousemove = (eve) => @handleMove1(eve) @mh.sv.container.onmousedown = (eve) => @handleDown1(eve) else console.log "! link0 miss" handleDown1: (event) -> ixs = @mh.sv.mouseHits(event) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! link1 " + e.constructor.name @mh.placingLink.ln.geom.vertices[1] = ixs[0].object.linep @mh.placingLink.linkEndpoint(1, ixs[0].object.userData) @mh.sv.surface.updateLink(@mh.placingLink.ln) @mh.placingLink.typeResolve() @mh.sv.render() @mh.sv.ve.addie.update([@mh.placingLink]) @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.style.cursor = "default" else console.log "! link1 miss" handleMove0: (event) -> @mh.updateMouse(event) handleMove1: (event) -> bix = @mh.sv.baseRectIx(event) if bix.length > 0 @mh.sv.scene.updateMatrixWorld() @mh.placingLink.ln.geom.vertices[1].x = bix[bix.length - 1].point.x @mh.placingLink.ln.geom.vertices[1].y = bix[bix.length - 1].point.y @mh.placingLink.ln.geom.verticesNeedUpdate = true @mh.sv.render() #Mouse handler encapsulates the logic of dealing with mouse events class MouseHandler constructor: (@sv) -> @pos = new THREE.Vector3(0, 0, 1) @spos = new THREE.Vector3(0, 0, 1) @eboxSH = new EBoxSelectHandler(this) @mboxSH = new MBoxSelectHandler(this) @surfaceESH = new SurfaceElementSelectHandler(this) @surfaceSSH = new SurfaceSpaceSelectHandler(this) @linkingH = new LinkingHandler(this) @panHandler = new PanHandler(this) @icam = null ondown: (event) -> @baseDown(event) onwheel: (event) => @apane = @sv.getPane(new THREE.Vector2(event.layerX, event.layerY)) @icam = @apane.camera @sv.zoomin(-event.deltaY / 5, new THREE.Vector2(event.layerX, event.layerY)) updateMouse: (event) -> @apane = @sv.getPane(new THREE.Vector2(event.layerX, event.layerY)) @icam = @apane.camera if @apane.id == 1 sr = @sv.ve.splitView.splitRatio() else sr = 1 - @sv.ve.splitView.splitRatio() @pos.x = ((event.layerX - @apane.viewport.left) / (@sv.cwidth * sr) ) * 2 - 1 @pos.y = -((event.layerY - @apane.viewport.bottom) / @sv.cheight ) * 2 + 1 @spos.x = (event.layerX / @sv.ve.scontainer.offsetWidth ) * 2 - 1 @spos.y = -(event.layerY / @sv.ve.scontainer.offsetHeight) * 2 + 1 baseRectIx: (event) -> @updateMouse(event) @sv.raycaster.setFromCamera(@pos, @icam) @sv.raycaster.intersectObject(@sv.ve.surface.baseRect.obj3d) placingObject: null placingLink: null makePlacingObject: (obj) -> @sv.raycaster.setFromCamera(@pos, @icam) bix = @sv.raycaster.intersectObject(@sv.ve.surface.baseRect.obj3d) x = y = 0 if bix.length > 0 ix = bix[bix.length - 1] x = ix.point.x y = ix.point.y @placingObject = @sv.surface.addElement(obj, x, y) #onmousedown handlers baseDown: (event) -> #the order actually matters here, need to hide the equation editor first #so the equations get saved to the underlying object before the props #editor sends them to addie @sv.ve.equationEditor.hide() @sv.ve.propsEditor.hide() #get the list of objects the mouse click intersected @updateMouse(event) console.log(@pos) #delegate the handling of the event to one of the handlers #check the model boxes first if event.which == 1 @sv.raycaster.setFromCamera(@spos, @sv.ve.scamera) sixs = @sv.raycaster.intersectObjects(@sv.ve.sscene.children, true) if @eboxSH.test(sixs) then @eboxSH.handleDown(sixs) else if @mboxSH.test(sixs) then @mboxSH.handleDown(sixs) else @sv.raycaster.setFromCamera(@pos, @icam) ixs = @sv.raycaster.intersectObjects(@sv.scene.children, true) if @surfaceESH.test(ixs) then @surfaceESH.handleDown(ixs) else if @surfaceSSH.test(ixs) then @surfaceSSH.handleDown(ixs) else if event.which = 3 @panHandler.handleDown(event) true doMultiplink = (sel) => class MultiLinker constructor: (@ve, @sel) -> console.log("multiplink") console.log(@sel) @ve.sview.container.style.cursor = "crosshair" @ve.sview.container.onmousedown = (eve) => @handleDown(eve) @tgtP = new THREE.Vector3(0,0,0) @links = [] for s in @sel l = new BaseElements.Link(@ve.surface.baseRect, s.shp.obj3d.linep, @tgtP, 0, 0, 5) BaseElements.initName(l, "link") l.linkEndpoint(0, s) @links.push(l) true handleDown: (eve) => ixs = @ve.sview.mouseHits(eve) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! multilink1 " + e.constructor.name @tgtP = ixs[0].object.linep for l in @links l.linkEndpoint(1, ixs[0].object.userData) l.typeResolve() @ve.surface.updateLink(l.ln) @ve.sview.render() @ve.addie.update([l]) @ve.sview.container.style.cursor = "default" @ve.sview.container.onmousedown = (eve) => @ve.sview.mouseh.baseDown(eve) true else console.log "! multilink miss" true class KeyHandler constructor: (@ve) -> @multiselect = false ondown: (event) => keycode = window.event.keyCode || event.which if(keycode == 8 || keycode == 46) @ve.surface.deleteSelection() event.preventDefault() else if(keycode == 16) console.log("multiselect start") @multiselect = true true else if(keycode == 67) xs = @ve.surface.getSelected() if xs.length == 0 @ve.sview.container.style.cursor = "crosshair" @ve.sview.container.onmousemove = (eve) => @ve.sview.mouseh.linkingH.handleMove0(eve) @ve.sview.container.onmousedown = (eve) => @ve.sview.mouseh.linkingH.handleDown0(eve) else ml = new MultiLinker(@ve, xs) true onup: (event) => keycode = window.event.keyCode || event.which if(keycode == 16) console.log("multiselect end") @multiselect = false true
true
root = exports ? this getParameterByName = (name) => name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]") regex = new RegExp("[\\?&]" + name + "=([^&#]*)") results = regex.exec(location.search) decodeURIComponent(results[1].replace(/\+/g, " ")) initViz = () => g.ve = new VisualEnvironment( document.getElementById("surface0"), document.getElementById("surface1"), document.getElementById("surface2"), document.getElementById("surface3"), document.getElementById("controlPanel") ) g.ve.ebox = new StaticElementBox(g.ve, 120, g.ve.cheight/2 - 65) mh = g.ve.cheight - 167 g.ve.mbox = new ModelBox(g.ve, mh, (g.ve.cheight - 140)/2 - mh/2.0 - 60) g.ve.datgui = null g.ve.render(g.ve) dsg = "" launchAddieInstance = () => ($.get "/gatekeeper/launchAddie?user="+g.user+"&design="+dsg, (data) => console.log("addie instance launched and ready!") g.ve.addie.init() ).fail () -> console.log("failed to launch addie instance") true #Entry point root.go = -> ($.get "/gatekeeper/thisUser", (data) => g.user = data console.log("the user is " + g.user) g.xp = getParameterByName("xp") dsg = g.xp console.log("the xp is " + g.xp) initViz() launchAddieInstance() true ).fail () -> console.log("fail to get current user, going back to login screen") window.location.href = location.origin true #Global event handlers root.vz_mousedown = (event, idx) -> g.ve.sview.mouseh.ondown(event) root.hsplit_mdown = (event) => g.ve.splitView.hdown(event) root.vsplit_mdown = (event) => g.ve.splitView.vdown(event) root.vz_keydown = (event) => g.ve.keyh.ondown(event) root.vz_keyup = (event) => g.ve.keyh.onup(event) root.vz_wheel = (event, idx) => g.ve.sview.mouseh.onwheel(event) root.run = (event) => g.ve.addie.run() root.materialize = (event) => g.ve.addie.materialize() root.newModel = (event) -> g.ve.mbox.newModel() root.compile = () => g.ve.addie.compile() root.showSimSettings = () => g.ve.showSimSettings() root.showDiagnostics = () => g.ve.showDiagnostics() #Global state holder g = {} #Shapes contains a collection of classes that comprise the basic shapes used to #represent Cypress CPS elements Shapes = { Rectangle : class Rectangle constructor: (color, x, y, z, width, height) -> @geom = new THREE.PlaneBufferGeometry(width, height) @material = new THREE.MeshBasicMaterial({color: color}) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Circle : class Circle constructor: (color, x, y, z, radius) -> @geom = new THREE.CircleGeometry(radius, 64) @material = new THREE.MeshBasicMaterial({color: color}) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Diamond: class Diamond constructor: (color, x, y, z, l) -> @shape = new THREE.Shape() @shape.moveTo(0,l) @shape.lineTo(l,0) @shape.lineTo(0,-l) @shape.lineTo(-l,0) @shape.lineTo(0,l) @material = new THREE.MeshBasicMaterial({color: color}) @geom = new THREE.ShapeGeometry(@shape) @obj3d = new THREE.Mesh(@geom, @material) @obj3d.position.x = x @obj3d.position.y = y @obj3d.position.z = z @obj3d.linep = new THREE.Vector3(x, y, 5) @obj3d.lines = [] select: -> Line: class Line constructor: (color, from, to, z) -> @material = new THREE.LineBasicMaterial( { color: color, linewidth: 3 } ) @geom = new THREE.Geometry() @geom.dynamic = true @geom.vertices.push(from, to) @obj3d = new THREE.Line(@geom, @material) @obj3d.position.x = 0 @obj3d.position.y = 0 @obj3d.position.z = z @obj3d.lines = [] select: -> Icon: class Icon constructor: (@texture, x, y, z) -> @material = new THREE.SpriteMaterial({ map: @texture, depthTest: false, depthWrite: false }) @obj3d= new THREE.Sprite(@material) @obj3d.position.set(x,y,z) @obj3d.scale.set(30, 30, 1.0) @obj3d.lines = [] @obj3d.linep = new THREE.Vector3(x, y, 5) select: -> SelectionCube: class SelectionCube constructor: () -> @geom = new THREE.Geometry() @geom.dynamic = true @aa = new THREE.Vector3(0, 0, 75) @ab = new THREE.Vector3(0, 0, 75) @ba = new THREE.Vector3(0, 0, 75) @bb = new THREE.Vector3(0, 0, 75) @geom.vertices.push( @aa, @ab, @ba, @bb, @ba, @ab ) @geom.faces.push( new THREE.Face3(0, 1, 2), new THREE.Face3(2, 1, 0), new THREE.Face3(3, 4, 5), new THREE.Face3(5, 4, 3) ) @geom.computeBoundingSphere() @material = new THREE.MeshBasicMaterial( { color: 0xFDBF3B, opacity: 0.2, transparent: true } ) @obj3d = new THREE.Mesh(@geom, @material) updateGFX: () -> @geom.verticesNeedUpdate = true @geom.lineDistancesNeedUpdate = true @geom.elementsNeedUpdate = true @geom.normalsNeedUpdate = true @geom.computeFaceNormals() @geom.computeVertexNormals() @geom.computeBoundingSphere() @geom.computeBoundingBox() init: (p) -> @aa.x = @ab.x = @ba.x = p.x @aa.y = @ba.y = @ab.y = p.y @bb.x = @aa.x @bb.y = @aa.y @updateGFX() update: (p) -> @bb.x = @ba.x = p.x @bb.y = @ab.y = p.y @updateGFX() reset: () -> @aa.x = @bb.x = @ba.x = @ab.x = 0 @aa.y = @bb.y = @ba.y = @ab.y = 0 @updateGFX() } #The BaseElements object holds classes which are Visual representations of the #objects that comprise a Cypress networked CPS system BaseElements = { updateId: (e) -> e.onIdUpdate() if e.onIdUpdate? e.id.name = e.props.name if e.id.sys? e.id.sys = e.props.sys currentId: (d) -> {name: d.props.name, sys: d.props.sys, design: dsg } setSshCmd: (x) => x.props.sshcmd = 'ssh -A -t '+g.user+'@users.PI:EMAIL:<EMAIL>END_PI.deterlab.net '+ 'ssh -A '+x.props.name+'.'+g.user+'-'+dsg+'.cypress' initName: (x, n) => x.props.name = g.ve.namemanager.getName(n) x.id.name = x.props.name addInterface: (x) => ifname = "" if x.props.interfaces? ifname = "ifx"+Object.keys(x.props.interfaces).length x.props.interfaces[ifname] = { name: ifname, latency: 0, capacity: 1000 } ifname #The Computer class is a representation of a computer Computer: class Computer constructor: (@parent, x, y, z) -> @shp = new Shapes.Diamond(0x2390ff, x, y, z, 15) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "computer0", sys: "root", os: "Ubuntu1404-64-STD", start_script: "", interfaces: {}, sshcmd: "" } @id = { name: "computer0" sys: "root" design: dsg } @links = [] showProps: (f) -> c = f.add(@props, 'name') c = f.add(@props, 'sys') c = f.add(@props, 'start_script') c = f.add(@props, 'os') #cyjs generates the json for this object cyjs: -> #The Model class is a represenation of a mathematical model of a physical object Model: class Model constructor: (@parent, x, y, z) -> @shp = new Shapes.Rectangle(0x239f5a, x, y, z, 25, 25) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @sprite = false @props = { name: "model0", params: "", equations: "", icon: "" } @funcs = { "Set Icon": () => console.log("setting sprite for " + @props.name) $("#upModelName").val(@props.name) $("#upModelIcon").change () => f = $("#upModelIcon")[0].files[0] console.log("sprite selected") mdl = $("#upModelName").val() console.log("model is " + mdl) console.log(f) $("#upModelIcon").off("change") fd = new FormData($("#uploadModelIconForm")[0]) xhr = new XMLHttpRequest() xhr.open("POST", "/addie/"+dsg+"/design/modelIco") xhr.onreadystatechange = () => if xhr.readyState == 4 && xhr.status == 200 g.ve.loadIcon(mdl, (tex) => @setIcon(tex) ) xhr.send(fd) true $("#upModelIcon").click() } @id = { name: "model0" } @instances = [] setIcon: (tex) => @parent.obj3d.remove(@shp.obj3d) _shp = new Shapes.Icon(tex, @shp.obj3d.position.x, @shp.obj3d.position.y, @shp.obj3d.position.z) @shp = _shp @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) g.ve.render() @tex = tex instantiate: (parent, x, y, z) -> if @tex? obj = new Phyo(parent, x, y, z, @tex.clone()) obj.tex.needsUpdate = true else obj = new Phyo(parent, x, y, z) obj.props.model = @props.name obj #cyjs generates the json for this object cyjs: -> Phyo: class Phyo constructor: (@parent, x, y, z, @tex = null) -> if @tex == null @shp = new Shapes.Rectangle(0x239f5a, x, y, z, 25, 25) @shp.obj3d.userData = this else @setIcon() @model = null if @parent? @parent.obj3d.add(@shp.obj3d) @props = { name: "model0", sys: "root", model: "", args: "", init: "", } @id = { name: "model0", sys: "root", design: dsg } @links = [] @args = [] setIcon: (x=0, y=0, z=50) => savelx = false if @shp? lp = @shp.obj3d.linep ls = @shp.obj3d.lines savelx = true if @parent? and @shp? @parent.obj3d.remove(@shp.obj3d) @shp = new Shapes.Icon(@tex, x, y, z) if savelx @shp.obj3d.linep = lp @shp.obj3d.lines = ls @shp.obj3d.userData = this if @parent? @parent.obj3d.add(@shp.obj3d) g.ve.render() addArgs: () -> _args = @model.props.params .replace(" ", "") .split(",") .map((x) -> x.replace(" ", "")) .filter((x) -> x.length != 0) for p in _args if !@props[p]? @props[p] = "" for p in @args if p not in _args delete @props[p] @args = _args true loadArgValues: () -> _args = @props.args .split(",") .filter((x) -> x.length != 0) .map((x) -> x.split("=").filter((y) -> y.length != 0)) for x in _args @props[x[0]] = x[1] @args.push(x[0]) sync: -> if @model? @props.model = @model.props.name @addArgs() @props.args = "" for p in @args @props.args += (p+"="+@props[p]+",") onIdUpdate: -> for x in @links if @id.name != @props.name x.props[@props.name] = x.props[@id.name] delete(x.props[@id.name]) #cyjs generates the json for this object cyjs: -> #The Sax class is a representation of a sensing and acutation unit Sax: class Sax constructor: (@parent, x, y, z) -> @shp = new Shapes.Circle(0x239f9c, x, y, z, 7) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "sax0", sys: "root", design: dsg, sense: "", actuate: "" interfaces: {}, sshcmd: "" } @id = { name: "sax0", sys: "root", design: dsg } @links = [] onIdUpdate: -> for x in @links if x.isPhysical() and @id.name != @props.name x.props[@props.name] = x.props[@id.name] delete(x.props[@id.name]) #cyjs generates the json for this object cyjs: -> #Router is a visual representation of an IP-network router Router: class Router constructor: (@parent, x, y, z) -> @shp = new Shapes.Circle(0x23549F, x, y, z, 15) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "PI:NAME:<NAME>END_PI0", sys: "root", capacity: 100, latency: 0, interfaces: {}, sshcmd: "" } @id = { name: "router0" sys: "root" design: dsg } @links = [] showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> #Switch is a visual representation of an IP-network swtich Switch: class Switch constructor: (@parent, x, y, z) -> @shp = new Shapes.Rectangle(0x23549F, x, y, z, 25, 25) @shp.obj3d.userData = this @parent.obj3d.add(@shp.obj3d) @props = { name: "switchPI:NAME:<NAME>END_PI", sys: "root", capacity: 1000, latency: 0, interfaces: {} } @id = { name: "switch0" sys: "root" design: dsg } @links = [] showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> Link: class Link constructor: (@parent, from, to, x, y, z, isIcon = false) -> @endpoint = [null, null] @ep_ifx = ["",""] #TODO: s/ln/shp/g for consistency @ln = new Shapes.Line(0xcacaca, from, to, z) @ln.obj3d.userData = this @props = { name: "PI:NAME:<NAME>END_PI", sys: "root", design: dsg, capacity: 1000, latency: 0, endpoints: [ {name: "linkPI:NAME:<NAME>END_PI", sys: "root", design: dsg, ifname: ""}, {name: "link0", sys: "root", design: dsg, ifname: ""} ] } @id = { name: "PI:NAME:<NAME>END_PI" sys: "root" design: dsg } if isIcon @shp = new Shapes.Rectangle(@parent.material.color, x, y, z, 25, 25) @shp.obj3d.userData = this @shp.obj3d.add(@ln.obj3d) @parent.obj3d.add(@shp.obj3d) else @parent.obj3d.add(@ln.obj3d) isInternet: -> @endpoint[0] instanceof Router and @endpoint[1] instanceof Router isPhysical: -> @endpoint[0] instanceof Phyo and @endpoint[1] instanceof Phyo or @endpoint[0] instanceof Phyo and @endpoint[1] instanceof Sax or @endpoint[1] instanceof Phyo and @endpoint[0] instanceof Sax isIfxPhysical: (i) -> @endpoint[i] instanceof Phyo applyWanProps: -> @props.capacity = 100 @props.latency = 7 applyPhysicalProps: -> @props = { name: @props.name, sys: @props.sys, design: @props.design, endpoints: [ {name: "link0", sys: "root", design: dsg}, {name: "link0", sys: "root", design: dsg} ], bindings: ["",""] } @props[@endpoint[0].props.name] = "" if @endpoint[0] #instanceof Phyo @props[@endpoint[1].props.name] = "" if @endpoint[1] #instanceof Phyo @ln.material.color = new THREE.Color(0x125634) @ln.geom.colorsNeedUpdate = true setColor: () -> if @isPhysical() @ln.material.color = new THREE.Color(0x125634) @ln.geom.colorsNeedUpdate = true else @ln.material.color = new THREE.Color(0x123456) @ln.geom.colorsNeedUpdate = true linkEndpoint: (i, x) -> ifname = BaseElements.addInterface(x) x.links.push(this) x.shp.obj3d.lines.push(@ln) @ln.geom.vertices[i] = x.shp.obj3d.linep @endpoint[i] = x @ep_ifx[i] = ifname setEndpointData: -> @props.endpoints[0].name = @endpoint[0].props.name @props.endpoints[0].sys = @endpoint[0].props.sys if !@isIfxPhysical(1) #yes, this is based on the other side of the connection @props.endpoints[0].ifname = @ep_ifx[0] if @isPhysical() @props.bindings[0] = @props[@endpoint[0].props.name] @props.endpoints[1].name = @endpoint[1].props.name @props.endpoints[1].sys = @endpoint[1].props.sys if !@isIfxPhysical(0) @props.endpoints[1].ifname = @ep_ifx[1] if @isPhysical() @props.bindings[1] = @props[@endpoint[1].props.name] unpackBindings: -> @props[@endpoint[0].props.name] = @props.bindings[0] @props[@endpoint[1].props.name] = @props.bindings[1] ifInternetToWanLink: -> @applyWanProps() if @isInternet() removePhantomEndpoint: (i) -> if @endpoint[i] instanceof Sax delete @endpoint[i].props.interfaces[@ep_ifx[i]] ifPhysicalToPlink: -> if @isPhysical() @removePhantomEndpoint(0) @removePhantomEndpoint(1) @applyPhysicalProps() else @ln.material.color = new THREE.Color(0x123456) @ln.geom.colorsNeedUpdate = true typeResolve: -> @ifInternetToWanLink() @ifPhysicalToPlink() @setEndpointData() showProps: (f) -> f.add(@props, 'name') f.add(@props, 'sys') f.add(@props, 'capacity') if @isInternet() f.add(@props, 'latency') #cyjs generates the json for this object cyjs: -> } #The ElementBox holds Element classes which may be added to a system, #aka the thing on the left side of the screen class ElementBox #Constructs an ElementBox object given a @ve visual environment constructor: (@ve, @height, @y) -> @width = 75 @x = -@ve.cwidth/2 + @width / 2 + 5 @z = 5 @box = new Shapes.Rectangle(0x404040, @x, @y, @z, @width, @height) @box.obj3d.userData = this @ve.sscene.add(@box.obj3d) @count = 0 @addBaseElements() #addElement adds a visual element to the ElementBox given an element #contruction lambda ef : (box, x, y) -> Object3D addElement: (ef) -> row = Math.floor(@count / 2) col = @count % 2 _x = if col == 0 then -18 else 18 _y = (@height / 2 - 25) - row * 35 e = ef(@box, _x, _y) @count++ e #addBaseElements adds the common base elements to the ElementBox addBaseElements: -> class StaticElementBox extends ElementBox addBaseElements: -> @addElement((box, x, y) -> new BaseElements.Computer(box, x, y, 5)) @addElement((box, x, y) -> new BaseElements.Router(box, x, y, 5)) @addElement((box, x, y) -> new BaseElements.Switch(box, x, y, 5)) @addElement((box, x, y) -> lnk = new BaseElements.Link(box, new THREE.Vector3(-12.5, 12.5, 5), new THREE.Vector3(12.5, -12.5, 5), x, y, 5, true ) lnk.ln.material.color = new THREE.Color(0xcacaca) lnk ) @addElement((box, x, y) -> new BaseElements.Sax(box, x, y, 5)) class ModelBox extends ElementBox newModel: ()-> m = @addElement((box, x, y) -> new BaseElements.Model(box, x, y, 5)) m.props.name = @ve.namemanager.getName("model") m.id.name = m.props.name @ve.render() @ve.addie.update([m]) addBaseElements: -> #The Surface holds visual representations of Systems and Elements #aka the majority of the screen class Surface #Constructs a Surface object given a @ve visual environment constructor: (@ve) -> @width = 5000 @height = 5000 @baseRect = new Shapes.Rectangle(0x262626, 0, 0, 0, @width, @height) @baseRect.obj3d.userData = this @ve.scene.add(@baseRect.obj3d) @selectGroup = new THREE.Group() @ve.scene.add(@selectGroup) @selectorGroup = new THREE.Group() @ve.scene.add(@selectorGroup) @elements = [] addElement: (ef, x, y) -> e = null if ef instanceof Phyo and ef.tex? e = new ef.constructor(@baseRect, x, y, 50, ef.tex) else e = new ef.constructor(@baseRect, x, y, 50) e.props.name = @ve.namemanager.getName(e.constructor.name.toLowerCase()) e.id.name = e.props.name e.props.design = dsg if e.props.sshcmd? BaseElements.setSshCmd(e) @elements.push(e) @ve.render() e removeElement: (e) => idx = @elements.indexOf(e) if idx > -1 @elements.splice(idx, 1) obj3d = null obj3d = e.shp.obj3d if e.shp? obj3d = e.ln.obj3d if e.ln? idx = @baseRect.obj3d.children.indexOf(obj3d) if idx > -1 @baseRect.obj3d.children.splice(idx, 1) if e.glowBubble? idx = @selectGroup.children.indexOf(e.glowBubble) if idx > -1 @selectGroup.children.splice(idx, 1) delete e.glowBubble @ve.render() getElement: (name, sys) -> e = null for x in @elements if x.props.name == name && x.props.sys == sys e = x break e addIfContains: (box, e, set) -> o3d = null if e.shp? o3d = e.shp.obj3d else if e.ln? o3d = e.ln.obj3d if o3d != null o3d.geometry.computeBoundingBox() bb = o3d.geometry.boundingBox bx = new THREE.Box2( o3d.localToWorld(bb.min), o3d.localToWorld(bb.max) ) set.push(e) if box.containsBox(bx) #for some reason computing the bounding box kills selection o3d.geometry.boundingBox = null true toBox2: (box) -> new THREE.Box2( new THREE.Vector2(box.min.x, box.min.y), new THREE.Vector2(box.max.x, box.max.y) ) getSelection: (box) -> xs = [] box2 = @toBox2(box) @addIfContains(box2, x, xs) for x in @elements xs getSelected: () -> xs = [] xs.push(x.userData) for x in @selectGroup.children xs updateLink: (ln) -> ln.geom.verticesNeedUpdate = true ln.geom.lineDistancesNeedUpdate = true ln.geom.elementsNeedUpdate = true ln.geom.normalsNeedUpdate = true ln.geom.computeFaceNormals() ln.geom.computeVertexNormals() ln.geom.computeBoundingSphere() ln.geom.computeBoundingBox() moveObject: (o, p) -> o.position.x = p.x o.position.y = p.y if o.linep? o.linep.x = p.x o.linep.y = p.y if o.userData.glowBubble? o.userData.glowBubble.position.x = p.x o.userData.glowBubble.position.y = p.y if o.lines? @updateLink(ln) for ln in o.lines true moveObjectRelative: (o, p) -> o.position.x += p.x o.position.y += p.y if o.linep? o.linep.x += p.x o.linep.y += p.y if o.lines? @updateLink(ln) for ln in o.lines true glowMaterial: () -> #cam = @ve.sview.camera new THREE.ShaderMaterial({ uniforms: { "c": { type: "f", value: 1.0 }, "p": { type: "f", value: 1.4 }, glowColor: { type: "c", value: new THREE.Color(0xFDBF3B) }, viewVector: { type: "v3", value: new THREE.Vector3(0, 0, 200) } }, vertexShader: document.getElementById("vertexShader").textContent, fragmentShader: document.getElementById("fragmentShader").textContent, side: THREE.FrontSide, blending: THREE.AdditiveBlending, transparent: true }) glowSphere: (radius, x, y, z) -> geom = new THREE.SphereGeometry(radius, 64, 64) mat = @glowMaterial() obj = new THREE.Mesh(geom, mat) obj.position.x = x obj.position.y = y obj.position.z = z obj glowCube: (width, height, depth, x, y, z) -> geom = new THREE.BoxGeometry(width, height, depth, 2, 2, 2) mat = @glowMaterial() obj = new THREE.Mesh(geom, mat) obj.position.x = x obj.position.y = y obj.position.z = z modifier = new THREE.SubdivisionModifier(2) modifier.modify(geom) obj glowDiamond: (w, h, d, x, y, z) -> obj = @glowCube(w, h, d, x, y, z) obj.rotateZ(Math.PI/4) obj clearPropsGUI: -> if @ve.datgui? @ve.datgui.destroy() @ve.datgui = null showPropsGUI: (s) -> @ve.datgui = new dat.GUI() addElem = (d, k, v) -> if !d[k]? d[k] = [v] else d[k].push(v) dict = new Array() addElem(dict, x.constructor.name, x) for x in s addGuiElems = (typ, xs) => f = @ve.datgui.addFolder(typ) x.showProps(f) for x in xs f.open() addGuiElems(k, v) for k,v of dict $(@ve.datgui.domElement).focusout () => @ve.addie.update([x]) for x in s true selectObj: (obj) -> doSelect = true if not obj.glowBubble? if obj.shp instanceof Shapes.Circle p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 gs = @glowSphere(s, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Rectangle p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 l = s*1.5 gs = @glowCube(l, l, l, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Icon p = obj.shp.obj3d.position obj.shp.obj3d.geometry.computeBoundingSphere() s = obj.shp.obj3d.geometry.boundingSphere.radius + 3 l = s*10.5 gs = @glowCube(l, l, l, p.x, p.y, p.z) else if obj.shp instanceof Shapes.Diamond p = obj.shp.obj3d.position s = obj.shp.geom.boundingSphere.radius + 3 l = s*1.5 gs = @glowDiamond(l, l, l, p.x, p.y, p.z) else if obj.ln instanceof Shapes.Line d = 10 h = 10 v0 = obj.ln.geom.vertices[0] v1 = obj.ln.geom.vertices[obj.ln.geom.vertices.length - 1] w = obj.ln.geom.boundingSphere.radius * 2 x = (v0.x + v1.x) / 2 y = (v0.y + v1.y) / 2 z = 5 gs = @glowCube(w, h, d, x, y, z) theta = Math.atan2(v0.y - v1.y, v0.x - v1.x) gs.rotateZ(theta) else console.log "unkown object to select" console.log obj doSelect = false if doSelect gs.userData = obj obj.glowBubble = gs @selectGroup.add(gs) @ve.render() true clearSelection: (clearProps = true) -> for x in @selectGroup.children if x.userData.glowBubble? delete x.userData.glowBubble @selectGroup.children = [] @clearPropsGUI() if clearProps @ve.render() clearSelector: -> @selectorGroup.children = [] @ve.render() deleteSelection: () => console.log("deleting selection") deletes = [] for x in @selectGroup.children deletes.push(x.userData) if x.userData.links? deletes.push.apply(deletes, x.userData.links) @ve.addie.delete(deletes) for d in deletes @removeElement(d) @ve.propsEditor.hide(false) @ve.equationEditor.hide() true class NameManager constructor: (@ve) -> @names = new Array() getName: (s, sys='root') -> n = "" if !@names[s]? @names[s] = 0 n = s + @names[s] else @names[s]++ n = s + @names[s] while @ve.surface.getElement(n, sys) != null @names[s]++ n = s + @names[s] n class SimSettings constructor: () -> @props = { begin: 0, end: 0, maxStep: 1e-3 } #VisualEnvironment holds the state associated with the Threejs objects used #to render Surfaces and the ElementBox. This class also contains methods #for controlling and interacting with this group of Threejs objects. class VisualEnvironment #Constructs a visual environment for the given @container. @container must #be a reference to a <div> dom element. The Threejs canvas the visual #environment renders onto will be appended as a child of the supplied #container constructor: (@sc0, @sc1, @sc2, @sc3, @scontainer) -> @scene = new THREE.Scene() @sscene = new THREE.Scene() @pscene = new THREE.Scene() @surface = new Surface(this) @cwidth = @scontainer.offsetWidth #200 @cheight = @scontainer.offsetHeight @iconCache = {} @scamera = new THREE.OrthographicCamera( @cwidth / -2, @cwidth / 2, @cheight / 2, @cheight / -2, 1, 1000) @keyh = new KeyHandler(this) @sview = new SurfaceView(this, @sc0) @srenderer = new THREE.WebGLRenderer({antialias: true, alpha: true}) @srenderer.setSize(@cwidth, @cheight) @clear = 0x262626 @alpha = 1 @srenderer.setClearColor(@clear, @alpha) @scontainer.appendChild(@srenderer.domElement) @scamera.position.z = 200 @scamera.zoom = 1 @namemanager = new NameManager(this) @addie = new Addie(this) @propsEditor = new PropsEditor(this) @equationEditor = new EquationEditor(this) @simSettings = new SimSettings() @splitView = new SplitView(this) loadIcon: (name, f = null) => if not @iconCache[name]? THREE.ImageUtils.loadTexture( "ico/"+g.user+"/"+name+".png", {}, (tex) => @iconCache[name] = tex if f? f(tex) true ) else f(@iconCache[name]) hsplit: () => console.log("hsplit") vsplit: () => console.log("vsplit") render: -> @sview.doRender() @srenderer.clear() @srenderer.clearDepth() @srenderer.render(@sscene, @scamera) showSimSettings: () -> @propsEditor.hide() @propsEditor.elements = [@simSettings] @propsEditor.show() showDiagnostics: () => console.log("Showing Diagnostics") h = window.innerHeight dh = parseInt($("#diagnosticsPanel").css("height").replace('px', '')) if dh > 0 $("#diagnosticsPanel").css("top", h+"px") $("#hsplitter").css("top", "auto") else $("#diagnosticsPanel").css("top", (h-200)+"px") $("#hsplitter").css("top", (h-205)+"px") $("#diagnosticsPanel").css("height", "auto") class SplitView constructor: (@ve) -> @c0 = window.innerWidth @c1 = @c0 splitRatio: () -> @c0 / window.innerWidth hdown: (event) => $("#metasurface").mouseup(@hup) $("#diagnosticsPanel").mouseup(@hup) $("#metasurface").mousemove(@hmove) $("#diagnosticsPanel").mousemove(@hmove) $("#diagnosticsPanel").css("height", "auto") hup: (event) => console.log("hup") $("#metasurface").off('mousemove') $("#metasurface").off('mouseup') $("#diagnosticsPanel").off('mousemove') $("#diagnosticsPanel").off('mouseup') hmove: (event) => $("#diagnosticsPanel").css("top", (event.clientY+5)+"px") $("#hsplitter").css("top", event.clientY+"px") vdown: (event) => $("#metasurface").mouseup(@vup) $("#metasurface").mousemove(@vmove) vup: (event) => console.log("vup") $("#metasurface").off('mousemove') $("#metasurface").off('mouseup') @ve.render() vmove: (event) => @c1 = event.clientX dc = @c1 - @c0 x = @c1+"px" r = ($("#metasurface").width() - @c1)+"px" $("#vsplitter").css("left", x) left = 0 center = event.clientX right = window.innerWidth @ve.sview.panes[0].viewport.width = center - left @ve.sview.panes[1].viewport.width = right - center @ve.sview.panes[1].viewport.left = center @ve.sview.panes[0].camera.right += dc @ve.sview.panes[1].camera.right -= dc @ve.sview.doRender() @c0 = @c1 class SurfaceView constructor: (@ve, @container) -> @scene = @ve.scene @surface = @ve.surface @cwidth = @container.offsetWidth @cheight = @container.offsetHeight @l = Math.max(window.innerWidth, window.innerHeight) @l = Math.max(@cwidth, @cheight) @clear = 0x262626 @alpha = 1 @renderer = new THREE.WebGLRenderer({antialias: true, alpha: true}) @renderer.setSize(@cwidth, @cheight) @renderer.setClearColor(@clear, @alpha) @mouseh = new MouseHandler(this) @raycaster = new THREE.Raycaster() @raycaster.linePrecision = 10 @container.appendChild(@renderer.domElement) @panes = [ { id: 1, zoomFactor: 1, background: 0x262626, viewport: { left: 0, bottom: 0, width: @cwidth, height: @cheight }, camera: new THREE.OrthographicCamera( 0, @cwidth, @cheight, 0, 1, 1000) } { id: 2, zoomFactor: 1, background: 0x464646, viewport: { left: @cwidth, bottom: 0, width: 0, height: @cheight }, camera: new THREE.OrthographicCamera( 0, 0, @cheight, 0, 1, 1000) } ] for p in @panes p.camera.position.z = 200 mouseHits: (eve) -> @mouseh.updateMouse(eve) @raycaster.setFromCamera(@mouseh.pos, @mouseh.icam) ixs = @raycaster.intersectObjects(@ve.surface.baseRect.obj3d.children) ixs baseRectIx: (eve) -> @mouseh.updateMouse(eve) @raycaster.setFromCamera(@mouseh.pos, @mouseh.icam) bix = @raycaster.intersectObject(@ve.surface.baseRect.obj3d) bix doRender: () -> for p in @panes vp = p.viewport @renderer.setViewport(vp.left, vp.bottom, vp.width, vp.height) @renderer.setScissor(vp.left, vp.bottom, vp.width, vp.height) @renderer.enableScissorTest(true) @renderer.setClearColor(p.background) p.camera.updateProjectionMatrix() @renderer.clear() @renderer.clearDepth() @renderer.render(@scene, p.camera) render: () -> @ve.render() getPane: (c) => result = {} for p in @panes if c.x > p.viewport.left and c.x < p.viewport.left + p.viewport.width and c.y > p.viewport.bottom and c.y < p.viewport.bottom + p.viewport.height result = p break p zoomin: (x = 3, p = new THREE.Vector2(0,0)) -> w = Math.abs(@mouseh.icam.right - @mouseh.icam.left) h = Math.abs(@mouseh.icam.top - @mouseh.icam.bottom) @mouseh.apane.zoomFactor -= x/(@mouseh.apane.viewport.width) @mouseh.icam.left += x * (p.x/w) @mouseh.icam.right -= x * (1 - p.x/w) @mouseh.icam.top -= x * (p.y/h) @mouseh.icam.bottom += x * (1 - p.y/h) @mouseh.icam.updateProjectionMatrix() @render() pan: (dx, dy) => @mouseh.icam.left += dx @mouseh.icam.right += dx @mouseh.icam.top += dy @mouseh.icam.bottom += dy @mouseh.icam.updateProjectionMatrix() @render() #This is the client side Addie, it talks to the Addie at cypress.deterlab.net #to manage a design class Addie constructor: (@ve) -> @mstate = { up: false } init: () => @load() @msync() update: (xs) => console.log("updating objects") console.log(xs) #build the update sets link_updates = {} node_updates = {} model_updates = {} settings_updates = [] for x in xs if x.links? #x is a node if it has links node_updates[JSON.stringify(x.id)] = x for l in x.links link_updates[JSON.stringify(l.id)] = l if x instanceof BaseElements.Link link_updates[JSON.stringify(x.id)] = x node_updates[JSON.stringify(x.endpoint[0].id)] = x.endpoint[0] node_updates[JSON.stringify(x.endpoint[1].id)] = x.endpoint[1] if x instanceof BaseElements.Model model_updates[x.id.name] = x for i in x.instances node_updates[JSON.stringify(i.id)] = i if x instanceof SimSettings settings_updates.push(x) true #build the update messages model_msg = { Elements: [] } node_msg = { Elements: [] } link_msg = { Elements: [] } settings_msg = { Elements: [] } for _, m of model_updates model_msg.Elements.push( { OID: { name: m.id.name, sys: "", design: dsg }, Type: "Model", Element: m.props } ) true for _, n of node_updates node_msg.Elements.push( { OID: n.id, Type: n.constructor.name, Element: n.props } ) true for _, l of link_updates type = "Link" type = "Plink" if l.isPhysical() link_msg.Elements.push( { OID: l.id, Type: type, Element: l.props } ) true for s in settings_updates settings_msg.Elements.push( { OID: { name: "", sys: "", design: dsg }, Type: "SimSettings", Element: s.props } ) true doLinkUpdate = () => console.log("link update") console.log(link_msg) if link_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(link_msg), (data) => for _, l of link_updates BaseElements.updateId(l) doNodeUpdate = () => console.log("node update") console.log(node_msg) if node_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(node_msg), (data) => for _, n of node_updates BaseElements.updateId(n) for _, l of link_updates l.setEndpointData() doLinkUpdate() doModelUpdate = () => console.log("model update") console.log(model_msg) if model_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(model_msg), (data) => for _, m of model_updates BaseElements.updateId(m) for _, n of node_updates n.sync() if n.sync? doNodeUpdate() doSettingsUpdate = () => console.log("settings update") console.log(settings_msg) if settings_msg.Elements.length > 0 $.post "/addie/"+dsg+"/design/update", JSON.stringify(settings_msg), (data) => console.log("settings update complete") #do the updates since this is a linked structure we have to be a bit careful #about update ordering, here we do models, then nodes then links. This is #because some nodes reference models, and all links reference nodes. At #each stage of the update we update the internals of the data structures at #synchronization points within the updates to ensure consistency if model_msg.Elements.length > 0 doModelUpdate() else if node_msg.Elements.length > 0 doNodeUpdate() else if link_msg.Elements.length > 0 doLinkUpdate() #settings update is independent of other updates so we can break out of the #above update structure doSettingsUpdate() delete: (xs) => console.log("addie deleting objects") console.log(xs) ds = [] for x in xs if x instanceof Phyo ds.push({type: "Phyo", element: x.props}) if x instanceof Computer ds.push({type: "Computer", element: x.props}) if x instanceof Router ds.push({type: "Router", element: x.props}) if x instanceof Switch ds.push({type: "Switch", element: x.props}) if x instanceof Sax ds.push({type: "Sax", element: x.props}) if x instanceof Link if x.isPhysical() ds.push({type: "Plink", element: x.props}) else ds.push({type: "Link", element: x.props}) delete_msg = { Elements: ds } $.post "/addie/"+dsg+"/design/delete", JSON.stringify(delete_msg), (data) => console.log("addie delete complete") console.log(data) load: () => ($.get "/addie/"+dsg+"/design/read", (data, status, jqXHR) => console.log("design read success") console.log(data) @doLoad(data) true ).fail (data) => console.log("design read fail " + data.status) loadedModels = {} loadElements: (elements) => links = [] plinks = [] for x in elements @ve.namemanager.getName(x.type.toLowerCase()) switch x.type when "Computer" @loadComputer(x.object) when "Router" @loadRouter(x.object) when "Switch" @loadSwitch(x.object) when "Phyo" @loadPhyo(x.object) when "Sax" @loadSax(x.object) when "Link" links.push(x.object) when "Plink" plinks.push(x.object) @ve.namemanager.getName("link") for x in links @loadLink(x) for x in plinks @loadPlink(x) for k, v of @ve.namemanager.names @ve.namemanager.names[k] = v + 10 @ve.render() true loadModels: (models) => for x in models m = @ve.mbox.addElement((box, x, y) -> new BaseElements.Model(box, x, y, 5)) m.props = x m.id.name = x.name loadedModels[m.props.name] = m if m.props.icon != '' do (m) => #capture m-ref before it gets clobbered by loop @ve.loadIcon(m.props.name, (tex) -> _tex = tex.clone() _tex.needsUpdate = true m.setIcon(_tex) for i in m.instances i.tex = tex.clone() i.tex.needsUpdate = true i.setIcon( i.shp.obj3d.position.x, i.shp.obj3d.position.y ) ) true loadSimSettings: (settings) => @ve.simSettings.props = settings doLoad: (m) => @loadModels(m.models) @loadElements(m.elements) @loadSimSettings(m.simSettings) true setProps: (x, p) => x.props = p x.id.name = p.name x.id.sys = p.sys x.id.design = p.design loadComputer: (x) => c = new BaseElements.Computer(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(c, x) BaseElements.setSshCmd(c) @ve.surface.elements.push(c) true loadPhyo: (x) => m = loadedModels[x.model] p = new BaseElements.Phyo(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(p, x) @ve.surface.elements.push(p) m.instances.push(p) p.model = m p.loadArgValues() true loadSax: (x) => s = new BaseElements.Sax(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(s, x) BaseElements.setSshCmd(s) @ve.surface.elements.push(s) true loadRouter: (x) => r = new BaseElements.Router(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(r, x) BaseElements.setSshCmd(r) @ve.surface.elements.push(r) true loadSwitch: (x) => s = new BaseElements.Switch(@ve.surface.baseRect, x.position.x, x.position.y, x.position.z) @setProps(s, x) @ve.surface.elements.push(s) true loadLink: (x) => a = @ve.surface.getElement( x.endpoints[0].name, x.endpoints[0].sys ) if a == null console.log("bad endpoint detected") b = @ve.surface.getElement( x.endpoints[1].name, x.endpoints[1].sys ) if b == null console.log("bad endpoint detected") l = new BaseElements.Link(@ve.surface.baseRect, a.shp.obj3d.linep, b.shp.obj3d.linep, 0, 0, 5) a.links.push(l) a.shp.obj3d.lines.push(l.ln) b.links.push(l) b.shp.obj3d.lines.push(l.ln) l.endpoint[0] = a l.endpoint[1] = b l.ep_ifx[0] = x.endpoints[0].ifname l.ep_ifx[1] = x.endpoints[1].ifname @setProps(l, x) l.setEndpointData() @ve.surface.elements.push(l) l.setColor() true #grosspants loadPlink: (x) => a = @ve.surface.getElement( x.endpoints[0].name, x.endpoints[0].sys ) if a == null console.log("bad endpoint detected") b = @ve.surface.getElement( x.endpoints[1].name, x.endpoints[1].sys ) if b == null console.log("bad endpoint detected") l = new BaseElements.Link(@ve.surface.baseRect, a.shp.obj3d.linep, b.shp.obj3d.linep, 0, 0, 5) a.links.push(l) a.shp.obj3d.lines.push(l.ln) b.links.push(l) b.shp.obj3d.lines.push(l.ln) l.endpoint[0] = a l.endpoint[1] = b l.applyPhysicalProps() @setProps(l, x) l.unpackBindings() l.setEndpointData() @ve.surface.elements.push(l) true levelColor: (l) => switch l when "info" then "blue" when "warning" then "orange" when "error" then "red" when "success" then "green" else "gray" compile: () => console.log("asking addie to compile the design") $("#diagText").html("") $("#ajaxLoading").css("display", "block") $.get "/addie/"+dsg+"/design/compile", (data) => console.log("compilation result:") console.log(data) $("#ajaxLoading").css("display", "none") if data.elements? for d in data.elements $("#diagText").append( "<span style='color:"+@levelColor(d.level)+"'><b>"+ d.level+ "</b></span> - " + d.message + "<br />" ) run: () => console.log("asking addie to run the experiment") $.get "/addie/"+dsg+"/design/run", (data) => console.log("run result: ") console.log(data) materialize: () => if @mstate.up console.log("asking addie to dematerialize the experiment") $("#materialize").html("Materialize") $.get "/addie/"+dsg+"/design/dematerialize", (data) => console.log("dematerialize result: ") console.log(data) #TODO do an async call here and then grey out the materialization button #until the async call returns @mstate.up = false else console.log("asking addie to materialize the experiment") $("#materialize").html("Dematerialize") @mstate.up = true $.get "/addie/"+dsg+"/design/materialize", (data) => console.log("materialize result: ") console.log(data) #synchronize materialization status msync: () => console.log("synchronizing materialization state with addie") $.get "/addie/"+dsg+"/design/mstate", (data) => console.log("materialization state:") console.log(data) if data.Status? and data.Status == "Active" @mstate.up = true $("#materialize").html("Dematerialize") class EBoxSelectHandler constructor: (@mh) -> test: (ixs) -> ixs.length > 0 and ixs[ixs.length - 1].object.userData instanceof StaticElementBox handleDown: (ixs) -> @mh.sv.surface.clearSelection() if ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! ebox select -- " + e.constructor.name console.log e #TODO double click should lock linking until link icon clicked again # this way many things may be linked without going back to the icon if e instanceof Link console.log "! linking objects" @mh.sv.container.style.cursor = "crosshair" @mh.placingObject = null @mh.sv.container.onmousemove = (eve) => @mh.linkingH.handleMove0(eve) @mh.sv.container.onmousedown = (eve) => @mh.linkingH.handleDown0(eve) else console.log "! placing objects" @mh.makePlacingObject(e) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) @mh.sv.ve.scontainer.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) stillOnEBox: (event) => @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.spos, @mh.sv.ve.scamera) ixs = @mh.sv.raycaster.intersectObjects(@mh.sv.ve.sscene.children, true) result = false for x in ixs if x.object.userData instanceof StaticElementBox result = true break result handleUp: (event) -> if @stillOnEBox(event) @mh.sv.surface.removeElement(@mh.placingObject) false else @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position @mh.sv.ve.addie.update([@mh.placingObject]) @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) -> @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) if bix.length > 0 @mh.sv.surface.moveObject(@mh.placingObject.shp.obj3d, bix[0].point) @mh.sv.render() class MBoxSelectHandler constructor: (@mh) -> @model = null @instance = null test: (ixs) -> ixs.length > 0 and ixs[ixs.length - 1].object.userData instanceof ModelBox handleDown: (ixs) -> @mh.sv.surface.clearSelection() if ixs[0].object.userData.cyjs? e = ixs[0].object.userData @model = e console.log('mbox down') @mh.sv.container.onmousemove = (eve) => @handleMove0(eve) @mh.sv.ve.scontainer.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) stillOnMBox: (event) => @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.spos, @mh.sv.ve.scamera) ixs = @mh.sv.raycaster.intersectObjects(@mh.sv.ve.sscene.children, true) result = false for x in ixs if x.object.userData instanceof ModelBox result = true break result handleUp: (event) -> console.log('mbox up') if @instance? if @stillOnMBox(event) @mh.sv.surface.removeElement(@mh.placingObject) idx = @model.instances.indexOf(@instance) if idx > -1 @model.instances.splice(idx, 1) @instance = null @mh.placingObject = null false else @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position @mh.placingObject.sync() @mh.sv.ve.addie.update([@mh.placingObject]) @mh.sv.surface.clearSelection() else if !@instance? @mh.sv.ve.propsEditor.elements = [@model] @mh.sv.ve.propsEditor.show() @mh.sv.ve.equationEditor.show(@model) @mh.sv.container.onmousemove = null @mh.sv.container.onmouseup = null @mh.sv.ve.scontainer.onmouseup = (eve) => null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @instance = null handleMove0: (event) -> @instance = @mh.makePlacingObject(@model.instantiate(null, 0, 0, 0, 25, 25)) @instance.model = @model @instance.addArgs() @model.instances.push(@instance) @mh.sv.container.onmousemove = (eve) => @handleMove1(eve) handleMove1: (event) -> @mh.updateMouse(event) @mh.sv.ve.propsEditor.hide() @mh.sv.ve.equationEditor.hide() @mh.sv.surface.clearSelection() @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) if bix.length > 0 #ox = @mh.placingObject.shp.geom.boundingSphere.radius @mh.sv.surface.moveObject(@mh.placingObject.shp.obj3d, bix[0].point) @mh.sv.render() class SurfaceElementSelectHandler constructor: (@mh) -> @start = new THREE.Vector3(0,0,0) @end= new THREE.Vector3(0,0,0) @p0 = new THREE.Vector3(0,0,0) @p1 = new THREE.Vector3(0,0,0) test: (ixs) -> ixs.length > 1 and ixs[ixs.length - 1].object.userData instanceof Surface and ixs[0].object.userData.cyjs? handleDown: (ixs) -> @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) @p0.copy(bix[0].point) @p1.copy(@p0) @mh.updateMouse(event) @start.copy(@mh.pos) e = ixs[0].object.userData console.log "! surface select -- " + e.constructor.name console.log "current selection" console.log @mh.sv.surface.selectGroup console.log("multiselect: " + @mh.sv.ve.keyh.multiselect) if not ixs[0].object.userData.glowBubble? && not @mh.sv.ve.keyh.multiselect @mh.sv.surface.clearSelection() @mh.sv.surface.selectObj(e) if @mh.sv.surface.selectGroup.children.length == 1 @mh.sv.ve.propsEditor.elements = [e] @mh.sv.ve.propsEditor.show() else @mh.sv.ve.propsEditor.elements = @mh.sv.surface.getSelected() @mh.sv.ve.propsEditor.show() if e instanceof BaseElements.Phyo @mh.sv.ve.equationEditor.show(e.model) @mh.placingObject = e @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) applyGroupMove: () -> for x in @mh.sv.surface.selectGroup.children p = new THREE.Vector3(@p1.x - @p0.x , @p1.y - @p0.y, @p0.z) if x.userData.shp? @mh.sv.surface.moveObjectRelative(x.userData.shp.obj3d, p) @mh.sv.surface.moveObjectRelative(x, p) updateGroupMove: () -> updates = [] for x in @mh.sv.surface.selectGroup.children x.userData.props.position = x.position updates.push(x.userData) @mh.sv.ve.addie.update(updates) handleUp: (ixs) -> @mh.updateMouse(event) @end.copy(@mh.pos) if @mh.placingObject.shp? @mh.placingObject.props.position = @mh.placingObject.shp.obj3d.position if @start.distanceTo(@end) > 0 @updateGroupMove() #@applyGroupMove() @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) -> @mh.updateMouse(event) @mh.sv.raycaster.setFromCamera(@mh.pos, @mh.icam) bix = @mh.sv.raycaster.intersectObject(@mh.sv.surface.baseRect.obj3d) @p1.copy(bix[0].point) if bix.length > 0 @applyGroupMove() @mh.sv.render() @p0.copy(@p1) #TODO, me thinks that react.js orangular.js is meant to deal with precisely #the problem we are tyring to solve with the props editor, in the future we #should look into replacing dat.gui (as nifty as it is) with an angular #based control that is a bit more intelligent class PropsEditor constructor: (@ve) -> @elements = [] @cprops = {} show: () -> for e in @elements e.sync() if e.sync? @commonProps() @datgui = new dat.GUI() for k, v of @cprops @datgui.add(@cprops, k) if @elements.length == 1 and @elements[0].funcs? for k, v of @elements[0].funcs @datgui.add(@elements[0].funcs, k) true save: () -> for k, v of @cprops for e in @elements e.props[k] = v if v != "..." e.sync() if e.sync? @ve.addie.update(@elements) hide: (doSave = true) -> if @datgui? @save() if doSave @datgui.destroy() @elements = [] @cprops = {} @datgui = null commonProps: () -> ps = {} cps = new Array() addProp = (d, k, v) -> if !d[k]? d[k] = [v] else d[k].push(v) addProps = (e) => for k, v of e.props continue if k == 'position' continue if k == 'design' continue if k == 'endpoints' continue if k == 'interfaces' continue if k == 'path' continue if k == 'args' continue if k == 'equations' continue if k == 'bindings' continue if k == 'icon' continue if k == 'name' and @elements.length > 1 addProp(ps, k, v) addProps(e) for e in @elements addCommon = (k, v, es) -> if v.length == es.length then cps[k] = v true addCommon(k, v, @elements) for k, v of ps isUniform = (xs) -> u = true i = xs[0] for x in xs u = (x == i) break if !u u setUniform = (k, v, e) -> if isUniform(v) e[k] = v[0] else e[k] = "..." true reduceUniform = (xps) -> setUniform(k, v, xps) for k, v of xps true reduceUniform(cps) @cprops = cps cps class EquationEditor constructor: (@ve) -> @model = null show: (m) -> @model = m console.log("showing equation editor") $("#eqtnSrc").val(@model.props.equations) if @ve.propsEditor.datgui? $("#eqtnEditor").css("display", "inline") $("#eqtnEditor").css("top", @ve.propsEditor.datgui.domElement.clientHeight + 30) hide: () -> console.log("hiding equation editor") if @model? @model.props.equations= $("#eqtnSrc").val() $("#eqtnEditor").css("display", "none") class PanHandler constructor: (@mh) -> @p0 = new THREE.Vector2(0,0) @p1 = new THREE.Vector2(0,0) handleDown: (event) => @mh.updateMouse(event) @p0.x = event.clientX @p0.y = event.clientY @p1.x = event.clientX @p1.y = event.clientY @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) handleUp: (event) => @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null handleMove: (event) => @p1.x = event.clientX @p1.y = event.clientY dx = -(@p1.x - @p0.x) dx *= @mh.apane.zoomFactor dy = @p1.y - @p0.y dy *= @mh.apane.zoomFactor @mh.sv.pan(dx, dy) @p0.x = @p1.x @p0.y = @p1.y class SurfaceSpaceSelectHandler constructor: (@mh) -> @selCube = new SelectionCube() test: (ixs) -> ixs.length > 0 and ixs[0].object.userData instanceof Surface handleDown: (ixs) -> @mh.sv.surface.clearSelection() console.log "! space select down" p = new THREE.Vector3( ixs[ixs.length - 1].point.x, ixs[ixs.length - 1].point.y, 75 ) @selCube.init(p) @mh.sv.container.onmouseup = (eve) => @handleUp(eve) @mh.sv.surface.selectorGroup.add(@selCube.obj3d) @mh.sv.container.onmousemove = (eve) => @handleMove(eve) @mh.sv.surface.clearSelection() handleUp: (event) -> console.log "! space select up" sel = @mh.sv.surface.getSelection(@selCube.obj3d.geometry.boundingBox) @mh.sv.surface.selectObj(o) for o in sel @mh.sv.ve.propsEditor.elements = sel console.log('common props') @mh.sv.ve.propsEditor.show() @selCube.reset() @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.onmouseup = null @mh.sv.render() handleMove: (event) -> bix = @mh.baseRectIx(event) if bix.length > 0 p = new THREE.Vector3( bix[bix.length - 1].point.x, bix[bix.length - 1].point.y, 75 ) @selCube.update(p) @mh.sv.render() class LinkingHandler constructor: (@mh) -> handleDown0: (event) -> ixs = @mh.sv.mouseHits(event) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! link0 " + e.constructor.name pos0 = ixs[0].object.linep pos1 = new THREE.Vector3( ixs[0].object.position.x, ixs[0].object.position.y, 5 ) @mh.placingLink = new BaseElements.Link(@mh.sv.surface.baseRect, pos0, pos1, 0, 0, 5 ) @mh.sv.surface.elements.push(@mh.placingLink) BaseElements.initName(@mh.placingLink, "link") @mh.placingLink.linkEndpoint(0, ixs[0].object.userData) @mh.sv.container.onmousemove = (eve) => @handleMove1(eve) @mh.sv.container.onmousedown = (eve) => @handleDown1(eve) else console.log "! link0 miss" handleDown1: (event) -> ixs = @mh.sv.mouseHits(event) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! link1 " + e.constructor.name @mh.placingLink.ln.geom.vertices[1] = ixs[0].object.linep @mh.placingLink.linkEndpoint(1, ixs[0].object.userData) @mh.sv.surface.updateLink(@mh.placingLink.ln) @mh.placingLink.typeResolve() @mh.sv.render() @mh.sv.ve.addie.update([@mh.placingLink]) @mh.sv.container.onmousemove = null @mh.sv.container.onmousedown = (eve) => @mh.baseDown(eve) @mh.sv.container.style.cursor = "default" else console.log "! link1 miss" handleMove0: (event) -> @mh.updateMouse(event) handleMove1: (event) -> bix = @mh.sv.baseRectIx(event) if bix.length > 0 @mh.sv.scene.updateMatrixWorld() @mh.placingLink.ln.geom.vertices[1].x = bix[bix.length - 1].point.x @mh.placingLink.ln.geom.vertices[1].y = bix[bix.length - 1].point.y @mh.placingLink.ln.geom.verticesNeedUpdate = true @mh.sv.render() #Mouse handler encapsulates the logic of dealing with mouse events class MouseHandler constructor: (@sv) -> @pos = new THREE.Vector3(0, 0, 1) @spos = new THREE.Vector3(0, 0, 1) @eboxSH = new EBoxSelectHandler(this) @mboxSH = new MBoxSelectHandler(this) @surfaceESH = new SurfaceElementSelectHandler(this) @surfaceSSH = new SurfaceSpaceSelectHandler(this) @linkingH = new LinkingHandler(this) @panHandler = new PanHandler(this) @icam = null ondown: (event) -> @baseDown(event) onwheel: (event) => @apane = @sv.getPane(new THREE.Vector2(event.layerX, event.layerY)) @icam = @apane.camera @sv.zoomin(-event.deltaY / 5, new THREE.Vector2(event.layerX, event.layerY)) updateMouse: (event) -> @apane = @sv.getPane(new THREE.Vector2(event.layerX, event.layerY)) @icam = @apane.camera if @apane.id == 1 sr = @sv.ve.splitView.splitRatio() else sr = 1 - @sv.ve.splitView.splitRatio() @pos.x = ((event.layerX - @apane.viewport.left) / (@sv.cwidth * sr) ) * 2 - 1 @pos.y = -((event.layerY - @apane.viewport.bottom) / @sv.cheight ) * 2 + 1 @spos.x = (event.layerX / @sv.ve.scontainer.offsetWidth ) * 2 - 1 @spos.y = -(event.layerY / @sv.ve.scontainer.offsetHeight) * 2 + 1 baseRectIx: (event) -> @updateMouse(event) @sv.raycaster.setFromCamera(@pos, @icam) @sv.raycaster.intersectObject(@sv.ve.surface.baseRect.obj3d) placingObject: null placingLink: null makePlacingObject: (obj) -> @sv.raycaster.setFromCamera(@pos, @icam) bix = @sv.raycaster.intersectObject(@sv.ve.surface.baseRect.obj3d) x = y = 0 if bix.length > 0 ix = bix[bix.length - 1] x = ix.point.x y = ix.point.y @placingObject = @sv.surface.addElement(obj, x, y) #onmousedown handlers baseDown: (event) -> #the order actually matters here, need to hide the equation editor first #so the equations get saved to the underlying object before the props #editor sends them to addie @sv.ve.equationEditor.hide() @sv.ve.propsEditor.hide() #get the list of objects the mouse click intersected @updateMouse(event) console.log(@pos) #delegate the handling of the event to one of the handlers #check the model boxes first if event.which == 1 @sv.raycaster.setFromCamera(@spos, @sv.ve.scamera) sixs = @sv.raycaster.intersectObjects(@sv.ve.sscene.children, true) if @eboxSH.test(sixs) then @eboxSH.handleDown(sixs) else if @mboxSH.test(sixs) then @mboxSH.handleDown(sixs) else @sv.raycaster.setFromCamera(@pos, @icam) ixs = @sv.raycaster.intersectObjects(@sv.scene.children, true) if @surfaceESH.test(ixs) then @surfaceESH.handleDown(ixs) else if @surfaceSSH.test(ixs) then @surfaceSSH.handleDown(ixs) else if event.which = 3 @panHandler.handleDown(event) true doMultiplink = (sel) => class MultiLinker constructor: (@ve, @sel) -> console.log("multiplink") console.log(@sel) @ve.sview.container.style.cursor = "crosshair" @ve.sview.container.onmousedown = (eve) => @handleDown(eve) @tgtP = new THREE.Vector3(0,0,0) @links = [] for s in @sel l = new BaseElements.Link(@ve.surface.baseRect, s.shp.obj3d.linep, @tgtP, 0, 0, 5) BaseElements.initName(l, "link") l.linkEndpoint(0, s) @links.push(l) true handleDown: (eve) => ixs = @ve.sview.mouseHits(eve) if ixs.length > 0 and ixs[0].object.userData.cyjs? e = ixs[0].object.userData console.log "! multilink1 " + e.constructor.name @tgtP = ixs[0].object.linep for l in @links l.linkEndpoint(1, ixs[0].object.userData) l.typeResolve() @ve.surface.updateLink(l.ln) @ve.sview.render() @ve.addie.update([l]) @ve.sview.container.style.cursor = "default" @ve.sview.container.onmousedown = (eve) => @ve.sview.mouseh.baseDown(eve) true else console.log "! multilink miss" true class KeyHandler constructor: (@ve) -> @multiselect = false ondown: (event) => keycode = window.event.keyCode || event.which if(keycode == 8 || keycode == 46) @ve.surface.deleteSelection() event.preventDefault() else if(keycode == 16) console.log("multiselect start") @multiselect = true true else if(keycode == 67) xs = @ve.surface.getSelected() if xs.length == 0 @ve.sview.container.style.cursor = "crosshair" @ve.sview.container.onmousemove = (eve) => @ve.sview.mouseh.linkingH.handleMove0(eve) @ve.sview.container.onmousedown = (eve) => @ve.sview.mouseh.linkingH.handleDown0(eve) else ml = new MultiLinker(@ve, xs) true onup: (event) => keycode = window.event.keyCode || event.which if(keycode == 16) console.log("multiselect end") @multiselect = false true
[ { "context": "###\n Superslides\n https://github.com/nicinabox/superslides\n Copyright (c) 2013 Nic Aitch; Licen", "end": 48, "score": 0.9992921352386475, "start": 39, "tag": "USERNAME", "value": "nicinabox" }, { "context": "hub.com/nicinabox/superslides\n Copyright (c) 2013 Nic Aitch; Licensed MIT\n###\n\nplugin = 'superslides'\n$ ", "end": 91, "score": 0.9998790621757507, "start": 82, "tag": "NAME", "value": "Nic Aitch" } ]
src/jquery.superslides.coffee
davgit/superslides
1
### Superslides https://github.com/nicinabox/superslides Copyright (c) 2013 Nic Aitch; Licensed MIT ### plugin = 'superslides' $ = jQuery Superslides = (el, options = {}) -> @options = $.extend play: false slide_speed: 'normal' slide_easing: 'linear' pagination: true hashchange: false scrollable: true classes: preserve: 'preserve' nav: 'slides-navigation' container: 'slides-container' pagination: 'slides-pagination' , options that = this $window = $(window) @el = $(el) $container = $(".#{@options.classes.container}", el) $children = $container.children() $pagination = $("<nav>", class: @options.classes.pagination) $control = $('<div>', class: 'slides-control') multiplier = 1 init = false width = $window.width() height = $window.height() # Private initialize = => return if init multiplier = findMultiplier() positions() @mobile = (/mobile/i).test(navigator.userAgent) $control = $container.wrap($control).parent('.slides-control') setupCss() setupContainers() toggleNav() addPagination() @start() this setupCss = => $('body').css margin: 0 @el.css position: 'relative' overflowX: 'hidden' width: '100%' $control.css position: 'relative' transform: 'translate3d(0)' $container.css display: 'none' margin: '0' padding: '0' listStyle: 'none' position: 'relative' setupImageCSS() setupImageCSS = => $container.find('img').not(".#{@options.classes.preserve}").css "-webkit-backface-visibility": 'hidden' "-ms-interpolation-mode": 'bicubic' "position": 'absolute' "left": '0' "top": '0' "z-index": '-1' setupContainers = => $('body').css margin: 0 overflow: 'hidden' @el.css height: height $control.css width: width * multiplier left: -width if @options.scrollable $children.each -> return if $('.scrollable', this).length $(this).wrapInner('<div class="scrollable" />'); $(this).find('img').not(".#{_this.options.classes.preserve}") .insertBefore($('.scrollable', this)); setupChildren = => if $children.is('img') $children.wrap('<div>') $children = $container.children() $container.children().css display: 'none' position: 'absolute' overflow: 'hidden' top: 0 left: width zIndex: 0 adjustSlidesSize $children toggleNav = => if @size() > 1 $(".#{@options.classes.nav}").show() else $(".#{@options.classes.nav}").hide() setupNextPrev = => $(".#{@options.classes.nav} a").each -> if $(this).hasClass('next') this.hash = that.next else this.hash = that.prev addPaginationItem = (i) => unless i >= 0 i = @size() - 1 # size is not zero indexed $pagination.append $("<a>", href: "##{i}" class: "current" if @current == $pagination.children().length ) addPagination = => return if !@options.pagination or @size() == 1 if $(el).find(".#{@options.classes.pagination}").length next_index = $pagination.children().last().index() + 1 array = $container.children() array = array.slice(next_index) else next_index = 0 array = new Array(@size() - next_index) $pagination = $pagination.appendTo(@el) $.each array, (i) -> addPaginationItem(i + next_index) loadImage = ($img, callback) => $("<img>", src: "#{$img.attr('src')}?#{new Date().getTime()}" ).load -> callback(this) if typeof callback == 'function' setVerticalPosition = ($img) -> scale_height = width / $img.data('aspect-ratio') if scale_height >= height $img.css top: -(scale_height - height) / 2 else $img.css top: 0 setHorizontalPosition = ($img) -> scale_width = height * $img.data('aspect-ratio') if scale_width >= width $img.css left: -(scale_width - width) / 2 else $img.css left: 0 adjustImagePosition = ($img) => unless $img.data('aspect-ratio') loadImage $img, (image) -> $img.removeAttr('width').removeAttr('height') $img.data('aspect-ratio', image.width / image.height) adjustImagePosition $img return if (width / height) >= $img.data('aspect-ratio') $img.css height: "auto" width: "100%" else $img.css height: "100%" width: "auto" setHorizontalPosition($img) setVerticalPosition($img) adjustSlidesSize = ($el) => $el.each (i) -> $(this).width(width).height(height) $(this).css left: width adjustImagePosition $('img', this).not(".#{that.options.classes.preserve}") findMultiplier = => if @size() == 1 then 1 else 3 next = => index = @current + 1 index = 0 if (index == @size()) index prev = => index = @current - 1 index = @size() - 1 if index < 0 index upcomingSlide = (direction) => switch true when /next/.test(direction) next() when /prev/.test(direction) prev() when /\d/.test(direction) direction else #bogus false parseHash = (hash = window.location.hash) => hash = hash.replace(/^#/, '') +hash if hash positions = (current = -1) => if init && @current >= 0 current = @current if current < 0 @current = current @next = next() @prev = prev() false animator = (direction, callback) => upcoming_slide = upcomingSlide(direction) return if upcoming_slide > @size() - 1 position = width * 2 offset = -position outgoing_slide = @current if direction == 'prev' or direction < outgoing_slide position = 0 offset = 0 upcoming_position = position $children .removeClass('current') .eq(upcoming_slide) .addClass('current') .css left: upcoming_position display: 'block' $pagination.children() .removeClass('current') .eq(upcoming_slide) .addClass('current') $control.animate useTranslate3d: @mobile left: offset , @options.slide_speed , @options.slide_easing , => positions(upcoming_slide) if @size() > 1 $control.css left: -width $children.eq(upcoming_slide).css left: width zIndex: 2 # reset last slide if outgoing_slide >= 0 $children.eq(outgoing_slide).css left: width display: 'none' zIndex: 0 if @options.hashchange window.location.hash = @current callback() if typeof callback == 'function' setupNextPrev() @animating = false if init $container.trigger('animated.slides') else init = true $('body').css('overflow', 'visible') $container.fadeIn('fast') $container.trigger('init.slides') # Public @$el = $(el) @animate = (direction = 'next', callback) => return if @animating @animating = true animator(direction, callback) @update = => $children = $container.children() adjustSlidesSize($children) setupChildren() setupImageCSS() $children.eq(@current).css( display: 'block' ) positions(@current) addPagination() toggleNav() $container.trigger('updated.slides') @destroy = => $(el).removeData() @size = => $container.children().length @stop = => clearInterval @play_id delete @play_id $container.trigger('stopped.slides') @start = => setupChildren() $window.trigger 'hashchange' if @options.hashchange @animate 'next' if @options.play @stop() if @play_id @play_id = setInterval => @animate 'next' , @options.play $container.trigger('started.slides') # Events $window .on 'hashchange', (e) => index = parseHash() if index >= 0 && index != @current @animate index .on 'resize', (e) -> width = $window.width() height = $window.height() setupContainers() adjustSlidesSize $children $('body').css overflow: 'visible' $(document) .on 'click', ".#{@options.classes.nav} a", (e) -> e.preventDefault() unless that.options.hashchange that.stop() if $(this).hasClass('next') that.animate 'next' else that.animate 'prev' .on 'click', ".#{@options.classes.pagination} a", (e) -> unless that.options.hashchange e.preventDefault() index = parseHash(this.hash) that.animate index initialize() # Plugin $.fn[plugin] = (option, args) -> result = [] @each -> $this = $(this) data = $this.data(plugin) options = typeof option == 'object' && option result = $this.data plugin, (data = new Superslides(this, options)) unless data if typeof option == "string" result = data[option] if typeof result == 'function' result = result.call(this, args) result
145500
### Superslides https://github.com/nicinabox/superslides Copyright (c) 2013 <NAME>; Licensed MIT ### plugin = 'superslides' $ = jQuery Superslides = (el, options = {}) -> @options = $.extend play: false slide_speed: 'normal' slide_easing: 'linear' pagination: true hashchange: false scrollable: true classes: preserve: 'preserve' nav: 'slides-navigation' container: 'slides-container' pagination: 'slides-pagination' , options that = this $window = $(window) @el = $(el) $container = $(".#{@options.classes.container}", el) $children = $container.children() $pagination = $("<nav>", class: @options.classes.pagination) $control = $('<div>', class: 'slides-control') multiplier = 1 init = false width = $window.width() height = $window.height() # Private initialize = => return if init multiplier = findMultiplier() positions() @mobile = (/mobile/i).test(navigator.userAgent) $control = $container.wrap($control).parent('.slides-control') setupCss() setupContainers() toggleNav() addPagination() @start() this setupCss = => $('body').css margin: 0 @el.css position: 'relative' overflowX: 'hidden' width: '100%' $control.css position: 'relative' transform: 'translate3d(0)' $container.css display: 'none' margin: '0' padding: '0' listStyle: 'none' position: 'relative' setupImageCSS() setupImageCSS = => $container.find('img').not(".#{@options.classes.preserve}").css "-webkit-backface-visibility": 'hidden' "-ms-interpolation-mode": 'bicubic' "position": 'absolute' "left": '0' "top": '0' "z-index": '-1' setupContainers = => $('body').css margin: 0 overflow: 'hidden' @el.css height: height $control.css width: width * multiplier left: -width if @options.scrollable $children.each -> return if $('.scrollable', this).length $(this).wrapInner('<div class="scrollable" />'); $(this).find('img').not(".#{_this.options.classes.preserve}") .insertBefore($('.scrollable', this)); setupChildren = => if $children.is('img') $children.wrap('<div>') $children = $container.children() $container.children().css display: 'none' position: 'absolute' overflow: 'hidden' top: 0 left: width zIndex: 0 adjustSlidesSize $children toggleNav = => if @size() > 1 $(".#{@options.classes.nav}").show() else $(".#{@options.classes.nav}").hide() setupNextPrev = => $(".#{@options.classes.nav} a").each -> if $(this).hasClass('next') this.hash = that.next else this.hash = that.prev addPaginationItem = (i) => unless i >= 0 i = @size() - 1 # size is not zero indexed $pagination.append $("<a>", href: "##{i}" class: "current" if @current == $pagination.children().length ) addPagination = => return if !@options.pagination or @size() == 1 if $(el).find(".#{@options.classes.pagination}").length next_index = $pagination.children().last().index() + 1 array = $container.children() array = array.slice(next_index) else next_index = 0 array = new Array(@size() - next_index) $pagination = $pagination.appendTo(@el) $.each array, (i) -> addPaginationItem(i + next_index) loadImage = ($img, callback) => $("<img>", src: "#{$img.attr('src')}?#{new Date().getTime()}" ).load -> callback(this) if typeof callback == 'function' setVerticalPosition = ($img) -> scale_height = width / $img.data('aspect-ratio') if scale_height >= height $img.css top: -(scale_height - height) / 2 else $img.css top: 0 setHorizontalPosition = ($img) -> scale_width = height * $img.data('aspect-ratio') if scale_width >= width $img.css left: -(scale_width - width) / 2 else $img.css left: 0 adjustImagePosition = ($img) => unless $img.data('aspect-ratio') loadImage $img, (image) -> $img.removeAttr('width').removeAttr('height') $img.data('aspect-ratio', image.width / image.height) adjustImagePosition $img return if (width / height) >= $img.data('aspect-ratio') $img.css height: "auto" width: "100%" else $img.css height: "100%" width: "auto" setHorizontalPosition($img) setVerticalPosition($img) adjustSlidesSize = ($el) => $el.each (i) -> $(this).width(width).height(height) $(this).css left: width adjustImagePosition $('img', this).not(".#{that.options.classes.preserve}") findMultiplier = => if @size() == 1 then 1 else 3 next = => index = @current + 1 index = 0 if (index == @size()) index prev = => index = @current - 1 index = @size() - 1 if index < 0 index upcomingSlide = (direction) => switch true when /next/.test(direction) next() when /prev/.test(direction) prev() when /\d/.test(direction) direction else #bogus false parseHash = (hash = window.location.hash) => hash = hash.replace(/^#/, '') +hash if hash positions = (current = -1) => if init && @current >= 0 current = @current if current < 0 @current = current @next = next() @prev = prev() false animator = (direction, callback) => upcoming_slide = upcomingSlide(direction) return if upcoming_slide > @size() - 1 position = width * 2 offset = -position outgoing_slide = @current if direction == 'prev' or direction < outgoing_slide position = 0 offset = 0 upcoming_position = position $children .removeClass('current') .eq(upcoming_slide) .addClass('current') .css left: upcoming_position display: 'block' $pagination.children() .removeClass('current') .eq(upcoming_slide) .addClass('current') $control.animate useTranslate3d: @mobile left: offset , @options.slide_speed , @options.slide_easing , => positions(upcoming_slide) if @size() > 1 $control.css left: -width $children.eq(upcoming_slide).css left: width zIndex: 2 # reset last slide if outgoing_slide >= 0 $children.eq(outgoing_slide).css left: width display: 'none' zIndex: 0 if @options.hashchange window.location.hash = @current callback() if typeof callback == 'function' setupNextPrev() @animating = false if init $container.trigger('animated.slides') else init = true $('body').css('overflow', 'visible') $container.fadeIn('fast') $container.trigger('init.slides') # Public @$el = $(el) @animate = (direction = 'next', callback) => return if @animating @animating = true animator(direction, callback) @update = => $children = $container.children() adjustSlidesSize($children) setupChildren() setupImageCSS() $children.eq(@current).css( display: 'block' ) positions(@current) addPagination() toggleNav() $container.trigger('updated.slides') @destroy = => $(el).removeData() @size = => $container.children().length @stop = => clearInterval @play_id delete @play_id $container.trigger('stopped.slides') @start = => setupChildren() $window.trigger 'hashchange' if @options.hashchange @animate 'next' if @options.play @stop() if @play_id @play_id = setInterval => @animate 'next' , @options.play $container.trigger('started.slides') # Events $window .on 'hashchange', (e) => index = parseHash() if index >= 0 && index != @current @animate index .on 'resize', (e) -> width = $window.width() height = $window.height() setupContainers() adjustSlidesSize $children $('body').css overflow: 'visible' $(document) .on 'click', ".#{@options.classes.nav} a", (e) -> e.preventDefault() unless that.options.hashchange that.stop() if $(this).hasClass('next') that.animate 'next' else that.animate 'prev' .on 'click', ".#{@options.classes.pagination} a", (e) -> unless that.options.hashchange e.preventDefault() index = parseHash(this.hash) that.animate index initialize() # Plugin $.fn[plugin] = (option, args) -> result = [] @each -> $this = $(this) data = $this.data(plugin) options = typeof option == 'object' && option result = $this.data plugin, (data = new Superslides(this, options)) unless data if typeof option == "string" result = data[option] if typeof result == 'function' result = result.call(this, args) result
true
### Superslides https://github.com/nicinabox/superslides Copyright (c) 2013 PI:NAME:<NAME>END_PI; Licensed MIT ### plugin = 'superslides' $ = jQuery Superslides = (el, options = {}) -> @options = $.extend play: false slide_speed: 'normal' slide_easing: 'linear' pagination: true hashchange: false scrollable: true classes: preserve: 'preserve' nav: 'slides-navigation' container: 'slides-container' pagination: 'slides-pagination' , options that = this $window = $(window) @el = $(el) $container = $(".#{@options.classes.container}", el) $children = $container.children() $pagination = $("<nav>", class: @options.classes.pagination) $control = $('<div>', class: 'slides-control') multiplier = 1 init = false width = $window.width() height = $window.height() # Private initialize = => return if init multiplier = findMultiplier() positions() @mobile = (/mobile/i).test(navigator.userAgent) $control = $container.wrap($control).parent('.slides-control') setupCss() setupContainers() toggleNav() addPagination() @start() this setupCss = => $('body').css margin: 0 @el.css position: 'relative' overflowX: 'hidden' width: '100%' $control.css position: 'relative' transform: 'translate3d(0)' $container.css display: 'none' margin: '0' padding: '0' listStyle: 'none' position: 'relative' setupImageCSS() setupImageCSS = => $container.find('img').not(".#{@options.classes.preserve}").css "-webkit-backface-visibility": 'hidden' "-ms-interpolation-mode": 'bicubic' "position": 'absolute' "left": '0' "top": '0' "z-index": '-1' setupContainers = => $('body').css margin: 0 overflow: 'hidden' @el.css height: height $control.css width: width * multiplier left: -width if @options.scrollable $children.each -> return if $('.scrollable', this).length $(this).wrapInner('<div class="scrollable" />'); $(this).find('img').not(".#{_this.options.classes.preserve}") .insertBefore($('.scrollable', this)); setupChildren = => if $children.is('img') $children.wrap('<div>') $children = $container.children() $container.children().css display: 'none' position: 'absolute' overflow: 'hidden' top: 0 left: width zIndex: 0 adjustSlidesSize $children toggleNav = => if @size() > 1 $(".#{@options.classes.nav}").show() else $(".#{@options.classes.nav}").hide() setupNextPrev = => $(".#{@options.classes.nav} a").each -> if $(this).hasClass('next') this.hash = that.next else this.hash = that.prev addPaginationItem = (i) => unless i >= 0 i = @size() - 1 # size is not zero indexed $pagination.append $("<a>", href: "##{i}" class: "current" if @current == $pagination.children().length ) addPagination = => return if !@options.pagination or @size() == 1 if $(el).find(".#{@options.classes.pagination}").length next_index = $pagination.children().last().index() + 1 array = $container.children() array = array.slice(next_index) else next_index = 0 array = new Array(@size() - next_index) $pagination = $pagination.appendTo(@el) $.each array, (i) -> addPaginationItem(i + next_index) loadImage = ($img, callback) => $("<img>", src: "#{$img.attr('src')}?#{new Date().getTime()}" ).load -> callback(this) if typeof callback == 'function' setVerticalPosition = ($img) -> scale_height = width / $img.data('aspect-ratio') if scale_height >= height $img.css top: -(scale_height - height) / 2 else $img.css top: 0 setHorizontalPosition = ($img) -> scale_width = height * $img.data('aspect-ratio') if scale_width >= width $img.css left: -(scale_width - width) / 2 else $img.css left: 0 adjustImagePosition = ($img) => unless $img.data('aspect-ratio') loadImage $img, (image) -> $img.removeAttr('width').removeAttr('height') $img.data('aspect-ratio', image.width / image.height) adjustImagePosition $img return if (width / height) >= $img.data('aspect-ratio') $img.css height: "auto" width: "100%" else $img.css height: "100%" width: "auto" setHorizontalPosition($img) setVerticalPosition($img) adjustSlidesSize = ($el) => $el.each (i) -> $(this).width(width).height(height) $(this).css left: width adjustImagePosition $('img', this).not(".#{that.options.classes.preserve}") findMultiplier = => if @size() == 1 then 1 else 3 next = => index = @current + 1 index = 0 if (index == @size()) index prev = => index = @current - 1 index = @size() - 1 if index < 0 index upcomingSlide = (direction) => switch true when /next/.test(direction) next() when /prev/.test(direction) prev() when /\d/.test(direction) direction else #bogus false parseHash = (hash = window.location.hash) => hash = hash.replace(/^#/, '') +hash if hash positions = (current = -1) => if init && @current >= 0 current = @current if current < 0 @current = current @next = next() @prev = prev() false animator = (direction, callback) => upcoming_slide = upcomingSlide(direction) return if upcoming_slide > @size() - 1 position = width * 2 offset = -position outgoing_slide = @current if direction == 'prev' or direction < outgoing_slide position = 0 offset = 0 upcoming_position = position $children .removeClass('current') .eq(upcoming_slide) .addClass('current') .css left: upcoming_position display: 'block' $pagination.children() .removeClass('current') .eq(upcoming_slide) .addClass('current') $control.animate useTranslate3d: @mobile left: offset , @options.slide_speed , @options.slide_easing , => positions(upcoming_slide) if @size() > 1 $control.css left: -width $children.eq(upcoming_slide).css left: width zIndex: 2 # reset last slide if outgoing_slide >= 0 $children.eq(outgoing_slide).css left: width display: 'none' zIndex: 0 if @options.hashchange window.location.hash = @current callback() if typeof callback == 'function' setupNextPrev() @animating = false if init $container.trigger('animated.slides') else init = true $('body').css('overflow', 'visible') $container.fadeIn('fast') $container.trigger('init.slides') # Public @$el = $(el) @animate = (direction = 'next', callback) => return if @animating @animating = true animator(direction, callback) @update = => $children = $container.children() adjustSlidesSize($children) setupChildren() setupImageCSS() $children.eq(@current).css( display: 'block' ) positions(@current) addPagination() toggleNav() $container.trigger('updated.slides') @destroy = => $(el).removeData() @size = => $container.children().length @stop = => clearInterval @play_id delete @play_id $container.trigger('stopped.slides') @start = => setupChildren() $window.trigger 'hashchange' if @options.hashchange @animate 'next' if @options.play @stop() if @play_id @play_id = setInterval => @animate 'next' , @options.play $container.trigger('started.slides') # Events $window .on 'hashchange', (e) => index = parseHash() if index >= 0 && index != @current @animate index .on 'resize', (e) -> width = $window.width() height = $window.height() setupContainers() adjustSlidesSize $children $('body').css overflow: 'visible' $(document) .on 'click', ".#{@options.classes.nav} a", (e) -> e.preventDefault() unless that.options.hashchange that.stop() if $(this).hasClass('next') that.animate 'next' else that.animate 'prev' .on 'click', ".#{@options.classes.pagination} a", (e) -> unless that.options.hashchange e.preventDefault() index = parseHash(this.hash) that.animate index initialize() # Plugin $.fn[plugin] = (option, args) -> result = [] @each -> $this = $(this) data = $this.data(plugin) options = typeof option == 'object' && option result = $this.data plugin, (data = new Superslides(this, options)) unless data if typeof option == "string" result = data[option] if typeof result == 'function' result = result.call(this, args) result
[ { "context": "pe.auth.isLoggedIn\n ###\n testData = {username: \"anish\", password: 'something'}\n saHttp.post(saApiEndpo", "end": 651, "score": 0.9996726512908936, "start": 646, "tag": "USERNAME", "value": "anish" }, { "context": " ###\n testData = {username: \"anish\", password: 'something'}\n saHttp.post(saApiEndpoints.echo, testData)\n ", "end": 674, "score": 0.9992116689682007, "start": 665, "tag": "PASSWORD", "value": "something" } ]
js/controllers/test.coffee
bassoGeorge/shuttle-up-2015
0
angular.module 'shuttleApp.controllers' .controller 'TestController', ($scope, $modal, $aside, toastr, $log, saApiEndpoints, saEncPass saHttp) -> $scope.openModal = () -> $modal.open( templateUrl: 'templates/modals/modal_test.html' ) $scope.openSide = () -> $aside.open({ templateUrl: 'templates/modals/modal_test.html' placement: 'left' size: 'sm' }) $scope.toast = () -> toastr.success("Yes, we have done it!!!") $scope.toggleLogin = () -> $scope.auth.isLoggedIn = not $scope.auth.isLoggedIn ### testData = {username: "anish", password: 'something'} saHttp.post(saApiEndpoints.echo, testData) .success (d) -> $log.info "Got back result from echo: "+JSON.stringify(d) ###
54617
angular.module 'shuttleApp.controllers' .controller 'TestController', ($scope, $modal, $aside, toastr, $log, saApiEndpoints, saEncPass saHttp) -> $scope.openModal = () -> $modal.open( templateUrl: 'templates/modals/modal_test.html' ) $scope.openSide = () -> $aside.open({ templateUrl: 'templates/modals/modal_test.html' placement: 'left' size: 'sm' }) $scope.toast = () -> toastr.success("Yes, we have done it!!!") $scope.toggleLogin = () -> $scope.auth.isLoggedIn = not $scope.auth.isLoggedIn ### testData = {username: "anish", password: '<PASSWORD>'} saHttp.post(saApiEndpoints.echo, testData) .success (d) -> $log.info "Got back result from echo: "+JSON.stringify(d) ###
true
angular.module 'shuttleApp.controllers' .controller 'TestController', ($scope, $modal, $aside, toastr, $log, saApiEndpoints, saEncPass saHttp) -> $scope.openModal = () -> $modal.open( templateUrl: 'templates/modals/modal_test.html' ) $scope.openSide = () -> $aside.open({ templateUrl: 'templates/modals/modal_test.html' placement: 'left' size: 'sm' }) $scope.toast = () -> toastr.success("Yes, we have done it!!!") $scope.toggleLogin = () -> $scope.auth.isLoggedIn = not $scope.auth.isLoggedIn ### testData = {username: "anish", password: 'PI:PASSWORD:<PASSWORD>END_PI'} saHttp.post(saApiEndpoints.echo, testData) .success (d) -> $log.info "Got back result from echo: "+JSON.stringify(d) ###
[ { "context": ")\n parent_id = el.data('taxon-id')\n name = 'New node'\n child_index = 0\n @create_taxon({name", "end": 2028, "score": 0.8567935228347778, "start": 2025, "tag": "NAME", "value": "New" }, { "context": "create: (e) ->\n e.preventDefault()\n name = 'New node'\n parent_id = this.model.get(\"root\").id\n ", "end": 2168, "score": 0.9102048277854919, "start": 2165, "tag": "NAME", "value": "New" } ]
backend/app/assets/javascripts/spree/backend/taxonomy.js.coffee
vexus2/solidus
0
Handlebars.registerHelper 'isRootTaxon', -> !@parent_id? TaxonTreeView = Backbone.View.extend create_taxon: ({name, parent_id, child_index}) -> Spree.ajax type: "POST", dataType: "json", url: "#{this.model.url()}/taxons", data: taxon: {name, parent_id, child_index} complete: @redraw_tree update_taxon: ({id, parent_id, child_index}) -> Spree.ajax type: "PUT" dataType: "json" url: "#{this.model.url()}/taxons/#{id}", data: taxon: {parent_id, child_index} error: @redraw_tree delete_taxon: ({id}) -> Spree.ajax type: "DELETE" dataType: "json" url: "#{this.model.url()}/taxons/#{id}", error: @redraw_tree render: -> taxons_template = HandlebarsTemplates["taxons/tree"] this.$el .html( taxons_template({ taxons: [this.model.get("root")] }) ) .find('ul') .sortable connectWith: '#taxonomy_tree ul' placeholder: 'sortable-placeholder ui-state-highlight' tolerance: 'pointer' cursorAt: { left: 5 } redraw_tree: -> this.model.fetch({ url: this.model.url() + '?set=nested' }) resize_placeholder: (e, ui) -> handleHeight = ui.helper.find('.sortable-handle').outerHeight() ui.placeholder.height(handleHeight) restore_sort_targets: -> $('.ui-sortable-over').removeClass('ui-sortable-over') highlight_sort_targets: (e, ui) -> @restore_sort_targets() ui.placeholder.parents('ul').addClass('ui-sortable-over') handle_move: (e, ui) -> return if ui.sender? el = ui.item @update_taxon id: el.data('taxon-id') parent_id: el.parent().closest('li').data('taxon-id') child_index: el.index() handle_delete: (e) -> el = $(e.target).closest('li') if confirm(Spree.translations.are_you_sure_delete) @delete_taxon({id: el.data('taxon-id')}) el.remove() handle_add_child: (e) -> el = $(e.target).closest('li') parent_id = el.data('taxon-id') name = 'New node' child_index = 0 @create_taxon({name, parent_id, child_index}) handle_create: (e) -> e.preventDefault() name = 'New node' parent_id = this.model.get("root").id child_index = 0 @create_taxon({name, parent_id, child_index}) events: { 'sortstart': 'resize_placeholder', 'sortover': 'highlight_sort_targets', 'sortstop': 'restore_sort_targets', 'sortupdate': 'handle_move', 'click .js-taxon-delete': 'handle_delete', 'click .js-taxon-add-child': 'handle_add_child', } initialize: -> _.bindAll(this, 'redraw_tree', 'handle_create') $('.add-taxon-button').on('click', @handle_create) this.listenTo(this.model, 'sync', this.render) @redraw_tree() $ -> if $('#taxonomy_tree').length model = new Spree.Models.Taxonomy({id: $('#taxonomy_tree').data("taxonomy-id")}) new TaxonTreeView el: $('#taxonomy_tree') model: model
13163
Handlebars.registerHelper 'isRootTaxon', -> !@parent_id? TaxonTreeView = Backbone.View.extend create_taxon: ({name, parent_id, child_index}) -> Spree.ajax type: "POST", dataType: "json", url: "#{this.model.url()}/taxons", data: taxon: {name, parent_id, child_index} complete: @redraw_tree update_taxon: ({id, parent_id, child_index}) -> Spree.ajax type: "PUT" dataType: "json" url: "#{this.model.url()}/taxons/#{id}", data: taxon: {parent_id, child_index} error: @redraw_tree delete_taxon: ({id}) -> Spree.ajax type: "DELETE" dataType: "json" url: "#{this.model.url()}/taxons/#{id}", error: @redraw_tree render: -> taxons_template = HandlebarsTemplates["taxons/tree"] this.$el .html( taxons_template({ taxons: [this.model.get("root")] }) ) .find('ul') .sortable connectWith: '#taxonomy_tree ul' placeholder: 'sortable-placeholder ui-state-highlight' tolerance: 'pointer' cursorAt: { left: 5 } redraw_tree: -> this.model.fetch({ url: this.model.url() + '?set=nested' }) resize_placeholder: (e, ui) -> handleHeight = ui.helper.find('.sortable-handle').outerHeight() ui.placeholder.height(handleHeight) restore_sort_targets: -> $('.ui-sortable-over').removeClass('ui-sortable-over') highlight_sort_targets: (e, ui) -> @restore_sort_targets() ui.placeholder.parents('ul').addClass('ui-sortable-over') handle_move: (e, ui) -> return if ui.sender? el = ui.item @update_taxon id: el.data('taxon-id') parent_id: el.parent().closest('li').data('taxon-id') child_index: el.index() handle_delete: (e) -> el = $(e.target).closest('li') if confirm(Spree.translations.are_you_sure_delete) @delete_taxon({id: el.data('taxon-id')}) el.remove() handle_add_child: (e) -> el = $(e.target).closest('li') parent_id = el.data('taxon-id') name = '<NAME> node' child_index = 0 @create_taxon({name, parent_id, child_index}) handle_create: (e) -> e.preventDefault() name = '<NAME> node' parent_id = this.model.get("root").id child_index = 0 @create_taxon({name, parent_id, child_index}) events: { 'sortstart': 'resize_placeholder', 'sortover': 'highlight_sort_targets', 'sortstop': 'restore_sort_targets', 'sortupdate': 'handle_move', 'click .js-taxon-delete': 'handle_delete', 'click .js-taxon-add-child': 'handle_add_child', } initialize: -> _.bindAll(this, 'redraw_tree', 'handle_create') $('.add-taxon-button').on('click', @handle_create) this.listenTo(this.model, 'sync', this.render) @redraw_tree() $ -> if $('#taxonomy_tree').length model = new Spree.Models.Taxonomy({id: $('#taxonomy_tree').data("taxonomy-id")}) new TaxonTreeView el: $('#taxonomy_tree') model: model
true
Handlebars.registerHelper 'isRootTaxon', -> !@parent_id? TaxonTreeView = Backbone.View.extend create_taxon: ({name, parent_id, child_index}) -> Spree.ajax type: "POST", dataType: "json", url: "#{this.model.url()}/taxons", data: taxon: {name, parent_id, child_index} complete: @redraw_tree update_taxon: ({id, parent_id, child_index}) -> Spree.ajax type: "PUT" dataType: "json" url: "#{this.model.url()}/taxons/#{id}", data: taxon: {parent_id, child_index} error: @redraw_tree delete_taxon: ({id}) -> Spree.ajax type: "DELETE" dataType: "json" url: "#{this.model.url()}/taxons/#{id}", error: @redraw_tree render: -> taxons_template = HandlebarsTemplates["taxons/tree"] this.$el .html( taxons_template({ taxons: [this.model.get("root")] }) ) .find('ul') .sortable connectWith: '#taxonomy_tree ul' placeholder: 'sortable-placeholder ui-state-highlight' tolerance: 'pointer' cursorAt: { left: 5 } redraw_tree: -> this.model.fetch({ url: this.model.url() + '?set=nested' }) resize_placeholder: (e, ui) -> handleHeight = ui.helper.find('.sortable-handle').outerHeight() ui.placeholder.height(handleHeight) restore_sort_targets: -> $('.ui-sortable-over').removeClass('ui-sortable-over') highlight_sort_targets: (e, ui) -> @restore_sort_targets() ui.placeholder.parents('ul').addClass('ui-sortable-over') handle_move: (e, ui) -> return if ui.sender? el = ui.item @update_taxon id: el.data('taxon-id') parent_id: el.parent().closest('li').data('taxon-id') child_index: el.index() handle_delete: (e) -> el = $(e.target).closest('li') if confirm(Spree.translations.are_you_sure_delete) @delete_taxon({id: el.data('taxon-id')}) el.remove() handle_add_child: (e) -> el = $(e.target).closest('li') parent_id = el.data('taxon-id') name = 'PI:NAME:<NAME>END_PI node' child_index = 0 @create_taxon({name, parent_id, child_index}) handle_create: (e) -> e.preventDefault() name = 'PI:NAME:<NAME>END_PI node' parent_id = this.model.get("root").id child_index = 0 @create_taxon({name, parent_id, child_index}) events: { 'sortstart': 'resize_placeholder', 'sortover': 'highlight_sort_targets', 'sortstop': 'restore_sort_targets', 'sortupdate': 'handle_move', 'click .js-taxon-delete': 'handle_delete', 'click .js-taxon-add-child': 'handle_add_child', } initialize: -> _.bindAll(this, 'redraw_tree', 'handle_create') $('.add-taxon-button').on('click', @handle_create) this.listenTo(this.model, 'sync', this.render) @redraw_tree() $ -> if $('#taxonomy_tree').length model = new Spree.Models.Taxonomy({id: $('#taxonomy_tree').data("taxonomy-id")}) new TaxonTreeView el: $('#taxonomy_tree') model: model
[ { "context": "equire 'mongoose'\n\nFactory.userData = {\n email: 'zap@brannigan.com'\n first_name: 'Zapp'\n last_name: 'Brannigan'\n ", "end": 140, "score": 0.9999296069145203, "start": 123, "tag": "EMAIL", "value": "zap@brannigan.com" }, { "context": "a = {\n email: 'zap@brannigan.com'\n first_name: 'Zapp'\n last_name: 'Brannigan'\n role: 'Captain'\n}\n\nif", "end": 161, "score": 0.9997942447662354, "start": 157, "tag": "NAME", "value": "Zapp" }, { "context": "brannigan.com'\n first_name: 'Zapp'\n last_name: 'Brannigan'\n role: 'Captain'\n}\n\nif Factory.connected = mong", "end": 186, "score": 0.9995342493057251, "start": 177, "tag": "NAME", "value": "Brannigan" } ]
test/helpers/factory.coffee
HarvestJS/crud-intro
1
Factory = require 'factory-worker' require '../../app/user' mongoose = require 'mongoose' Factory.userData = { email: 'zap@brannigan.com' first_name: 'Zapp' last_name: 'Brannigan' role: 'Captain' } if Factory.connected = mongoose?.connections?[0]?.collections?.users {User} = mongoose.models Factory.define 'user', User, Factory.userData module.exports = Factory
141646
Factory = require 'factory-worker' require '../../app/user' mongoose = require 'mongoose' Factory.userData = { email: '<EMAIL>' first_name: '<NAME>' last_name: '<NAME>' role: 'Captain' } if Factory.connected = mongoose?.connections?[0]?.collections?.users {User} = mongoose.models Factory.define 'user', User, Factory.userData module.exports = Factory
true
Factory = require 'factory-worker' require '../../app/user' mongoose = require 'mongoose' Factory.userData = { email: 'PI:EMAIL:<EMAIL>END_PI' first_name: 'PI:NAME:<NAME>END_PI' last_name: 'PI:NAME:<NAME>END_PI' role: 'Captain' } if Factory.connected = mongoose?.connections?[0]?.collections?.users {User} = mongoose.models Factory.define 'user', User, Factory.userData module.exports = Factory
[ { "context": "nel = null\nSEP_IID = 'SEP1'\nIID = 'A1'\nCONNKEY = '123456'\nEXPECTED_REPLY = 'Hello'\nEXPECTED_PAYLOAD = 'Mor", "end": 1819, "score": 0.999522864818573, "start": 1813, "tag": "KEY", "value": "123456" }, { "context": "ay(100)\n # When ...\n # Sec-WebSocket-Key = HdBhQ5Lz9JV8S+/7PC3bCw=='\n # sec-websocket-accept = Teu0yrJZBLH0+gJYYr", "end": 10154, "score": 0.9867275357246399, "start": 10129, "tag": "KEY", "value": "HdBhQ5Lz9JV8S+/7PC3bCw=='" }, { "context": "+/7PC3bCw=='\n # sec-websocket-accept = Teu0yrJZBLH0+gJYYr3MPaqqUL8=\\r\\n\\r\\n'\n # ... then, the we", "end": 10196, "score": 0.5500013828277588, "start": 10192, "tag": "KEY", "value": "JZBL" }, { "context": "Socket-Version': 13\n 'Sec-WebSocket-Key': 'HdBhQ5Lz9JV8S+/7PC3bCw=='\n return JSON.stringify {\n protocol: prot\n ", "end": 15849, "score": 0.9994764924049377, "start": 15824, "tag": "KEY", "value": "HdBhQ5Lz9JV8S+/7PC3bCw=='" } ]
tests/http-message.test.coffee
kumori-systems/http-message
0
http = require '../src/index' q = require 'q' net = require 'net' EventEmitter = require('events').EventEmitter should = require 'should' supertest = require 'supertest' WebSocketServer = require('websocket').server #### START: ENABLE LOG LINES FOR DEBUGGING #### # This will show all log lines in the code if the test are executed with # DEBUG="kumori:*" set in the environment. For example, running: # # $ DEBUG="kumori:*" npm test # debug = require 'debug' # debug.enable 'kumori:*' # debug.enable 'kumori:info, kumori:debug' debug.log = () -> console.log arguments... #### END: ENABLE LOG LINES FOR DEBUGGING #### #------------------------------------------------------------------------------- class Reply extends EventEmitter @dynCount = 0 constructor: (@name, iid) -> @config = {} @runtimeAgent = { config: { iid: iid }, createChannel: () -> return new Reply("dyn_rep_#{Reply.dynCount++}", iid) } setConfig: () -> handleRequest: () -> throw new Error 'NOT IMPLEMENTED' #------------------------------------------------------------------------------- class Request extends EventEmitter constructor: (@name, iid) -> @sentMessages = [] @config = {} @runtimeAgent = { config: { iid: iid } } sendRequest: (message) -> @sentMessages.push message return q.promise (resolve, reject) -> resolve [{status: 'OK'}] reject 'NOT IMPLEMENTED' setConfig: () -> resetSentMesages: () -> @sentMessages = [] getLastSentMessage: () -> return @sentMessages.pop() #------------------------------------------------------------------------------- httpMessageServer = null wsServer = null replyChannel = null dynReplyChannel = null dynRequestChannel = null SEP_IID = 'SEP1' IID = 'A1' CONNKEY = '123456' EXPECTED_REPLY = 'Hello' EXPECTED_PAYLOAD = 'More data' reqIdCount = 1 describe 'http-message test', -> before (done) -> httpMessageServer = http.createServer() httpMessageServer.on 'error', (err) -> @logger.warn "httpMessageServer.on error = #{err.message}" replyChannel = new Reply('main_rep_channel', IID) dynRequestChannel = new Request('dyn_req', IID) done() after (done) -> if httpMessageServer? then httpMessageServer.close() if wsServer? then wsServer.shutDown() done() it 'Listen', (done) -> httpMessageServer.listen replyChannel httpMessageServer.on 'listening', () -> done() it 'Send an invalid request', (done) -> request = JSON.stringify { type: 'XXX' fromInstance: IID } replyChannel.handleRequest([request], [dynRequestChannel]) .then (message) -> done new Error 'Expected <invalid request type> error' .fail (err) -> done() undefined it 'Establish dynamic channel', () -> request = JSON.stringify { type: 'getDynChannel' fromInstance: SEP_IID } replyChannel.handleRequest([request], [dynRequestChannel]) .then (message) -> reply = message[0][0] # when test, we dont receive a "status" segment reply.should.be.eql IID dynReplyChannel = message[1][0] dynReplyChannel.constructor.name.should.be.eql 'Reply' dynReplyChannel.name.should.be.eql 'dyn_rep_0' it 'Process a request', () -> httpMessageServer.once 'request', (req, res) -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r1.data.headers.instancespath.should.be.eql ",iid=#{IID}" r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Process a request with payload', () -> httpMessageServer.once 'request', (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> data.should.be.eql EXPECTED_PAYLOAD res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Process an aborted request with payload', (done) -> httpMessageServer.once 'request', (req, res) -> req.on 'aborted', () -> done() req.on 'end', () -> done new Error 'Aborted expected' reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> m3 = _createMessage 'http', 'aborted', reqId dynReplyChannel.handleRequest [m3] undefined it 'Fail a request because timeout', () -> httpMessageServer.once 'request', (req, res) -> q.delay(1000) .then () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() dynRequestChannel.resetSentMesages() httpMessageServer.setTimeout 500 reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] .then () -> q.delay(1000) .then () -> last = dynRequestChannel.getLastSentMessage()[0] JSON.parse(last).type.should.be.eql 'error' it 'Interleave a correct request and a timeout request', (done) -> processRequest = (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> if data is 'normal request' then sleep = 200 else if data is 'timeout request' then sleep = 600 else done Error "Invalid test request type: #{data}" q.delay(sleep) .then () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() httpMessageServer.on 'request', processRequest httpMessageServer.setTimeout 500 dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, 'timeout request'] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .fail (err) -> done err setTimeout () -> reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, 'normal request'] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .fail (err) -> done err , 400 setTimeout () -> next = () -> return JSON.parse(dynRequestChannel.getLastSentMessage()[0]) next().type.should.be.eql 'end' next().type.should.be.eql 'data' next().type.should.be.eql 'response' next().type.should.be.eql 'error' httpMessageServer.removeListener 'request', processRequest done() , 1000 it 'Upgrade current connection to websocket and use it', (done) -> wsServer = new WebSocketServer { httpServer: httpMessageServer autoAccepConnections: false keepalive: true } wsReceivedMessages = 0 wsServer.on 'error', (err) -> done err wsServer.on 'request', (request) -> try conn = request.accept() conn.on 'error', (err) -> done err conn.on 'message', (message) -> wsReceivedMessages++ conn.sendUTF "echo_#{message.utf8Data}" conn.close() conn.on 'close', () -> # do nothing catch err done err dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'ws', 'upgrade', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> q.delay(100) .then () -> [received, receivedData] = dynRequestChannel.getLastSentMessage() expected = 'HTTP/1.1 101 Switching Protocols\r\n\ upgrade: websocket\r\n\ connection: Upgrade\r\n\ sec-websocket-accept: Teu0yrJZBLH0+gJYYr3MPaqqUL8=\r\n\r\n' receivedData.should.be.equal expected q.delay(100) # When ... # Sec-WebSocket-Key = HdBhQ5Lz9JV8S+/7PC3bCw==' # sec-websocket-accept = Teu0yrJZBLH0+gJYYr3MPaqqUL8=\r\n\r\n' # ... then, the websocket frame for text 'hello', is: # <Buffer 81 85 40 78 5a 9d 28 1d 36 f1 2f> # (value sniffed from a websocket server) # WsServer responses with 'echo_hello' and close connection (normal # connection closure). # The websocket frame for response 'echo_hello' + close is: # <Buffer 81 0a 65 63 68 6f 5f 68 65 6c 6c 6f 88 1b 03 e8 4e 6f 72 6d # 61 6c 20 63 6f 6e 6e 65 63 74 69 6f 6e 20 63 6c 6f 73 75 72 65> .then () -> dynRequestChannel.resetSentMesages() m2 = _createMessage 'ws', 'data', reqId helloBuffer = new Buffer([0x81, 0x85, 0x40, 0x78, 0x5a, 0x9d, 0x28, \ 0x1d, 0x36, 0xf1, 0x2f]) dynReplyChannel.handleRequest [m2, helloBuffer] q.delay(100) .then () -> # We checked that 'echo_hello' + close has arrived [received, receivedData] = dynRequestChannel.getLastSentMessage() echohelloBuffer = new Buffer([0x81, 0x0a, 0x65, 0x63, 0x68, 0x6f, 0x5f, \ 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x88, 0x1b, \ 0x03, 0xe8, 0x4e, 0x6f, 0x72, 0x6d, 0x61, \ 0x6c, 0x20, 0x63, 0x6f, 0x6e, 0x6e, 0x65, \ 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x63, \ 0x6c, 0x6f, 0x73, 0x75, 0x72, 0x65]) [received, receivedData] = dynRequestChannel.getLastSentMessage() receivedData.should.eql(echohelloBuffer) wsReceivedMessages.should.eql 1 # This message will not arrive, since the connection is closed. m3 = _createMessage 'ws', 'data', reqId helloBuffer2 = new Buffer([0x81, 0x85, 0x40, 0x78, 0x5a, 0x9d, 0x28, \ 0x1d, 0x36, 0xf1, 0x2f]) dynReplyChannel.handleRequest [m3, helloBuffer2] q.delay(100) .then () -> # We checked that the previous message hasn't arrived. wsReceivedMessages.should.eql 1 done() .fail (err) -> done err undefined it 'Process a request setting content-lengt (ticket 656)', () -> httpMessageServer.once 'request', (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> data.should.be.eql EXPECTED_PAYLOAD res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() reqId = "#{reqIdCount++}" contentLength = EXPECTED_PAYLOAD.length m1 = _createMessage 'http', 'request', reqId, 'post', false, contentLength dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> # Force ticket656 q.delay(250) .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Force garbage request collector', (done) -> @timeout(5000) httpMessageServer._startGarbageRequests(1000) httpMessageServer.setTimeout(4000) httpMessageServer.once 'garbageRequests', (numRequests) -> numRequests.should.be.eql 1 done() httpMessageServer.once 'request', (req, res) -> setTimeout () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() , 2000 # Force garbage requests dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] undefined it 'Several ServerMessage objects instances', (done) -> # Ticket920 CONCURRENT_SERVERS = 3 servers = [] completedListen = 0 createServer = () -> server = http.createServer() server.on 'error', (err) -> done err server.repChann = new Reply('main_rep_channel_' + servers.length, IID) servers.push server onListen = () -> completedListen++ if completedListen is servers.length server.close() for server in servers done() createServer() for i in [1 .. CONCURRENT_SERVERS] server.listen server.repChann, onListen for server in servers _createMessage = (prot, type, reqId, method, use_instancespath, datalength) -> if prot is 'http' and type is 'request' requestData = protocol: 'http' url: '/' method: method headers: host:"localhost:8080", #connection:"keep-alive" if use_instancespath? then requestData.headers.instancespath = '' if datalength? then requestData.headers['content-length'] = datalength else if prot is 'ws' and type is 'upgrade' requestData = protocol: 'http' url: '/' method: method headers: Upgrade: 'websocket' Connection: 'Upgrade' 'Sec-WebSocket-Version': 13 'Sec-WebSocket-Key': 'HdBhQ5Lz9JV8S+/7PC3bCw==' return JSON.stringify { protocol: prot type: type domain: 'uno.empresa.es' fromInstance: SEP_IID connKey: CONNKEY reqId: reqId data: requestData }
8117
http = require '../src/index' q = require 'q' net = require 'net' EventEmitter = require('events').EventEmitter should = require 'should' supertest = require 'supertest' WebSocketServer = require('websocket').server #### START: ENABLE LOG LINES FOR DEBUGGING #### # This will show all log lines in the code if the test are executed with # DEBUG="kumori:*" set in the environment. For example, running: # # $ DEBUG="kumori:*" npm test # debug = require 'debug' # debug.enable 'kumori:*' # debug.enable 'kumori:info, kumori:debug' debug.log = () -> console.log arguments... #### END: ENABLE LOG LINES FOR DEBUGGING #### #------------------------------------------------------------------------------- class Reply extends EventEmitter @dynCount = 0 constructor: (@name, iid) -> @config = {} @runtimeAgent = { config: { iid: iid }, createChannel: () -> return new Reply("dyn_rep_#{Reply.dynCount++}", iid) } setConfig: () -> handleRequest: () -> throw new Error 'NOT IMPLEMENTED' #------------------------------------------------------------------------------- class Request extends EventEmitter constructor: (@name, iid) -> @sentMessages = [] @config = {} @runtimeAgent = { config: { iid: iid } } sendRequest: (message) -> @sentMessages.push message return q.promise (resolve, reject) -> resolve [{status: 'OK'}] reject 'NOT IMPLEMENTED' setConfig: () -> resetSentMesages: () -> @sentMessages = [] getLastSentMessage: () -> return @sentMessages.pop() #------------------------------------------------------------------------------- httpMessageServer = null wsServer = null replyChannel = null dynReplyChannel = null dynRequestChannel = null SEP_IID = 'SEP1' IID = 'A1' CONNKEY = '<KEY>' EXPECTED_REPLY = 'Hello' EXPECTED_PAYLOAD = 'More data' reqIdCount = 1 describe 'http-message test', -> before (done) -> httpMessageServer = http.createServer() httpMessageServer.on 'error', (err) -> @logger.warn "httpMessageServer.on error = #{err.message}" replyChannel = new Reply('main_rep_channel', IID) dynRequestChannel = new Request('dyn_req', IID) done() after (done) -> if httpMessageServer? then httpMessageServer.close() if wsServer? then wsServer.shutDown() done() it 'Listen', (done) -> httpMessageServer.listen replyChannel httpMessageServer.on 'listening', () -> done() it 'Send an invalid request', (done) -> request = JSON.stringify { type: 'XXX' fromInstance: IID } replyChannel.handleRequest([request], [dynRequestChannel]) .then (message) -> done new Error 'Expected <invalid request type> error' .fail (err) -> done() undefined it 'Establish dynamic channel', () -> request = JSON.stringify { type: 'getDynChannel' fromInstance: SEP_IID } replyChannel.handleRequest([request], [dynRequestChannel]) .then (message) -> reply = message[0][0] # when test, we dont receive a "status" segment reply.should.be.eql IID dynReplyChannel = message[1][0] dynReplyChannel.constructor.name.should.be.eql 'Reply' dynReplyChannel.name.should.be.eql 'dyn_rep_0' it 'Process a request', () -> httpMessageServer.once 'request', (req, res) -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r1.data.headers.instancespath.should.be.eql ",iid=#{IID}" r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Process a request with payload', () -> httpMessageServer.once 'request', (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> data.should.be.eql EXPECTED_PAYLOAD res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Process an aborted request with payload', (done) -> httpMessageServer.once 'request', (req, res) -> req.on 'aborted', () -> done() req.on 'end', () -> done new Error 'Aborted expected' reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> m3 = _createMessage 'http', 'aborted', reqId dynReplyChannel.handleRequest [m3] undefined it 'Fail a request because timeout', () -> httpMessageServer.once 'request', (req, res) -> q.delay(1000) .then () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() dynRequestChannel.resetSentMesages() httpMessageServer.setTimeout 500 reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] .then () -> q.delay(1000) .then () -> last = dynRequestChannel.getLastSentMessage()[0] JSON.parse(last).type.should.be.eql 'error' it 'Interleave a correct request and a timeout request', (done) -> processRequest = (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> if data is 'normal request' then sleep = 200 else if data is 'timeout request' then sleep = 600 else done Error "Invalid test request type: #{data}" q.delay(sleep) .then () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() httpMessageServer.on 'request', processRequest httpMessageServer.setTimeout 500 dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, 'timeout request'] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .fail (err) -> done err setTimeout () -> reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, 'normal request'] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .fail (err) -> done err , 400 setTimeout () -> next = () -> return JSON.parse(dynRequestChannel.getLastSentMessage()[0]) next().type.should.be.eql 'end' next().type.should.be.eql 'data' next().type.should.be.eql 'response' next().type.should.be.eql 'error' httpMessageServer.removeListener 'request', processRequest done() , 1000 it 'Upgrade current connection to websocket and use it', (done) -> wsServer = new WebSocketServer { httpServer: httpMessageServer autoAccepConnections: false keepalive: true } wsReceivedMessages = 0 wsServer.on 'error', (err) -> done err wsServer.on 'request', (request) -> try conn = request.accept() conn.on 'error', (err) -> done err conn.on 'message', (message) -> wsReceivedMessages++ conn.sendUTF "echo_#{message.utf8Data}" conn.close() conn.on 'close', () -> # do nothing catch err done err dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'ws', 'upgrade', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> q.delay(100) .then () -> [received, receivedData] = dynRequestChannel.getLastSentMessage() expected = 'HTTP/1.1 101 Switching Protocols\r\n\ upgrade: websocket\r\n\ connection: Upgrade\r\n\ sec-websocket-accept: Teu0yrJZBLH0+gJYYr3MPaqqUL8=\r\n\r\n' receivedData.should.be.equal expected q.delay(100) # When ... # Sec-WebSocket-Key = <KEY> # sec-websocket-accept = Teu0yr<KEY>H0+gJYYr3MPaqqUL8=\r\n\r\n' # ... then, the websocket frame for text 'hello', is: # <Buffer 81 85 40 78 5a 9d 28 1d 36 f1 2f> # (value sniffed from a websocket server) # WsServer responses with 'echo_hello' and close connection (normal # connection closure). # The websocket frame for response 'echo_hello' + close is: # <Buffer 81 0a 65 63 68 6f 5f 68 65 6c 6c 6f 88 1b 03 e8 4e 6f 72 6d # 61 6c 20 63 6f 6e 6e 65 63 74 69 6f 6e 20 63 6c 6f 73 75 72 65> .then () -> dynRequestChannel.resetSentMesages() m2 = _createMessage 'ws', 'data', reqId helloBuffer = new Buffer([0x81, 0x85, 0x40, 0x78, 0x5a, 0x9d, 0x28, \ 0x1d, 0x36, 0xf1, 0x2f]) dynReplyChannel.handleRequest [m2, helloBuffer] q.delay(100) .then () -> # We checked that 'echo_hello' + close has arrived [received, receivedData] = dynRequestChannel.getLastSentMessage() echohelloBuffer = new Buffer([0x81, 0x0a, 0x65, 0x63, 0x68, 0x6f, 0x5f, \ 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x88, 0x1b, \ 0x03, 0xe8, 0x4e, 0x6f, 0x72, 0x6d, 0x61, \ 0x6c, 0x20, 0x63, 0x6f, 0x6e, 0x6e, 0x65, \ 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x63, \ 0x6c, 0x6f, 0x73, 0x75, 0x72, 0x65]) [received, receivedData] = dynRequestChannel.getLastSentMessage() receivedData.should.eql(echohelloBuffer) wsReceivedMessages.should.eql 1 # This message will not arrive, since the connection is closed. m3 = _createMessage 'ws', 'data', reqId helloBuffer2 = new Buffer([0x81, 0x85, 0x40, 0x78, 0x5a, 0x9d, 0x28, \ 0x1d, 0x36, 0xf1, 0x2f]) dynReplyChannel.handleRequest [m3, helloBuffer2] q.delay(100) .then () -> # We checked that the previous message hasn't arrived. wsReceivedMessages.should.eql 1 done() .fail (err) -> done err undefined it 'Process a request setting content-lengt (ticket 656)', () -> httpMessageServer.once 'request', (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> data.should.be.eql EXPECTED_PAYLOAD res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() reqId = "#{reqIdCount++}" contentLength = EXPECTED_PAYLOAD.length m1 = _createMessage 'http', 'request', reqId, 'post', false, contentLength dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> # Force ticket656 q.delay(250) .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Force garbage request collector', (done) -> @timeout(5000) httpMessageServer._startGarbageRequests(1000) httpMessageServer.setTimeout(4000) httpMessageServer.once 'garbageRequests', (numRequests) -> numRequests.should.be.eql 1 done() httpMessageServer.once 'request', (req, res) -> setTimeout () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() , 2000 # Force garbage requests dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] undefined it 'Several ServerMessage objects instances', (done) -> # Ticket920 CONCURRENT_SERVERS = 3 servers = [] completedListen = 0 createServer = () -> server = http.createServer() server.on 'error', (err) -> done err server.repChann = new Reply('main_rep_channel_' + servers.length, IID) servers.push server onListen = () -> completedListen++ if completedListen is servers.length server.close() for server in servers done() createServer() for i in [1 .. CONCURRENT_SERVERS] server.listen server.repChann, onListen for server in servers _createMessage = (prot, type, reqId, method, use_instancespath, datalength) -> if prot is 'http' and type is 'request' requestData = protocol: 'http' url: '/' method: method headers: host:"localhost:8080", #connection:"keep-alive" if use_instancespath? then requestData.headers.instancespath = '' if datalength? then requestData.headers['content-length'] = datalength else if prot is 'ws' and type is 'upgrade' requestData = protocol: 'http' url: '/' method: method headers: Upgrade: 'websocket' Connection: 'Upgrade' 'Sec-WebSocket-Version': 13 'Sec-WebSocket-Key': '<KEY> return JSON.stringify { protocol: prot type: type domain: 'uno.empresa.es' fromInstance: SEP_IID connKey: CONNKEY reqId: reqId data: requestData }
true
http = require '../src/index' q = require 'q' net = require 'net' EventEmitter = require('events').EventEmitter should = require 'should' supertest = require 'supertest' WebSocketServer = require('websocket').server #### START: ENABLE LOG LINES FOR DEBUGGING #### # This will show all log lines in the code if the test are executed with # DEBUG="kumori:*" set in the environment. For example, running: # # $ DEBUG="kumori:*" npm test # debug = require 'debug' # debug.enable 'kumori:*' # debug.enable 'kumori:info, kumori:debug' debug.log = () -> console.log arguments... #### END: ENABLE LOG LINES FOR DEBUGGING #### #------------------------------------------------------------------------------- class Reply extends EventEmitter @dynCount = 0 constructor: (@name, iid) -> @config = {} @runtimeAgent = { config: { iid: iid }, createChannel: () -> return new Reply("dyn_rep_#{Reply.dynCount++}", iid) } setConfig: () -> handleRequest: () -> throw new Error 'NOT IMPLEMENTED' #------------------------------------------------------------------------------- class Request extends EventEmitter constructor: (@name, iid) -> @sentMessages = [] @config = {} @runtimeAgent = { config: { iid: iid } } sendRequest: (message) -> @sentMessages.push message return q.promise (resolve, reject) -> resolve [{status: 'OK'}] reject 'NOT IMPLEMENTED' setConfig: () -> resetSentMesages: () -> @sentMessages = [] getLastSentMessage: () -> return @sentMessages.pop() #------------------------------------------------------------------------------- httpMessageServer = null wsServer = null replyChannel = null dynReplyChannel = null dynRequestChannel = null SEP_IID = 'SEP1' IID = 'A1' CONNKEY = 'PI:KEY:<KEY>END_PI' EXPECTED_REPLY = 'Hello' EXPECTED_PAYLOAD = 'More data' reqIdCount = 1 describe 'http-message test', -> before (done) -> httpMessageServer = http.createServer() httpMessageServer.on 'error', (err) -> @logger.warn "httpMessageServer.on error = #{err.message}" replyChannel = new Reply('main_rep_channel', IID) dynRequestChannel = new Request('dyn_req', IID) done() after (done) -> if httpMessageServer? then httpMessageServer.close() if wsServer? then wsServer.shutDown() done() it 'Listen', (done) -> httpMessageServer.listen replyChannel httpMessageServer.on 'listening', () -> done() it 'Send an invalid request', (done) -> request = JSON.stringify { type: 'XXX' fromInstance: IID } replyChannel.handleRequest([request], [dynRequestChannel]) .then (message) -> done new Error 'Expected <invalid request type> error' .fail (err) -> done() undefined it 'Establish dynamic channel', () -> request = JSON.stringify { type: 'getDynChannel' fromInstance: SEP_IID } replyChannel.handleRequest([request], [dynRequestChannel]) .then (message) -> reply = message[0][0] # when test, we dont receive a "status" segment reply.should.be.eql IID dynReplyChannel = message[1][0] dynReplyChannel.constructor.name.should.be.eql 'Reply' dynReplyChannel.name.should.be.eql 'dyn_rep_0' it 'Process a request', () -> httpMessageServer.once 'request', (req, res) -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r1.data.headers.instancespath.should.be.eql ",iid=#{IID}" r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Process a request with payload', () -> httpMessageServer.once 'request', (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> data.should.be.eql EXPECTED_PAYLOAD res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Process an aborted request with payload', (done) -> httpMessageServer.once 'request', (req, res) -> req.on 'aborted', () -> done() req.on 'end', () -> done new Error 'Aborted expected' reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> m3 = _createMessage 'http', 'aborted', reqId dynReplyChannel.handleRequest [m3] undefined it 'Fail a request because timeout', () -> httpMessageServer.once 'request', (req, res) -> q.delay(1000) .then () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() dynRequestChannel.resetSentMesages() httpMessageServer.setTimeout 500 reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] .then () -> q.delay(1000) .then () -> last = dynRequestChannel.getLastSentMessage()[0] JSON.parse(last).type.should.be.eql 'error' it 'Interleave a correct request and a timeout request', (done) -> processRequest = (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> if data is 'normal request' then sleep = 200 else if data is 'timeout request' then sleep = 600 else done Error "Invalid test request type: #{data}" q.delay(sleep) .then () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() httpMessageServer.on 'request', processRequest httpMessageServer.setTimeout 500 dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, 'timeout request'] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .fail (err) -> done err setTimeout () -> reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'post' dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, 'normal request'] .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .fail (err) -> done err , 400 setTimeout () -> next = () -> return JSON.parse(dynRequestChannel.getLastSentMessage()[0]) next().type.should.be.eql 'end' next().type.should.be.eql 'data' next().type.should.be.eql 'response' next().type.should.be.eql 'error' httpMessageServer.removeListener 'request', processRequest done() , 1000 it 'Upgrade current connection to websocket and use it', (done) -> wsServer = new WebSocketServer { httpServer: httpMessageServer autoAccepConnections: false keepalive: true } wsReceivedMessages = 0 wsServer.on 'error', (err) -> done err wsServer.on 'request', (request) -> try conn = request.accept() conn.on 'error', (err) -> done err conn.on 'message', (message) -> wsReceivedMessages++ conn.sendUTF "echo_#{message.utf8Data}" conn.close() conn.on 'close', () -> # do nothing catch err done err dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'ws', 'upgrade', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> q.delay(100) .then () -> [received, receivedData] = dynRequestChannel.getLastSentMessage() expected = 'HTTP/1.1 101 Switching Protocols\r\n\ upgrade: websocket\r\n\ connection: Upgrade\r\n\ sec-websocket-accept: Teu0yrJZBLH0+gJYYr3MPaqqUL8=\r\n\r\n' receivedData.should.be.equal expected q.delay(100) # When ... # Sec-WebSocket-Key = PI:KEY:<KEY>END_PI # sec-websocket-accept = Teu0yrPI:KEY:<KEY>END_PIH0+gJYYr3MPaqqUL8=\r\n\r\n' # ... then, the websocket frame for text 'hello', is: # <Buffer 81 85 40 78 5a 9d 28 1d 36 f1 2f> # (value sniffed from a websocket server) # WsServer responses with 'echo_hello' and close connection (normal # connection closure). # The websocket frame for response 'echo_hello' + close is: # <Buffer 81 0a 65 63 68 6f 5f 68 65 6c 6c 6f 88 1b 03 e8 4e 6f 72 6d # 61 6c 20 63 6f 6e 6e 65 63 74 69 6f 6e 20 63 6c 6f 73 75 72 65> .then () -> dynRequestChannel.resetSentMesages() m2 = _createMessage 'ws', 'data', reqId helloBuffer = new Buffer([0x81, 0x85, 0x40, 0x78, 0x5a, 0x9d, 0x28, \ 0x1d, 0x36, 0xf1, 0x2f]) dynReplyChannel.handleRequest [m2, helloBuffer] q.delay(100) .then () -> # We checked that 'echo_hello' + close has arrived [received, receivedData] = dynRequestChannel.getLastSentMessage() echohelloBuffer = new Buffer([0x81, 0x0a, 0x65, 0x63, 0x68, 0x6f, 0x5f, \ 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x88, 0x1b, \ 0x03, 0xe8, 0x4e, 0x6f, 0x72, 0x6d, 0x61, \ 0x6c, 0x20, 0x63, 0x6f, 0x6e, 0x6e, 0x65, \ 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x63, \ 0x6c, 0x6f, 0x73, 0x75, 0x72, 0x65]) [received, receivedData] = dynRequestChannel.getLastSentMessage() receivedData.should.eql(echohelloBuffer) wsReceivedMessages.should.eql 1 # This message will not arrive, since the connection is closed. m3 = _createMessage 'ws', 'data', reqId helloBuffer2 = new Buffer([0x81, 0x85, 0x40, 0x78, 0x5a, 0x9d, 0x28, \ 0x1d, 0x36, 0xf1, 0x2f]) dynReplyChannel.handleRequest [m3, helloBuffer2] q.delay(100) .then () -> # We checked that the previous message hasn't arrived. wsReceivedMessages.should.eql 1 done() .fail (err) -> done err undefined it 'Process a request setting content-lengt (ticket 656)', () -> httpMessageServer.once 'request', (req, res) -> data = '' req.on 'data', (chunk) -> data += chunk req.on 'end', () -> data.should.be.eql EXPECTED_PAYLOAD res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() reqId = "#{reqIdCount++}" contentLength = EXPECTED_PAYLOAD.length m1 = _createMessage 'http', 'request', reqId, 'post', false, contentLength dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'data', reqId dynReplyChannel.handleRequest [m2, EXPECTED_PAYLOAD] .then () -> # Force ticket656 q.delay(250) .then () -> m3 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m3] .then () -> q.delay(100) .then () -> r3 = dynRequestChannel.getLastSentMessage() r3 = JSON.parse r3 [r2, r2data] = dynRequestChannel.getLastSentMessage() r2 = JSON.parse r2 r2data = r2data.toString() r1 = dynRequestChannel.getLastSentMessage() r1 = JSON.parse r1 r1.type.should.be.eql 'response' r1.reqId.should.be.eql reqId r2.type.should.be.eql 'data' r2.reqId.should.be.eql reqId r2data.should.be.eql EXPECTED_REPLY r3.type.should.be.eql 'end' r3.reqId.should.be.eql reqId it 'Force garbage request collector', (done) -> @timeout(5000) httpMessageServer._startGarbageRequests(1000) httpMessageServer.setTimeout(4000) httpMessageServer.once 'garbageRequests', (numRequests) -> numRequests.should.be.eql 1 done() httpMessageServer.once 'request', (req, res) -> setTimeout () -> res.statusCode = 200 res.setHeader('content-type', 'text/plain') res.write EXPECTED_REPLY res.end() , 2000 # Force garbage requests dynRequestChannel.resetSentMesages() reqId = "#{reqIdCount++}" m1 = _createMessage 'http', 'request', reqId, 'get', true dynReplyChannel.handleRequest [m1] .then () -> m2 = _createMessage 'http', 'end', reqId dynReplyChannel.handleRequest [m2] undefined it 'Several ServerMessage objects instances', (done) -> # Ticket920 CONCURRENT_SERVERS = 3 servers = [] completedListen = 0 createServer = () -> server = http.createServer() server.on 'error', (err) -> done err server.repChann = new Reply('main_rep_channel_' + servers.length, IID) servers.push server onListen = () -> completedListen++ if completedListen is servers.length server.close() for server in servers done() createServer() for i in [1 .. CONCURRENT_SERVERS] server.listen server.repChann, onListen for server in servers _createMessage = (prot, type, reqId, method, use_instancespath, datalength) -> if prot is 'http' and type is 'request' requestData = protocol: 'http' url: '/' method: method headers: host:"localhost:8080", #connection:"keep-alive" if use_instancespath? then requestData.headers.instancespath = '' if datalength? then requestData.headers['content-length'] = datalength else if prot is 'ws' and type is 'upgrade' requestData = protocol: 'http' url: '/' method: method headers: Upgrade: 'websocket' Connection: 'Upgrade' 'Sec-WebSocket-Version': 13 'Sec-WebSocket-Key': 'PI:KEY:<KEY>END_PI return JSON.stringify { protocol: prot type: type domain: 'uno.empresa.es' fromInstance: SEP_IID connKey: CONNKEY reqId: reqId data: requestData }
[ { "context": "eness. For example, while <em>My\nfavorite works of William Shakespeare</em> will most likely be an original\ncollection, ", "end": 1246, "score": 0.9478300213813782, "start": 1227, "tag": "NAME", "value": "William Shakespeare" }, { "context": "y be an original\ncollection, <em>Complete works of William Shakespeare</em> will not, as it leaves\nno room f", "end": 1325, "score": 0.8349053859710693, "start": 1318, "tag": "NAME", "value": "William" }, { "context": "original\ncollection, <em>Complete works of William Shakespeare</em> will not, as it leaves\nno room for personal ", "end": 1337, "score": 0.8567323684692383, "start": 1326, "tag": "NAME", "value": "Shakespeare" }, { "context": "turn\n return\n\n\n# Inspired by devblog.orgsync.com/hangover/\nclass Tooltip\n constructor: (el, anchor, option", "end": 6349, "score": 0.9746144413948059, "start": 6341, "tag": "USERNAME", "value": "hangover" }, { "context": "s Modal\n # based on css-modal https://github.com/drublic/css-modal\n\n MODAL_SMALL_BREAKPOINT = 480\n MODAL", "end": 15454, "score": 0.9985160231590271, "start": 15447, "tag": "USERNAME", "value": "drublic" } ]
src/license-selector.coffee
CodeMaster7000/public-license-selector
39
EVENT_NS = 'license-selector' $ = require 'jquery'; _ = require 'lodash'; {LicenseDefinitions, LicenseCompatibility, QuestionDefinitions, LabelsDefinitions} = require './definitions.coffee' # keyword : text Explanations = 'the scope of copyright and related rights': """ <p> Copyright protects original works. Originality is defined as the author’s own intellectual creation. Therefore, mere statements of historical facts, results of measurements etc. are not protected by copyright, because they exist objectively and therefore cannot be <em>created</em>. The same applies to ideas, mathematical formulas, elements of folklore etc. While quantitative data are usually not protected by copyright, qualitative data (as their creation involve some intellectual judgment) or language data are usually copyrightable. </p> <p> Apart from copyright in the data itself, a compilation of data (a dataset) may also be protected by copyright as an original work. It is the case when the selection and arrangement of the dataset involves some degree of intellectual creation or choice. This is not the case when the guiding principle of the collection is exhaustivity and/or completeness. For example, while <em>My favorite works of William Shakespeare</em> will most likely be an original collection, <em>Complete works of William Shakespeare</em> will not, as it leaves no room for personal creativity. </p> <p> The investment (of money and/or labor) into the making of the dataset is irrelevant from the point of view of copyright law; however, a substantial investment into the creation of a database may attract a specific kind of protection, the sui generis database right. If your data and your dataset are not original, but you made a substantial investment into the making of a database, you can still benefit from legal protection (in such a case, answer YES to this question). </p> <p>Answer <strong>Yes</strong> if ...</p> <ul> <li>selecting a license for language data (in most cases)</li> <li>selecting a license for original (creative) selection or arrangement of the dataset</li> <li>substantial investment went into the making of the database</li> <li>you are not sure that the answer should be <strong>No</strong></li> </ul> <p>answer <strong>No</strong> if ...</p> <ul> <li>your dataset contains only quantitative data and/or raw facts</li> <li>your dataset is exhaustive and complete (or at least aims to be)</li> <li>only if you are sure!</li> </ul> """ 'copyright and similar rights': """ <p> <strong>copyright</strong> &ndash; protects original works or original compilations of works </p> <p> <strong>sui generis database rights</strong> &ndash; protects substantial investment into the making of a database </p> """ 'licensed under a public license': """ <p> By <em>licensed</em> data we understand data available under a public license, such as Creative Commons or ODC licenses. If you have a bespoke license for the data (i.e. a license drafted for a specific contractual agreement, such as between a publisher and a research institution), contact our legal help desk. </p> """ 'Public Domain': """ <p> Public Domain is a category including works that are not protected by copyright (such as raw facts, ideas) or that are no longer protected by copyright (copyright expires 70 years after the death of the author). In many jurisdictions, some official texts such as court decisions or statutes are also regarded as part of the public domain. </p> """ 'additional permission': """ <p> In order to be able to deposit your data in our repository, you will have to contact the copyright holder (usually the publisher or the author) and ask him for a written permission to do so. Our legal help desk will help you draft the permission. We will also tell you what to do if you cannot identify the copyright holder. </p> """ 'derivative works': """ <p> Derivative works are works that are derived from or based upon an original work and in which the original work is translated, altered, arranged, transformed, or otherwise modified. This category does not include parodies. </p> <p> Please note that the use of language resources consists of making derivative works. If you do not allow others to build on your work, it will be of very little use for the community. </p> """ 'commercial use': """ <p> Commercial use is a use that is primarily intended for or directed towards commercial advantage or monetary compensation. </p> <p> Please note that the meaning of this term is not entirely clear (although it seems to be generally agreed upon that academic research, even carried out by professional researchers, is not commercial use) and if you choose this restriction, it may have a chilling effect on the re-use of your resource by some projects (public-private partnerships). </p> """ 'attribute': """ <p> It is your moral right to have your work attributed to you (i.e. your name mentioned every time someone uses your work). However, be aware of the fact that the attribution requirement in Creative Commons licenses is more extended than just mentioning your name. </p> <p> In fact, the attribution clause in Creative Commons licenses obliges the user to mention a whole set of information (identity of the creator, a copyright notice, a reference to the chosen CC license and a hyperlink to its text, a disclaimer of warranties, an indication of any modifications made to the original work and even a hyperlink to the work itself). This may lead to a phenomenon known as <em>attribution stacking</em>, which will make your work difficult to compile with other works. </p> """ ExplanationsTerms = _.keys(Explanations) addExplanations = (text) -> for term in ExplanationsTerms index = text.indexOf(term) if ( index >= 0 ) text = text.substring(0,index) + '<span class="ls-term">' + text.substring(index, index + term.length) + '</span>' + text.substring(index + term.length) return text explanationTooltips = (scope, container) -> $('.ls-term', scope).each -> $el = $(this) term = $el.html() return unless Explanations[term] new Tooltip($('<div />').addClass('ls-term-tooltip').html(Explanations[term]), $el, { 'container': container position: 'bottom' }) return return # Inspired by devblog.orgsync.com/hangover/ class Tooltip constructor: (el, anchor, options) -> # defaults @position = 'top' # The position of $el relative to the $anchor. @preserve = false # Preserve $el's listeners and data by using detach instead of remove. @container = false # Append to specified container @beforeShow = false # Before show callback - used often to populate tooltip _.extend(@, options) if options @container = $(@container) if @container && !(@container instanceof $) @hovered = false _.bindAll(@, ['onEvenIn', 'onEventOut']) @buildContainer().setElement(el).setAnchor(anchor) buildContainer: -> @$wrapper = $('<div/>') .addClass('ls-tooltip-wrapper') .addClass("ls-tooltip-#{@position}") @ setElement: (el) -> @$wrapper.empty().append(@$el = if el instanceof $ then el else $(el)) @ setAnchor: (anchor) -> @$anchor.css('position', null) if @$anchor @$anchor = if anchor instanceof $ then anchor else $(anchor) @$anchor.on( focusin: @onEvenIn mouseenter: @onEvenIn mouseleave: @onEventOut focusout: @onEventOut ).css('position', 'relative') @ show: -> if !@beforeShow || @beforeShow(@, @$anchor, @$el) if @container @container.append(@$wrapper) else @$anchor.parent().append(@$wrapper) @move() @ hide: -> @$wrapper[if @preserve then 'detach' else 'remove' ]() @hovered = false @ move: -> $wrapper = @$wrapper $anchor = @$anchor wWidth = $wrapper.outerWidth() wHeight = $wrapper.outerHeight() aWidth = $anchor.outerWidth() aHeight = $anchor.outerHeight() aPosition = $anchor.offset() position = left: aPosition.left + parseInt($anchor.css('marginLeft'), 10) top: aPosition.top + parseInt($anchor.css('marginTop'), 10) switch @position when 'top' position.left += (aWidth - wWidth) / 2 position.top -= wHeight when 'right' position.left += aWidth position.top += (aHeight - wHeight) / 2 when 'bottom' position.left += (aWidth - wWidth) / 2 position.top += aHeight when 'left' position.left -= wWidth position.top += (aHeight - wHeight) / 2 $wrapper.css(position) @move() if ($wrapper.outerWidth() > wWidth || $wrapper.outerHeight() > wHeight) @ destroy: -> @hide() @$anchor.off focusin: @onEvenIn mouseenter: @onEvenIn mouseleave: @onEventOut focusout: @onEventOut @ onEvenIn : -> return if (@hovered) @hovered = true @show() onEventOut: -> return unless (@hovered) @hovered = false @hide() class History constructor: (@parent, @licenseSelector) -> @current = -1 @historyStack = [] @prevButton = $('<button/>') .addClass('ls-history-prev') .attr('title', 'Previous question') .append($('<span/>').addClass('icon-left')) .click => @go(@current - 1) @nextButton = $('<button/>') .addClass('ls-history-next') .attr('title', 'Next question') .append($('<span/>').addClass('icon-right')) .click => @go(@current + 1) @restartButton = $('<button/>') .addClass('ls-restart') .attr('title', 'Start again') .append($('<span/>').addClass('icon-ccw')) .append(' Start again') .click => @licenseSelector.restart() @progress = $('<div/>').addClass('ls-history-progress') history = $('<div/>').addClass('ls-history') .append(@restartButton) .append(@prevButton) .append(@progress) .append(@nextButton) .appendTo(@parent) @setupTooltips(history) @update() go: (point) -> @current = point state = _.cloneDeep @historyStack[@current] @licenseSelector.setState state @update() return reset: -> @current = -1 @historyStack = [] @progress.empty() @update() return setupTooltips: (root) -> self = @ $('[title]', root).each -> $el = $(@) title = $el.attr('title') $el.removeAttr('title') new Tooltip($('<div />').addClass('ls-tooltip').text(title), $el, { container: self.licenseSelector.container }) return return setAnswer: (text) -> return if @current == -1 state = @historyStack[@current] state.answer = text return setOptionSelected: (option, value) -> return if @current == -1 state = @historyStack[@current] state.options[option].selected = value return update: -> progressBarBlocks = @progress.children() # remove class ls-active from all children # then get @current and addClass 'ls-active' if progressBarBlocks.size() > 0 activeBlock = progressBarBlocks.removeClass('ls-active').get(@current) $(activeBlock).addClass('ls-active') if activeBlock? @nextButton.attr('disabled', @historyStack.length == 0 || @historyStack.length == @current + 1) @prevButton.attr('disabled', @current <= 0) return createProgressBlock: -> self = @ block = $('<button/>') .html('&nbsp;') .click -> self.go(self.progress.children().index(@)) new Tooltip($('<div/>').addClass('ls-tooltip'), block, { container: self.licenseSelector.container beforeShow: (tooltip, block, el) -> index = self.progress.children().index(block.get(0)) state = self.historyStack[index] el.empty() unless state.finished el.append($('<p/>').text(state.questionText)) if state.options ul = $('<ul />') for option in state.options continue unless option.selected span = $('<span/>') for license in option.licenses span.append($('<span/>').addClass('ls-license-name').text(license.name)) ul.append($('<li />').append(span)) el.append(ul) else el.append($('<p/>').html("Answered: <strong>#{state.answer}</strong>")) if (state.answer) else el.append($('<p/>').text("Final Step")) el.append($('<p/>').text("Choose your license below ...")) return true }) return block pushState: (state) -> # shallow clone of the state state = _.cloneDeep state # Trim stack if needed @current += 1 @historyStack = @historyStack.slice(0, @current) if @historyStack.length > @current @historyStack.push(state) #console.log @historyStack # trim progress bar progressBarBlocks = @progress.children().size() index = @current + 1 if progressBarBlocks != index if progressBarBlocks > index @progress.children().slice(index).remove() else @progress.append(@createProgressBlock()) @update() return class Question constructor: (@parent, @licenseSelector) -> @element = $('<div/>').addClass('ls-question') @errorContainer = $('<div/>').addClass('ls-question-error').append($('<h4/>').text("Can't choose a license")).appendTo(@element) @errorContainer.hide() @error = $('<span/>').appendTo(@errorContainer) @text = $('<p/>').addClass('ls-question-text').appendTo(@element) @options = $('<ul/>').appendTo($('<div/>').addClass('ls-question-options').appendTo(@element)) @answers = $('<div/>').addClass('ls-question-answers').appendTo(@element) @element.appendTo(@parent) show: -> @element.show() hide: -> @element.hide() reset: -> @errorContainer.hide() @answers.empty() @options.empty() @options.hide() @licenseSelector.licensesList.show() @element.off('update-answers') finished: -> @hide() @licenseSelector.licensesList.show() setQuestion: (text) -> @reset() @text.empty().append(addExplanations(text)) explanationTooltips(@text, @licenseSelector.container) return addAnswer: (answer) -> button = $('<button />') .text(answer.text) .click(-> answer.action()) .prop('disabled', answer.disabled()) @element.on('update-answers', -> button.prop('disabled', answer.disabled())) @answers.append(button) return addOption: (option) -> @options.show() @licenseSelector.licensesList.hide() element = @element self = @ checkbox = $('<input/>') .attr('type', 'checkbox') .prop('checked', option.selected) .click(-> option.selected = this.checked index = self.licenseSelector.state.options.indexOf(option) self.licenseSelector.historyModule.setOptionSelected(index, option.selected) element.trigger('update-answers') ) label = $('<label/>').append(checkbox) span = $('<span/>') for license in option.licenses span.append($('<span/>').addClass('ls-license-name').text(license.name)) label.append(span).appendTo($('<li/>').appendTo(@options)) return setError: (html) -> @errorContainer.show() @error.html(addExplanations(html)) explanationTooltips(@error, @licenseSelector.container) @licenseSelector.licensesList.hide() return class Modal # based on css-modal https://github.com/drublic/css-modal MODAL_SMALL_BREAKPOINT = 480 MODAL_MAX_WIDTH = 800 stylesheet = null scale = -> stylesheet = $('<style></style>').appendTo('head') unless stylesheet width = $(window).width() margin = 10 if width < MODAL_MAX_WIDTH currentMaxWidth = width - (margin * 2) leftMargin = currentMaxWidth / 2 closeButtonMarginRight = '-' + Math.floor(currentMaxWidth / 2) stylesheet.html(""" .license-selector .ls-modal { max-width: #{currentMaxWidth}px !important; margin-left: -#{leftMargin}px !important;} .license-selector .ls-modal-close:after { margin-right: #{closeButtonMarginRight}px !important; } """) else currentMaxWidth = MODAL_MAX_WIDTH - (margin * 2) leftMargin = currentMaxWidth / 2 stylesheet.html(""" .license-selector .ls-modal { max-width: #{currentMaxWidth}px; margin-left: -#{leftMargin}px;} .license-selector .ls-modal-close:after { margin-right: -#{leftMargin}px !important; } """) $(window).on 'resize', scale # create jquery && DOM constructor: (@parent) -> @element = $('<section/>') .addClass('license-selector') .attr( tabindex: '-1' 'aria-hidden': 'true' role: 'dialog' ).on 'show.lsmodal', scale inner = $('<div/>').addClass('ls-modal') @header = $('<header/>') .append($('<h2/>').text('Choose a License')) .append($('<p/>').text('Answer the questions or use the search to find the license you want')) .appendTo(inner) @content = $('<div/>').addClass('ls-modal-content').appendTo(inner) closeButton = $('<a/>') .addClass('ls-modal-close') .attr( 'title': 'Close License Selector' 'data-dismiss': 'modal' 'data-close': 'Close' ) .click(=> @hide()) @element.append(inner) .append(closeButton) .appendTo(@parent) hide: -> @element.removeClass('is-active') .trigger('hide.lsmodal') .attr('aria-hidden', 'true') show: -> @element.addClass('is-active') .trigger('show.lsmodal') .attr('aria-hidden', 'false') class Search constructor: (@parent, @licenseList) -> @textbox = $('<input/>') .attr( type: 'text', placeholder: 'Search for a license...' ) .on 'input', => @licenseList.filter(@textbox.val()) @container = $('<div/>') .addClass('ls-search') .append(@textbox) .appendTo(@parent) hide: -> @container.hide() show: -> @container.show() class LicenseList comperator = (obj, text) -> text = (''+text).toLowerCase() return (''+obj).toLowerCase().indexOf(text) > -1 constructor: (@parent, @licenseSelector) -> @availableLicenses = _.where @licenseSelector.licenses, { available: true } @list = $('<ul />') @error = $('<div/>').addClass('ls-not-found').append($('<h4/>').text('No license found')).append('Try change the search criteria or start the questionnaire again.') @error.hide() @container = $('<div class="ls-license-list" />') .append(@error) .append(@list) .appendTo(@parent) @update() createElement: (license) -> customTemplate = false el = $ '<li />' select = (e) => @selectLicense(license, el) @licenseSelector.selectLicense license if e? e.preventDefault() e.stopPropagation() if license.template if _.isFunction(license.template) license.template(el, license, select) customTemplate = true else if license.template instanceof $ el.append(license.template) else el.attr('title', 'Click to select the license') h = $('<h4 />').text(license.name) h.append($('<a/>').attr({ href: license.url target: '_blank' }).addClass('ls-button').text('See full text')) if license.url el.append(h) el.append($('<p />').text(license.description)) unless _.isEmpty(license.description) el.addClass(license.cssClass) if license.cssClass license.labels ||= [] if @licenseSelector.options.showLabels l = $('<div/>').addClass('ls-labels') for label in license.labels continue unless LabelsDefinitions[label] d = LabelsDefinitions[label] l.addClass(d.parentClass) if d.parentClass item = $('<span/>').addClass('ls-label') item.addClass(d.itemClass) if d.itemClass item.text(d.text) if d.text item.attr('title', d.title) if d.title l.append(item) el.append(l) el.addClass(license.cssClass) if license.cssClass unless customTemplate el.click (e) -> return if e.target && $(e.target).is('button, a') select(e) el.data 'license', license return el hide: -> @parent.hide() @licenseSelector.searchModule.hide() show: -> @parent.show() @licenseSelector.searchModule.show() filter: (newterm) -> if (newterm isnt @term) @term = newterm @update() return sortLicenses: (licenses) -> _.sortBy(licenses, ['priority','name']) selectLicense: (license, element) -> selectedLicense = @deselectLicense() if selectedLicense? and selectedLicense is license return element.addClass 'ls-active' @selectedLicense = license: license element: element deselectLicense: -> @selectedLicense ?= {} {element, license} = @selectedLicense element.removeClass 'ls-active' if element @selectedLicense = {} return license matchFilter: (license) -> return false unless license.available return true unless @term return comperator(license.name, @term) || comperator(license.description, @term) update: (licenses) -> unless licenses? licenses = @availableLicenses else licenses = @availableLicenses = _.where licenses, { available: true } elements = {} for el in @list.children() el = $(el) license = el.data 'license' if licenses[license.key]? and @matchFilter(licenses[license.key]) elements[license.key] = el else el.remove() previous = null for license in @sortLicenses(licenses) continue unless @matchFilter(license) if elements[license.key]? previous = elements[license.key] else el = @createElement license if previous? previous.after el else @list.prepend el previous = el if @list.children().size() == 0 @error.show() else @error.hide() return has: (category) -> _.any @availableLicenses, (license) -> _.contains(license.categories, category) only: (category) -> _.all @availableLicenses, (license) -> _.contains(license.categories, category) hasnt: (category) -> _.all @availableLicenses, (license) -> !_.contains(license.categories, category) include: (category) -> @availableLicenses = _.filter @availableLicenses, (license) -> _.contains(license.categories, category) @update() exclude: (category) -> @availableLicenses = _.filter @availableLicenses, (license) -> !_.contains(license.categories, category) @update() class LicenseSelector @defaultOptions = showLabels: true onLicenseSelected: _.noop licenseItemTemplate: null appendTo: 'body' start: 'KindOfContent' constructor: (@licenses, @questions, @options = {}) -> _.defaults(@options, LicenseSelector.defaultOptions) for key, license of @licenses license.key = key if @options.licenseItemTemplate and !license.template license.template = @options.licenseItemTemplate @state = {} @container = if @options.appendTo instanceof $ then @options.appendTo else $(@options.appendTo) @modal = new Modal(@container) @licensesList = new LicenseList(@modal.content, this) @historyModule = new History(@modal.header, this) @questionModule = new Question(@modal.header, this) @searchModule = new Search(@modal.header, @licensesList) @goto @options.start restart: -> @licensesList.update(@licenses) @historyModule.reset() @state = {} @goto @options.start return setState: (state) -> @state = state @questionModule.setQuestion(state.questionText) @questionModule.show() unless @state.finished @questionModule.hide() if @state.finished if state.options for option in state.options @questionModule.addOption(option) for answer in state.answers @questionModule.addAnswer(answer) @licensesList.update(state.licenses) return selectLicense: (license, force = false) -> if @selectedLicense is license or force @options.onLicenseSelected(license) @modal.hide() else @selectedLicense = license license: (choices...) -> if choices? and choices.length > 0 licenses = [] for choice in _.flatten(choices) license = @licenses[choice] if _.isString(choice) licenses.push license @licensesList.update(licenses) @state.licenses = licenses @state.finished = true @historyModule.pushState(@state) @questionModule.finished() return cantlicense: (reason) -> @questionModule.setError(reason) return goto: (where, safeState = true) -> @questionModule.show() unless @state.finished @questionModule.hide() if @state.finished if safeState @state.question = where @state.licenses ?= @licenses @state.finished = false func = @questions[where] func.call(@) @historyModule.pushState(@state) if safeState return question: (text) -> # setting question also resets the whole module @questionModule.setQuestion(text) delete @state.options delete @state.answers @state.answer = false @state.finished = false @state.questionText = text return answer: (text, action, disabled = _.noop) -> answer = text: text action: => @historyModule.setAnswer(text) action.call(@, @state) disabled: => disabled.call(@, @state) @state.answer = false @state.answers ?= [] @state.answers.push(answer) @questionModule.addAnswer(answer) return option: (list, action = _.noop) -> option = licenses: (@licenses[license] for license in list) action: => action.call(@, @state) @state.options ?= [] @state.options.push(option) @questionModule.addOption option return yes: (action) -> @answer 'Yes', action no: (action) -> @answer 'No', action has: (category) -> @licensesList.has(category) only: (category) -> @licensesList.only(category) hasnt: (category) -> @licensesList.hasnt(category) include: (category) -> @licensesList.include(category) @state.licenses = _.clone @licensesList.availableLicenses exclude: (category) -> @licensesList.exclude(category) @state.licenses = _.clone @licensesList.availableLicenses $.fn.licenseSelector = (options, args...) -> return @each -> if args.length > 0 throw new Error('Method has to be a string') unless _.isString(options) ls = $(this).data('license-selector') method = ls[options] throw new Error("Method #{options} does't exists") unless method? return method.apply(ls, args) licenses = _.merge(_.cloneDeep(LicenseDefinitions), options.licenses) questions = _.merge(_.cloneDeep(QuestionDefinitions), options.questions) delete options.questions delete options.licenses ls = new LicenseSelector(licenses, questions, options) $(this).data('license-selector', ls) $(this).click (e) -> ls.modal.show() e.preventDefault()
133583
EVENT_NS = 'license-selector' $ = require 'jquery'; _ = require 'lodash'; {LicenseDefinitions, LicenseCompatibility, QuestionDefinitions, LabelsDefinitions} = require './definitions.coffee' # keyword : text Explanations = 'the scope of copyright and related rights': """ <p> Copyright protects original works. Originality is defined as the author’s own intellectual creation. Therefore, mere statements of historical facts, results of measurements etc. are not protected by copyright, because they exist objectively and therefore cannot be <em>created</em>. The same applies to ideas, mathematical formulas, elements of folklore etc. While quantitative data are usually not protected by copyright, qualitative data (as their creation involve some intellectual judgment) or language data are usually copyrightable. </p> <p> Apart from copyright in the data itself, a compilation of data (a dataset) may also be protected by copyright as an original work. It is the case when the selection and arrangement of the dataset involves some degree of intellectual creation or choice. This is not the case when the guiding principle of the collection is exhaustivity and/or completeness. For example, while <em>My favorite works of <NAME></em> will most likely be an original collection, <em>Complete works of <NAME> <NAME></em> will not, as it leaves no room for personal creativity. </p> <p> The investment (of money and/or labor) into the making of the dataset is irrelevant from the point of view of copyright law; however, a substantial investment into the creation of a database may attract a specific kind of protection, the sui generis database right. If your data and your dataset are not original, but you made a substantial investment into the making of a database, you can still benefit from legal protection (in such a case, answer YES to this question). </p> <p>Answer <strong>Yes</strong> if ...</p> <ul> <li>selecting a license for language data (in most cases)</li> <li>selecting a license for original (creative) selection or arrangement of the dataset</li> <li>substantial investment went into the making of the database</li> <li>you are not sure that the answer should be <strong>No</strong></li> </ul> <p>answer <strong>No</strong> if ...</p> <ul> <li>your dataset contains only quantitative data and/or raw facts</li> <li>your dataset is exhaustive and complete (or at least aims to be)</li> <li>only if you are sure!</li> </ul> """ 'copyright and similar rights': """ <p> <strong>copyright</strong> &ndash; protects original works or original compilations of works </p> <p> <strong>sui generis database rights</strong> &ndash; protects substantial investment into the making of a database </p> """ 'licensed under a public license': """ <p> By <em>licensed</em> data we understand data available under a public license, such as Creative Commons or ODC licenses. If you have a bespoke license for the data (i.e. a license drafted for a specific contractual agreement, such as between a publisher and a research institution), contact our legal help desk. </p> """ 'Public Domain': """ <p> Public Domain is a category including works that are not protected by copyright (such as raw facts, ideas) or that are no longer protected by copyright (copyright expires 70 years after the death of the author). In many jurisdictions, some official texts such as court decisions or statutes are also regarded as part of the public domain. </p> """ 'additional permission': """ <p> In order to be able to deposit your data in our repository, you will have to contact the copyright holder (usually the publisher or the author) and ask him for a written permission to do so. Our legal help desk will help you draft the permission. We will also tell you what to do if you cannot identify the copyright holder. </p> """ 'derivative works': """ <p> Derivative works are works that are derived from or based upon an original work and in which the original work is translated, altered, arranged, transformed, or otherwise modified. This category does not include parodies. </p> <p> Please note that the use of language resources consists of making derivative works. If you do not allow others to build on your work, it will be of very little use for the community. </p> """ 'commercial use': """ <p> Commercial use is a use that is primarily intended for or directed towards commercial advantage or monetary compensation. </p> <p> Please note that the meaning of this term is not entirely clear (although it seems to be generally agreed upon that academic research, even carried out by professional researchers, is not commercial use) and if you choose this restriction, it may have a chilling effect on the re-use of your resource by some projects (public-private partnerships). </p> """ 'attribute': """ <p> It is your moral right to have your work attributed to you (i.e. your name mentioned every time someone uses your work). However, be aware of the fact that the attribution requirement in Creative Commons licenses is more extended than just mentioning your name. </p> <p> In fact, the attribution clause in Creative Commons licenses obliges the user to mention a whole set of information (identity of the creator, a copyright notice, a reference to the chosen CC license and a hyperlink to its text, a disclaimer of warranties, an indication of any modifications made to the original work and even a hyperlink to the work itself). This may lead to a phenomenon known as <em>attribution stacking</em>, which will make your work difficult to compile with other works. </p> """ ExplanationsTerms = _.keys(Explanations) addExplanations = (text) -> for term in ExplanationsTerms index = text.indexOf(term) if ( index >= 0 ) text = text.substring(0,index) + '<span class="ls-term">' + text.substring(index, index + term.length) + '</span>' + text.substring(index + term.length) return text explanationTooltips = (scope, container) -> $('.ls-term', scope).each -> $el = $(this) term = $el.html() return unless Explanations[term] new Tooltip($('<div />').addClass('ls-term-tooltip').html(Explanations[term]), $el, { 'container': container position: 'bottom' }) return return # Inspired by devblog.orgsync.com/hangover/ class Tooltip constructor: (el, anchor, options) -> # defaults @position = 'top' # The position of $el relative to the $anchor. @preserve = false # Preserve $el's listeners and data by using detach instead of remove. @container = false # Append to specified container @beforeShow = false # Before show callback - used often to populate tooltip _.extend(@, options) if options @container = $(@container) if @container && !(@container instanceof $) @hovered = false _.bindAll(@, ['onEvenIn', 'onEventOut']) @buildContainer().setElement(el).setAnchor(anchor) buildContainer: -> @$wrapper = $('<div/>') .addClass('ls-tooltip-wrapper') .addClass("ls-tooltip-#{@position}") @ setElement: (el) -> @$wrapper.empty().append(@$el = if el instanceof $ then el else $(el)) @ setAnchor: (anchor) -> @$anchor.css('position', null) if @$anchor @$anchor = if anchor instanceof $ then anchor else $(anchor) @$anchor.on( focusin: @onEvenIn mouseenter: @onEvenIn mouseleave: @onEventOut focusout: @onEventOut ).css('position', 'relative') @ show: -> if !@beforeShow || @beforeShow(@, @$anchor, @$el) if @container @container.append(@$wrapper) else @$anchor.parent().append(@$wrapper) @move() @ hide: -> @$wrapper[if @preserve then 'detach' else 'remove' ]() @hovered = false @ move: -> $wrapper = @$wrapper $anchor = @$anchor wWidth = $wrapper.outerWidth() wHeight = $wrapper.outerHeight() aWidth = $anchor.outerWidth() aHeight = $anchor.outerHeight() aPosition = $anchor.offset() position = left: aPosition.left + parseInt($anchor.css('marginLeft'), 10) top: aPosition.top + parseInt($anchor.css('marginTop'), 10) switch @position when 'top' position.left += (aWidth - wWidth) / 2 position.top -= wHeight when 'right' position.left += aWidth position.top += (aHeight - wHeight) / 2 when 'bottom' position.left += (aWidth - wWidth) / 2 position.top += aHeight when 'left' position.left -= wWidth position.top += (aHeight - wHeight) / 2 $wrapper.css(position) @move() if ($wrapper.outerWidth() > wWidth || $wrapper.outerHeight() > wHeight) @ destroy: -> @hide() @$anchor.off focusin: @onEvenIn mouseenter: @onEvenIn mouseleave: @onEventOut focusout: @onEventOut @ onEvenIn : -> return if (@hovered) @hovered = true @show() onEventOut: -> return unless (@hovered) @hovered = false @hide() class History constructor: (@parent, @licenseSelector) -> @current = -1 @historyStack = [] @prevButton = $('<button/>') .addClass('ls-history-prev') .attr('title', 'Previous question') .append($('<span/>').addClass('icon-left')) .click => @go(@current - 1) @nextButton = $('<button/>') .addClass('ls-history-next') .attr('title', 'Next question') .append($('<span/>').addClass('icon-right')) .click => @go(@current + 1) @restartButton = $('<button/>') .addClass('ls-restart') .attr('title', 'Start again') .append($('<span/>').addClass('icon-ccw')) .append(' Start again') .click => @licenseSelector.restart() @progress = $('<div/>').addClass('ls-history-progress') history = $('<div/>').addClass('ls-history') .append(@restartButton) .append(@prevButton) .append(@progress) .append(@nextButton) .appendTo(@parent) @setupTooltips(history) @update() go: (point) -> @current = point state = _.cloneDeep @historyStack[@current] @licenseSelector.setState state @update() return reset: -> @current = -1 @historyStack = [] @progress.empty() @update() return setupTooltips: (root) -> self = @ $('[title]', root).each -> $el = $(@) title = $el.attr('title') $el.removeAttr('title') new Tooltip($('<div />').addClass('ls-tooltip').text(title), $el, { container: self.licenseSelector.container }) return return setAnswer: (text) -> return if @current == -1 state = @historyStack[@current] state.answer = text return setOptionSelected: (option, value) -> return if @current == -1 state = @historyStack[@current] state.options[option].selected = value return update: -> progressBarBlocks = @progress.children() # remove class ls-active from all children # then get @current and addClass 'ls-active' if progressBarBlocks.size() > 0 activeBlock = progressBarBlocks.removeClass('ls-active').get(@current) $(activeBlock).addClass('ls-active') if activeBlock? @nextButton.attr('disabled', @historyStack.length == 0 || @historyStack.length == @current + 1) @prevButton.attr('disabled', @current <= 0) return createProgressBlock: -> self = @ block = $('<button/>') .html('&nbsp;') .click -> self.go(self.progress.children().index(@)) new Tooltip($('<div/>').addClass('ls-tooltip'), block, { container: self.licenseSelector.container beforeShow: (tooltip, block, el) -> index = self.progress.children().index(block.get(0)) state = self.historyStack[index] el.empty() unless state.finished el.append($('<p/>').text(state.questionText)) if state.options ul = $('<ul />') for option in state.options continue unless option.selected span = $('<span/>') for license in option.licenses span.append($('<span/>').addClass('ls-license-name').text(license.name)) ul.append($('<li />').append(span)) el.append(ul) else el.append($('<p/>').html("Answered: <strong>#{state.answer}</strong>")) if (state.answer) else el.append($('<p/>').text("Final Step")) el.append($('<p/>').text("Choose your license below ...")) return true }) return block pushState: (state) -> # shallow clone of the state state = _.cloneDeep state # Trim stack if needed @current += 1 @historyStack = @historyStack.slice(0, @current) if @historyStack.length > @current @historyStack.push(state) #console.log @historyStack # trim progress bar progressBarBlocks = @progress.children().size() index = @current + 1 if progressBarBlocks != index if progressBarBlocks > index @progress.children().slice(index).remove() else @progress.append(@createProgressBlock()) @update() return class Question constructor: (@parent, @licenseSelector) -> @element = $('<div/>').addClass('ls-question') @errorContainer = $('<div/>').addClass('ls-question-error').append($('<h4/>').text("Can't choose a license")).appendTo(@element) @errorContainer.hide() @error = $('<span/>').appendTo(@errorContainer) @text = $('<p/>').addClass('ls-question-text').appendTo(@element) @options = $('<ul/>').appendTo($('<div/>').addClass('ls-question-options').appendTo(@element)) @answers = $('<div/>').addClass('ls-question-answers').appendTo(@element) @element.appendTo(@parent) show: -> @element.show() hide: -> @element.hide() reset: -> @errorContainer.hide() @answers.empty() @options.empty() @options.hide() @licenseSelector.licensesList.show() @element.off('update-answers') finished: -> @hide() @licenseSelector.licensesList.show() setQuestion: (text) -> @reset() @text.empty().append(addExplanations(text)) explanationTooltips(@text, @licenseSelector.container) return addAnswer: (answer) -> button = $('<button />') .text(answer.text) .click(-> answer.action()) .prop('disabled', answer.disabled()) @element.on('update-answers', -> button.prop('disabled', answer.disabled())) @answers.append(button) return addOption: (option) -> @options.show() @licenseSelector.licensesList.hide() element = @element self = @ checkbox = $('<input/>') .attr('type', 'checkbox') .prop('checked', option.selected) .click(-> option.selected = this.checked index = self.licenseSelector.state.options.indexOf(option) self.licenseSelector.historyModule.setOptionSelected(index, option.selected) element.trigger('update-answers') ) label = $('<label/>').append(checkbox) span = $('<span/>') for license in option.licenses span.append($('<span/>').addClass('ls-license-name').text(license.name)) label.append(span).appendTo($('<li/>').appendTo(@options)) return setError: (html) -> @errorContainer.show() @error.html(addExplanations(html)) explanationTooltips(@error, @licenseSelector.container) @licenseSelector.licensesList.hide() return class Modal # based on css-modal https://github.com/drublic/css-modal MODAL_SMALL_BREAKPOINT = 480 MODAL_MAX_WIDTH = 800 stylesheet = null scale = -> stylesheet = $('<style></style>').appendTo('head') unless stylesheet width = $(window).width() margin = 10 if width < MODAL_MAX_WIDTH currentMaxWidth = width - (margin * 2) leftMargin = currentMaxWidth / 2 closeButtonMarginRight = '-' + Math.floor(currentMaxWidth / 2) stylesheet.html(""" .license-selector .ls-modal { max-width: #{currentMaxWidth}px !important; margin-left: -#{leftMargin}px !important;} .license-selector .ls-modal-close:after { margin-right: #{closeButtonMarginRight}px !important; } """) else currentMaxWidth = MODAL_MAX_WIDTH - (margin * 2) leftMargin = currentMaxWidth / 2 stylesheet.html(""" .license-selector .ls-modal { max-width: #{currentMaxWidth}px; margin-left: -#{leftMargin}px;} .license-selector .ls-modal-close:after { margin-right: -#{leftMargin}px !important; } """) $(window).on 'resize', scale # create jquery && DOM constructor: (@parent) -> @element = $('<section/>') .addClass('license-selector') .attr( tabindex: '-1' 'aria-hidden': 'true' role: 'dialog' ).on 'show.lsmodal', scale inner = $('<div/>').addClass('ls-modal') @header = $('<header/>') .append($('<h2/>').text('Choose a License')) .append($('<p/>').text('Answer the questions or use the search to find the license you want')) .appendTo(inner) @content = $('<div/>').addClass('ls-modal-content').appendTo(inner) closeButton = $('<a/>') .addClass('ls-modal-close') .attr( 'title': 'Close License Selector' 'data-dismiss': 'modal' 'data-close': 'Close' ) .click(=> @hide()) @element.append(inner) .append(closeButton) .appendTo(@parent) hide: -> @element.removeClass('is-active') .trigger('hide.lsmodal') .attr('aria-hidden', 'true') show: -> @element.addClass('is-active') .trigger('show.lsmodal') .attr('aria-hidden', 'false') class Search constructor: (@parent, @licenseList) -> @textbox = $('<input/>') .attr( type: 'text', placeholder: 'Search for a license...' ) .on 'input', => @licenseList.filter(@textbox.val()) @container = $('<div/>') .addClass('ls-search') .append(@textbox) .appendTo(@parent) hide: -> @container.hide() show: -> @container.show() class LicenseList comperator = (obj, text) -> text = (''+text).toLowerCase() return (''+obj).toLowerCase().indexOf(text) > -1 constructor: (@parent, @licenseSelector) -> @availableLicenses = _.where @licenseSelector.licenses, { available: true } @list = $('<ul />') @error = $('<div/>').addClass('ls-not-found').append($('<h4/>').text('No license found')).append('Try change the search criteria or start the questionnaire again.') @error.hide() @container = $('<div class="ls-license-list" />') .append(@error) .append(@list) .appendTo(@parent) @update() createElement: (license) -> customTemplate = false el = $ '<li />' select = (e) => @selectLicense(license, el) @licenseSelector.selectLicense license if e? e.preventDefault() e.stopPropagation() if license.template if _.isFunction(license.template) license.template(el, license, select) customTemplate = true else if license.template instanceof $ el.append(license.template) else el.attr('title', 'Click to select the license') h = $('<h4 />').text(license.name) h.append($('<a/>').attr({ href: license.url target: '_blank' }).addClass('ls-button').text('See full text')) if license.url el.append(h) el.append($('<p />').text(license.description)) unless _.isEmpty(license.description) el.addClass(license.cssClass) if license.cssClass license.labels ||= [] if @licenseSelector.options.showLabels l = $('<div/>').addClass('ls-labels') for label in license.labels continue unless LabelsDefinitions[label] d = LabelsDefinitions[label] l.addClass(d.parentClass) if d.parentClass item = $('<span/>').addClass('ls-label') item.addClass(d.itemClass) if d.itemClass item.text(d.text) if d.text item.attr('title', d.title) if d.title l.append(item) el.append(l) el.addClass(license.cssClass) if license.cssClass unless customTemplate el.click (e) -> return if e.target && $(e.target).is('button, a') select(e) el.data 'license', license return el hide: -> @parent.hide() @licenseSelector.searchModule.hide() show: -> @parent.show() @licenseSelector.searchModule.show() filter: (newterm) -> if (newterm isnt @term) @term = newterm @update() return sortLicenses: (licenses) -> _.sortBy(licenses, ['priority','name']) selectLicense: (license, element) -> selectedLicense = @deselectLicense() if selectedLicense? and selectedLicense is license return element.addClass 'ls-active' @selectedLicense = license: license element: element deselectLicense: -> @selectedLicense ?= {} {element, license} = @selectedLicense element.removeClass 'ls-active' if element @selectedLicense = {} return license matchFilter: (license) -> return false unless license.available return true unless @term return comperator(license.name, @term) || comperator(license.description, @term) update: (licenses) -> unless licenses? licenses = @availableLicenses else licenses = @availableLicenses = _.where licenses, { available: true } elements = {} for el in @list.children() el = $(el) license = el.data 'license' if licenses[license.key]? and @matchFilter(licenses[license.key]) elements[license.key] = el else el.remove() previous = null for license in @sortLicenses(licenses) continue unless @matchFilter(license) if elements[license.key]? previous = elements[license.key] else el = @createElement license if previous? previous.after el else @list.prepend el previous = el if @list.children().size() == 0 @error.show() else @error.hide() return has: (category) -> _.any @availableLicenses, (license) -> _.contains(license.categories, category) only: (category) -> _.all @availableLicenses, (license) -> _.contains(license.categories, category) hasnt: (category) -> _.all @availableLicenses, (license) -> !_.contains(license.categories, category) include: (category) -> @availableLicenses = _.filter @availableLicenses, (license) -> _.contains(license.categories, category) @update() exclude: (category) -> @availableLicenses = _.filter @availableLicenses, (license) -> !_.contains(license.categories, category) @update() class LicenseSelector @defaultOptions = showLabels: true onLicenseSelected: _.noop licenseItemTemplate: null appendTo: 'body' start: 'KindOfContent' constructor: (@licenses, @questions, @options = {}) -> _.defaults(@options, LicenseSelector.defaultOptions) for key, license of @licenses license.key = key if @options.licenseItemTemplate and !license.template license.template = @options.licenseItemTemplate @state = {} @container = if @options.appendTo instanceof $ then @options.appendTo else $(@options.appendTo) @modal = new Modal(@container) @licensesList = new LicenseList(@modal.content, this) @historyModule = new History(@modal.header, this) @questionModule = new Question(@modal.header, this) @searchModule = new Search(@modal.header, @licensesList) @goto @options.start restart: -> @licensesList.update(@licenses) @historyModule.reset() @state = {} @goto @options.start return setState: (state) -> @state = state @questionModule.setQuestion(state.questionText) @questionModule.show() unless @state.finished @questionModule.hide() if @state.finished if state.options for option in state.options @questionModule.addOption(option) for answer in state.answers @questionModule.addAnswer(answer) @licensesList.update(state.licenses) return selectLicense: (license, force = false) -> if @selectedLicense is license or force @options.onLicenseSelected(license) @modal.hide() else @selectedLicense = license license: (choices...) -> if choices? and choices.length > 0 licenses = [] for choice in _.flatten(choices) license = @licenses[choice] if _.isString(choice) licenses.push license @licensesList.update(licenses) @state.licenses = licenses @state.finished = true @historyModule.pushState(@state) @questionModule.finished() return cantlicense: (reason) -> @questionModule.setError(reason) return goto: (where, safeState = true) -> @questionModule.show() unless @state.finished @questionModule.hide() if @state.finished if safeState @state.question = where @state.licenses ?= @licenses @state.finished = false func = @questions[where] func.call(@) @historyModule.pushState(@state) if safeState return question: (text) -> # setting question also resets the whole module @questionModule.setQuestion(text) delete @state.options delete @state.answers @state.answer = false @state.finished = false @state.questionText = text return answer: (text, action, disabled = _.noop) -> answer = text: text action: => @historyModule.setAnswer(text) action.call(@, @state) disabled: => disabled.call(@, @state) @state.answer = false @state.answers ?= [] @state.answers.push(answer) @questionModule.addAnswer(answer) return option: (list, action = _.noop) -> option = licenses: (@licenses[license] for license in list) action: => action.call(@, @state) @state.options ?= [] @state.options.push(option) @questionModule.addOption option return yes: (action) -> @answer 'Yes', action no: (action) -> @answer 'No', action has: (category) -> @licensesList.has(category) only: (category) -> @licensesList.only(category) hasnt: (category) -> @licensesList.hasnt(category) include: (category) -> @licensesList.include(category) @state.licenses = _.clone @licensesList.availableLicenses exclude: (category) -> @licensesList.exclude(category) @state.licenses = _.clone @licensesList.availableLicenses $.fn.licenseSelector = (options, args...) -> return @each -> if args.length > 0 throw new Error('Method has to be a string') unless _.isString(options) ls = $(this).data('license-selector') method = ls[options] throw new Error("Method #{options} does't exists") unless method? return method.apply(ls, args) licenses = _.merge(_.cloneDeep(LicenseDefinitions), options.licenses) questions = _.merge(_.cloneDeep(QuestionDefinitions), options.questions) delete options.questions delete options.licenses ls = new LicenseSelector(licenses, questions, options) $(this).data('license-selector', ls) $(this).click (e) -> ls.modal.show() e.preventDefault()
true
EVENT_NS = 'license-selector' $ = require 'jquery'; _ = require 'lodash'; {LicenseDefinitions, LicenseCompatibility, QuestionDefinitions, LabelsDefinitions} = require './definitions.coffee' # keyword : text Explanations = 'the scope of copyright and related rights': """ <p> Copyright protects original works. Originality is defined as the author’s own intellectual creation. Therefore, mere statements of historical facts, results of measurements etc. are not protected by copyright, because they exist objectively and therefore cannot be <em>created</em>. The same applies to ideas, mathematical formulas, elements of folklore etc. While quantitative data are usually not protected by copyright, qualitative data (as their creation involve some intellectual judgment) or language data are usually copyrightable. </p> <p> Apart from copyright in the data itself, a compilation of data (a dataset) may also be protected by copyright as an original work. It is the case when the selection and arrangement of the dataset involves some degree of intellectual creation or choice. This is not the case when the guiding principle of the collection is exhaustivity and/or completeness. For example, while <em>My favorite works of PI:NAME:<NAME>END_PI</em> will most likely be an original collection, <em>Complete works of PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI</em> will not, as it leaves no room for personal creativity. </p> <p> The investment (of money and/or labor) into the making of the dataset is irrelevant from the point of view of copyright law; however, a substantial investment into the creation of a database may attract a specific kind of protection, the sui generis database right. If your data and your dataset are not original, but you made a substantial investment into the making of a database, you can still benefit from legal protection (in such a case, answer YES to this question). </p> <p>Answer <strong>Yes</strong> if ...</p> <ul> <li>selecting a license for language data (in most cases)</li> <li>selecting a license for original (creative) selection or arrangement of the dataset</li> <li>substantial investment went into the making of the database</li> <li>you are not sure that the answer should be <strong>No</strong></li> </ul> <p>answer <strong>No</strong> if ...</p> <ul> <li>your dataset contains only quantitative data and/or raw facts</li> <li>your dataset is exhaustive and complete (or at least aims to be)</li> <li>only if you are sure!</li> </ul> """ 'copyright and similar rights': """ <p> <strong>copyright</strong> &ndash; protects original works or original compilations of works </p> <p> <strong>sui generis database rights</strong> &ndash; protects substantial investment into the making of a database </p> """ 'licensed under a public license': """ <p> By <em>licensed</em> data we understand data available under a public license, such as Creative Commons or ODC licenses. If you have a bespoke license for the data (i.e. a license drafted for a specific contractual agreement, such as between a publisher and a research institution), contact our legal help desk. </p> """ 'Public Domain': """ <p> Public Domain is a category including works that are not protected by copyright (such as raw facts, ideas) or that are no longer protected by copyright (copyright expires 70 years after the death of the author). In many jurisdictions, some official texts such as court decisions or statutes are also regarded as part of the public domain. </p> """ 'additional permission': """ <p> In order to be able to deposit your data in our repository, you will have to contact the copyright holder (usually the publisher or the author) and ask him for a written permission to do so. Our legal help desk will help you draft the permission. We will also tell you what to do if you cannot identify the copyright holder. </p> """ 'derivative works': """ <p> Derivative works are works that are derived from or based upon an original work and in which the original work is translated, altered, arranged, transformed, or otherwise modified. This category does not include parodies. </p> <p> Please note that the use of language resources consists of making derivative works. If you do not allow others to build on your work, it will be of very little use for the community. </p> """ 'commercial use': """ <p> Commercial use is a use that is primarily intended for or directed towards commercial advantage or monetary compensation. </p> <p> Please note that the meaning of this term is not entirely clear (although it seems to be generally agreed upon that academic research, even carried out by professional researchers, is not commercial use) and if you choose this restriction, it may have a chilling effect on the re-use of your resource by some projects (public-private partnerships). </p> """ 'attribute': """ <p> It is your moral right to have your work attributed to you (i.e. your name mentioned every time someone uses your work). However, be aware of the fact that the attribution requirement in Creative Commons licenses is more extended than just mentioning your name. </p> <p> In fact, the attribution clause in Creative Commons licenses obliges the user to mention a whole set of information (identity of the creator, a copyright notice, a reference to the chosen CC license and a hyperlink to its text, a disclaimer of warranties, an indication of any modifications made to the original work and even a hyperlink to the work itself). This may lead to a phenomenon known as <em>attribution stacking</em>, which will make your work difficult to compile with other works. </p> """ ExplanationsTerms = _.keys(Explanations) addExplanations = (text) -> for term in ExplanationsTerms index = text.indexOf(term) if ( index >= 0 ) text = text.substring(0,index) + '<span class="ls-term">' + text.substring(index, index + term.length) + '</span>' + text.substring(index + term.length) return text explanationTooltips = (scope, container) -> $('.ls-term', scope).each -> $el = $(this) term = $el.html() return unless Explanations[term] new Tooltip($('<div />').addClass('ls-term-tooltip').html(Explanations[term]), $el, { 'container': container position: 'bottom' }) return return # Inspired by devblog.orgsync.com/hangover/ class Tooltip constructor: (el, anchor, options) -> # defaults @position = 'top' # The position of $el relative to the $anchor. @preserve = false # Preserve $el's listeners and data by using detach instead of remove. @container = false # Append to specified container @beforeShow = false # Before show callback - used often to populate tooltip _.extend(@, options) if options @container = $(@container) if @container && !(@container instanceof $) @hovered = false _.bindAll(@, ['onEvenIn', 'onEventOut']) @buildContainer().setElement(el).setAnchor(anchor) buildContainer: -> @$wrapper = $('<div/>') .addClass('ls-tooltip-wrapper') .addClass("ls-tooltip-#{@position}") @ setElement: (el) -> @$wrapper.empty().append(@$el = if el instanceof $ then el else $(el)) @ setAnchor: (anchor) -> @$anchor.css('position', null) if @$anchor @$anchor = if anchor instanceof $ then anchor else $(anchor) @$anchor.on( focusin: @onEvenIn mouseenter: @onEvenIn mouseleave: @onEventOut focusout: @onEventOut ).css('position', 'relative') @ show: -> if !@beforeShow || @beforeShow(@, @$anchor, @$el) if @container @container.append(@$wrapper) else @$anchor.parent().append(@$wrapper) @move() @ hide: -> @$wrapper[if @preserve then 'detach' else 'remove' ]() @hovered = false @ move: -> $wrapper = @$wrapper $anchor = @$anchor wWidth = $wrapper.outerWidth() wHeight = $wrapper.outerHeight() aWidth = $anchor.outerWidth() aHeight = $anchor.outerHeight() aPosition = $anchor.offset() position = left: aPosition.left + parseInt($anchor.css('marginLeft'), 10) top: aPosition.top + parseInt($anchor.css('marginTop'), 10) switch @position when 'top' position.left += (aWidth - wWidth) / 2 position.top -= wHeight when 'right' position.left += aWidth position.top += (aHeight - wHeight) / 2 when 'bottom' position.left += (aWidth - wWidth) / 2 position.top += aHeight when 'left' position.left -= wWidth position.top += (aHeight - wHeight) / 2 $wrapper.css(position) @move() if ($wrapper.outerWidth() > wWidth || $wrapper.outerHeight() > wHeight) @ destroy: -> @hide() @$anchor.off focusin: @onEvenIn mouseenter: @onEvenIn mouseleave: @onEventOut focusout: @onEventOut @ onEvenIn : -> return if (@hovered) @hovered = true @show() onEventOut: -> return unless (@hovered) @hovered = false @hide() class History constructor: (@parent, @licenseSelector) -> @current = -1 @historyStack = [] @prevButton = $('<button/>') .addClass('ls-history-prev') .attr('title', 'Previous question') .append($('<span/>').addClass('icon-left')) .click => @go(@current - 1) @nextButton = $('<button/>') .addClass('ls-history-next') .attr('title', 'Next question') .append($('<span/>').addClass('icon-right')) .click => @go(@current + 1) @restartButton = $('<button/>') .addClass('ls-restart') .attr('title', 'Start again') .append($('<span/>').addClass('icon-ccw')) .append(' Start again') .click => @licenseSelector.restart() @progress = $('<div/>').addClass('ls-history-progress') history = $('<div/>').addClass('ls-history') .append(@restartButton) .append(@prevButton) .append(@progress) .append(@nextButton) .appendTo(@parent) @setupTooltips(history) @update() go: (point) -> @current = point state = _.cloneDeep @historyStack[@current] @licenseSelector.setState state @update() return reset: -> @current = -1 @historyStack = [] @progress.empty() @update() return setupTooltips: (root) -> self = @ $('[title]', root).each -> $el = $(@) title = $el.attr('title') $el.removeAttr('title') new Tooltip($('<div />').addClass('ls-tooltip').text(title), $el, { container: self.licenseSelector.container }) return return setAnswer: (text) -> return if @current == -1 state = @historyStack[@current] state.answer = text return setOptionSelected: (option, value) -> return if @current == -1 state = @historyStack[@current] state.options[option].selected = value return update: -> progressBarBlocks = @progress.children() # remove class ls-active from all children # then get @current and addClass 'ls-active' if progressBarBlocks.size() > 0 activeBlock = progressBarBlocks.removeClass('ls-active').get(@current) $(activeBlock).addClass('ls-active') if activeBlock? @nextButton.attr('disabled', @historyStack.length == 0 || @historyStack.length == @current + 1) @prevButton.attr('disabled', @current <= 0) return createProgressBlock: -> self = @ block = $('<button/>') .html('&nbsp;') .click -> self.go(self.progress.children().index(@)) new Tooltip($('<div/>').addClass('ls-tooltip'), block, { container: self.licenseSelector.container beforeShow: (tooltip, block, el) -> index = self.progress.children().index(block.get(0)) state = self.historyStack[index] el.empty() unless state.finished el.append($('<p/>').text(state.questionText)) if state.options ul = $('<ul />') for option in state.options continue unless option.selected span = $('<span/>') for license in option.licenses span.append($('<span/>').addClass('ls-license-name').text(license.name)) ul.append($('<li />').append(span)) el.append(ul) else el.append($('<p/>').html("Answered: <strong>#{state.answer}</strong>")) if (state.answer) else el.append($('<p/>').text("Final Step")) el.append($('<p/>').text("Choose your license below ...")) return true }) return block pushState: (state) -> # shallow clone of the state state = _.cloneDeep state # Trim stack if needed @current += 1 @historyStack = @historyStack.slice(0, @current) if @historyStack.length > @current @historyStack.push(state) #console.log @historyStack # trim progress bar progressBarBlocks = @progress.children().size() index = @current + 1 if progressBarBlocks != index if progressBarBlocks > index @progress.children().slice(index).remove() else @progress.append(@createProgressBlock()) @update() return class Question constructor: (@parent, @licenseSelector) -> @element = $('<div/>').addClass('ls-question') @errorContainer = $('<div/>').addClass('ls-question-error').append($('<h4/>').text("Can't choose a license")).appendTo(@element) @errorContainer.hide() @error = $('<span/>').appendTo(@errorContainer) @text = $('<p/>').addClass('ls-question-text').appendTo(@element) @options = $('<ul/>').appendTo($('<div/>').addClass('ls-question-options').appendTo(@element)) @answers = $('<div/>').addClass('ls-question-answers').appendTo(@element) @element.appendTo(@parent) show: -> @element.show() hide: -> @element.hide() reset: -> @errorContainer.hide() @answers.empty() @options.empty() @options.hide() @licenseSelector.licensesList.show() @element.off('update-answers') finished: -> @hide() @licenseSelector.licensesList.show() setQuestion: (text) -> @reset() @text.empty().append(addExplanations(text)) explanationTooltips(@text, @licenseSelector.container) return addAnswer: (answer) -> button = $('<button />') .text(answer.text) .click(-> answer.action()) .prop('disabled', answer.disabled()) @element.on('update-answers', -> button.prop('disabled', answer.disabled())) @answers.append(button) return addOption: (option) -> @options.show() @licenseSelector.licensesList.hide() element = @element self = @ checkbox = $('<input/>') .attr('type', 'checkbox') .prop('checked', option.selected) .click(-> option.selected = this.checked index = self.licenseSelector.state.options.indexOf(option) self.licenseSelector.historyModule.setOptionSelected(index, option.selected) element.trigger('update-answers') ) label = $('<label/>').append(checkbox) span = $('<span/>') for license in option.licenses span.append($('<span/>').addClass('ls-license-name').text(license.name)) label.append(span).appendTo($('<li/>').appendTo(@options)) return setError: (html) -> @errorContainer.show() @error.html(addExplanations(html)) explanationTooltips(@error, @licenseSelector.container) @licenseSelector.licensesList.hide() return class Modal # based on css-modal https://github.com/drublic/css-modal MODAL_SMALL_BREAKPOINT = 480 MODAL_MAX_WIDTH = 800 stylesheet = null scale = -> stylesheet = $('<style></style>').appendTo('head') unless stylesheet width = $(window).width() margin = 10 if width < MODAL_MAX_WIDTH currentMaxWidth = width - (margin * 2) leftMargin = currentMaxWidth / 2 closeButtonMarginRight = '-' + Math.floor(currentMaxWidth / 2) stylesheet.html(""" .license-selector .ls-modal { max-width: #{currentMaxWidth}px !important; margin-left: -#{leftMargin}px !important;} .license-selector .ls-modal-close:after { margin-right: #{closeButtonMarginRight}px !important; } """) else currentMaxWidth = MODAL_MAX_WIDTH - (margin * 2) leftMargin = currentMaxWidth / 2 stylesheet.html(""" .license-selector .ls-modal { max-width: #{currentMaxWidth}px; margin-left: -#{leftMargin}px;} .license-selector .ls-modal-close:after { margin-right: -#{leftMargin}px !important; } """) $(window).on 'resize', scale # create jquery && DOM constructor: (@parent) -> @element = $('<section/>') .addClass('license-selector') .attr( tabindex: '-1' 'aria-hidden': 'true' role: 'dialog' ).on 'show.lsmodal', scale inner = $('<div/>').addClass('ls-modal') @header = $('<header/>') .append($('<h2/>').text('Choose a License')) .append($('<p/>').text('Answer the questions or use the search to find the license you want')) .appendTo(inner) @content = $('<div/>').addClass('ls-modal-content').appendTo(inner) closeButton = $('<a/>') .addClass('ls-modal-close') .attr( 'title': 'Close License Selector' 'data-dismiss': 'modal' 'data-close': 'Close' ) .click(=> @hide()) @element.append(inner) .append(closeButton) .appendTo(@parent) hide: -> @element.removeClass('is-active') .trigger('hide.lsmodal') .attr('aria-hidden', 'true') show: -> @element.addClass('is-active') .trigger('show.lsmodal') .attr('aria-hidden', 'false') class Search constructor: (@parent, @licenseList) -> @textbox = $('<input/>') .attr( type: 'text', placeholder: 'Search for a license...' ) .on 'input', => @licenseList.filter(@textbox.val()) @container = $('<div/>') .addClass('ls-search') .append(@textbox) .appendTo(@parent) hide: -> @container.hide() show: -> @container.show() class LicenseList comperator = (obj, text) -> text = (''+text).toLowerCase() return (''+obj).toLowerCase().indexOf(text) > -1 constructor: (@parent, @licenseSelector) -> @availableLicenses = _.where @licenseSelector.licenses, { available: true } @list = $('<ul />') @error = $('<div/>').addClass('ls-not-found').append($('<h4/>').text('No license found')).append('Try change the search criteria or start the questionnaire again.') @error.hide() @container = $('<div class="ls-license-list" />') .append(@error) .append(@list) .appendTo(@parent) @update() createElement: (license) -> customTemplate = false el = $ '<li />' select = (e) => @selectLicense(license, el) @licenseSelector.selectLicense license if e? e.preventDefault() e.stopPropagation() if license.template if _.isFunction(license.template) license.template(el, license, select) customTemplate = true else if license.template instanceof $ el.append(license.template) else el.attr('title', 'Click to select the license') h = $('<h4 />').text(license.name) h.append($('<a/>').attr({ href: license.url target: '_blank' }).addClass('ls-button').text('See full text')) if license.url el.append(h) el.append($('<p />').text(license.description)) unless _.isEmpty(license.description) el.addClass(license.cssClass) if license.cssClass license.labels ||= [] if @licenseSelector.options.showLabels l = $('<div/>').addClass('ls-labels') for label in license.labels continue unless LabelsDefinitions[label] d = LabelsDefinitions[label] l.addClass(d.parentClass) if d.parentClass item = $('<span/>').addClass('ls-label') item.addClass(d.itemClass) if d.itemClass item.text(d.text) if d.text item.attr('title', d.title) if d.title l.append(item) el.append(l) el.addClass(license.cssClass) if license.cssClass unless customTemplate el.click (e) -> return if e.target && $(e.target).is('button, a') select(e) el.data 'license', license return el hide: -> @parent.hide() @licenseSelector.searchModule.hide() show: -> @parent.show() @licenseSelector.searchModule.show() filter: (newterm) -> if (newterm isnt @term) @term = newterm @update() return sortLicenses: (licenses) -> _.sortBy(licenses, ['priority','name']) selectLicense: (license, element) -> selectedLicense = @deselectLicense() if selectedLicense? and selectedLicense is license return element.addClass 'ls-active' @selectedLicense = license: license element: element deselectLicense: -> @selectedLicense ?= {} {element, license} = @selectedLicense element.removeClass 'ls-active' if element @selectedLicense = {} return license matchFilter: (license) -> return false unless license.available return true unless @term return comperator(license.name, @term) || comperator(license.description, @term) update: (licenses) -> unless licenses? licenses = @availableLicenses else licenses = @availableLicenses = _.where licenses, { available: true } elements = {} for el in @list.children() el = $(el) license = el.data 'license' if licenses[license.key]? and @matchFilter(licenses[license.key]) elements[license.key] = el else el.remove() previous = null for license in @sortLicenses(licenses) continue unless @matchFilter(license) if elements[license.key]? previous = elements[license.key] else el = @createElement license if previous? previous.after el else @list.prepend el previous = el if @list.children().size() == 0 @error.show() else @error.hide() return has: (category) -> _.any @availableLicenses, (license) -> _.contains(license.categories, category) only: (category) -> _.all @availableLicenses, (license) -> _.contains(license.categories, category) hasnt: (category) -> _.all @availableLicenses, (license) -> !_.contains(license.categories, category) include: (category) -> @availableLicenses = _.filter @availableLicenses, (license) -> _.contains(license.categories, category) @update() exclude: (category) -> @availableLicenses = _.filter @availableLicenses, (license) -> !_.contains(license.categories, category) @update() class LicenseSelector @defaultOptions = showLabels: true onLicenseSelected: _.noop licenseItemTemplate: null appendTo: 'body' start: 'KindOfContent' constructor: (@licenses, @questions, @options = {}) -> _.defaults(@options, LicenseSelector.defaultOptions) for key, license of @licenses license.key = key if @options.licenseItemTemplate and !license.template license.template = @options.licenseItemTemplate @state = {} @container = if @options.appendTo instanceof $ then @options.appendTo else $(@options.appendTo) @modal = new Modal(@container) @licensesList = new LicenseList(@modal.content, this) @historyModule = new History(@modal.header, this) @questionModule = new Question(@modal.header, this) @searchModule = new Search(@modal.header, @licensesList) @goto @options.start restart: -> @licensesList.update(@licenses) @historyModule.reset() @state = {} @goto @options.start return setState: (state) -> @state = state @questionModule.setQuestion(state.questionText) @questionModule.show() unless @state.finished @questionModule.hide() if @state.finished if state.options for option in state.options @questionModule.addOption(option) for answer in state.answers @questionModule.addAnswer(answer) @licensesList.update(state.licenses) return selectLicense: (license, force = false) -> if @selectedLicense is license or force @options.onLicenseSelected(license) @modal.hide() else @selectedLicense = license license: (choices...) -> if choices? and choices.length > 0 licenses = [] for choice in _.flatten(choices) license = @licenses[choice] if _.isString(choice) licenses.push license @licensesList.update(licenses) @state.licenses = licenses @state.finished = true @historyModule.pushState(@state) @questionModule.finished() return cantlicense: (reason) -> @questionModule.setError(reason) return goto: (where, safeState = true) -> @questionModule.show() unless @state.finished @questionModule.hide() if @state.finished if safeState @state.question = where @state.licenses ?= @licenses @state.finished = false func = @questions[where] func.call(@) @historyModule.pushState(@state) if safeState return question: (text) -> # setting question also resets the whole module @questionModule.setQuestion(text) delete @state.options delete @state.answers @state.answer = false @state.finished = false @state.questionText = text return answer: (text, action, disabled = _.noop) -> answer = text: text action: => @historyModule.setAnswer(text) action.call(@, @state) disabled: => disabled.call(@, @state) @state.answer = false @state.answers ?= [] @state.answers.push(answer) @questionModule.addAnswer(answer) return option: (list, action = _.noop) -> option = licenses: (@licenses[license] for license in list) action: => action.call(@, @state) @state.options ?= [] @state.options.push(option) @questionModule.addOption option return yes: (action) -> @answer 'Yes', action no: (action) -> @answer 'No', action has: (category) -> @licensesList.has(category) only: (category) -> @licensesList.only(category) hasnt: (category) -> @licensesList.hasnt(category) include: (category) -> @licensesList.include(category) @state.licenses = _.clone @licensesList.availableLicenses exclude: (category) -> @licensesList.exclude(category) @state.licenses = _.clone @licensesList.availableLicenses $.fn.licenseSelector = (options, args...) -> return @each -> if args.length > 0 throw new Error('Method has to be a string') unless _.isString(options) ls = $(this).data('license-selector') method = ls[options] throw new Error("Method #{options} does't exists") unless method? return method.apply(ls, args) licenses = _.merge(_.cloneDeep(LicenseDefinitions), options.licenses) questions = _.merge(_.cloneDeep(QuestionDefinitions), options.questions) delete options.questions delete options.licenses ls = new LicenseSelector(licenses, questions, options) $(this).data('license-selector', ls) $(this).click (e) -> ls.modal.show() e.preventDefault()
[ { "context": "KOU_CONDUCTOR_ROUTING_KEY\"]\n\n# https://github.com/joukou/joukou-conductor-rabbitmq/blob/develop/src/lib/co", "end": 1159, "score": 0.9993212223052979, "start": 1153, "tag": "USERNAME", "value": "joukou" }, { "context": "onductorRoutingKey\n JoukouConductorRoutingKey = \"CONDUCTOR\"\n process.env[\"JOUKOU_CONDUCTOR_ROUTING_KEY\"] = ", "end": 1456, "score": 0.9987029433250427, "start": 1447, "tag": "KEY", "value": "CONDUCTOR" } ]
src/persona/graph/network/routes.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. ### ###* {@link module:joukou-api/persona/graph/network/Model|Network} APIs. @module joukou-api/persona/graph/network/routes ### authn = require( '../../../authn' ) authz = require( '../../../authz' ) env = require( '../../../env' ) GraphModel = require( '../model' ) _ = require( 'lodash' ) { RabbitMQClient } = require( 'joukou-conductor-rabbitmq' ) JoukouConductorExchange = process.env["JOUKOU_CONDUCTOR_EXCHANGE"] JoukouConductorRoutingKey = process.env["JOUKOU_CONDUCTOR_ROUTING_KEY"] # https://github.com/joukou/joukou-conductor-rabbitmq/blob/develop/src/lib/conductor-client.coffee#L13 if not JoukouConductorExchange JoukouConductorExchange = "amqp://localhost" process.env["JOUKOU_CONDUCTOR_EXCHANGE"] = JoukouConductorExchange if not JoukouConductorRoutingKey JoukouConductorRoutingKey = "CONDUCTOR" process.env["JOUKOU_CONDUCTOR_ROUTING_KEY"] = JoukouConductorRoutingKey self = ###* @param {joukou-api/server} server ### registerRoutes: ( server ) -> server.get( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.retrieve ) server.post( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.update ) server.put( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.update ) retrieve: (req, res, next) -> GraphModel.retrieve(req.params.graphKey) .then( (model) -> res.send(200, model.getValue().network or {}) ) .fail(next) update: (req, res) -> authz.hasGraph(req.user, req.params.graphKey, req.params.personaKey) .then( ( { graph, persona } ) -> value = graph.getValue() value.network = _.assign(value.network or {}, req.body) graph.setValue(value.network) graph.save() .then((graph) -> client = new RabbitMQClient( JoukouConductorExchange, JoukouConductorRoutingKey ) host = env.getHost() message = { '_links': { 'joukou:graph': { #TODO change host to env href: "#{host}/persona/#{req.params.personaKey}/graph/#{req.params.graphKey}" } } } client.send( message ) .then( -> res.send(200, graph.getValue().network) ) ) ) .fail(next) module.exports = self
65466
"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. ### ###* {@link module:joukou-api/persona/graph/network/Model|Network} APIs. @module joukou-api/persona/graph/network/routes ### authn = require( '../../../authn' ) authz = require( '../../../authz' ) env = require( '../../../env' ) GraphModel = require( '../model' ) _ = require( 'lodash' ) { RabbitMQClient } = require( 'joukou-conductor-rabbitmq' ) JoukouConductorExchange = process.env["JOUKOU_CONDUCTOR_EXCHANGE"] JoukouConductorRoutingKey = process.env["JOUKOU_CONDUCTOR_ROUTING_KEY"] # https://github.com/joukou/joukou-conductor-rabbitmq/blob/develop/src/lib/conductor-client.coffee#L13 if not JoukouConductorExchange JoukouConductorExchange = "amqp://localhost" process.env["JOUKOU_CONDUCTOR_EXCHANGE"] = JoukouConductorExchange if not JoukouConductorRoutingKey JoukouConductorRoutingKey = "<KEY>" process.env["JOUKOU_CONDUCTOR_ROUTING_KEY"] = JoukouConductorRoutingKey self = ###* @param {joukou-api/server} server ### registerRoutes: ( server ) -> server.get( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.retrieve ) server.post( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.update ) server.put( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.update ) retrieve: (req, res, next) -> GraphModel.retrieve(req.params.graphKey) .then( (model) -> res.send(200, model.getValue().network or {}) ) .fail(next) update: (req, res) -> authz.hasGraph(req.user, req.params.graphKey, req.params.personaKey) .then( ( { graph, persona } ) -> value = graph.getValue() value.network = _.assign(value.network or {}, req.body) graph.setValue(value.network) graph.save() .then((graph) -> client = new RabbitMQClient( JoukouConductorExchange, JoukouConductorRoutingKey ) host = env.getHost() message = { '_links': { 'joukou:graph': { #TODO change host to env href: "#{host}/persona/#{req.params.personaKey}/graph/#{req.params.graphKey}" } } } client.send( message ) .then( -> res.send(200, graph.getValue().network) ) ) ) .fail(next) module.exports = self
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. ### ###* {@link module:joukou-api/persona/graph/network/Model|Network} APIs. @module joukou-api/persona/graph/network/routes ### authn = require( '../../../authn' ) authz = require( '../../../authz' ) env = require( '../../../env' ) GraphModel = require( '../model' ) _ = require( 'lodash' ) { RabbitMQClient } = require( 'joukou-conductor-rabbitmq' ) JoukouConductorExchange = process.env["JOUKOU_CONDUCTOR_EXCHANGE"] JoukouConductorRoutingKey = process.env["JOUKOU_CONDUCTOR_ROUTING_KEY"] # https://github.com/joukou/joukou-conductor-rabbitmq/blob/develop/src/lib/conductor-client.coffee#L13 if not JoukouConductorExchange JoukouConductorExchange = "amqp://localhost" process.env["JOUKOU_CONDUCTOR_EXCHANGE"] = JoukouConductorExchange if not JoukouConductorRoutingKey JoukouConductorRoutingKey = "PI:KEY:<KEY>END_PI" process.env["JOUKOU_CONDUCTOR_ROUTING_KEY"] = JoukouConductorRoutingKey self = ###* @param {joukou-api/server} server ### registerRoutes: ( server ) -> server.get( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.retrieve ) server.post( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.update ) server.put( '/persona/:personaKey/graph/:graphKey/network', authn.authenticate, self.update ) retrieve: (req, res, next) -> GraphModel.retrieve(req.params.graphKey) .then( (model) -> res.send(200, model.getValue().network or {}) ) .fail(next) update: (req, res) -> authz.hasGraph(req.user, req.params.graphKey, req.params.personaKey) .then( ( { graph, persona } ) -> value = graph.getValue() value.network = _.assign(value.network or {}, req.body) graph.setValue(value.network) graph.save() .then((graph) -> client = new RabbitMQClient( JoukouConductorExchange, JoukouConductorRoutingKey ) host = env.getHost() message = { '_links': { 'joukou:graph': { #TODO change host to env href: "#{host}/persona/#{req.params.personaKey}/graph/#{req.params.graphKey}" } } } client.send( message ) .then( -> res.send(200, graph.getValue().network) ) ) ) .fail(next) module.exports = self
[ { "context": "#!/usr/bin/env node\n\n###\n# @author Jinzulen\n# @license MIT License\n# @copyright Copyright (C)", "end": 43, "score": 0.9997485876083374, "start": 35, "tag": "NAME", "value": "Jinzulen" }, { "context": "icense MIT License\n# @copyright Copyright (C) 2020 Jinzulen\n###\n\n# Core dependencies.\nOS = require ", "end": 107, "score": 0.9989837408065796, "start": 99, "tag": "NAME", "value": "Jinzulen" }, { "context": "the <MIT> license by Jinzulen (https://github.com/Jinzulen).\\n\"\n console.log \"# Bug reports/featu", "end": 1804, "score": 0.9996238946914673, "start": 1796, "tag": "USERNAME", "value": "Jinzulen" }, { "context": " Bug reports/feature requests: https://github.com/Jinzulen/Yume-Console/issues\"\n console.log \"# P", "end": 1894, "score": 0.9995847940444946, "start": 1886, "tag": "USERNAME", "value": "Jinzulen" }, { "context": " Package = [\"https://raw.githubusercontent.com/Jinzulen/Yume-Console/master/package.json\", YumeVersion]\n\n", "end": 9653, "score": 0.9832966923713684, "start": 9645, "tag": "USERNAME", "value": "Jinzulen" } ]
src/index.coffee
Jinzulen/YumeCLI
1
#!/usr/bin/env node ### # @author Jinzulen # @license MIT License # @copyright Copyright (C) 2020 Jinzulen ### # Core dependencies. OS = require "os" FS = require "fs" Path = require "path" JSZip = require "jszip" Moment = require "moment" Request = require "request" Commander = require "commander" Underscore = require "underscore" consoleTable = require "console.table" # Initialize JSZip. ZIP = new JSZip # Mangadex. Gateway = "https://mangadex.org/api" Mangadex = require "../mangadex.json" YumeVersion = require(Path.join(__dirname, "../package.json"))["version"] module.exports = new class Yume constructor: () -> App = new Commander.Command ## --version App.version YumeVersion App .option "-a, --about", "About dialog." .option "-g, --group <name>", "Sort out chapter display by group." .option "-m, --manga <id>", "Show the chapter list for a given manga." .option "-z, --zip", "(Optional) Zips the downloaded chapter in an archive." .option "-c, --chapter <id>", "The ID for the chapter you wish to download." .option "-o, --order <type>", "Sort out chapter display either in ascending or descending." .option "-l, --language <code>", "(Optional) Limit chapter display to ones of a specific language." .option "-s, --show", "(Optional) Will show the image link in the 'Finished downloading' notice." .parse process.argv # Check for a new version of the app. this.isUpdateAvailable() # About dialog. if App.about console.log "# Yume - Convenient CLI solution for manga downloads." console.log "# Published under the <MIT> license by Jinzulen (https://github.com/Jinzulen).\n" console.log "# Bug reports/feature requests: https://github.com/Jinzulen/Yume-Console/issues" console.log "# P.S: Don't be a douche, use this tool with care and don't abuse the kindness of Mangadex." # Handle manga/listing requests. if App.manga then this.handleManga App # If the user has selected a chapter for download, we want a different process to handle it. if App.chapter then this.handleChapter App handleManga: (App) -> try this.contactAPI "manga", App.manga, (Error, Data) -> if Error throw Error # Store data. Manga = Data.manga Chapters = Data.chapter # Get language and group specific chapter amounts. cAmount = Object.keys(Chapters).length if App.language and not App.group then cAmount = Underscore.where(Chapters, {lang_code: App.language}).length if App.group and not App.language then cAmount = Underscore.where(Chapters, {group_name: (App.group).toLowerCase().split(" ").map((S) -> S.charAt(0).toUpperCase() + S.substring(1)).join(" ")}).length # Print data. console.log "### " + Manga.title console.log "# Artist: " + Manga.artist console.log "# Author: " + Manga.author console.log "# Status: " + Mangadex.Status[Manga.status] + "\n" console.log "# Chapters (" + cAmount + "):" # List chapters. chapterList = [] Chaps = Object.keys Chapters # Why not just include this in the data object to begin with? istg... for i in Chaps then Chapters[i]["chapter_id"] = i # If a group is specified then search the data for matches. if App.order == "desc" then Chapters = (Underscore.sortBy Chapters, Chapters.chapter).reverse() else Chapters = Underscore.sortBy Chapters, Chapters.chapter # If a group is specified then search the data for matches. if App.language then Chapters = Underscore.where(Chapters, { lang_code: App.language }) # If a group is specified then search the data for matches. if App.group then Chapters = Underscore.where(Chapters, { group_name: (App.group).toLowerCase().split(" ").map((S) -> S.charAt(0).toUpperCase() + S.substring(1)).join(" ") }) i = 0 while i < Object.keys(Chapters).length # Fill-up the table. chapterList.push [ Chapters[i].chapter_id, Mangadex.Language[Chapters[i].lang_code], Chapters[i].chapter, Chapters[i].volume, Chapters[i].title, Chapters[i].group_name, Moment.unix(Chapters[i].timestamp).format("DD/MM/YYYY") ] i++ console.table ["ID", "Lang", "Ch.", "Vol.", "Title", "Group Name", "Date"], chapterList catch E throw E handleChapter: (App) -> try this.contactAPI "chapter", App.chapter, (Error, Data) -> if Error throw Error # Get around Windows' folder naming issues. Title = (Data.title).replace(/[/:*?"<>|.]/g, "") # Define our directories. YumeFolder = OS.homedir() + "/Downloads/Yume/" # Chapter naming conditionals. if Data.chapter and Data.title then Stat = "Ch " + Data.chapter + " - " + Title if Data.chapter and not Data.title then Stat = "Ch " + Data.chapter if Data.title and not Data.chapter then Stat = Data.title if not Data.title and not Data.chapter then Stat = Data.id chapterFolder = Stat # Check for the existence of necessary directories and create them if they don't exist. if not FS.existsSync YumeFolder then FS.mkdirSync YumeFolder if not App.zip and not FS.existsSync YumeFolder + chapterFolder then FS.mkdirSync YumeFolder + chapterFolder Download = (URI, Page, Callback) -> Request.head URI, (Error, Response, Body) -> if Error throw Error if App.zip Request { uri: URI, encoding: null }, (Error, Response, DataP) -> Buff = new Buffer.from DataP, "binary" Image = Buff.toString "base64" ZIP.file Page, Image, { base64: true } ZIP .generateNodeStream { type: "nodebuffer", streamFiles: true } .pipe FS.createWriteStream YumeFolder + chapterFolder + ".zip" .on "finish", () -> if App.show console.log "# [" + Data.id + "] Finished downloading: " + Page + " @ " + URI else console.log "# [" + Data.id + "] Finished downloading: " + Page .on "close", Callback .on "error", console.error else Stream = Request URI .pipe FS.createWriteStream YumeFolder + chapterFolder + "/" + Page .on "close", Callback .on "error", console.error Stream.on "finish", () -> if App.show console.log "# [" + Data.id + "] Finished downloading: " + Page + " @ " + URI else console.log "# [" + Data.id + "] Finished downloading: " + Page # Initiate download. chapterPages = Data.page_array; i = 0 while i < chapterPages.length Download Data.server + Data.hash + "/" + chapterPages[i], chapterPages[i], () -> # Nothing. i++ catch E throw E contactAPI: (subjectType, subjectId, Callback) -> try return new Promise (Resolve, Reject) -> if typeof Callback == "function" return new Promise (Resolve, Reject) -> Request { json: true, uri: Gateway + "/" + subjectType + "/" + subjectId }, (Error, Data) -> if Error throw Error if Data.body.status != "OK" if subjectType == "manga" then return console.log "# [Error] " + Data.body.status if subjectType == "chapter" then return console.log "# [Error] " + Data.body.message else Callback null, Data.body catch E throw E isUpdateAvailable: () -> try Package = ["https://raw.githubusercontent.com/Jinzulen/Yume-Console/master/package.json", YumeVersion] return Request Package[0], (Error, Data) -> Version = JSON.parse(Data.body).version if Package[1] < Version console.log "# You are running an oudated version of Yume-Console (v" + Package[1] + "), please update to v" + Version + " as soon as possible." console.log "# You can update Yume-Console by using its install command: npm i yumec -g" process.exit 1 catch E throw E
191667
#!/usr/bin/env node ### # @author <NAME> # @license MIT License # @copyright Copyright (C) 2020 <NAME> ### # Core dependencies. OS = require "os" FS = require "fs" Path = require "path" JSZip = require "jszip" Moment = require "moment" Request = require "request" Commander = require "commander" Underscore = require "underscore" consoleTable = require "console.table" # Initialize JSZip. ZIP = new JSZip # Mangadex. Gateway = "https://mangadex.org/api" Mangadex = require "../mangadex.json" YumeVersion = require(Path.join(__dirname, "../package.json"))["version"] module.exports = new class Yume constructor: () -> App = new Commander.Command ## --version App.version YumeVersion App .option "-a, --about", "About dialog." .option "-g, --group <name>", "Sort out chapter display by group." .option "-m, --manga <id>", "Show the chapter list for a given manga." .option "-z, --zip", "(Optional) Zips the downloaded chapter in an archive." .option "-c, --chapter <id>", "The ID for the chapter you wish to download." .option "-o, --order <type>", "Sort out chapter display either in ascending or descending." .option "-l, --language <code>", "(Optional) Limit chapter display to ones of a specific language." .option "-s, --show", "(Optional) Will show the image link in the 'Finished downloading' notice." .parse process.argv # Check for a new version of the app. this.isUpdateAvailable() # About dialog. if App.about console.log "# Yume - Convenient CLI solution for manga downloads." console.log "# Published under the <MIT> license by Jinzulen (https://github.com/Jinzulen).\n" console.log "# Bug reports/feature requests: https://github.com/Jinzulen/Yume-Console/issues" console.log "# P.S: Don't be a douche, use this tool with care and don't abuse the kindness of Mangadex." # Handle manga/listing requests. if App.manga then this.handleManga App # If the user has selected a chapter for download, we want a different process to handle it. if App.chapter then this.handleChapter App handleManga: (App) -> try this.contactAPI "manga", App.manga, (Error, Data) -> if Error throw Error # Store data. Manga = Data.manga Chapters = Data.chapter # Get language and group specific chapter amounts. cAmount = Object.keys(Chapters).length if App.language and not App.group then cAmount = Underscore.where(Chapters, {lang_code: App.language}).length if App.group and not App.language then cAmount = Underscore.where(Chapters, {group_name: (App.group).toLowerCase().split(" ").map((S) -> S.charAt(0).toUpperCase() + S.substring(1)).join(" ")}).length # Print data. console.log "### " + Manga.title console.log "# Artist: " + Manga.artist console.log "# Author: " + Manga.author console.log "# Status: " + Mangadex.Status[Manga.status] + "\n" console.log "# Chapters (" + cAmount + "):" # List chapters. chapterList = [] Chaps = Object.keys Chapters # Why not just include this in the data object to begin with? istg... for i in Chaps then Chapters[i]["chapter_id"] = i # If a group is specified then search the data for matches. if App.order == "desc" then Chapters = (Underscore.sortBy Chapters, Chapters.chapter).reverse() else Chapters = Underscore.sortBy Chapters, Chapters.chapter # If a group is specified then search the data for matches. if App.language then Chapters = Underscore.where(Chapters, { lang_code: App.language }) # If a group is specified then search the data for matches. if App.group then Chapters = Underscore.where(Chapters, { group_name: (App.group).toLowerCase().split(" ").map((S) -> S.charAt(0).toUpperCase() + S.substring(1)).join(" ") }) i = 0 while i < Object.keys(Chapters).length # Fill-up the table. chapterList.push [ Chapters[i].chapter_id, Mangadex.Language[Chapters[i].lang_code], Chapters[i].chapter, Chapters[i].volume, Chapters[i].title, Chapters[i].group_name, Moment.unix(Chapters[i].timestamp).format("DD/MM/YYYY") ] i++ console.table ["ID", "Lang", "Ch.", "Vol.", "Title", "Group Name", "Date"], chapterList catch E throw E handleChapter: (App) -> try this.contactAPI "chapter", App.chapter, (Error, Data) -> if Error throw Error # Get around Windows' folder naming issues. Title = (Data.title).replace(/[/:*?"<>|.]/g, "") # Define our directories. YumeFolder = OS.homedir() + "/Downloads/Yume/" # Chapter naming conditionals. if Data.chapter and Data.title then Stat = "Ch " + Data.chapter + " - " + Title if Data.chapter and not Data.title then Stat = "Ch " + Data.chapter if Data.title and not Data.chapter then Stat = Data.title if not Data.title and not Data.chapter then Stat = Data.id chapterFolder = Stat # Check for the existence of necessary directories and create them if they don't exist. if not FS.existsSync YumeFolder then FS.mkdirSync YumeFolder if not App.zip and not FS.existsSync YumeFolder + chapterFolder then FS.mkdirSync YumeFolder + chapterFolder Download = (URI, Page, Callback) -> Request.head URI, (Error, Response, Body) -> if Error throw Error if App.zip Request { uri: URI, encoding: null }, (Error, Response, DataP) -> Buff = new Buffer.from DataP, "binary" Image = Buff.toString "base64" ZIP.file Page, Image, { base64: true } ZIP .generateNodeStream { type: "nodebuffer", streamFiles: true } .pipe FS.createWriteStream YumeFolder + chapterFolder + ".zip" .on "finish", () -> if App.show console.log "# [" + Data.id + "] Finished downloading: " + Page + " @ " + URI else console.log "# [" + Data.id + "] Finished downloading: " + Page .on "close", Callback .on "error", console.error else Stream = Request URI .pipe FS.createWriteStream YumeFolder + chapterFolder + "/" + Page .on "close", Callback .on "error", console.error Stream.on "finish", () -> if App.show console.log "# [" + Data.id + "] Finished downloading: " + Page + " @ " + URI else console.log "# [" + Data.id + "] Finished downloading: " + Page # Initiate download. chapterPages = Data.page_array; i = 0 while i < chapterPages.length Download Data.server + Data.hash + "/" + chapterPages[i], chapterPages[i], () -> # Nothing. i++ catch E throw E contactAPI: (subjectType, subjectId, Callback) -> try return new Promise (Resolve, Reject) -> if typeof Callback == "function" return new Promise (Resolve, Reject) -> Request { json: true, uri: Gateway + "/" + subjectType + "/" + subjectId }, (Error, Data) -> if Error throw Error if Data.body.status != "OK" if subjectType == "manga" then return console.log "# [Error] " + Data.body.status if subjectType == "chapter" then return console.log "# [Error] " + Data.body.message else Callback null, Data.body catch E throw E isUpdateAvailable: () -> try Package = ["https://raw.githubusercontent.com/Jinzulen/Yume-Console/master/package.json", YumeVersion] return Request Package[0], (Error, Data) -> Version = JSON.parse(Data.body).version if Package[1] < Version console.log "# You are running an oudated version of Yume-Console (v" + Package[1] + "), please update to v" + Version + " as soon as possible." console.log "# You can update Yume-Console by using its install command: npm i yumec -g" process.exit 1 catch E throw E
true
#!/usr/bin/env node ### # @author PI:NAME:<NAME>END_PI # @license MIT License # @copyright Copyright (C) 2020 PI:NAME:<NAME>END_PI ### # Core dependencies. OS = require "os" FS = require "fs" Path = require "path" JSZip = require "jszip" Moment = require "moment" Request = require "request" Commander = require "commander" Underscore = require "underscore" consoleTable = require "console.table" # Initialize JSZip. ZIP = new JSZip # Mangadex. Gateway = "https://mangadex.org/api" Mangadex = require "../mangadex.json" YumeVersion = require(Path.join(__dirname, "../package.json"))["version"] module.exports = new class Yume constructor: () -> App = new Commander.Command ## --version App.version YumeVersion App .option "-a, --about", "About dialog." .option "-g, --group <name>", "Sort out chapter display by group." .option "-m, --manga <id>", "Show the chapter list for a given manga." .option "-z, --zip", "(Optional) Zips the downloaded chapter in an archive." .option "-c, --chapter <id>", "The ID for the chapter you wish to download." .option "-o, --order <type>", "Sort out chapter display either in ascending or descending." .option "-l, --language <code>", "(Optional) Limit chapter display to ones of a specific language." .option "-s, --show", "(Optional) Will show the image link in the 'Finished downloading' notice." .parse process.argv # Check for a new version of the app. this.isUpdateAvailable() # About dialog. if App.about console.log "# Yume - Convenient CLI solution for manga downloads." console.log "# Published under the <MIT> license by Jinzulen (https://github.com/Jinzulen).\n" console.log "# Bug reports/feature requests: https://github.com/Jinzulen/Yume-Console/issues" console.log "# P.S: Don't be a douche, use this tool with care and don't abuse the kindness of Mangadex." # Handle manga/listing requests. if App.manga then this.handleManga App # If the user has selected a chapter for download, we want a different process to handle it. if App.chapter then this.handleChapter App handleManga: (App) -> try this.contactAPI "manga", App.manga, (Error, Data) -> if Error throw Error # Store data. Manga = Data.manga Chapters = Data.chapter # Get language and group specific chapter amounts. cAmount = Object.keys(Chapters).length if App.language and not App.group then cAmount = Underscore.where(Chapters, {lang_code: App.language}).length if App.group and not App.language then cAmount = Underscore.where(Chapters, {group_name: (App.group).toLowerCase().split(" ").map((S) -> S.charAt(0).toUpperCase() + S.substring(1)).join(" ")}).length # Print data. console.log "### " + Manga.title console.log "# Artist: " + Manga.artist console.log "# Author: " + Manga.author console.log "# Status: " + Mangadex.Status[Manga.status] + "\n" console.log "# Chapters (" + cAmount + "):" # List chapters. chapterList = [] Chaps = Object.keys Chapters # Why not just include this in the data object to begin with? istg... for i in Chaps then Chapters[i]["chapter_id"] = i # If a group is specified then search the data for matches. if App.order == "desc" then Chapters = (Underscore.sortBy Chapters, Chapters.chapter).reverse() else Chapters = Underscore.sortBy Chapters, Chapters.chapter # If a group is specified then search the data for matches. if App.language then Chapters = Underscore.where(Chapters, { lang_code: App.language }) # If a group is specified then search the data for matches. if App.group then Chapters = Underscore.where(Chapters, { group_name: (App.group).toLowerCase().split(" ").map((S) -> S.charAt(0).toUpperCase() + S.substring(1)).join(" ") }) i = 0 while i < Object.keys(Chapters).length # Fill-up the table. chapterList.push [ Chapters[i].chapter_id, Mangadex.Language[Chapters[i].lang_code], Chapters[i].chapter, Chapters[i].volume, Chapters[i].title, Chapters[i].group_name, Moment.unix(Chapters[i].timestamp).format("DD/MM/YYYY") ] i++ console.table ["ID", "Lang", "Ch.", "Vol.", "Title", "Group Name", "Date"], chapterList catch E throw E handleChapter: (App) -> try this.contactAPI "chapter", App.chapter, (Error, Data) -> if Error throw Error # Get around Windows' folder naming issues. Title = (Data.title).replace(/[/:*?"<>|.]/g, "") # Define our directories. YumeFolder = OS.homedir() + "/Downloads/Yume/" # Chapter naming conditionals. if Data.chapter and Data.title then Stat = "Ch " + Data.chapter + " - " + Title if Data.chapter and not Data.title then Stat = "Ch " + Data.chapter if Data.title and not Data.chapter then Stat = Data.title if not Data.title and not Data.chapter then Stat = Data.id chapterFolder = Stat # Check for the existence of necessary directories and create them if they don't exist. if not FS.existsSync YumeFolder then FS.mkdirSync YumeFolder if not App.zip and not FS.existsSync YumeFolder + chapterFolder then FS.mkdirSync YumeFolder + chapterFolder Download = (URI, Page, Callback) -> Request.head URI, (Error, Response, Body) -> if Error throw Error if App.zip Request { uri: URI, encoding: null }, (Error, Response, DataP) -> Buff = new Buffer.from DataP, "binary" Image = Buff.toString "base64" ZIP.file Page, Image, { base64: true } ZIP .generateNodeStream { type: "nodebuffer", streamFiles: true } .pipe FS.createWriteStream YumeFolder + chapterFolder + ".zip" .on "finish", () -> if App.show console.log "# [" + Data.id + "] Finished downloading: " + Page + " @ " + URI else console.log "# [" + Data.id + "] Finished downloading: " + Page .on "close", Callback .on "error", console.error else Stream = Request URI .pipe FS.createWriteStream YumeFolder + chapterFolder + "/" + Page .on "close", Callback .on "error", console.error Stream.on "finish", () -> if App.show console.log "# [" + Data.id + "] Finished downloading: " + Page + " @ " + URI else console.log "# [" + Data.id + "] Finished downloading: " + Page # Initiate download. chapterPages = Data.page_array; i = 0 while i < chapterPages.length Download Data.server + Data.hash + "/" + chapterPages[i], chapterPages[i], () -> # Nothing. i++ catch E throw E contactAPI: (subjectType, subjectId, Callback) -> try return new Promise (Resolve, Reject) -> if typeof Callback == "function" return new Promise (Resolve, Reject) -> Request { json: true, uri: Gateway + "/" + subjectType + "/" + subjectId }, (Error, Data) -> if Error throw Error if Data.body.status != "OK" if subjectType == "manga" then return console.log "# [Error] " + Data.body.status if subjectType == "chapter" then return console.log "# [Error] " + Data.body.message else Callback null, Data.body catch E throw E isUpdateAvailable: () -> try Package = ["https://raw.githubusercontent.com/Jinzulen/Yume-Console/master/package.json", YumeVersion] return Request Package[0], (Error, Data) -> Version = JSON.parse(Data.body).version if Package[1] < Version console.log "# You are running an oudated version of Yume-Console (v" + Package[1] + "), please update to v" + Version + " as soon as possible." console.log "# You can update Yume-Console by using its install command: npm i yumec -g" process.exit 1 catch E throw E
[ { "context": "_id}/contents/main.tex\"\n\t\t\t\tauth:\n\t\t\t\t\tusername: \"sharelatex\"\n\t\t\t\t\tpassword: \"password\"\n\t\t\t\t\tsendImmediately: ", "end": 628, "score": 0.9992351531982422, "start": 618, "tag": "USERNAME", "value": "sharelatex" }, { "context": "auth:\n\t\t\t\t\tusername: \"sharelatex\"\n\t\t\t\t\tpassword: \"password\"\n\t\t\t\t\tsendImmediately: true\n\t\t\t}, (error, respons", "end": 654, "score": 0.9992918968200684, "start": 646, "tag": "PASSWORD", "value": "password" } ]
test/acceptance/coffee/TpdsUpdateTests.coffee
davidmehren/web-sharelatex
1
expect = require("chai").expect ProjectGetter = require "../../../app/js/Features/Project/ProjectGetter.js" request = require "./helpers/request" User = require "./helpers/User" describe "TpdsUpdateTests", -> before (done) -> @owner = new User() @owner.login (error) => throw error if error? @owner.createProject "test-project", {template: "example"}, (error, project_id) => throw error if error? @project_id = project_id done() describe "deleting a file", -> before (done) -> request { method: "DELETE" url: "/project/#{@project_id}/contents/main.tex" auth: username: "sharelatex" password: "password" sendImmediately: true }, (error, response, body) -> throw error if error? expect(response.statusCode).to.equal 200 done() it "should have deleted the file", (done) -> ProjectGetter.getProject @project_id, (error, project) -> throw error if error? projectFolder = project.rootFolder[0] for doc in projectFolder.docs if doc.name == "main.tex" throw new Error("expected main.tex to have been deleted") done()
51768
expect = require("chai").expect ProjectGetter = require "../../../app/js/Features/Project/ProjectGetter.js" request = require "./helpers/request" User = require "./helpers/User" describe "TpdsUpdateTests", -> before (done) -> @owner = new User() @owner.login (error) => throw error if error? @owner.createProject "test-project", {template: "example"}, (error, project_id) => throw error if error? @project_id = project_id done() describe "deleting a file", -> before (done) -> request { method: "DELETE" url: "/project/#{@project_id}/contents/main.tex" auth: username: "sharelatex" password: "<PASSWORD>" sendImmediately: true }, (error, response, body) -> throw error if error? expect(response.statusCode).to.equal 200 done() it "should have deleted the file", (done) -> ProjectGetter.getProject @project_id, (error, project) -> throw error if error? projectFolder = project.rootFolder[0] for doc in projectFolder.docs if doc.name == "main.tex" throw new Error("expected main.tex to have been deleted") done()
true
expect = require("chai").expect ProjectGetter = require "../../../app/js/Features/Project/ProjectGetter.js" request = require "./helpers/request" User = require "./helpers/User" describe "TpdsUpdateTests", -> before (done) -> @owner = new User() @owner.login (error) => throw error if error? @owner.createProject "test-project", {template: "example"}, (error, project_id) => throw error if error? @project_id = project_id done() describe "deleting a file", -> before (done) -> request { method: "DELETE" url: "/project/#{@project_id}/contents/main.tex" auth: username: "sharelatex" password: "PI:PASSWORD:<PASSWORD>END_PI" sendImmediately: true }, (error, response, body) -> throw error if error? expect(response.statusCode).to.equal 200 done() it "should have deleted the file", (done) -> ProjectGetter.getProject @project_id, (error, project) -> throw error if error? projectFolder = project.rootFolder[0] for doc in projectFolder.docs if doc.name == "main.tex" throw new Error("expected main.tex to have been deleted") done()
[ { "context": "->\n\n setSucc: (@succ) ->\n\n\n ###\n I love you artur\n hackerkate nows the sick code\n ###\n\n inRa", "end": 6993, "score": 0.8555888533592224, "start": 6988, "tag": "NAME", "value": "artur" } ]
src/coffee/geometry/posn.coffee
agiza/mondrian
226
### Posn • (x, y) Lowest-level geometry class. Consists of x, y coordinates. Provides methods for manipulating or representing the point in two-dimensional space. Superclass: Point ### class Posn constructor: (@x, @y, @zoomLevel = 1.0) -> # I/P: # x: number # y: number # # OR # # e: Event object with clientX and clientY values if @x instanceof Object # Support for providing an Event object as the only arg. # Reads the clientX and clientY values if @x.clientX? and @x.clientY? @y = @x.clientY @x = @x.clientX else if @x.left? and @x.top? @y = @x.top @x = @x.left else if @x.x? and @x.y? @y = @x.y @x = @x.x else if (typeof @x == "string") and (@x.mentions ",") # Support for giving a string of two numbers and a comma "12.3,840" split = @x.split(",").map parseFloat x = split[0] y = split[1] @x = x @y = y # That's fucking it. @ # Rounding an you know cleanUp: -> # TODO # This was giving me NaN bullshit. Don't enable again until the app is stable # and we can test it properly return @x = cleanUpNumber @x @y = cleanUpNumber @y # Zoom compensation # By default, all Posns are interpreted as they are explicitly invoked. x is x, y is y. # You can call Posn.zoom() to ensure you're using a zoom-adjusted version of this Posn. # # In this case, x is x times the zoom level, and the same goes for y. # # Posn.unzoom() takes it back to zoom-agnostic mode - 1.0 zoomed: (level = ui.canvas.zoom) -> # Return this Posn after ensuring it is at the given zoom level. # If no level is given, current zoom level of document is used. # # I/P: level: float (optional) # # O/P: adjusted Posn return @ if @zoomLevel is level @unzoomed() @alterValues (val) -> val *= level @zoomLevel = level @ unzoomed: -> # Return this Posn after ensuring it is in 100% "true" mode. # # No I/P # # O/P: adjusted Posn return @ if @zoomLevel is 1.0 @alterValues (val) => val /= @zoomLevel @zoomLevel = 1.0 @ setZoom: (@zoomLevel) -> @x /= @zoomLevel @y /= @zoomLevel @ # Aliases: zoomedc: -> @clone().zoomed() unzoomedc: -> @clone.unzoomed() # Helper: alterValues: (fun) -> # Do something to all the values this Posn has. Kind of like map, but return is immediately applied. # # Since Posns get superclassed into Points which get superclassed into CurvePoints, # they may have x2, y2, x3, y3 attributes. This checks which ones it has and alters all of them. # # I/P: fun: one-argument function to be called on each of this Posn's values. # # O/P: self for a in ["x", "y", "x2", "y2", "x3", "y3"] @[a] = if @[a]? then fun(@[a]) else @[a] @ toString: -> "#{@x},#{@y}" toJSON: -> x: @x y: @y toConstructorString: -> "new Posn(#{@x},#{@y})" nudge: (x, y) -> @x += x @y -= y @ lerp: (b, factor) -> new Posn(@x + (b.x - @x) * factor, @y + (b.y - @y) * factor) gte: (p) -> @x >= p.x and @y >= p.y lte: (p) -> @x <= p.x and @y <= p.y directionRelativeTo: (p) -> "#{if @y < p.y then "t" else (if @y > p.y then "b" else "")}#{if @x < p.x then "l" else (if @x > p.x then "r" else "")}" squareUpAgainst: (p) -> # Takes another posn as an anchor, and nudges this one # so that it's on the nearest 45° going off of the anchor posn. xDiff = Math.abs(@x - p.x) yDiff = Math.abs(@y - p.y) direction = @directionRelativeTo p return p if (xDiff is 0) and (yDiff is 0) switch direction when "tl" if xDiff < yDiff @nudge(xDiff - yDiff, 0) else if yDiff < xDiff @nudge(0, xDiff - yDiff, 0) when "tr" if xDiff < yDiff @nudge(yDiff - xDiff, 0) else if yDiff < xDiff @nudge(0, xDiff - yDiff) when "br" if xDiff < yDiff @nudge(yDiff - xDiff, 0) else if yDiff < xDiff @nudge(0, yDiff - xDiff) when "bl" if xDiff < yDiff @nudge(xDiff - yDiff, 0) else if yDiff < xDiff @nudge(0, yDiff - xDiff) when "t", "b" @nudge(yDiff, 0) when "r", "l" @nudge(0, xDiff) @ equal: (p) -> @x is p.x and @y is p.y min: (p) -> new Posn(Math.min(@x, p.x), Math.min(@y, p.y)) max: (p) -> new Posn(Math.max(@x, p.x), Math.max(@y, p.y)) angle360: (base) -> a = 90 - new LineSegment(base, @).angle return a + (if @x < base.x then 180 else 0) rotate: (angle, origin = new Posn(0, 0)) -> return @ if origin.equal @ angle *= (Math.PI / 180) # Normalize the point on the origin. @x -= origin.x @y -= origin.y x = (@x * (Math.cos(angle))) - (@y * Math.sin(angle)) y = (@x * (Math.sin(angle))) + (@y * Math.cos(angle)) # Move points back to where they were. @x = x + origin.x @y = y + origin.y @ scale: (x, y, origin = new Posn(0, 0)) -> @x += (@x - origin.x) * (x - 1) @y += (@y - origin.y) * (y - 1) @ copy: (p) -> @x = p.x @y = p.y clone: -> # Just make a new Posn, and maintain the zoomLevel new Posn(@x, @y, @zoomLevel) snap: (to, threshold = Math.INFINITY) -> # Algorithm: bisect the line on this posn's x and y # coordinates and return the midpoint of that line. perpLine = @verti(10000) perpLine.rotate(to.angle360() + 90, @) perpLine.intersection to reflect: (posn) -> ### Reflect the point over an x and/or y axis I/P: posn: Posn ### x = posn.x y = posn.y return new Posn(x + (x - @x), y + (y - @y)) distanceFrom: (p) -> new LineSegment(@, p).length perpendicularDistanceFrom: (ls) -> ray = @verti(1e5) ray.rotate(ls.angle360() + 90, @) #ui.annotations.drawLine(ray.a, ray.b) inter = ray.intersection ls if inter? ls = new LineSegment(@, inter) len = ls.length return [len, inter, ls] else return null multiplyBy: (s) -> switch typeof s when 'number' np = @clone() np.x *= s np.y *= s return np when 'object' np = @clone() np.x *= s.x np.y *= s.y return np multiplyByMutable: (s) -> @x *= s @y *= s if @x2? @x2 *= s @y2 *= s if @x3? @x3 *= s @y3 *= s add: (s) -> switch typeof s when 'number' return new Posn(@x + s, @y + s) when 'object' return new Posn(@x + s.x, @y + s.y) subtract: (s) -> switch typeof s when 'number' return new Posn(@x - s, @y - s) when 'object' return new Posn(@x - s.x, @y - s.y) setPrec: (@prec) -> setSucc: (@succ) -> ### I love you artur hackerkate nows the sick code ### inRanges: (xr, yr) -> xr.contains @x and yr.contains @y inRangesInclusive: (xr, yr) -> xr.containsInclusive(@x) and yr.containsInclusive(@y) verti: (ln) -> new LineSegment(@clone().nudge(0, -ln), @clone().nudge(0, ln)) insideOf: (shape) -> # Draw a horizontal ray starting at this posn. # If it intersects the shape's perimeter an odd # number of times, the posn's inside of it. # # _____ # / \ # | o----X------------ # \______/ # # 1 intersection - it's inside. # # __ __ # / \ / \ # | o--X----X-----X--------- # | \__/ | # \______________/ # # 3 intersections - it's inside. # # etc. if shape instanceof Polygon or shape instanceof Path ray = new LineSegment(@, new Posn(@x + 1e+20, @y)) counter = 0 shape.lineSegments().map((a) -> inter = a.intersection(ray) if inter instanceof Posn ++ counter else if inter instanceof Array counter += inter.length ) # If there's an odd number of intersections, we are inside. return counter % 2 == 1 # Rect # This one is trivial. Method lives in the Rect class. if shape instanceof Rect return shape.contains @ dot: (v) -> @x * v.x + @y * v.y within: (tolerance, posn) -> Math.abs(@x - posn.x) < tolerance and Math.abs(@y - posn.y) < tolerance parseInt: -> @x = parseInt(@x, 10) @y = parseInt(@y, 10) Posn.fromJSON = (json) -> new Posn(json.x, json.y)
201513
### Posn • (x, y) Lowest-level geometry class. Consists of x, y coordinates. Provides methods for manipulating or representing the point in two-dimensional space. Superclass: Point ### class Posn constructor: (@x, @y, @zoomLevel = 1.0) -> # I/P: # x: number # y: number # # OR # # e: Event object with clientX and clientY values if @x instanceof Object # Support for providing an Event object as the only arg. # Reads the clientX and clientY values if @x.clientX? and @x.clientY? @y = @x.clientY @x = @x.clientX else if @x.left? and @x.top? @y = @x.top @x = @x.left else if @x.x? and @x.y? @y = @x.y @x = @x.x else if (typeof @x == "string") and (@x.mentions ",") # Support for giving a string of two numbers and a comma "12.3,840" split = @x.split(",").map parseFloat x = split[0] y = split[1] @x = x @y = y # That's fucking it. @ # Rounding an you know cleanUp: -> # TODO # This was giving me NaN bullshit. Don't enable again until the app is stable # and we can test it properly return @x = cleanUpNumber @x @y = cleanUpNumber @y # Zoom compensation # By default, all Posns are interpreted as they are explicitly invoked. x is x, y is y. # You can call Posn.zoom() to ensure you're using a zoom-adjusted version of this Posn. # # In this case, x is x times the zoom level, and the same goes for y. # # Posn.unzoom() takes it back to zoom-agnostic mode - 1.0 zoomed: (level = ui.canvas.zoom) -> # Return this Posn after ensuring it is at the given zoom level. # If no level is given, current zoom level of document is used. # # I/P: level: float (optional) # # O/P: adjusted Posn return @ if @zoomLevel is level @unzoomed() @alterValues (val) -> val *= level @zoomLevel = level @ unzoomed: -> # Return this Posn after ensuring it is in 100% "true" mode. # # No I/P # # O/P: adjusted Posn return @ if @zoomLevel is 1.0 @alterValues (val) => val /= @zoomLevel @zoomLevel = 1.0 @ setZoom: (@zoomLevel) -> @x /= @zoomLevel @y /= @zoomLevel @ # Aliases: zoomedc: -> @clone().zoomed() unzoomedc: -> @clone.unzoomed() # Helper: alterValues: (fun) -> # Do something to all the values this Posn has. Kind of like map, but return is immediately applied. # # Since Posns get superclassed into Points which get superclassed into CurvePoints, # they may have x2, y2, x3, y3 attributes. This checks which ones it has and alters all of them. # # I/P: fun: one-argument function to be called on each of this Posn's values. # # O/P: self for a in ["x", "y", "x2", "y2", "x3", "y3"] @[a] = if @[a]? then fun(@[a]) else @[a] @ toString: -> "#{@x},#{@y}" toJSON: -> x: @x y: @y toConstructorString: -> "new Posn(#{@x},#{@y})" nudge: (x, y) -> @x += x @y -= y @ lerp: (b, factor) -> new Posn(@x + (b.x - @x) * factor, @y + (b.y - @y) * factor) gte: (p) -> @x >= p.x and @y >= p.y lte: (p) -> @x <= p.x and @y <= p.y directionRelativeTo: (p) -> "#{if @y < p.y then "t" else (if @y > p.y then "b" else "")}#{if @x < p.x then "l" else (if @x > p.x then "r" else "")}" squareUpAgainst: (p) -> # Takes another posn as an anchor, and nudges this one # so that it's on the nearest 45° going off of the anchor posn. xDiff = Math.abs(@x - p.x) yDiff = Math.abs(@y - p.y) direction = @directionRelativeTo p return p if (xDiff is 0) and (yDiff is 0) switch direction when "tl" if xDiff < yDiff @nudge(xDiff - yDiff, 0) else if yDiff < xDiff @nudge(0, xDiff - yDiff, 0) when "tr" if xDiff < yDiff @nudge(yDiff - xDiff, 0) else if yDiff < xDiff @nudge(0, xDiff - yDiff) when "br" if xDiff < yDiff @nudge(yDiff - xDiff, 0) else if yDiff < xDiff @nudge(0, yDiff - xDiff) when "bl" if xDiff < yDiff @nudge(xDiff - yDiff, 0) else if yDiff < xDiff @nudge(0, yDiff - xDiff) when "t", "b" @nudge(yDiff, 0) when "r", "l" @nudge(0, xDiff) @ equal: (p) -> @x is p.x and @y is p.y min: (p) -> new Posn(Math.min(@x, p.x), Math.min(@y, p.y)) max: (p) -> new Posn(Math.max(@x, p.x), Math.max(@y, p.y)) angle360: (base) -> a = 90 - new LineSegment(base, @).angle return a + (if @x < base.x then 180 else 0) rotate: (angle, origin = new Posn(0, 0)) -> return @ if origin.equal @ angle *= (Math.PI / 180) # Normalize the point on the origin. @x -= origin.x @y -= origin.y x = (@x * (Math.cos(angle))) - (@y * Math.sin(angle)) y = (@x * (Math.sin(angle))) + (@y * Math.cos(angle)) # Move points back to where they were. @x = x + origin.x @y = y + origin.y @ scale: (x, y, origin = new Posn(0, 0)) -> @x += (@x - origin.x) * (x - 1) @y += (@y - origin.y) * (y - 1) @ copy: (p) -> @x = p.x @y = p.y clone: -> # Just make a new Posn, and maintain the zoomLevel new Posn(@x, @y, @zoomLevel) snap: (to, threshold = Math.INFINITY) -> # Algorithm: bisect the line on this posn's x and y # coordinates and return the midpoint of that line. perpLine = @verti(10000) perpLine.rotate(to.angle360() + 90, @) perpLine.intersection to reflect: (posn) -> ### Reflect the point over an x and/or y axis I/P: posn: Posn ### x = posn.x y = posn.y return new Posn(x + (x - @x), y + (y - @y)) distanceFrom: (p) -> new LineSegment(@, p).length perpendicularDistanceFrom: (ls) -> ray = @verti(1e5) ray.rotate(ls.angle360() + 90, @) #ui.annotations.drawLine(ray.a, ray.b) inter = ray.intersection ls if inter? ls = new LineSegment(@, inter) len = ls.length return [len, inter, ls] else return null multiplyBy: (s) -> switch typeof s when 'number' np = @clone() np.x *= s np.y *= s return np when 'object' np = @clone() np.x *= s.x np.y *= s.y return np multiplyByMutable: (s) -> @x *= s @y *= s if @x2? @x2 *= s @y2 *= s if @x3? @x3 *= s @y3 *= s add: (s) -> switch typeof s when 'number' return new Posn(@x + s, @y + s) when 'object' return new Posn(@x + s.x, @y + s.y) subtract: (s) -> switch typeof s when 'number' return new Posn(@x - s, @y - s) when 'object' return new Posn(@x - s.x, @y - s.y) setPrec: (@prec) -> setSucc: (@succ) -> ### I love you <NAME> hackerkate nows the sick code ### inRanges: (xr, yr) -> xr.contains @x and yr.contains @y inRangesInclusive: (xr, yr) -> xr.containsInclusive(@x) and yr.containsInclusive(@y) verti: (ln) -> new LineSegment(@clone().nudge(0, -ln), @clone().nudge(0, ln)) insideOf: (shape) -> # Draw a horizontal ray starting at this posn. # If it intersects the shape's perimeter an odd # number of times, the posn's inside of it. # # _____ # / \ # | o----X------------ # \______/ # # 1 intersection - it's inside. # # __ __ # / \ / \ # | o--X----X-----X--------- # | \__/ | # \______________/ # # 3 intersections - it's inside. # # etc. if shape instanceof Polygon or shape instanceof Path ray = new LineSegment(@, new Posn(@x + 1e+20, @y)) counter = 0 shape.lineSegments().map((a) -> inter = a.intersection(ray) if inter instanceof Posn ++ counter else if inter instanceof Array counter += inter.length ) # If there's an odd number of intersections, we are inside. return counter % 2 == 1 # Rect # This one is trivial. Method lives in the Rect class. if shape instanceof Rect return shape.contains @ dot: (v) -> @x * v.x + @y * v.y within: (tolerance, posn) -> Math.abs(@x - posn.x) < tolerance and Math.abs(@y - posn.y) < tolerance parseInt: -> @x = parseInt(@x, 10) @y = parseInt(@y, 10) Posn.fromJSON = (json) -> new Posn(json.x, json.y)
true
### Posn • (x, y) Lowest-level geometry class. Consists of x, y coordinates. Provides methods for manipulating or representing the point in two-dimensional space. Superclass: Point ### class Posn constructor: (@x, @y, @zoomLevel = 1.0) -> # I/P: # x: number # y: number # # OR # # e: Event object with clientX and clientY values if @x instanceof Object # Support for providing an Event object as the only arg. # Reads the clientX and clientY values if @x.clientX? and @x.clientY? @y = @x.clientY @x = @x.clientX else if @x.left? and @x.top? @y = @x.top @x = @x.left else if @x.x? and @x.y? @y = @x.y @x = @x.x else if (typeof @x == "string") and (@x.mentions ",") # Support for giving a string of two numbers and a comma "12.3,840" split = @x.split(",").map parseFloat x = split[0] y = split[1] @x = x @y = y # That's fucking it. @ # Rounding an you know cleanUp: -> # TODO # This was giving me NaN bullshit. Don't enable again until the app is stable # and we can test it properly return @x = cleanUpNumber @x @y = cleanUpNumber @y # Zoom compensation # By default, all Posns are interpreted as they are explicitly invoked. x is x, y is y. # You can call Posn.zoom() to ensure you're using a zoom-adjusted version of this Posn. # # In this case, x is x times the zoom level, and the same goes for y. # # Posn.unzoom() takes it back to zoom-agnostic mode - 1.0 zoomed: (level = ui.canvas.zoom) -> # Return this Posn after ensuring it is at the given zoom level. # If no level is given, current zoom level of document is used. # # I/P: level: float (optional) # # O/P: adjusted Posn return @ if @zoomLevel is level @unzoomed() @alterValues (val) -> val *= level @zoomLevel = level @ unzoomed: -> # Return this Posn after ensuring it is in 100% "true" mode. # # No I/P # # O/P: adjusted Posn return @ if @zoomLevel is 1.0 @alterValues (val) => val /= @zoomLevel @zoomLevel = 1.0 @ setZoom: (@zoomLevel) -> @x /= @zoomLevel @y /= @zoomLevel @ # Aliases: zoomedc: -> @clone().zoomed() unzoomedc: -> @clone.unzoomed() # Helper: alterValues: (fun) -> # Do something to all the values this Posn has. Kind of like map, but return is immediately applied. # # Since Posns get superclassed into Points which get superclassed into CurvePoints, # they may have x2, y2, x3, y3 attributes. This checks which ones it has and alters all of them. # # I/P: fun: one-argument function to be called on each of this Posn's values. # # O/P: self for a in ["x", "y", "x2", "y2", "x3", "y3"] @[a] = if @[a]? then fun(@[a]) else @[a] @ toString: -> "#{@x},#{@y}" toJSON: -> x: @x y: @y toConstructorString: -> "new Posn(#{@x},#{@y})" nudge: (x, y) -> @x += x @y -= y @ lerp: (b, factor) -> new Posn(@x + (b.x - @x) * factor, @y + (b.y - @y) * factor) gte: (p) -> @x >= p.x and @y >= p.y lte: (p) -> @x <= p.x and @y <= p.y directionRelativeTo: (p) -> "#{if @y < p.y then "t" else (if @y > p.y then "b" else "")}#{if @x < p.x then "l" else (if @x > p.x then "r" else "")}" squareUpAgainst: (p) -> # Takes another posn as an anchor, and nudges this one # so that it's on the nearest 45° going off of the anchor posn. xDiff = Math.abs(@x - p.x) yDiff = Math.abs(@y - p.y) direction = @directionRelativeTo p return p if (xDiff is 0) and (yDiff is 0) switch direction when "tl" if xDiff < yDiff @nudge(xDiff - yDiff, 0) else if yDiff < xDiff @nudge(0, xDiff - yDiff, 0) when "tr" if xDiff < yDiff @nudge(yDiff - xDiff, 0) else if yDiff < xDiff @nudge(0, xDiff - yDiff) when "br" if xDiff < yDiff @nudge(yDiff - xDiff, 0) else if yDiff < xDiff @nudge(0, yDiff - xDiff) when "bl" if xDiff < yDiff @nudge(xDiff - yDiff, 0) else if yDiff < xDiff @nudge(0, yDiff - xDiff) when "t", "b" @nudge(yDiff, 0) when "r", "l" @nudge(0, xDiff) @ equal: (p) -> @x is p.x and @y is p.y min: (p) -> new Posn(Math.min(@x, p.x), Math.min(@y, p.y)) max: (p) -> new Posn(Math.max(@x, p.x), Math.max(@y, p.y)) angle360: (base) -> a = 90 - new LineSegment(base, @).angle return a + (if @x < base.x then 180 else 0) rotate: (angle, origin = new Posn(0, 0)) -> return @ if origin.equal @ angle *= (Math.PI / 180) # Normalize the point on the origin. @x -= origin.x @y -= origin.y x = (@x * (Math.cos(angle))) - (@y * Math.sin(angle)) y = (@x * (Math.sin(angle))) + (@y * Math.cos(angle)) # Move points back to where they were. @x = x + origin.x @y = y + origin.y @ scale: (x, y, origin = new Posn(0, 0)) -> @x += (@x - origin.x) * (x - 1) @y += (@y - origin.y) * (y - 1) @ copy: (p) -> @x = p.x @y = p.y clone: -> # Just make a new Posn, and maintain the zoomLevel new Posn(@x, @y, @zoomLevel) snap: (to, threshold = Math.INFINITY) -> # Algorithm: bisect the line on this posn's x and y # coordinates and return the midpoint of that line. perpLine = @verti(10000) perpLine.rotate(to.angle360() + 90, @) perpLine.intersection to reflect: (posn) -> ### Reflect the point over an x and/or y axis I/P: posn: Posn ### x = posn.x y = posn.y return new Posn(x + (x - @x), y + (y - @y)) distanceFrom: (p) -> new LineSegment(@, p).length perpendicularDistanceFrom: (ls) -> ray = @verti(1e5) ray.rotate(ls.angle360() + 90, @) #ui.annotations.drawLine(ray.a, ray.b) inter = ray.intersection ls if inter? ls = new LineSegment(@, inter) len = ls.length return [len, inter, ls] else return null multiplyBy: (s) -> switch typeof s when 'number' np = @clone() np.x *= s np.y *= s return np when 'object' np = @clone() np.x *= s.x np.y *= s.y return np multiplyByMutable: (s) -> @x *= s @y *= s if @x2? @x2 *= s @y2 *= s if @x3? @x3 *= s @y3 *= s add: (s) -> switch typeof s when 'number' return new Posn(@x + s, @y + s) when 'object' return new Posn(@x + s.x, @y + s.y) subtract: (s) -> switch typeof s when 'number' return new Posn(@x - s, @y - s) when 'object' return new Posn(@x - s.x, @y - s.y) setPrec: (@prec) -> setSucc: (@succ) -> ### I love you PI:NAME:<NAME>END_PI hackerkate nows the sick code ### inRanges: (xr, yr) -> xr.contains @x and yr.contains @y inRangesInclusive: (xr, yr) -> xr.containsInclusive(@x) and yr.containsInclusive(@y) verti: (ln) -> new LineSegment(@clone().nudge(0, -ln), @clone().nudge(0, ln)) insideOf: (shape) -> # Draw a horizontal ray starting at this posn. # If it intersects the shape's perimeter an odd # number of times, the posn's inside of it. # # _____ # / \ # | o----X------------ # \______/ # # 1 intersection - it's inside. # # __ __ # / \ / \ # | o--X----X-----X--------- # | \__/ | # \______________/ # # 3 intersections - it's inside. # # etc. if shape instanceof Polygon or shape instanceof Path ray = new LineSegment(@, new Posn(@x + 1e+20, @y)) counter = 0 shape.lineSegments().map((a) -> inter = a.intersection(ray) if inter instanceof Posn ++ counter else if inter instanceof Array counter += inter.length ) # If there's an odd number of intersections, we are inside. return counter % 2 == 1 # Rect # This one is trivial. Method lives in the Rect class. if shape instanceof Rect return shape.contains @ dot: (v) -> @x * v.x + @y * v.y within: (tolerance, posn) -> Math.abs(@x - posn.x) < tolerance and Math.abs(@y - posn.y) < tolerance parseInt: -> @x = parseInt(@x, 10) @y = parseInt(@y, 10) Posn.fromJSON = (json) -> new Posn(json.x, json.y)
[ { "context": "he latest English versions:\n## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascri", "end": 185, "score": 0.9927756786346436, "start": 175, "tag": "USERNAME", "value": "uploadcare" }, { "context": "oad: 'Kann nicht hochgeladen werden'\n user: 'Hochladen abgebrochen'\n info: 'Informationen kö", "end": 610, "score": 0.5626503825187683, "start": 608, "tag": "USERNAME", "value": "Ho" }, { "context": "d: 'Kann nicht hochgeladen werden'\n user: 'Hochladen abgebrochen'\n info: 'Informationen können nicht geladen ", "end": 629, "score": 0.9510879516601562, "start": 610, "tag": "NAME", "value": "chladen abgebrochen" } ]
app/assets/javascripts/uploadcare/locale/de.js.coffee
nd0ut/uploadcare-widget
1
## ## Please, do not use this locale as a reference for new translations. ## It could be outdated or incomplete. Always use the latest English versions: ## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee ## ## Any fixes are welcome. ## uploadcare.namespace 'locale.translations', (ns) -> ns.de = uploading: 'Hochladen... Bitte warten.' loadingInfo: 'Laden der Informationen...' errors: default: 'Error' baddata: 'Falscher Wert' size: 'Datei zu groß' upload: 'Kann nicht hochgeladen werden' user: 'Hochladen abgebrochen' info: 'Informationen können nicht geladen werden' image: 'Nur Bilder sind erlaubt' createGroup: 'Datei-Gruppe kann nicht erstellt werden' deleted: 'Datei wurde gelöscht' draghere: 'Ziehen Sie eine Datei hier hinein' file: one: '%1 Datei' other: '%1 Dateien' buttons: cancel: 'Abbrechen' remove: 'Löschen' choose: files: one: 'Wählen Sie eine Datei' other: 'Wählen Sie die Dateien' images: one: 'Wählen Sie ein Bild' other: 'Wählen Sie Bilder' dialog: done: 'Fertig' showFiles: 'Dateien anzeigen' tabs: names: 'empty-pubkey': 'Willkommen' preview: 'Vorschau' file: 'Lokale Dateien' url: 'Web-Links' camera: 'Kamera' file: drag: 'Ziehen Sie eine Datei hier hinein' nodrop: 'Laden Sie Dateien von Ihrem PC hoch' cloudsTip: 'Cloud Speicher<br>und soziale Dienste' or: 'oder' button: 'Wählen Sie eine lokale Datei' also: 'Sie können sie auch wählen von' url: title: 'Dateien vom Web' line1: 'Holen Sie sich irgendeine Datei vom Web.' line2: 'Geben Sie einfach den Link an.' input: 'Bitte geben Sie den Link hier an...' button: 'Hochladen' camera: capture: 'Machen Sie ein Foto' mirror: 'Spiegel' retry: 'Berechtigungen erneut anfordern' pleaseAllow: title: 'Bitte erlauben Sie den Zugriff auf Ihre Kamera' text: 'Sie wurden gebeten, dieser Website den Zugriff auf Ihre Kamera zu erlauben. Um mit Ihrer Kamera Fotos machen zu können, müssen Sie diese Erlaubnis erteilen.' notFound: title: 'Keine Kamera festgestellt' text: 'Es sieht so aus, als hätten Sie keine Kamera an dieses Gerät angeschlossen.' preview: unknownName: 'nicht bekannt' change: 'Abbrechen' back: 'Zurück' done: 'Hinzufügen' unknown: title: 'Hochladen... Bitte warten Sie auf die Vorschau.' done: 'Vorschau überspringen und Datei annehmen' regular: title: 'Diese Datei hinzufügen?' line1: 'Diese Datei wird nun hinzugefügt.' line2: 'Bitte bestätigen Sie.' image: title: 'Dieses Bild hinzufügen?' change: 'Abbrechen' crop: title: 'Dieses Bild beschneiden und hinzufügen' done: 'Fertig' free: 'frei' error: default: title: 'Oops!' text: 'Etwas ist während dem Hochladen schief gelaufen.' back: 'Bitte versuchen Sie es erneut' image: title: 'Nur Bilder sind akzeptiert.' text: 'Bitte veruschen Sie es erneut mit einer anderen Datei.' back: 'Bild wählen' size: title: 'Die gewählte Datei überschreitet das Limit.' text: 'Bitte veruschen Sie es erneut mit einer anderen Datei.' loadImage: title: 'Fehler' text: 'Das Bild kann nicht geladen werden' multiple: title: 'Sie haben %files% Dateien gewählt' question: 'Möchten Sie all diese Datein hinzufügen?' tooManyFiles: 'Sie haben zu viele Dateien gewählt. %max% ist das Maximum.' tooFewFiles: 'Sie haben %files% Dateien. Es sind mindestens %min% nötig.' clear: 'Alle löschen' done: 'Fertig' # Pluralization rules taken from: # http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html uploadcare.namespace 'locale.pluralize', (ns) -> ns.de = (n) -> return 'one' if n == 1 'other'
36416
## ## Please, do not use this locale as a reference for new translations. ## It could be outdated or incomplete. Always use the latest English versions: ## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee ## ## Any fixes are welcome. ## uploadcare.namespace 'locale.translations', (ns) -> ns.de = uploading: 'Hochladen... Bitte warten.' loadingInfo: 'Laden der Informationen...' errors: default: 'Error' baddata: 'Falscher Wert' size: 'Datei zu groß' upload: 'Kann nicht hochgeladen werden' user: 'Ho<NAME>' info: 'Informationen können nicht geladen werden' image: 'Nur Bilder sind erlaubt' createGroup: 'Datei-Gruppe kann nicht erstellt werden' deleted: 'Datei wurde gelöscht' draghere: 'Ziehen Sie eine Datei hier hinein' file: one: '%1 Datei' other: '%1 Dateien' buttons: cancel: 'Abbrechen' remove: 'Löschen' choose: files: one: 'Wählen Sie eine Datei' other: 'Wählen Sie die Dateien' images: one: 'Wählen Sie ein Bild' other: 'Wählen Sie Bilder' dialog: done: 'Fertig' showFiles: 'Dateien anzeigen' tabs: names: 'empty-pubkey': 'Willkommen' preview: 'Vorschau' file: 'Lokale Dateien' url: 'Web-Links' camera: 'Kamera' file: drag: 'Ziehen Sie eine Datei hier hinein' nodrop: 'Laden Sie Dateien von Ihrem PC hoch' cloudsTip: 'Cloud Speicher<br>und soziale Dienste' or: 'oder' button: 'Wählen Sie eine lokale Datei' also: 'Sie können sie auch wählen von' url: title: 'Dateien vom Web' line1: 'Holen Sie sich irgendeine Datei vom Web.' line2: 'Geben Sie einfach den Link an.' input: 'Bitte geben Sie den Link hier an...' button: 'Hochladen' camera: capture: 'Machen Sie ein Foto' mirror: 'Spiegel' retry: 'Berechtigungen erneut anfordern' pleaseAllow: title: 'Bitte erlauben Sie den Zugriff auf Ihre Kamera' text: 'Sie wurden gebeten, dieser Website den Zugriff auf Ihre Kamera zu erlauben. Um mit Ihrer Kamera Fotos machen zu können, müssen Sie diese Erlaubnis erteilen.' notFound: title: 'Keine Kamera festgestellt' text: 'Es sieht so aus, als hätten Sie keine Kamera an dieses Gerät angeschlossen.' preview: unknownName: 'nicht bekannt' change: 'Abbrechen' back: 'Zurück' done: 'Hinzufügen' unknown: title: 'Hochladen... Bitte warten Sie auf die Vorschau.' done: 'Vorschau überspringen und Datei annehmen' regular: title: 'Diese Datei hinzufügen?' line1: 'Diese Datei wird nun hinzugefügt.' line2: 'Bitte bestätigen Sie.' image: title: 'Dieses Bild hinzufügen?' change: 'Abbrechen' crop: title: 'Dieses Bild beschneiden und hinzufügen' done: 'Fertig' free: 'frei' error: default: title: 'Oops!' text: 'Etwas ist während dem Hochladen schief gelaufen.' back: 'Bitte versuchen Sie es erneut' image: title: 'Nur Bilder sind akzeptiert.' text: 'Bitte veruschen Sie es erneut mit einer anderen Datei.' back: 'Bild wählen' size: title: 'Die gewählte Datei überschreitet das Limit.' text: 'Bitte veruschen Sie es erneut mit einer anderen Datei.' loadImage: title: 'Fehler' text: 'Das Bild kann nicht geladen werden' multiple: title: 'Sie haben %files% Dateien gewählt' question: 'Möchten Sie all diese Datein hinzufügen?' tooManyFiles: 'Sie haben zu viele Dateien gewählt. %max% ist das Maximum.' tooFewFiles: 'Sie haben %files% Dateien. Es sind mindestens %min% nötig.' clear: 'Alle löschen' done: 'Fertig' # Pluralization rules taken from: # http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html uploadcare.namespace 'locale.pluralize', (ns) -> ns.de = (n) -> return 'one' if n == 1 'other'
true
## ## Please, do not use this locale as a reference for new translations. ## It could be outdated or incomplete. Always use the latest English versions: ## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee ## ## Any fixes are welcome. ## uploadcare.namespace 'locale.translations', (ns) -> ns.de = uploading: 'Hochladen... Bitte warten.' loadingInfo: 'Laden der Informationen...' errors: default: 'Error' baddata: 'Falscher Wert' size: 'Datei zu groß' upload: 'Kann nicht hochgeladen werden' user: 'HoPI:NAME:<NAME>END_PI' info: 'Informationen können nicht geladen werden' image: 'Nur Bilder sind erlaubt' createGroup: 'Datei-Gruppe kann nicht erstellt werden' deleted: 'Datei wurde gelöscht' draghere: 'Ziehen Sie eine Datei hier hinein' file: one: '%1 Datei' other: '%1 Dateien' buttons: cancel: 'Abbrechen' remove: 'Löschen' choose: files: one: 'Wählen Sie eine Datei' other: 'Wählen Sie die Dateien' images: one: 'Wählen Sie ein Bild' other: 'Wählen Sie Bilder' dialog: done: 'Fertig' showFiles: 'Dateien anzeigen' tabs: names: 'empty-pubkey': 'Willkommen' preview: 'Vorschau' file: 'Lokale Dateien' url: 'Web-Links' camera: 'Kamera' file: drag: 'Ziehen Sie eine Datei hier hinein' nodrop: 'Laden Sie Dateien von Ihrem PC hoch' cloudsTip: 'Cloud Speicher<br>und soziale Dienste' or: 'oder' button: 'Wählen Sie eine lokale Datei' also: 'Sie können sie auch wählen von' url: title: 'Dateien vom Web' line1: 'Holen Sie sich irgendeine Datei vom Web.' line2: 'Geben Sie einfach den Link an.' input: 'Bitte geben Sie den Link hier an...' button: 'Hochladen' camera: capture: 'Machen Sie ein Foto' mirror: 'Spiegel' retry: 'Berechtigungen erneut anfordern' pleaseAllow: title: 'Bitte erlauben Sie den Zugriff auf Ihre Kamera' text: 'Sie wurden gebeten, dieser Website den Zugriff auf Ihre Kamera zu erlauben. Um mit Ihrer Kamera Fotos machen zu können, müssen Sie diese Erlaubnis erteilen.' notFound: title: 'Keine Kamera festgestellt' text: 'Es sieht so aus, als hätten Sie keine Kamera an dieses Gerät angeschlossen.' preview: unknownName: 'nicht bekannt' change: 'Abbrechen' back: 'Zurück' done: 'Hinzufügen' unknown: title: 'Hochladen... Bitte warten Sie auf die Vorschau.' done: 'Vorschau überspringen und Datei annehmen' regular: title: 'Diese Datei hinzufügen?' line1: 'Diese Datei wird nun hinzugefügt.' line2: 'Bitte bestätigen Sie.' image: title: 'Dieses Bild hinzufügen?' change: 'Abbrechen' crop: title: 'Dieses Bild beschneiden und hinzufügen' done: 'Fertig' free: 'frei' error: default: title: 'Oops!' text: 'Etwas ist während dem Hochladen schief gelaufen.' back: 'Bitte versuchen Sie es erneut' image: title: 'Nur Bilder sind akzeptiert.' text: 'Bitte veruschen Sie es erneut mit einer anderen Datei.' back: 'Bild wählen' size: title: 'Die gewählte Datei überschreitet das Limit.' text: 'Bitte veruschen Sie es erneut mit einer anderen Datei.' loadImage: title: 'Fehler' text: 'Das Bild kann nicht geladen werden' multiple: title: 'Sie haben %files% Dateien gewählt' question: 'Möchten Sie all diese Datein hinzufügen?' tooManyFiles: 'Sie haben zu viele Dateien gewählt. %max% ist das Maximum.' tooFewFiles: 'Sie haben %files% Dateien. Es sind mindestens %min% nötig.' clear: 'Alle löschen' done: 'Fertig' # Pluralization rules taken from: # http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html uploadcare.namespace 'locale.pluralize', (ns) -> ns.de = (n) -> return 'one' if n == 1 'other'
[ { "context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http", "end": 63, "score": 0.5680813789367676, "start": 62, "tag": "NAME", "value": "H" } ]
src/event.coffee
heartyoh/dou
1
# ========================================== # Copyright 2014 Hatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './utils' './collection' ], (utils, collection) -> "use strict" Event = withEvent: -> (this[method] = Event[method]) for method in ['on', 'off', 'once', 'delegate_on', 'delegate_off', 'trigger'] on: (name, callback, context) -> return this if (!eventsApi(this, 'on', name, [callback, context]) || !callback) this._listeners || (this._listeners = {}); events = this._listeners[name] || (this._listeners[name] = []); events.push callback: callback context: context ctx: context || this this # Bind an event to only be triggered a single time. After the first time # the callback is invoked, it will be removed. once: (name, callback, context) -> return this if (!eventsApi(this, 'once', name, [callback, context]) || !callback) self = this once = utils.once -> self.off name, once callback.apply this, arguments once._callback = callback this.on name, once, context # Remove one or many callbacks. If `context` is null, removes all # callbacks with that function. If `callback` is null, removes all # callbacks for the event. If `name` is null, removes all bound # callbacks for all events. off: (name, callback, context) -> return this if (!this._listeners || !eventsApi(this, 'off', name, [callback, context])) if (!name && !callback && !context) this._listeners = undefined; return this; names = if name then [name] else Object.keys(this._listeners); for name, i in names if (events = this._listeners[name]) this._listeners[name] = retain = [] if (callback || context) for ev, j in events if ((callback && callback isnt ev.callback && callback isnt ev.callback._callback) || (context && context isnt ev.context)) retain.push ev delete this._listeners[name] if (!retain.length) this delegate_on: (delegator) -> this._delegators || (this._delegators = new collection.List()); this._delegators.append delegator this delegate_off: (delegator) -> return this if not this._delegators this._delegators.remove delegator this delegate: -> delegateEvents(this._delegators, arguments) if this._delegators and this._delegators.size() > 0 return this if (!this._listeners) event = arguments[arguments.length - 1] event.deliverer = this listeners = this._listeners[event.name] listenersForAll = this._listeners.all triggerEvents(listeners, arguments) if (listeners) triggerEvents(listenersForAll, arguments) if (listenersForAll) this # Trigger one or many events, firing all bound callbacks. Callbacks are # passed the same arguments as `trigger` is, apart from the event name # (unless you're listening on `"all"`, which will cause your callback to # receive the true name of the event as the first argument). trigger: (name) -> args = [].slice.call(arguments, 1) args.push({ origin: this, name: name, deliverer: this }); delegateEvents(this._delegators, args) if this._delegators and this._delegators.size() > 0 return this if not this._listeners return this if (!eventsApi(this, 'trigger', name, args)) listeners = this._listeners[name] listenersForAll = this._listeners.all triggerEvents(listeners, args) if (listeners) triggerEvents(listenersForAll, args) if (listenersForAll) this # Tell this object to stop listening to either specific events ... or # to every object it's currently listening to. stopListening: (obj, name, callback) -> listeningTo = this._listeningTo return this if (!listeningTo) remove = !name && !callback; callback = this if (!callback && typeof name is 'object') (listeningTo = {})[obj._listenId] = obj if (obj) for id, obj of listeningTo obj.off(name, callback, this) delete this._listeningTo[id] if (remove || _.isEmpty(obj._events)) this # Regular expression used to split event strings. eventSplitter = /\s+/ # Implement fancy features of the Event API such as multiple event # names `"change blur"` and jQuery-style event maps `{change: action}` # in terms of the existing API. eventsApi = (obj, action, name, rest) -> return true if !name # Handle event maps. if typeof name is 'object' obj[action].apply(obj, [key, val].concat(rest)) for key, val of name return false; # Handle space separated event names. if eventSplitter.test(name) names = name.split(eventSplitter) obj[action].apply(obj, [val].concat(rest)) for val in names return false; true triggerEvents = (listeners, args) -> ev.callback.apply(ev.ctx, args) for ev in listeners delegateEvents = (delegators, args) -> delegators.forEach (delegator) -> Event.delegate.apply(delegator, args) listenMethods = listenTo: 'on' listenToOnce: 'once' # Inversion-of-control versions of `on` and `once`. Tell *this* object to # listen to an event in another object ... keeping track of what it's # listening to. for method, implementation of listenMethods Event[method] = (obj, name, callback) -> listeningTo = this._listeningTo || (this._listeningTo = {}) id = obj._listenId || (obj._listenId = utils.uniqueId('l')) listeningTo[id] = obj callback = this if (!callback && typeof name is 'object') obj[implementation](name, callback, this) return this Event
3777
# ========================================== # Copyright 2014 <NAME>atio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './utils' './collection' ], (utils, collection) -> "use strict" Event = withEvent: -> (this[method] = Event[method]) for method in ['on', 'off', 'once', 'delegate_on', 'delegate_off', 'trigger'] on: (name, callback, context) -> return this if (!eventsApi(this, 'on', name, [callback, context]) || !callback) this._listeners || (this._listeners = {}); events = this._listeners[name] || (this._listeners[name] = []); events.push callback: callback context: context ctx: context || this this # Bind an event to only be triggered a single time. After the first time # the callback is invoked, it will be removed. once: (name, callback, context) -> return this if (!eventsApi(this, 'once', name, [callback, context]) || !callback) self = this once = utils.once -> self.off name, once callback.apply this, arguments once._callback = callback this.on name, once, context # Remove one or many callbacks. If `context` is null, removes all # callbacks with that function. If `callback` is null, removes all # callbacks for the event. If `name` is null, removes all bound # callbacks for all events. off: (name, callback, context) -> return this if (!this._listeners || !eventsApi(this, 'off', name, [callback, context])) if (!name && !callback && !context) this._listeners = undefined; return this; names = if name then [name] else Object.keys(this._listeners); for name, i in names if (events = this._listeners[name]) this._listeners[name] = retain = [] if (callback || context) for ev, j in events if ((callback && callback isnt ev.callback && callback isnt ev.callback._callback) || (context && context isnt ev.context)) retain.push ev delete this._listeners[name] if (!retain.length) this delegate_on: (delegator) -> this._delegators || (this._delegators = new collection.List()); this._delegators.append delegator this delegate_off: (delegator) -> return this if not this._delegators this._delegators.remove delegator this delegate: -> delegateEvents(this._delegators, arguments) if this._delegators and this._delegators.size() > 0 return this if (!this._listeners) event = arguments[arguments.length - 1] event.deliverer = this listeners = this._listeners[event.name] listenersForAll = this._listeners.all triggerEvents(listeners, arguments) if (listeners) triggerEvents(listenersForAll, arguments) if (listenersForAll) this # Trigger one or many events, firing all bound callbacks. Callbacks are # passed the same arguments as `trigger` is, apart from the event name # (unless you're listening on `"all"`, which will cause your callback to # receive the true name of the event as the first argument). trigger: (name) -> args = [].slice.call(arguments, 1) args.push({ origin: this, name: name, deliverer: this }); delegateEvents(this._delegators, args) if this._delegators and this._delegators.size() > 0 return this if not this._listeners return this if (!eventsApi(this, 'trigger', name, args)) listeners = this._listeners[name] listenersForAll = this._listeners.all triggerEvents(listeners, args) if (listeners) triggerEvents(listenersForAll, args) if (listenersForAll) this # Tell this object to stop listening to either specific events ... or # to every object it's currently listening to. stopListening: (obj, name, callback) -> listeningTo = this._listeningTo return this if (!listeningTo) remove = !name && !callback; callback = this if (!callback && typeof name is 'object') (listeningTo = {})[obj._listenId] = obj if (obj) for id, obj of listeningTo obj.off(name, callback, this) delete this._listeningTo[id] if (remove || _.isEmpty(obj._events)) this # Regular expression used to split event strings. eventSplitter = /\s+/ # Implement fancy features of the Event API such as multiple event # names `"change blur"` and jQuery-style event maps `{change: action}` # in terms of the existing API. eventsApi = (obj, action, name, rest) -> return true if !name # Handle event maps. if typeof name is 'object' obj[action].apply(obj, [key, val].concat(rest)) for key, val of name return false; # Handle space separated event names. if eventSplitter.test(name) names = name.split(eventSplitter) obj[action].apply(obj, [val].concat(rest)) for val in names return false; true triggerEvents = (listeners, args) -> ev.callback.apply(ev.ctx, args) for ev in listeners delegateEvents = (delegators, args) -> delegators.forEach (delegator) -> Event.delegate.apply(delegator, args) listenMethods = listenTo: 'on' listenToOnce: 'once' # Inversion-of-control versions of `on` and `once`. Tell *this* object to # listen to an event in another object ... keeping track of what it's # listening to. for method, implementation of listenMethods Event[method] = (obj, name, callback) -> listeningTo = this._listeningTo || (this._listeningTo = {}) id = obj._listenId || (obj._listenId = utils.uniqueId('l')) listeningTo[id] = obj callback = this if (!callback && typeof name is 'object') obj[implementation](name, callback, this) return this Event
true
# ========================================== # Copyright 2014 PI:NAME:<NAME>END_PIatio, Lab. # Licensed under The MIT License # http://opensource.org/licenses/MIT # ========================================== define [ './utils' './collection' ], (utils, collection) -> "use strict" Event = withEvent: -> (this[method] = Event[method]) for method in ['on', 'off', 'once', 'delegate_on', 'delegate_off', 'trigger'] on: (name, callback, context) -> return this if (!eventsApi(this, 'on', name, [callback, context]) || !callback) this._listeners || (this._listeners = {}); events = this._listeners[name] || (this._listeners[name] = []); events.push callback: callback context: context ctx: context || this this # Bind an event to only be triggered a single time. After the first time # the callback is invoked, it will be removed. once: (name, callback, context) -> return this if (!eventsApi(this, 'once', name, [callback, context]) || !callback) self = this once = utils.once -> self.off name, once callback.apply this, arguments once._callback = callback this.on name, once, context # Remove one or many callbacks. If `context` is null, removes all # callbacks with that function. If `callback` is null, removes all # callbacks for the event. If `name` is null, removes all bound # callbacks for all events. off: (name, callback, context) -> return this if (!this._listeners || !eventsApi(this, 'off', name, [callback, context])) if (!name && !callback && !context) this._listeners = undefined; return this; names = if name then [name] else Object.keys(this._listeners); for name, i in names if (events = this._listeners[name]) this._listeners[name] = retain = [] if (callback || context) for ev, j in events if ((callback && callback isnt ev.callback && callback isnt ev.callback._callback) || (context && context isnt ev.context)) retain.push ev delete this._listeners[name] if (!retain.length) this delegate_on: (delegator) -> this._delegators || (this._delegators = new collection.List()); this._delegators.append delegator this delegate_off: (delegator) -> return this if not this._delegators this._delegators.remove delegator this delegate: -> delegateEvents(this._delegators, arguments) if this._delegators and this._delegators.size() > 0 return this if (!this._listeners) event = arguments[arguments.length - 1] event.deliverer = this listeners = this._listeners[event.name] listenersForAll = this._listeners.all triggerEvents(listeners, arguments) if (listeners) triggerEvents(listenersForAll, arguments) if (listenersForAll) this # Trigger one or many events, firing all bound callbacks. Callbacks are # passed the same arguments as `trigger` is, apart from the event name # (unless you're listening on `"all"`, which will cause your callback to # receive the true name of the event as the first argument). trigger: (name) -> args = [].slice.call(arguments, 1) args.push({ origin: this, name: name, deliverer: this }); delegateEvents(this._delegators, args) if this._delegators and this._delegators.size() > 0 return this if not this._listeners return this if (!eventsApi(this, 'trigger', name, args)) listeners = this._listeners[name] listenersForAll = this._listeners.all triggerEvents(listeners, args) if (listeners) triggerEvents(listenersForAll, args) if (listenersForAll) this # Tell this object to stop listening to either specific events ... or # to every object it's currently listening to. stopListening: (obj, name, callback) -> listeningTo = this._listeningTo return this if (!listeningTo) remove = !name && !callback; callback = this if (!callback && typeof name is 'object') (listeningTo = {})[obj._listenId] = obj if (obj) for id, obj of listeningTo obj.off(name, callback, this) delete this._listeningTo[id] if (remove || _.isEmpty(obj._events)) this # Regular expression used to split event strings. eventSplitter = /\s+/ # Implement fancy features of the Event API such as multiple event # names `"change blur"` and jQuery-style event maps `{change: action}` # in terms of the existing API. eventsApi = (obj, action, name, rest) -> return true if !name # Handle event maps. if typeof name is 'object' obj[action].apply(obj, [key, val].concat(rest)) for key, val of name return false; # Handle space separated event names. if eventSplitter.test(name) names = name.split(eventSplitter) obj[action].apply(obj, [val].concat(rest)) for val in names return false; true triggerEvents = (listeners, args) -> ev.callback.apply(ev.ctx, args) for ev in listeners delegateEvents = (delegators, args) -> delegators.forEach (delegator) -> Event.delegate.apply(delegator, args) listenMethods = listenTo: 'on' listenToOnce: 'once' # Inversion-of-control versions of `on` and `once`. Tell *this* object to # listen to an event in another object ... keeping track of what it's # listening to. for method, implementation of listenMethods Event[method] = (obj, name, callback) -> listeningTo = this._listeningTo || (this._listeningTo = {}) id = obj._listenId || (obj._listenId = utils.uniqueId('l')) listeningTo[id] = obj callback = this if (!callback && typeof name is 'object') obj[implementation](name, callback, this) return this Event
[ { "context": "# user : 'bob',\n# password : 'secret',\n# create_tables_automatically: true\n# ", "end": 531, "score": 0.99946528673172, "start": 525, "tag": "PASSWORD", "value": "secret" } ]
node_modules/share/src/server/db/mysql.coffee
abraarsyed/workshare
2
# This is an implementation of the OT data backend for MySQL. It requires # that you have two tables defined in your schema: one for the snapshots # and one for the operations. You must also install the 'mysql' package. # # # Example usage: # # var connect = require('connect'); # var share = require('share').server; # # var server = connect(connect.logger()); # # var options = { # db: { # type: 'mysql', # host : 'example.org', # user : 'bob', # password : 'secret', # create_tables_automatically: true # } # }; # # share.attach(server, options); # server.listen(9000); # # You can run bin/setup_pg to create the SQL tables initially. mysql = require('mysql') defaultOptions = schema: 'sharejs' uri: null # An optional uri for connection create_tables_automatically: true operations_table: 'ops' snapshot_table: 'snapshots' module.exports = MysqlDb = (options) -> return new Db if !(this instanceof MysqlDb) options ?= {} options[k] ?= v for k, v of defaultOptions client = options.client or mysql.createConnection options client.connect() snapshot_table = options.schema and "#{options.schema}.#{options.snapshot_table}" or options.snapshot_table operations_table = options.schema and "#{options.schema}.#{options.operations_table}" or options.operations_table @close = -> client.end() @initialize = (callback) -> console.warn 'Creating mysql database tables' sql = """ CREATE SCHEMA #{options.schema}; """ client.query sql, (error, result) -> error?.message sql = """ CREATE TABLE #{snapshot_table} ( doc varchar(256) NOT NULL, v int NOT NULL, type varchar(256) NOT NULL, snapshot text NOT NULL, meta text NOT NULL, created_at timestamp NOT NULL, CONSTRAINT snapshots_pkey PRIMARY KEY (doc, v) ); """ client.query sql, (error, result) -> error?.message sql = """ CREATE TABLE #{operations_table} ( doc varchar(256) NOT NULL, v int NOT NULL, op text NOT NULL, meta text NOT NULL, CONSTRAINT operations_pkey PRIMARY KEY (doc, v) ); """ client.query sql, (error, result) -> callback? error?.message # This will perminantly delete all data in the database. @dropTables = (callback) -> sql = "DROP SCHEMA #{options.schema} CASCADE;" client.query sql, (error, result) -> callback? error.message @create = (docName, docData, callback) -> sql = """ INSERT INTO #{snapshot_table} SET ? """ values = doc: docName, v: docData.v snapshot: JSON.stringify(docData.snapshot), meta: JSON.stringify(docData.meta), type: docData.type, created_at: new Date client.query sql, values, (error, result) -> if !error? callback?() else if error.toString().match "duplicate key value violates unique constraint" callback? "Document already exists" else callback? error?.message @delete = (docName, dbMeta, callback) -> sql = """ DELETE FROM #{operations_table} WHERE doc = ? """ values = [docName] client.query sql, values, (error, result) -> if !error? sql = """ DELETE FROM #{snapshot_table} WHERE doc = ? """ client.query sql, values, (error, result) -> if !error? and result.length > 0 callback?() else if !error? callback? "Document does not exist" else callback? error?.message else callback? error?.message @getSnapshot = (docName, callback) -> sql = """ SELECT * FROM #{snapshot_table} WHERE doc = ? ORDER BY v DESC LIMIT 1 """ values = [docName] client.query sql, values, (error, result) -> if !error? and result.length > 0 row = result[0] data = v: row.v snapshot: JSON.parse(row.snapshot) meta: JSON.parse(row.meta) type: row.type callback? null, data else if !error? callback? "Document does not exist" else callback? error?.message @writeSnapshot = (docName, docData, dbMeta, callback) -> sql = """ UPDATE #{snapshot_table} SET ? WHERE doc = ? """ values = v: docData.v snapshot: JSON.stringify(docData.snapshot) meta: JSON.stringify(docData.meta) client.query sql, [values, docName], (error, result) -> if !error? callback?() else callback? error?.message @getOps = (docName, start, end, callback) -> end = if end? then end - 1 else 2147483647 sql = """ SELECT * FROM #{operations_table} WHERE v BETWEEN ? AND ? AND doc = ? ORDER BY v ASC """ values = [start, end, docName] client.query sql, values, (error, result) -> if !error? data = result.map (row) -> return { op: JSON.parse row.op # v: row.version meta: JSON.parse row.meta } callback? null, data else callback? error?.message @writeOp = (docName, opData, callback) -> sql = """ INSERT INTO #{operations_table} SET ? """ values = doc: docName op: JSON.stringify(opData.op) v: opData.v meta: JSON.stringify(opData.meta) client.query sql, values, (error, result) -> if !error? callback?() else callback? error?.message # Immediately try and create the database tables if need be. Its possible that a query # which happens immediately will happen before the database has been initialized. # # But, its not really a big problem. if options.create_tables_automatically client.query "SELECT * from #{snapshot_table} LIMIT 0", (error, result) => @initialize() if error?.message.match "(does not exist|ER_NO_SUCH_TABLE)" this
28652
# This is an implementation of the OT data backend for MySQL. It requires # that you have two tables defined in your schema: one for the snapshots # and one for the operations. You must also install the 'mysql' package. # # # Example usage: # # var connect = require('connect'); # var share = require('share').server; # # var server = connect(connect.logger()); # # var options = { # db: { # type: 'mysql', # host : 'example.org', # user : 'bob', # password : '<PASSWORD>', # create_tables_automatically: true # } # }; # # share.attach(server, options); # server.listen(9000); # # You can run bin/setup_pg to create the SQL tables initially. mysql = require('mysql') defaultOptions = schema: 'sharejs' uri: null # An optional uri for connection create_tables_automatically: true operations_table: 'ops' snapshot_table: 'snapshots' module.exports = MysqlDb = (options) -> return new Db if !(this instanceof MysqlDb) options ?= {} options[k] ?= v for k, v of defaultOptions client = options.client or mysql.createConnection options client.connect() snapshot_table = options.schema and "#{options.schema}.#{options.snapshot_table}" or options.snapshot_table operations_table = options.schema and "#{options.schema}.#{options.operations_table}" or options.operations_table @close = -> client.end() @initialize = (callback) -> console.warn 'Creating mysql database tables' sql = """ CREATE SCHEMA #{options.schema}; """ client.query sql, (error, result) -> error?.message sql = """ CREATE TABLE #{snapshot_table} ( doc varchar(256) NOT NULL, v int NOT NULL, type varchar(256) NOT NULL, snapshot text NOT NULL, meta text NOT NULL, created_at timestamp NOT NULL, CONSTRAINT snapshots_pkey PRIMARY KEY (doc, v) ); """ client.query sql, (error, result) -> error?.message sql = """ CREATE TABLE #{operations_table} ( doc varchar(256) NOT NULL, v int NOT NULL, op text NOT NULL, meta text NOT NULL, CONSTRAINT operations_pkey PRIMARY KEY (doc, v) ); """ client.query sql, (error, result) -> callback? error?.message # This will perminantly delete all data in the database. @dropTables = (callback) -> sql = "DROP SCHEMA #{options.schema} CASCADE;" client.query sql, (error, result) -> callback? error.message @create = (docName, docData, callback) -> sql = """ INSERT INTO #{snapshot_table} SET ? """ values = doc: docName, v: docData.v snapshot: JSON.stringify(docData.snapshot), meta: JSON.stringify(docData.meta), type: docData.type, created_at: new Date client.query sql, values, (error, result) -> if !error? callback?() else if error.toString().match "duplicate key value violates unique constraint" callback? "Document already exists" else callback? error?.message @delete = (docName, dbMeta, callback) -> sql = """ DELETE FROM #{operations_table} WHERE doc = ? """ values = [docName] client.query sql, values, (error, result) -> if !error? sql = """ DELETE FROM #{snapshot_table} WHERE doc = ? """ client.query sql, values, (error, result) -> if !error? and result.length > 0 callback?() else if !error? callback? "Document does not exist" else callback? error?.message else callback? error?.message @getSnapshot = (docName, callback) -> sql = """ SELECT * FROM #{snapshot_table} WHERE doc = ? ORDER BY v DESC LIMIT 1 """ values = [docName] client.query sql, values, (error, result) -> if !error? and result.length > 0 row = result[0] data = v: row.v snapshot: JSON.parse(row.snapshot) meta: JSON.parse(row.meta) type: row.type callback? null, data else if !error? callback? "Document does not exist" else callback? error?.message @writeSnapshot = (docName, docData, dbMeta, callback) -> sql = """ UPDATE #{snapshot_table} SET ? WHERE doc = ? """ values = v: docData.v snapshot: JSON.stringify(docData.snapshot) meta: JSON.stringify(docData.meta) client.query sql, [values, docName], (error, result) -> if !error? callback?() else callback? error?.message @getOps = (docName, start, end, callback) -> end = if end? then end - 1 else 2147483647 sql = """ SELECT * FROM #{operations_table} WHERE v BETWEEN ? AND ? AND doc = ? ORDER BY v ASC """ values = [start, end, docName] client.query sql, values, (error, result) -> if !error? data = result.map (row) -> return { op: JSON.parse row.op # v: row.version meta: JSON.parse row.meta } callback? null, data else callback? error?.message @writeOp = (docName, opData, callback) -> sql = """ INSERT INTO #{operations_table} SET ? """ values = doc: docName op: JSON.stringify(opData.op) v: opData.v meta: JSON.stringify(opData.meta) client.query sql, values, (error, result) -> if !error? callback?() else callback? error?.message # Immediately try and create the database tables if need be. Its possible that a query # which happens immediately will happen before the database has been initialized. # # But, its not really a big problem. if options.create_tables_automatically client.query "SELECT * from #{snapshot_table} LIMIT 0", (error, result) => @initialize() if error?.message.match "(does not exist|ER_NO_SUCH_TABLE)" this
true
# This is an implementation of the OT data backend for MySQL. It requires # that you have two tables defined in your schema: one for the snapshots # and one for the operations. You must also install the 'mysql' package. # # # Example usage: # # var connect = require('connect'); # var share = require('share').server; # # var server = connect(connect.logger()); # # var options = { # db: { # type: 'mysql', # host : 'example.org', # user : 'bob', # password : 'PI:PASSWORD:<PASSWORD>END_PI', # create_tables_automatically: true # } # }; # # share.attach(server, options); # server.listen(9000); # # You can run bin/setup_pg to create the SQL tables initially. mysql = require('mysql') defaultOptions = schema: 'sharejs' uri: null # An optional uri for connection create_tables_automatically: true operations_table: 'ops' snapshot_table: 'snapshots' module.exports = MysqlDb = (options) -> return new Db if !(this instanceof MysqlDb) options ?= {} options[k] ?= v for k, v of defaultOptions client = options.client or mysql.createConnection options client.connect() snapshot_table = options.schema and "#{options.schema}.#{options.snapshot_table}" or options.snapshot_table operations_table = options.schema and "#{options.schema}.#{options.operations_table}" or options.operations_table @close = -> client.end() @initialize = (callback) -> console.warn 'Creating mysql database tables' sql = """ CREATE SCHEMA #{options.schema}; """ client.query sql, (error, result) -> error?.message sql = """ CREATE TABLE #{snapshot_table} ( doc varchar(256) NOT NULL, v int NOT NULL, type varchar(256) NOT NULL, snapshot text NOT NULL, meta text NOT NULL, created_at timestamp NOT NULL, CONSTRAINT snapshots_pkey PRIMARY KEY (doc, v) ); """ client.query sql, (error, result) -> error?.message sql = """ CREATE TABLE #{operations_table} ( doc varchar(256) NOT NULL, v int NOT NULL, op text NOT NULL, meta text NOT NULL, CONSTRAINT operations_pkey PRIMARY KEY (doc, v) ); """ client.query sql, (error, result) -> callback? error?.message # This will perminantly delete all data in the database. @dropTables = (callback) -> sql = "DROP SCHEMA #{options.schema} CASCADE;" client.query sql, (error, result) -> callback? error.message @create = (docName, docData, callback) -> sql = """ INSERT INTO #{snapshot_table} SET ? """ values = doc: docName, v: docData.v snapshot: JSON.stringify(docData.snapshot), meta: JSON.stringify(docData.meta), type: docData.type, created_at: new Date client.query sql, values, (error, result) -> if !error? callback?() else if error.toString().match "duplicate key value violates unique constraint" callback? "Document already exists" else callback? error?.message @delete = (docName, dbMeta, callback) -> sql = """ DELETE FROM #{operations_table} WHERE doc = ? """ values = [docName] client.query sql, values, (error, result) -> if !error? sql = """ DELETE FROM #{snapshot_table} WHERE doc = ? """ client.query sql, values, (error, result) -> if !error? and result.length > 0 callback?() else if !error? callback? "Document does not exist" else callback? error?.message else callback? error?.message @getSnapshot = (docName, callback) -> sql = """ SELECT * FROM #{snapshot_table} WHERE doc = ? ORDER BY v DESC LIMIT 1 """ values = [docName] client.query sql, values, (error, result) -> if !error? and result.length > 0 row = result[0] data = v: row.v snapshot: JSON.parse(row.snapshot) meta: JSON.parse(row.meta) type: row.type callback? null, data else if !error? callback? "Document does not exist" else callback? error?.message @writeSnapshot = (docName, docData, dbMeta, callback) -> sql = """ UPDATE #{snapshot_table} SET ? WHERE doc = ? """ values = v: docData.v snapshot: JSON.stringify(docData.snapshot) meta: JSON.stringify(docData.meta) client.query sql, [values, docName], (error, result) -> if !error? callback?() else callback? error?.message @getOps = (docName, start, end, callback) -> end = if end? then end - 1 else 2147483647 sql = """ SELECT * FROM #{operations_table} WHERE v BETWEEN ? AND ? AND doc = ? ORDER BY v ASC """ values = [start, end, docName] client.query sql, values, (error, result) -> if !error? data = result.map (row) -> return { op: JSON.parse row.op # v: row.version meta: JSON.parse row.meta } callback? null, data else callback? error?.message @writeOp = (docName, opData, callback) -> sql = """ INSERT INTO #{operations_table} SET ? """ values = doc: docName op: JSON.stringify(opData.op) v: opData.v meta: JSON.stringify(opData.meta) client.query sql, values, (error, result) -> if !error? callback?() else callback? error?.message # Immediately try and create the database tables if need be. Its possible that a query # which happens immediately will happen before the database has been initialized. # # But, its not really a big problem. if options.create_tables_automatically client.query "SELECT * from #{snapshot_table} LIMIT 0", (error, result) => @initialize() if error?.message.match "(does not exist|ER_NO_SUCH_TABLE)" this
[ { "context": "\n\n\n\nattributes =\n client: [\n \"client_id\"\n \"first_name\"\n \"email\"\n \"username\"\n \"home_phone\"", "end": 981, "score": 0.527849018573761, "start": 976, "tag": "NAME", "value": "first" }, { "context": " \"client_id\"\n \"first_name\"\n \"email\"\n \"username\"\n \"home_phone\"\n \"mobile\"\n \"organization\"", "end": 1013, "score": 0.9879164099693298, "start": 1005, "tag": "USERNAME", "value": "username" }, { "context": " \"folder\"\n \"staff_id\"\n ] \n staff: [\n \"username\"\n \"first_name\"\n \"last_name\"\n \"email\"\n ", "end": 2978, "score": 0.9991869330406189, "start": 2970, "tag": "USERNAME", "value": "username" }, { "context": "\"staff_id\"\n ] \n staff: [\n \"username\"\n \"first_name\"\n \"last_name\"\n \"email\"\n \"business_p", "end": 2990, "score": 0.8748350739479065, "start": 2985, "tag": "NAME", "value": "first" } ]
src/lib/services/freshbooks.coffee
assignittous/knodeo_workshop
0
# freshbooks.coffee 'use strict' require('sugar') config = require("../../lib/configuration").Configuration logger = require('../../lib/logger').Logger output = require('../../lib/data').Data request = require("../../lib/http").Http thisService = "freshbooks" serviceConfig = config.forService thisService data_dir = config.dataDirectoryForService thisService FreshBooks = require("freshbooks") # Note: Freshbooks doesn't work with Node 0.12 because of the versoin of libxml2 required by the npm # http://www.freshbooks.com/developers/authentication freshbooks = new FreshBooks serviceConfig.api_url, serviceConfig.api_token # Some freshbooks attributes are line feed separated values # use this fn to clean cleanedArrayAttribute = (stringArray)-> if stringArray.length > 0 values = stringArray.split('\n').map (object)-> return object.trim() values.remove('') return values else return [] attributes = client: [ "client_id" "first_name" "email" "username" "home_phone" "mobile" "organization" "work_phone" "fax" "vat_name" "vat_number" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "s_street1" "s_street2" "s_city" "s_state" "s_country" "s_code" "notes" "language" "currency_code" "folder" "updated" "credit" ] project: [ "project_id" "name" "description" "rate" "bill_method" "client_id" "project_manager_id" "external" "budget" ] estimate: [ "estimate_id" "number" "staff_id" "client_id" "contact_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "date" "notes" "terms" "discount" "language" "currency_code" "vat_name" "vat_number" "folder" ] invoice: [ "invoice_id" "number" "client_id" "contact_id" "recurring_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "amount_outstanding" "paid" "date" "notes" "terms" "discount" "return_uri" "updated" "currency_code" "language" "vat_name" "vat_number" "folder" "staff_id" ] recurring: [ "recurring_id" "number" "client_id" "contact_id" "recurring_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "amount_outstanding" "paid" "date" "notes" "terms" "discount" "return_uri" "updated" "currency_code" "language" "vat_name" "vat_number" "folder" "staff_id" ] staff: [ "username" "first_name" "last_name" "email" "business_phone" "mobile_phone" "home_phone" "fax" "rate" "last_login" "number_of_logins" "signup_date" "street1" "street2" "city" "state" "country" "code" "notes" "staff_id" ] day = Date.create() datestamp = day.format('{yyyy}-{MM}-{dd}') # start with clients client = new freshbooks.Client() client.list {}, (err, clients)-> if err? console.log "invoice list error" console.log err else output.toCsv "#{data_dir}/#{datestamp}_clients.csv", clients, attributes.client project = new freshbooks.Project() project.list {}, (err, projects)-> if err? console.log "project list error" console.log err else resources = [] tasks = [] projects.each (project)-> project.budget = project.budget.trim() project.contractors = cleanedArrayAttribute(project.contractors) project.staff = cleanedArrayAttribute(project.staff) if project.contractors.length > 0 project.contractors.each (contractor)-> resources.push project_id: project.project_id staff_id: null contractor_id: contractor if project.staff.length > 0 project.staff.each (staff)-> resources.push project_id: project.project_id staff_id: staff contractor_id: null if project.tasks.length > 0 project.tasks.each (task)-> tasks.push project_id: project.project_id task_id: task.task_id rate: task.rate if projects.length > 0 output.toCsv "#{data_dir}/#{datestamp}_projects.csv", projects, attributes.project if resources.length > 0 output.toCsv "#{data_dir}/#{datestamp}_resources.csv", resources if tasks.length > 0 output.toCsv "#{data_dir}/#{datestamp}_tasks.csv", tasks # expense categories category = new freshbooks.Category() category.list {}, (err, categories)-> if err? console.log "category list error" console.log err else if categories.length > 0 output.toCsv "#{data_dir}/#{datestamp}_expense_categories.csv", categories # estimates estimate = new freshbooks.Estimate() estimate_lines = [] estimate.list {}, (err, estimates)-> if err? console.log "estimate list error" console.log err else #console.log JSON.stringify(estimates,null,'\t') estimates.each (estimate)-> console.log "estimate id: #{estimate.estimate_id}" estimate.lines.each (line)-> estimate_lines.push Object.merge( {estimate_id: estimate.estimate_id }, line) if estimates.length > 0 output.toCsv "#{data_dir}/#{datestamp}_estimates.csv", estimates, attributes.estimate if estimate_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_estimate_line_items.csv", estimate_lines expense = new freshbooks.Expense() expense.list {}, (err, expenses)-> if err? console.log "expense list error" console.log err else if expenses.length > 0 output.toCsv "#{data_dir}/#{datestamp}_expenses.csv", expenses invoice = new freshbooks.Invoice() invoice_lines = [] invoice.list {}, (err, invoices)-> if err? console.log "invoice list error" console.log err else #console.log JSON.stringify(invoices,null,"\t") invoices.each (invoice)-> console.log "invoice id: #{invoice.invoice_id}" invoice.lines.each (line)-> invoice_lines.push Object.merge( {invoice_id: invoice.invoice_id }, line) if invoices.length > 0 output.toCsv "#{data_dir}/#{datestamp}_invoices.csv", invoices, attributes.invoice if invoice_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_invoice_line_items.csv", invoice_lines item = new freshbooks.Item() item.list {}, (err, items)-> if err? console.log "item list error" console.log err else if items.length > 0 output.toCsv "#{data_dir}/#{datestamp}_items.csv", items language = new freshbooks.Language() language.list {}, (err, languages)-> if err? console.log "language list error" console.log err else if languages.length > 0 output.toCsv "#{data_dir}/#{datestamp}_languages.csv", languages staff = new freshbooks.Staff() staff.list {}, (err, people)-> if err? console.log "staff list error" console.log err else #people.each (person)-> # person.staff = cleanedArrayAttribute(project.staff) #console.log JSON.stringify(people,null,"\t") if people.length > 0 output.toCsv "#{data_dir}/#{datestamp}_staff.csv", people, attributes.staff payment = new freshbooks.Payment() payment.list {}, (err, payments)-> if err? console.log "payment list error" console.log err else if payments.length > 0 output.toCsv "#{data_dir}/#{datestamp}_payments.csv", payments recurring = new freshbooks.Recurring() recurring_lines = [] recurring.list {}, (err, recurrings)-> if err? console.log "recurring list error" console.log err else #console.log JSON.stringify(recurrings,null,"\t") recurrings.each (recurring)-> console.log "recurring id: #{recurring.recurring_id}" recurring.lines.each (line)-> recurring_lines.push Object.merge( {recurring_id: recurring.recurring_id }, line) if recurrings.length > 0 output.toCsv "#{data_dir}/#{datestamp}_recurrings.csv", recurrings, attributes.recurring if recurring_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_recurring_line_items.csv", recurring_lines tax = new freshbooks.Tax() tax.list {}, (err, taxes)-> if err? console.log "tax list error" console.log err else if taxes.length > 0 output.toCsv "#{data_dir}/#{datestamp}_taxes.csv", taxes ## billable tasks task = new freshbooks.Task() task.list {}, (err, tasks)-> if err? console.log "task list error" console.log err else console.log JSON.stringify(tasks,null,"\t") if tasks.length > 0 output.toCsv "#{data_dir}/#{datestamp}_tasks.csv", tasks time_entry = new freshbooks.Time_Entry() time_entry.list {}, (err, time_entries)-> if err? console.log "time_entry list error" console.log err else if time_entries.length > 0 output.toCsv "#{data_dir}/#{datestamp}_time_entries.csv", time_entries
212939
# freshbooks.coffee 'use strict' require('sugar') config = require("../../lib/configuration").Configuration logger = require('../../lib/logger').Logger output = require('../../lib/data').Data request = require("../../lib/http").Http thisService = "freshbooks" serviceConfig = config.forService thisService data_dir = config.dataDirectoryForService thisService FreshBooks = require("freshbooks") # Note: Freshbooks doesn't work with Node 0.12 because of the versoin of libxml2 required by the npm # http://www.freshbooks.com/developers/authentication freshbooks = new FreshBooks serviceConfig.api_url, serviceConfig.api_token # Some freshbooks attributes are line feed separated values # use this fn to clean cleanedArrayAttribute = (stringArray)-> if stringArray.length > 0 values = stringArray.split('\n').map (object)-> return object.trim() values.remove('') return values else return [] attributes = client: [ "client_id" "<NAME>_name" "email" "username" "home_phone" "mobile" "organization" "work_phone" "fax" "vat_name" "vat_number" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "s_street1" "s_street2" "s_city" "s_state" "s_country" "s_code" "notes" "language" "currency_code" "folder" "updated" "credit" ] project: [ "project_id" "name" "description" "rate" "bill_method" "client_id" "project_manager_id" "external" "budget" ] estimate: [ "estimate_id" "number" "staff_id" "client_id" "contact_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "date" "notes" "terms" "discount" "language" "currency_code" "vat_name" "vat_number" "folder" ] invoice: [ "invoice_id" "number" "client_id" "contact_id" "recurring_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "amount_outstanding" "paid" "date" "notes" "terms" "discount" "return_uri" "updated" "currency_code" "language" "vat_name" "vat_number" "folder" "staff_id" ] recurring: [ "recurring_id" "number" "client_id" "contact_id" "recurring_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "amount_outstanding" "paid" "date" "notes" "terms" "discount" "return_uri" "updated" "currency_code" "language" "vat_name" "vat_number" "folder" "staff_id" ] staff: [ "username" "<NAME>_name" "last_name" "email" "business_phone" "mobile_phone" "home_phone" "fax" "rate" "last_login" "number_of_logins" "signup_date" "street1" "street2" "city" "state" "country" "code" "notes" "staff_id" ] day = Date.create() datestamp = day.format('{yyyy}-{MM}-{dd}') # start with clients client = new freshbooks.Client() client.list {}, (err, clients)-> if err? console.log "invoice list error" console.log err else output.toCsv "#{data_dir}/#{datestamp}_clients.csv", clients, attributes.client project = new freshbooks.Project() project.list {}, (err, projects)-> if err? console.log "project list error" console.log err else resources = [] tasks = [] projects.each (project)-> project.budget = project.budget.trim() project.contractors = cleanedArrayAttribute(project.contractors) project.staff = cleanedArrayAttribute(project.staff) if project.contractors.length > 0 project.contractors.each (contractor)-> resources.push project_id: project.project_id staff_id: null contractor_id: contractor if project.staff.length > 0 project.staff.each (staff)-> resources.push project_id: project.project_id staff_id: staff contractor_id: null if project.tasks.length > 0 project.tasks.each (task)-> tasks.push project_id: project.project_id task_id: task.task_id rate: task.rate if projects.length > 0 output.toCsv "#{data_dir}/#{datestamp}_projects.csv", projects, attributes.project if resources.length > 0 output.toCsv "#{data_dir}/#{datestamp}_resources.csv", resources if tasks.length > 0 output.toCsv "#{data_dir}/#{datestamp}_tasks.csv", tasks # expense categories category = new freshbooks.Category() category.list {}, (err, categories)-> if err? console.log "category list error" console.log err else if categories.length > 0 output.toCsv "#{data_dir}/#{datestamp}_expense_categories.csv", categories # estimates estimate = new freshbooks.Estimate() estimate_lines = [] estimate.list {}, (err, estimates)-> if err? console.log "estimate list error" console.log err else #console.log JSON.stringify(estimates,null,'\t') estimates.each (estimate)-> console.log "estimate id: #{estimate.estimate_id}" estimate.lines.each (line)-> estimate_lines.push Object.merge( {estimate_id: estimate.estimate_id }, line) if estimates.length > 0 output.toCsv "#{data_dir}/#{datestamp}_estimates.csv", estimates, attributes.estimate if estimate_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_estimate_line_items.csv", estimate_lines expense = new freshbooks.Expense() expense.list {}, (err, expenses)-> if err? console.log "expense list error" console.log err else if expenses.length > 0 output.toCsv "#{data_dir}/#{datestamp}_expenses.csv", expenses invoice = new freshbooks.Invoice() invoice_lines = [] invoice.list {}, (err, invoices)-> if err? console.log "invoice list error" console.log err else #console.log JSON.stringify(invoices,null,"\t") invoices.each (invoice)-> console.log "invoice id: #{invoice.invoice_id}" invoice.lines.each (line)-> invoice_lines.push Object.merge( {invoice_id: invoice.invoice_id }, line) if invoices.length > 0 output.toCsv "#{data_dir}/#{datestamp}_invoices.csv", invoices, attributes.invoice if invoice_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_invoice_line_items.csv", invoice_lines item = new freshbooks.Item() item.list {}, (err, items)-> if err? console.log "item list error" console.log err else if items.length > 0 output.toCsv "#{data_dir}/#{datestamp}_items.csv", items language = new freshbooks.Language() language.list {}, (err, languages)-> if err? console.log "language list error" console.log err else if languages.length > 0 output.toCsv "#{data_dir}/#{datestamp}_languages.csv", languages staff = new freshbooks.Staff() staff.list {}, (err, people)-> if err? console.log "staff list error" console.log err else #people.each (person)-> # person.staff = cleanedArrayAttribute(project.staff) #console.log JSON.stringify(people,null,"\t") if people.length > 0 output.toCsv "#{data_dir}/#{datestamp}_staff.csv", people, attributes.staff payment = new freshbooks.Payment() payment.list {}, (err, payments)-> if err? console.log "payment list error" console.log err else if payments.length > 0 output.toCsv "#{data_dir}/#{datestamp}_payments.csv", payments recurring = new freshbooks.Recurring() recurring_lines = [] recurring.list {}, (err, recurrings)-> if err? console.log "recurring list error" console.log err else #console.log JSON.stringify(recurrings,null,"\t") recurrings.each (recurring)-> console.log "recurring id: #{recurring.recurring_id}" recurring.lines.each (line)-> recurring_lines.push Object.merge( {recurring_id: recurring.recurring_id }, line) if recurrings.length > 0 output.toCsv "#{data_dir}/#{datestamp}_recurrings.csv", recurrings, attributes.recurring if recurring_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_recurring_line_items.csv", recurring_lines tax = new freshbooks.Tax() tax.list {}, (err, taxes)-> if err? console.log "tax list error" console.log err else if taxes.length > 0 output.toCsv "#{data_dir}/#{datestamp}_taxes.csv", taxes ## billable tasks task = new freshbooks.Task() task.list {}, (err, tasks)-> if err? console.log "task list error" console.log err else console.log JSON.stringify(tasks,null,"\t") if tasks.length > 0 output.toCsv "#{data_dir}/#{datestamp}_tasks.csv", tasks time_entry = new freshbooks.Time_Entry() time_entry.list {}, (err, time_entries)-> if err? console.log "time_entry list error" console.log err else if time_entries.length > 0 output.toCsv "#{data_dir}/#{datestamp}_time_entries.csv", time_entries
true
# freshbooks.coffee 'use strict' require('sugar') config = require("../../lib/configuration").Configuration logger = require('../../lib/logger').Logger output = require('../../lib/data').Data request = require("../../lib/http").Http thisService = "freshbooks" serviceConfig = config.forService thisService data_dir = config.dataDirectoryForService thisService FreshBooks = require("freshbooks") # Note: Freshbooks doesn't work with Node 0.12 because of the versoin of libxml2 required by the npm # http://www.freshbooks.com/developers/authentication freshbooks = new FreshBooks serviceConfig.api_url, serviceConfig.api_token # Some freshbooks attributes are line feed separated values # use this fn to clean cleanedArrayAttribute = (stringArray)-> if stringArray.length > 0 values = stringArray.split('\n').map (object)-> return object.trim() values.remove('') return values else return [] attributes = client: [ "client_id" "PI:NAME:<NAME>END_PI_name" "email" "username" "home_phone" "mobile" "organization" "work_phone" "fax" "vat_name" "vat_number" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "s_street1" "s_street2" "s_city" "s_state" "s_country" "s_code" "notes" "language" "currency_code" "folder" "updated" "credit" ] project: [ "project_id" "name" "description" "rate" "bill_method" "client_id" "project_manager_id" "external" "budget" ] estimate: [ "estimate_id" "number" "staff_id" "client_id" "contact_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "date" "notes" "terms" "discount" "language" "currency_code" "vat_name" "vat_number" "folder" ] invoice: [ "invoice_id" "number" "client_id" "contact_id" "recurring_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "amount_outstanding" "paid" "date" "notes" "terms" "discount" "return_uri" "updated" "currency_code" "language" "vat_name" "vat_number" "folder" "staff_id" ] recurring: [ "recurring_id" "number" "client_id" "contact_id" "recurring_id" "organization" "first_name" "last_name" "p_street1" "p_street2" "p_city" "p_state" "p_country" "p_code" "po_number" "status" "amount" "amount_outstanding" "paid" "date" "notes" "terms" "discount" "return_uri" "updated" "currency_code" "language" "vat_name" "vat_number" "folder" "staff_id" ] staff: [ "username" "PI:NAME:<NAME>END_PI_name" "last_name" "email" "business_phone" "mobile_phone" "home_phone" "fax" "rate" "last_login" "number_of_logins" "signup_date" "street1" "street2" "city" "state" "country" "code" "notes" "staff_id" ] day = Date.create() datestamp = day.format('{yyyy}-{MM}-{dd}') # start with clients client = new freshbooks.Client() client.list {}, (err, clients)-> if err? console.log "invoice list error" console.log err else output.toCsv "#{data_dir}/#{datestamp}_clients.csv", clients, attributes.client project = new freshbooks.Project() project.list {}, (err, projects)-> if err? console.log "project list error" console.log err else resources = [] tasks = [] projects.each (project)-> project.budget = project.budget.trim() project.contractors = cleanedArrayAttribute(project.contractors) project.staff = cleanedArrayAttribute(project.staff) if project.contractors.length > 0 project.contractors.each (contractor)-> resources.push project_id: project.project_id staff_id: null contractor_id: contractor if project.staff.length > 0 project.staff.each (staff)-> resources.push project_id: project.project_id staff_id: staff contractor_id: null if project.tasks.length > 0 project.tasks.each (task)-> tasks.push project_id: project.project_id task_id: task.task_id rate: task.rate if projects.length > 0 output.toCsv "#{data_dir}/#{datestamp}_projects.csv", projects, attributes.project if resources.length > 0 output.toCsv "#{data_dir}/#{datestamp}_resources.csv", resources if tasks.length > 0 output.toCsv "#{data_dir}/#{datestamp}_tasks.csv", tasks # expense categories category = new freshbooks.Category() category.list {}, (err, categories)-> if err? console.log "category list error" console.log err else if categories.length > 0 output.toCsv "#{data_dir}/#{datestamp}_expense_categories.csv", categories # estimates estimate = new freshbooks.Estimate() estimate_lines = [] estimate.list {}, (err, estimates)-> if err? console.log "estimate list error" console.log err else #console.log JSON.stringify(estimates,null,'\t') estimates.each (estimate)-> console.log "estimate id: #{estimate.estimate_id}" estimate.lines.each (line)-> estimate_lines.push Object.merge( {estimate_id: estimate.estimate_id }, line) if estimates.length > 0 output.toCsv "#{data_dir}/#{datestamp}_estimates.csv", estimates, attributes.estimate if estimate_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_estimate_line_items.csv", estimate_lines expense = new freshbooks.Expense() expense.list {}, (err, expenses)-> if err? console.log "expense list error" console.log err else if expenses.length > 0 output.toCsv "#{data_dir}/#{datestamp}_expenses.csv", expenses invoice = new freshbooks.Invoice() invoice_lines = [] invoice.list {}, (err, invoices)-> if err? console.log "invoice list error" console.log err else #console.log JSON.stringify(invoices,null,"\t") invoices.each (invoice)-> console.log "invoice id: #{invoice.invoice_id}" invoice.lines.each (line)-> invoice_lines.push Object.merge( {invoice_id: invoice.invoice_id }, line) if invoices.length > 0 output.toCsv "#{data_dir}/#{datestamp}_invoices.csv", invoices, attributes.invoice if invoice_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_invoice_line_items.csv", invoice_lines item = new freshbooks.Item() item.list {}, (err, items)-> if err? console.log "item list error" console.log err else if items.length > 0 output.toCsv "#{data_dir}/#{datestamp}_items.csv", items language = new freshbooks.Language() language.list {}, (err, languages)-> if err? console.log "language list error" console.log err else if languages.length > 0 output.toCsv "#{data_dir}/#{datestamp}_languages.csv", languages staff = new freshbooks.Staff() staff.list {}, (err, people)-> if err? console.log "staff list error" console.log err else #people.each (person)-> # person.staff = cleanedArrayAttribute(project.staff) #console.log JSON.stringify(people,null,"\t") if people.length > 0 output.toCsv "#{data_dir}/#{datestamp}_staff.csv", people, attributes.staff payment = new freshbooks.Payment() payment.list {}, (err, payments)-> if err? console.log "payment list error" console.log err else if payments.length > 0 output.toCsv "#{data_dir}/#{datestamp}_payments.csv", payments recurring = new freshbooks.Recurring() recurring_lines = [] recurring.list {}, (err, recurrings)-> if err? console.log "recurring list error" console.log err else #console.log JSON.stringify(recurrings,null,"\t") recurrings.each (recurring)-> console.log "recurring id: #{recurring.recurring_id}" recurring.lines.each (line)-> recurring_lines.push Object.merge( {recurring_id: recurring.recurring_id }, line) if recurrings.length > 0 output.toCsv "#{data_dir}/#{datestamp}_recurrings.csv", recurrings, attributes.recurring if recurring_lines.length > 0 output.toCsv "#{data_dir}/#{datestamp}_recurring_line_items.csv", recurring_lines tax = new freshbooks.Tax() tax.list {}, (err, taxes)-> if err? console.log "tax list error" console.log err else if taxes.length > 0 output.toCsv "#{data_dir}/#{datestamp}_taxes.csv", taxes ## billable tasks task = new freshbooks.Task() task.list {}, (err, tasks)-> if err? console.log "task list error" console.log err else console.log JSON.stringify(tasks,null,"\t") if tasks.length > 0 output.toCsv "#{data_dir}/#{datestamp}_tasks.csv", tasks time_entry = new freshbooks.Time_Entry() time_entry.list {}, (err, time_entries)-> if err? console.log "time_entry list error" console.log err else if time_entries.length > 0 output.toCsv "#{data_dir}/#{datestamp}_time_entries.csv", time_entries
[ { "context": " a player's move\", ->\n @battle.recordMove(@id1, @battle.getMove('Tackle'))\n action = _(@bat", "end": 1546, "score": 0.6915391683578491, "start": 1545, "tag": "USERNAME", "value": "1" }, { "context": "c priority bracket\", ->\n @battle.recordMove(@id1, @battle.getMove('Tackle'))\n @battle.record", "end": 5753, "score": 0.5380949974060059, "start": 5751, "tag": "USERNAME", "value": "id" }, { "context": "ng in that bracket\", ->\n @battle.recordMove(@id1, @battle.getMove('Tackle'))\n @battle.recordM", "end": 6086, "score": 0.7854204177856445, "start": 6083, "tag": "USERNAME", "value": "id1" }, { "context": "ng in that bracket\", ->\n @battle.recordMove(@id1, @battle.getMove('Tackle'))\n @battle.recordM", "end": 7416, "score": 0.5608935356140137, "start": 7413, "tag": "USERNAME", "value": "id1" }, { "context": "pectator = @server.findOrCreateUser(id: 1, name: \"derp\", connection)\n length = @battle.sparks.lengt", "end": 8731, "score": 0.9472223520278931, "start": 8727, "tag": "NAME", "value": "derp" }, { "context": "pectator = @server.findOrCreateUser(id: 1, name: \"derp\", connection)\n spy = @sandbox.spy(connection", "end": 9062, "score": 0.9460228085517883, "start": 9058, "tag": "NAME", "value": "derp" }, { "context": "pectator = @server.findOrCreateUser(id: 1, name: \"derp\", connection)\n spy = @sandbox.spy(connection", "end": 9464, "score": 0.9824221730232239, "start": 9460, "tag": "NAME", "value": "derp" }, { "context": "pectator = @server.findOrCreateUser(id: 1, name: \"derp\", connection)\n length = @battle.sparks.lengt", "end": 9958, "score": 0.9604215621948242, "start": 9954, "tag": "NAME", "value": "derp" }, { "context": " @clock.tick(delta)\n @battle.forfeit(@id1)\n @battle.isOver().should.be.true\n spy.", "end": 16396, "score": 0.5224926471710205, "start": 16395, "tag": "USERNAME", "value": "1" }, { "context": "shared.create.call this,\n team1: [Factory('Hitmonchan')]\n team2: [Factory('Mew')]\n ", "end": 17427, "score": 0.5466153621673584, "start": 17424, "tag": "USERNAME", "value": "Hit" }, { "context": "red.create.call this,\n team1: [Factory('Hitmonchan')]\n team2: [Factory('Mew')]\n condit", "end": 17434, "score": 0.9861962795257568, "start": 17427, "tag": "NAME", "value": "monchan" } ]
test/bw/battle.coffee
sarenji/pokebattle-sim
5
require '../helpers' sinon = require('sinon') {Attachment} = require('../../server/bw/attachment') {Battle} = require('../../server/bw/battle') {Weather} = require('../../shared/weather') {Conditions} = require '../../shared/conditions' {Factory} = require('../factory') {BattleServer} = require('../../server/server') {Protocol} = require '../../shared/protocol' shared = require('../shared') should = require 'should' {_} = require 'underscore' ratings = require('../../server/ratings') describe 'Battle', -> beforeEach -> @server = new BattleServer() shared.create.call this, format: 'xy1000' team1: [Factory('Hitmonchan'), Factory('Heracross')] team2: [Factory('Hitmonchan'), Factory('Heracross')] it 'starts at turn 1', -> @battle.turn.should.equal 1 describe '#hasWeather(weatherName)', -> it 'returns true if the current battle weather is weatherName', -> @battle.weather = "Sunny" @battle.hasWeather("Sunny").should.be.true it 'returns false on non-None in presence of a weather-cancel ability', -> @battle.weather = "Sunny" @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.hasWeather("Sunny").should.be.false it 'returns true on None in presence of a weather-cancel ability', -> @battle.weather = "Sunny" @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.hasWeather("None").should.be.true describe '#recordMove', -> it "records a player's move", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) action = _(@battle.pokemonActions).find((a) => a.pokemon == @p1) should.exist(action) action.should.have.property("move") action.move.should.equal @battle.getMove('Tackle') it "does not record a move if player has already made an action", -> length = @battle.pokemonActions.length @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.length.should.equal(1 + length) describe '#undoCompletedRequest', -> it "fails if the player didn't make any action", -> @battle.undoCompletedRequest(@id1).should.be.false it "fails on the second turn as well if the player didn't make any action", -> @controller.makeMove(@id1, "Mach Punch") @controller.makeMove(@id2, "Mach Punch") @battle.turn.should.equal 2 @battle.undoCompletedRequest(@id1).should.be.false it "succeeds if the player selected an action already", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.should.not.be.empty @battle.undoCompletedRequest(@id1).should.be.true @battle.pokemonActions.should.be.empty it "can cancel an action multiple times", -> for i in [0..5] @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.should.not.be.empty @battle.undoCompletedRequest(@id1).should.be.true @battle.pokemonActions.should.be.empty describe '#recordSwitch', -> it "records a player's switch", -> @battle.recordSwitch(@id1, 1) action = _(@battle.pokemonActions).find((a) => a.pokemon == @p1) should.exist(action) action.should.have.property("to") action.to.should.equal 1 it "does not record a switch if player has already made an action", -> length = @battle.pokemonActions.length @battle.recordSwitch(@id1, 1) @battle.recordSwitch(@id1, 1) @battle.pokemonActions.length.should.equal(1 + length) describe '#performSwitch', -> it "swaps pokemon positions of a player's team", -> [poke1, poke2] = @team1.pokemon @battle.performSwitch(@p1, 1) @team1.pokemon.slice(0, 2).should.eql [poke2, poke1] it "calls the pokemon's switchOut() method", -> pokemon = @p1 mock = @sandbox.mock(pokemon) mock.expects('switchOut').once() @battle.performSwitch(@p1, 1) mock.verify() describe "#setWeather", -> it "can last a set number of turns", -> @battle.setWeather(Weather.SUN, 5) for i in [0...5] @battle.endTurn() @battle.weather.should.equal Weather.NONE describe "weather", -> it "damages pokemon who are not of a certain type", -> @battle.setWeather(Weather.SAND) @battle.endTurn() maxHP = @p1.stat('hp') (maxHP - @p1.currentHP).should.equal Math.floor(maxHP / 16) (maxHP - @p2.currentHP).should.equal Math.floor(maxHP / 16) @battle.setWeather(Weather.HAIL) @battle.endTurn() maxHP = @p1.stat('hp') (maxHP - @p1.currentHP).should.equal 2*Math.floor(maxHP / 16) (maxHP - @p2.currentHP).should.equal 2*Math.floor(maxHP / 16) describe "move PP", -> it "goes down after a pokemon uses a move", -> pokemon = @p1 move = @p1.moves[0] @battle.performMove(@p1, move) @p1.pp(move).should.equal(@p1.maxPP(move) - 1) describe "#performMove", -> it "records this move as the battle's last move", -> move = @p1.moves[0] @battle.performMove(@p1, move) should.exist @battle.lastMove @battle.lastMove.should.equal move describe "#bump", -> it "bumps a pokemon to the front of its priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Splash')) @battle.determineTurnOrder() # Get last pokemon to move and bump it up {pokemon} = @battle.pokemonActions[@battle.pokemonActions.length - 1] @battle.bump(pokemon) @battle.pokemonActions[0].pokemon.should.eql pokemon it "bumps a pokemon to the front of a specific priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() @battle.bump(@p1, @battle.getMove('Mach Punch').priority) queue[0].pokemon.should.eql @p1 it "still works even if there's nothing in that bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() queue.should.have.length(2) @battle.bump(@p1) queue.should.have.length(2) queue[0].pokemon.should.eql @p2 queue[1].pokemon.should.eql @p1 it "is a no-op if no actions", -> queue = @battle.determineTurnOrder() queue.should.have.length(0) @battle.bump(@p1) queue.should.have.length(0) describe "#delay", -> it "delays a pokemon to the end of its priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Splash')) @battle.determineTurnOrder() # Get first pokemon to move and delay it {pokemon} = @battle.pokemonActions[0] @battle.delay(pokemon) @battle.pokemonActions[1].pokemon.should.eql pokemon it "delays a pokemon to the end of a specific priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Mach Punch')) @battle.recordMove(@id2, @battle.getMove('Tackle')) queue = @battle.determineTurnOrder() @battle.delay(@p1, @battle.getMove('Tackle').priority) queue[1].pokemon.should.eql @p1 it "still works even if there's nothing in that bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() queue.should.have.length(2) @battle.delay(@p1) queue.should.have.length(2) queue[0].pokemon.should.eql @p2 queue[1].pokemon.should.eql @p1 it "is a no-op if no actions", -> queue = @battle.determineTurnOrder() queue.should.have.length(0) @battle.delay(@p1) queue.should.have.length(0) describe "#weatherUpkeep", -> it "does not damage Pokemon if a weather-cancel ability is on the field", -> @battle.setWeather(Weather.HAIL) @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.endTurn() @p1.currentHP.should.not.be.lessThan @p1.stat('hp') @p2.currentHP.should.not.be.lessThan @p2.stat('hp') it "does not damage a Pokemon who is immune to a weather", -> @battle.setWeather(Weather.HAIL) @sandbox.stub(@p2, 'isWeatherDamageImmune', -> true) @battle.endTurn() @p1.currentHP.should.be.lessThan @p1.stat('hp') @p2.currentHP.should.not.be.lessThan @p2.stat('hp') describe "#add", -> it "adds the spectator to an internal array", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "derp", connection) length = @battle.sparks.length @battle.add(connection) @battle.sparks.should.have.length(length + 1) @battle.sparks.should.containEql(connection) it "gives the spectator battle information", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "derp", connection) spy = @sandbox.spy(connection, 'send') @battle.add(connection) {id, numActive, log} = @battle spy.calledWithMatch("spectateBattle", id, sinon.match.string, numActive, null, @battle.playerNames, log).should.be.true it "receives the correct set of initial teams", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "derp", connection) spy = @sandbox.spy(connection, 'send') teams = @battle.getTeams().map((team) -> team.toJSON(hidden: true)) @team1.switch(@p1, 1) @battle.add(connection) {id, numActive, log} = @battle spy.calledWithMatch("spectateBattle", id, sinon.match.string, numActive, null, @battle.playerNames, log).should.be.true it "does not add a spectator twice", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "derp", connection) length = @battle.sparks.length @battle.add(connection) @battle.add(connection) @battle.sparks.should.have.length(length + 1) describe "#getWinner", -> it "returns player 1 if player 2's team has all fainted", -> pokemon.faint() for pokemon in @team2.pokemon @battle.getWinner().should.equal(@id1) it "returns player 2 if player 1's team has all fainted", -> pokemon.faint() for pokemon in @team1.pokemon @battle.getWinner().should.equal(@id2) it "declares the pokemon dying of recoil the winner", -> shared.create.call this, team1: [Factory('Talonflame', moves: ["Brave Bird"])] team2: [Factory('Magikarp')] @p1.currentHP = @p2.currentHP = 1 spy = @sandbox.spy(@battle, 'getWinner') @controller.makeMove(@id1, "Brave Bird") @controller.makeMove(@id2, "Splash") spy.returned(@id1).should.be.true describe "#endBattle", -> it "cannot end multiple times", -> spy = @sandbox.spy(@battle, 'emit') spy.withArgs("end") @battle.endBattle() @battle.endBattle() spy.withArgs("end").calledOnce.should.be.true it "marks the battle as over", -> @battle.endBattle() @battle.isOver().should.be.true it "updates the winner and losers' ratings", (done) -> shared.create.call this, team1: [Factory('Hitmonchan')] team2: [Factory('Mew')] conditions: [ Conditions.RATED_BATTLE ] @battle.on "ratingsUpdated", => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.be.greaterThan(ratings.DEFAULT_RATING) rating2.rating.should.be.lessThan(ratings.DEFAULT_RATING) done() @p2.currentHP = 1 mock = @sandbox.mock(@controller) @controller.makeMove(@id1, 'Mach Punch') @controller.makeMove(@id2, 'Psychic') it "doesn't update ratings if an unrated battle", (done) -> shared.create.call this, team1: [Factory('Hitmonchan')] team2: [Factory('Mew')] @battle.on 'end', => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.equal(ratings.DEFAULT_RATING) rating2.rating.should.equal(ratings.DEFAULT_RATING) done() @p2.currentHP = 1 mock = @sandbox.mock(@controller) @controller.makeMove(@id1, 'Mach Punch') @controller.makeMove(@id2, 'Psychic') describe "#forfeit", -> it "prematurely ends the battle", -> spy = @sandbox.spy(@battle, 'tell') spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) @battle.forfeit(@id1) spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) .called.should.be.true it "does not forfeit if the player given is invalid", -> mock = @sandbox.mock(@battle).expects('tell').never() @battle.forfeit('this definitely should not work') mock.verify() it "cannot forfeit multiple times", -> spy = @sandbox.spy(@battle, 'tell') spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) @battle.forfeit(@id1) @battle.forfeit(@id1) spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) .calledOnce.should.be.true it "marks the battle as over", -> @battle.forfeit(@id1) @battle.isOver().should.be.true it "doesn't update the winner and losers' ratings if not a rated battle", (done) -> @battle.on 'end', => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.equal(ratings.DEFAULT_RATING) rating2.rating.should.equal(ratings.DEFAULT_RATING) done() @battle.forfeit(@id2) describe "#hasStarted", -> it "returns false if the battle has not started", -> battle = new Battle('id', []) battle.hasStarted().should.be.false it "returns true if the battle has started", -> battle = new Battle('id', []) battle.begin() battle.hasStarted().should.be.true describe "#getAllAttachments", -> it "returns a list of attachments for all pokemon, teams, and battles", -> @battle.attach(Attachment.TrickRoom) @team2.attach(Attachment.Reflect) @p1.attach(Attachment.Ingrain) attachments = @battle.getAllAttachments() should.exist(attachments) attachments = attachments.map((a) -> a.constructor) attachments.length.should.be.greaterThan(2) attachments.should.containEql(Attachment.TrickRoom) attachments.should.containEql(Attachment.Reflect) attachments.should.containEql(Attachment.Ingrain) describe "#query", -> it "queries all attachments attached to a specific event", -> @battle.attach(Attachment.TrickRoom) @team2.attach(Attachment.Reflect) @p1.attach(Attachment.Ingrain) mocks = [] mocks.push @sandbox.mock(Attachment.TrickRoom.prototype) mocks.push @sandbox.mock(Attachment.Reflect.prototype) mocks.push @sandbox.mock(Attachment.Ingrain.prototype) mock.expects("endTurn").once() for mock in mocks attachments = @battle.query("endTurn") mock.verify() for mock in mocks describe "#getOpponents", -> it "returns all opponents of a particular pokemon as an array", -> @battle.getOpponents(@p1).should.be.an.instanceOf(Array) @battle.getOpponents(@p1).should.have.length(1) it "does not include fainted opponents", -> @p2.faint() @battle.getOpponents(@p1).should.have.length(0) describe "#sendRequestTo", -> it "sends all requests to a certain player", -> mock = @sandbox.mock(@battle).expects('tellPlayer').once() mock.withArgs(@id1, Protocol.REQUEST_ACTIONS) @battle.sendRequestTo(@id1) mock.verify() describe "expiration", -> beforeEach -> shared.create.call(this) it "ends ongoing battles after a specific amount", -> time = Battle::ONGOING_BATTLE_TTL @clock.tick(time) @battle.isOver().should.be.true it "sends BATTLE_EXPIRED after a specific amount after battle end", -> time = Battle::ENDED_BATTLE_TTL delta = 5000 spy = @sandbox.spy(@battle, 'tell').withArgs(Protocol.BATTLE_EXPIRED) @clock.tick(delta) @battle.forfeit(@id1) @battle.isOver().should.be.true spy.withArgs(Protocol.BATTLE_EXPIRED).called.should.be.false @battle.tell.restore() spy = @sandbox.spy(@battle, 'tell').withArgs(Protocol.BATTLE_EXPIRED) @clock.tick(time) @battle.isOver().should.be.true spy.withArgs(Protocol.BATTLE_EXPIRED).calledOnce.should.be.true it "doesn't call 'expire' if expiring twice", -> firstExpire = 24 * 60 * 60 * 1000 secondExpire = 48 * 60 * 60 * 1000 spy = @sandbox.spy(@battle, 'expire') @clock.tick(firstExpire) @battle.isOver().should.be.true @clock.tick(secondExpire) spy.calledOnce.should.be.true it "doesn't call 'end' twice", -> longExpire = 48 * 60 * 60 * 1000 spy = @sandbox.spy() @battle.on('end', spy) @battle.forfeit(@id1) @battle.isOver().should.be.true @clock.tick(longExpire) spy.calledOnce.should.be.true describe "Rated battles", -> beforeEach -> shared.create.call this, team1: [Factory('Hitmonchan')] team2: [Factory('Mew')] conditions: [ Conditions.RATED_BATTLE ] it "updates the winner and losers' ratings", (done) -> @battle.on "ratingsUpdated", => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => defaultPlayer = ratings.algorithm.createPlayer() rating1.rating.should.be.greaterThan(defaultPlayer.rating) rating2.rating.should.be.lessThan(defaultPlayer.rating) done() @battle.forfeit(@id2)
223330
require '../helpers' sinon = require('sinon') {Attachment} = require('../../server/bw/attachment') {Battle} = require('../../server/bw/battle') {Weather} = require('../../shared/weather') {Conditions} = require '../../shared/conditions' {Factory} = require('../factory') {BattleServer} = require('../../server/server') {Protocol} = require '../../shared/protocol' shared = require('../shared') should = require 'should' {_} = require 'underscore' ratings = require('../../server/ratings') describe 'Battle', -> beforeEach -> @server = new BattleServer() shared.create.call this, format: 'xy1000' team1: [Factory('Hitmonchan'), Factory('Heracross')] team2: [Factory('Hitmonchan'), Factory('Heracross')] it 'starts at turn 1', -> @battle.turn.should.equal 1 describe '#hasWeather(weatherName)', -> it 'returns true if the current battle weather is weatherName', -> @battle.weather = "Sunny" @battle.hasWeather("Sunny").should.be.true it 'returns false on non-None in presence of a weather-cancel ability', -> @battle.weather = "Sunny" @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.hasWeather("Sunny").should.be.false it 'returns true on None in presence of a weather-cancel ability', -> @battle.weather = "Sunny" @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.hasWeather("None").should.be.true describe '#recordMove', -> it "records a player's move", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) action = _(@battle.pokemonActions).find((a) => a.pokemon == @p1) should.exist(action) action.should.have.property("move") action.move.should.equal @battle.getMove('Tackle') it "does not record a move if player has already made an action", -> length = @battle.pokemonActions.length @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.length.should.equal(1 + length) describe '#undoCompletedRequest', -> it "fails if the player didn't make any action", -> @battle.undoCompletedRequest(@id1).should.be.false it "fails on the second turn as well if the player didn't make any action", -> @controller.makeMove(@id1, "Mach Punch") @controller.makeMove(@id2, "Mach Punch") @battle.turn.should.equal 2 @battle.undoCompletedRequest(@id1).should.be.false it "succeeds if the player selected an action already", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.should.not.be.empty @battle.undoCompletedRequest(@id1).should.be.true @battle.pokemonActions.should.be.empty it "can cancel an action multiple times", -> for i in [0..5] @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.should.not.be.empty @battle.undoCompletedRequest(@id1).should.be.true @battle.pokemonActions.should.be.empty describe '#recordSwitch', -> it "records a player's switch", -> @battle.recordSwitch(@id1, 1) action = _(@battle.pokemonActions).find((a) => a.pokemon == @p1) should.exist(action) action.should.have.property("to") action.to.should.equal 1 it "does not record a switch if player has already made an action", -> length = @battle.pokemonActions.length @battle.recordSwitch(@id1, 1) @battle.recordSwitch(@id1, 1) @battle.pokemonActions.length.should.equal(1 + length) describe '#performSwitch', -> it "swaps pokemon positions of a player's team", -> [poke1, poke2] = @team1.pokemon @battle.performSwitch(@p1, 1) @team1.pokemon.slice(0, 2).should.eql [poke2, poke1] it "calls the pokemon's switchOut() method", -> pokemon = @p1 mock = @sandbox.mock(pokemon) mock.expects('switchOut').once() @battle.performSwitch(@p1, 1) mock.verify() describe "#setWeather", -> it "can last a set number of turns", -> @battle.setWeather(Weather.SUN, 5) for i in [0...5] @battle.endTurn() @battle.weather.should.equal Weather.NONE describe "weather", -> it "damages pokemon who are not of a certain type", -> @battle.setWeather(Weather.SAND) @battle.endTurn() maxHP = @p1.stat('hp') (maxHP - @p1.currentHP).should.equal Math.floor(maxHP / 16) (maxHP - @p2.currentHP).should.equal Math.floor(maxHP / 16) @battle.setWeather(Weather.HAIL) @battle.endTurn() maxHP = @p1.stat('hp') (maxHP - @p1.currentHP).should.equal 2*Math.floor(maxHP / 16) (maxHP - @p2.currentHP).should.equal 2*Math.floor(maxHP / 16) describe "move PP", -> it "goes down after a pokemon uses a move", -> pokemon = @p1 move = @p1.moves[0] @battle.performMove(@p1, move) @p1.pp(move).should.equal(@p1.maxPP(move) - 1) describe "#performMove", -> it "records this move as the battle's last move", -> move = @p1.moves[0] @battle.performMove(@p1, move) should.exist @battle.lastMove @battle.lastMove.should.equal move describe "#bump", -> it "bumps a pokemon to the front of its priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Splash')) @battle.determineTurnOrder() # Get last pokemon to move and bump it up {pokemon} = @battle.pokemonActions[@battle.pokemonActions.length - 1] @battle.bump(pokemon) @battle.pokemonActions[0].pokemon.should.eql pokemon it "bumps a pokemon to the front of a specific priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() @battle.bump(@p1, @battle.getMove('Mach Punch').priority) queue[0].pokemon.should.eql @p1 it "still works even if there's nothing in that bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() queue.should.have.length(2) @battle.bump(@p1) queue.should.have.length(2) queue[0].pokemon.should.eql @p2 queue[1].pokemon.should.eql @p1 it "is a no-op if no actions", -> queue = @battle.determineTurnOrder() queue.should.have.length(0) @battle.bump(@p1) queue.should.have.length(0) describe "#delay", -> it "delays a pokemon to the end of its priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Splash')) @battle.determineTurnOrder() # Get first pokemon to move and delay it {pokemon} = @battle.pokemonActions[0] @battle.delay(pokemon) @battle.pokemonActions[1].pokemon.should.eql pokemon it "delays a pokemon to the end of a specific priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Mach Punch')) @battle.recordMove(@id2, @battle.getMove('Tackle')) queue = @battle.determineTurnOrder() @battle.delay(@p1, @battle.getMove('Tackle').priority) queue[1].pokemon.should.eql @p1 it "still works even if there's nothing in that bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() queue.should.have.length(2) @battle.delay(@p1) queue.should.have.length(2) queue[0].pokemon.should.eql @p2 queue[1].pokemon.should.eql @p1 it "is a no-op if no actions", -> queue = @battle.determineTurnOrder() queue.should.have.length(0) @battle.delay(@p1) queue.should.have.length(0) describe "#weatherUpkeep", -> it "does not damage Pokemon if a weather-cancel ability is on the field", -> @battle.setWeather(Weather.HAIL) @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.endTurn() @p1.currentHP.should.not.be.lessThan @p1.stat('hp') @p2.currentHP.should.not.be.lessThan @p2.stat('hp') it "does not damage a Pokemon who is immune to a weather", -> @battle.setWeather(Weather.HAIL) @sandbox.stub(@p2, 'isWeatherDamageImmune', -> true) @battle.endTurn() @p1.currentHP.should.be.lessThan @p1.stat('hp') @p2.currentHP.should.not.be.lessThan @p2.stat('hp') describe "#add", -> it "adds the spectator to an internal array", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "<NAME>", connection) length = @battle.sparks.length @battle.add(connection) @battle.sparks.should.have.length(length + 1) @battle.sparks.should.containEql(connection) it "gives the spectator battle information", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "<NAME>", connection) spy = @sandbox.spy(connection, 'send') @battle.add(connection) {id, numActive, log} = @battle spy.calledWithMatch("spectateBattle", id, sinon.match.string, numActive, null, @battle.playerNames, log).should.be.true it "receives the correct set of initial teams", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "<NAME>", connection) spy = @sandbox.spy(connection, 'send') teams = @battle.getTeams().map((team) -> team.toJSON(hidden: true)) @team1.switch(@p1, 1) @battle.add(connection) {id, numActive, log} = @battle spy.calledWithMatch("spectateBattle", id, sinon.match.string, numActive, null, @battle.playerNames, log).should.be.true it "does not add a spectator twice", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "<NAME>", connection) length = @battle.sparks.length @battle.add(connection) @battle.add(connection) @battle.sparks.should.have.length(length + 1) describe "#getWinner", -> it "returns player 1 if player 2's team has all fainted", -> pokemon.faint() for pokemon in @team2.pokemon @battle.getWinner().should.equal(@id1) it "returns player 2 if player 1's team has all fainted", -> pokemon.faint() for pokemon in @team1.pokemon @battle.getWinner().should.equal(@id2) it "declares the pokemon dying of recoil the winner", -> shared.create.call this, team1: [Factory('Talonflame', moves: ["Brave Bird"])] team2: [Factory('Magikarp')] @p1.currentHP = @p2.currentHP = 1 spy = @sandbox.spy(@battle, 'getWinner') @controller.makeMove(@id1, "Brave Bird") @controller.makeMove(@id2, "Splash") spy.returned(@id1).should.be.true describe "#endBattle", -> it "cannot end multiple times", -> spy = @sandbox.spy(@battle, 'emit') spy.withArgs("end") @battle.endBattle() @battle.endBattle() spy.withArgs("end").calledOnce.should.be.true it "marks the battle as over", -> @battle.endBattle() @battle.isOver().should.be.true it "updates the winner and losers' ratings", (done) -> shared.create.call this, team1: [Factory('Hitmonchan')] team2: [Factory('Mew')] conditions: [ Conditions.RATED_BATTLE ] @battle.on "ratingsUpdated", => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.be.greaterThan(ratings.DEFAULT_RATING) rating2.rating.should.be.lessThan(ratings.DEFAULT_RATING) done() @p2.currentHP = 1 mock = @sandbox.mock(@controller) @controller.makeMove(@id1, 'Mach Punch') @controller.makeMove(@id2, 'Psychic') it "doesn't update ratings if an unrated battle", (done) -> shared.create.call this, team1: [Factory('Hitmonchan')] team2: [Factory('Mew')] @battle.on 'end', => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.equal(ratings.DEFAULT_RATING) rating2.rating.should.equal(ratings.DEFAULT_RATING) done() @p2.currentHP = 1 mock = @sandbox.mock(@controller) @controller.makeMove(@id1, 'Mach Punch') @controller.makeMove(@id2, 'Psychic') describe "#forfeit", -> it "prematurely ends the battle", -> spy = @sandbox.spy(@battle, 'tell') spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) @battle.forfeit(@id1) spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) .called.should.be.true it "does not forfeit if the player given is invalid", -> mock = @sandbox.mock(@battle).expects('tell').never() @battle.forfeit('this definitely should not work') mock.verify() it "cannot forfeit multiple times", -> spy = @sandbox.spy(@battle, 'tell') spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) @battle.forfeit(@id1) @battle.forfeit(@id1) spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) .calledOnce.should.be.true it "marks the battle as over", -> @battle.forfeit(@id1) @battle.isOver().should.be.true it "doesn't update the winner and losers' ratings if not a rated battle", (done) -> @battle.on 'end', => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.equal(ratings.DEFAULT_RATING) rating2.rating.should.equal(ratings.DEFAULT_RATING) done() @battle.forfeit(@id2) describe "#hasStarted", -> it "returns false if the battle has not started", -> battle = new Battle('id', []) battle.hasStarted().should.be.false it "returns true if the battle has started", -> battle = new Battle('id', []) battle.begin() battle.hasStarted().should.be.true describe "#getAllAttachments", -> it "returns a list of attachments for all pokemon, teams, and battles", -> @battle.attach(Attachment.TrickRoom) @team2.attach(Attachment.Reflect) @p1.attach(Attachment.Ingrain) attachments = @battle.getAllAttachments() should.exist(attachments) attachments = attachments.map((a) -> a.constructor) attachments.length.should.be.greaterThan(2) attachments.should.containEql(Attachment.TrickRoom) attachments.should.containEql(Attachment.Reflect) attachments.should.containEql(Attachment.Ingrain) describe "#query", -> it "queries all attachments attached to a specific event", -> @battle.attach(Attachment.TrickRoom) @team2.attach(Attachment.Reflect) @p1.attach(Attachment.Ingrain) mocks = [] mocks.push @sandbox.mock(Attachment.TrickRoom.prototype) mocks.push @sandbox.mock(Attachment.Reflect.prototype) mocks.push @sandbox.mock(Attachment.Ingrain.prototype) mock.expects("endTurn").once() for mock in mocks attachments = @battle.query("endTurn") mock.verify() for mock in mocks describe "#getOpponents", -> it "returns all opponents of a particular pokemon as an array", -> @battle.getOpponents(@p1).should.be.an.instanceOf(Array) @battle.getOpponents(@p1).should.have.length(1) it "does not include fainted opponents", -> @p2.faint() @battle.getOpponents(@p1).should.have.length(0) describe "#sendRequestTo", -> it "sends all requests to a certain player", -> mock = @sandbox.mock(@battle).expects('tellPlayer').once() mock.withArgs(@id1, Protocol.REQUEST_ACTIONS) @battle.sendRequestTo(@id1) mock.verify() describe "expiration", -> beforeEach -> shared.create.call(this) it "ends ongoing battles after a specific amount", -> time = Battle::ONGOING_BATTLE_TTL @clock.tick(time) @battle.isOver().should.be.true it "sends BATTLE_EXPIRED after a specific amount after battle end", -> time = Battle::ENDED_BATTLE_TTL delta = 5000 spy = @sandbox.spy(@battle, 'tell').withArgs(Protocol.BATTLE_EXPIRED) @clock.tick(delta) @battle.forfeit(@id1) @battle.isOver().should.be.true spy.withArgs(Protocol.BATTLE_EXPIRED).called.should.be.false @battle.tell.restore() spy = @sandbox.spy(@battle, 'tell').withArgs(Protocol.BATTLE_EXPIRED) @clock.tick(time) @battle.isOver().should.be.true spy.withArgs(Protocol.BATTLE_EXPIRED).calledOnce.should.be.true it "doesn't call 'expire' if expiring twice", -> firstExpire = 24 * 60 * 60 * 1000 secondExpire = 48 * 60 * 60 * 1000 spy = @sandbox.spy(@battle, 'expire') @clock.tick(firstExpire) @battle.isOver().should.be.true @clock.tick(secondExpire) spy.calledOnce.should.be.true it "doesn't call 'end' twice", -> longExpire = 48 * 60 * 60 * 1000 spy = @sandbox.spy() @battle.on('end', spy) @battle.forfeit(@id1) @battle.isOver().should.be.true @clock.tick(longExpire) spy.calledOnce.should.be.true describe "Rated battles", -> beforeEach -> shared.create.call this, team1: [Factory('Hit<NAME>')] team2: [Factory('Mew')] conditions: [ Conditions.RATED_BATTLE ] it "updates the winner and losers' ratings", (done) -> @battle.on "ratingsUpdated", => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => defaultPlayer = ratings.algorithm.createPlayer() rating1.rating.should.be.greaterThan(defaultPlayer.rating) rating2.rating.should.be.lessThan(defaultPlayer.rating) done() @battle.forfeit(@id2)
true
require '../helpers' sinon = require('sinon') {Attachment} = require('../../server/bw/attachment') {Battle} = require('../../server/bw/battle') {Weather} = require('../../shared/weather') {Conditions} = require '../../shared/conditions' {Factory} = require('../factory') {BattleServer} = require('../../server/server') {Protocol} = require '../../shared/protocol' shared = require('../shared') should = require 'should' {_} = require 'underscore' ratings = require('../../server/ratings') describe 'Battle', -> beforeEach -> @server = new BattleServer() shared.create.call this, format: 'xy1000' team1: [Factory('Hitmonchan'), Factory('Heracross')] team2: [Factory('Hitmonchan'), Factory('Heracross')] it 'starts at turn 1', -> @battle.turn.should.equal 1 describe '#hasWeather(weatherName)', -> it 'returns true if the current battle weather is weatherName', -> @battle.weather = "Sunny" @battle.hasWeather("Sunny").should.be.true it 'returns false on non-None in presence of a weather-cancel ability', -> @battle.weather = "Sunny" @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.hasWeather("Sunny").should.be.false it 'returns true on None in presence of a weather-cancel ability', -> @battle.weather = "Sunny" @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.hasWeather("None").should.be.true describe '#recordMove', -> it "records a player's move", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) action = _(@battle.pokemonActions).find((a) => a.pokemon == @p1) should.exist(action) action.should.have.property("move") action.move.should.equal @battle.getMove('Tackle') it "does not record a move if player has already made an action", -> length = @battle.pokemonActions.length @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.length.should.equal(1 + length) describe '#undoCompletedRequest', -> it "fails if the player didn't make any action", -> @battle.undoCompletedRequest(@id1).should.be.false it "fails on the second turn as well if the player didn't make any action", -> @controller.makeMove(@id1, "Mach Punch") @controller.makeMove(@id2, "Mach Punch") @battle.turn.should.equal 2 @battle.undoCompletedRequest(@id1).should.be.false it "succeeds if the player selected an action already", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.should.not.be.empty @battle.undoCompletedRequest(@id1).should.be.true @battle.pokemonActions.should.be.empty it "can cancel an action multiple times", -> for i in [0..5] @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.pokemonActions.should.not.be.empty @battle.undoCompletedRequest(@id1).should.be.true @battle.pokemonActions.should.be.empty describe '#recordSwitch', -> it "records a player's switch", -> @battle.recordSwitch(@id1, 1) action = _(@battle.pokemonActions).find((a) => a.pokemon == @p1) should.exist(action) action.should.have.property("to") action.to.should.equal 1 it "does not record a switch if player has already made an action", -> length = @battle.pokemonActions.length @battle.recordSwitch(@id1, 1) @battle.recordSwitch(@id1, 1) @battle.pokemonActions.length.should.equal(1 + length) describe '#performSwitch', -> it "swaps pokemon positions of a player's team", -> [poke1, poke2] = @team1.pokemon @battle.performSwitch(@p1, 1) @team1.pokemon.slice(0, 2).should.eql [poke2, poke1] it "calls the pokemon's switchOut() method", -> pokemon = @p1 mock = @sandbox.mock(pokemon) mock.expects('switchOut').once() @battle.performSwitch(@p1, 1) mock.verify() describe "#setWeather", -> it "can last a set number of turns", -> @battle.setWeather(Weather.SUN, 5) for i in [0...5] @battle.endTurn() @battle.weather.should.equal Weather.NONE describe "weather", -> it "damages pokemon who are not of a certain type", -> @battle.setWeather(Weather.SAND) @battle.endTurn() maxHP = @p1.stat('hp') (maxHP - @p1.currentHP).should.equal Math.floor(maxHP / 16) (maxHP - @p2.currentHP).should.equal Math.floor(maxHP / 16) @battle.setWeather(Weather.HAIL) @battle.endTurn() maxHP = @p1.stat('hp') (maxHP - @p1.currentHP).should.equal 2*Math.floor(maxHP / 16) (maxHP - @p2.currentHP).should.equal 2*Math.floor(maxHP / 16) describe "move PP", -> it "goes down after a pokemon uses a move", -> pokemon = @p1 move = @p1.moves[0] @battle.performMove(@p1, move) @p1.pp(move).should.equal(@p1.maxPP(move) - 1) describe "#performMove", -> it "records this move as the battle's last move", -> move = @p1.moves[0] @battle.performMove(@p1, move) should.exist @battle.lastMove @battle.lastMove.should.equal move describe "#bump", -> it "bumps a pokemon to the front of its priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Splash')) @battle.determineTurnOrder() # Get last pokemon to move and bump it up {pokemon} = @battle.pokemonActions[@battle.pokemonActions.length - 1] @battle.bump(pokemon) @battle.pokemonActions[0].pokemon.should.eql pokemon it "bumps a pokemon to the front of a specific priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() @battle.bump(@p1, @battle.getMove('Mach Punch').priority) queue[0].pokemon.should.eql @p1 it "still works even if there's nothing in that bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() queue.should.have.length(2) @battle.bump(@p1) queue.should.have.length(2) queue[0].pokemon.should.eql @p2 queue[1].pokemon.should.eql @p1 it "is a no-op if no actions", -> queue = @battle.determineTurnOrder() queue.should.have.length(0) @battle.bump(@p1) queue.should.have.length(0) describe "#delay", -> it "delays a pokemon to the end of its priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Splash')) @battle.determineTurnOrder() # Get first pokemon to move and delay it {pokemon} = @battle.pokemonActions[0] @battle.delay(pokemon) @battle.pokemonActions[1].pokemon.should.eql pokemon it "delays a pokemon to the end of a specific priority bracket", -> @battle.recordMove(@id1, @battle.getMove('Mach Punch')) @battle.recordMove(@id2, @battle.getMove('Tackle')) queue = @battle.determineTurnOrder() @battle.delay(@p1, @battle.getMove('Tackle').priority) queue[1].pokemon.should.eql @p1 it "still works even if there's nothing in that bracket", -> @battle.recordMove(@id1, @battle.getMove('Tackle')) @battle.recordMove(@id2, @battle.getMove('Mach Punch')) queue = @battle.determineTurnOrder() queue.should.have.length(2) @battle.delay(@p1) queue.should.have.length(2) queue[0].pokemon.should.eql @p2 queue[1].pokemon.should.eql @p1 it "is a no-op if no actions", -> queue = @battle.determineTurnOrder() queue.should.have.length(0) @battle.delay(@p1) queue.should.have.length(0) describe "#weatherUpkeep", -> it "does not damage Pokemon if a weather-cancel ability is on the field", -> @battle.setWeather(Weather.HAIL) @sandbox.stub(@battle, 'hasWeatherCancelAbilityOnField', -> true) @battle.endTurn() @p1.currentHP.should.not.be.lessThan @p1.stat('hp') @p2.currentHP.should.not.be.lessThan @p2.stat('hp') it "does not damage a Pokemon who is immune to a weather", -> @battle.setWeather(Weather.HAIL) @sandbox.stub(@p2, 'isWeatherDamageImmune', -> true) @battle.endTurn() @p1.currentHP.should.be.lessThan @p1.stat('hp') @p2.currentHP.should.not.be.lessThan @p2.stat('hp') describe "#add", -> it "adds the spectator to an internal array", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", connection) length = @battle.sparks.length @battle.add(connection) @battle.sparks.should.have.length(length + 1) @battle.sparks.should.containEql(connection) it "gives the spectator battle information", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", connection) spy = @sandbox.spy(connection, 'send') @battle.add(connection) {id, numActive, log} = @battle spy.calledWithMatch("spectateBattle", id, sinon.match.string, numActive, null, @battle.playerNames, log).should.be.true it "receives the correct set of initial teams", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", connection) spy = @sandbox.spy(connection, 'send') teams = @battle.getTeams().map((team) -> team.toJSON(hidden: true)) @team1.switch(@p1, 1) @battle.add(connection) {id, numActive, log} = @battle spy.calledWithMatch("spectateBattle", id, sinon.match.string, numActive, null, @battle.playerNames, log).should.be.true it "does not add a spectator twice", -> connection = @stubSpark() spectator = @server.findOrCreateUser(id: 1, name: "PI:NAME:<NAME>END_PI", connection) length = @battle.sparks.length @battle.add(connection) @battle.add(connection) @battle.sparks.should.have.length(length + 1) describe "#getWinner", -> it "returns player 1 if player 2's team has all fainted", -> pokemon.faint() for pokemon in @team2.pokemon @battle.getWinner().should.equal(@id1) it "returns player 2 if player 1's team has all fainted", -> pokemon.faint() for pokemon in @team1.pokemon @battle.getWinner().should.equal(@id2) it "declares the pokemon dying of recoil the winner", -> shared.create.call this, team1: [Factory('Talonflame', moves: ["Brave Bird"])] team2: [Factory('Magikarp')] @p1.currentHP = @p2.currentHP = 1 spy = @sandbox.spy(@battle, 'getWinner') @controller.makeMove(@id1, "Brave Bird") @controller.makeMove(@id2, "Splash") spy.returned(@id1).should.be.true describe "#endBattle", -> it "cannot end multiple times", -> spy = @sandbox.spy(@battle, 'emit') spy.withArgs("end") @battle.endBattle() @battle.endBattle() spy.withArgs("end").calledOnce.should.be.true it "marks the battle as over", -> @battle.endBattle() @battle.isOver().should.be.true it "updates the winner and losers' ratings", (done) -> shared.create.call this, team1: [Factory('Hitmonchan')] team2: [Factory('Mew')] conditions: [ Conditions.RATED_BATTLE ] @battle.on "ratingsUpdated", => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.be.greaterThan(ratings.DEFAULT_RATING) rating2.rating.should.be.lessThan(ratings.DEFAULT_RATING) done() @p2.currentHP = 1 mock = @sandbox.mock(@controller) @controller.makeMove(@id1, 'Mach Punch') @controller.makeMove(@id2, 'Psychic') it "doesn't update ratings if an unrated battle", (done) -> shared.create.call this, team1: [Factory('Hitmonchan')] team2: [Factory('Mew')] @battle.on 'end', => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.equal(ratings.DEFAULT_RATING) rating2.rating.should.equal(ratings.DEFAULT_RATING) done() @p2.currentHP = 1 mock = @sandbox.mock(@controller) @controller.makeMove(@id1, 'Mach Punch') @controller.makeMove(@id2, 'Psychic') describe "#forfeit", -> it "prematurely ends the battle", -> spy = @sandbox.spy(@battle, 'tell') spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) @battle.forfeit(@id1) spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) .called.should.be.true it "does not forfeit if the player given is invalid", -> mock = @sandbox.mock(@battle).expects('tell').never() @battle.forfeit('this definitely should not work') mock.verify() it "cannot forfeit multiple times", -> spy = @sandbox.spy(@battle, 'tell') spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) @battle.forfeit(@id1) @battle.forfeit(@id1) spy.withArgs(Protocol.FORFEIT_BATTLE, @battle.getPlayerIndex(@id1)) .calledOnce.should.be.true it "marks the battle as over", -> @battle.forfeit(@id1) @battle.isOver().should.be.true it "doesn't update the winner and losers' ratings if not a rated battle", (done) -> @battle.on 'end', => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => rating1.rating.should.equal(ratings.DEFAULT_RATING) rating2.rating.should.equal(ratings.DEFAULT_RATING) done() @battle.forfeit(@id2) describe "#hasStarted", -> it "returns false if the battle has not started", -> battle = new Battle('id', []) battle.hasStarted().should.be.false it "returns true if the battle has started", -> battle = new Battle('id', []) battle.begin() battle.hasStarted().should.be.true describe "#getAllAttachments", -> it "returns a list of attachments for all pokemon, teams, and battles", -> @battle.attach(Attachment.TrickRoom) @team2.attach(Attachment.Reflect) @p1.attach(Attachment.Ingrain) attachments = @battle.getAllAttachments() should.exist(attachments) attachments = attachments.map((a) -> a.constructor) attachments.length.should.be.greaterThan(2) attachments.should.containEql(Attachment.TrickRoom) attachments.should.containEql(Attachment.Reflect) attachments.should.containEql(Attachment.Ingrain) describe "#query", -> it "queries all attachments attached to a specific event", -> @battle.attach(Attachment.TrickRoom) @team2.attach(Attachment.Reflect) @p1.attach(Attachment.Ingrain) mocks = [] mocks.push @sandbox.mock(Attachment.TrickRoom.prototype) mocks.push @sandbox.mock(Attachment.Reflect.prototype) mocks.push @sandbox.mock(Attachment.Ingrain.prototype) mock.expects("endTurn").once() for mock in mocks attachments = @battle.query("endTurn") mock.verify() for mock in mocks describe "#getOpponents", -> it "returns all opponents of a particular pokemon as an array", -> @battle.getOpponents(@p1).should.be.an.instanceOf(Array) @battle.getOpponents(@p1).should.have.length(1) it "does not include fainted opponents", -> @p2.faint() @battle.getOpponents(@p1).should.have.length(0) describe "#sendRequestTo", -> it "sends all requests to a certain player", -> mock = @sandbox.mock(@battle).expects('tellPlayer').once() mock.withArgs(@id1, Protocol.REQUEST_ACTIONS) @battle.sendRequestTo(@id1) mock.verify() describe "expiration", -> beforeEach -> shared.create.call(this) it "ends ongoing battles after a specific amount", -> time = Battle::ONGOING_BATTLE_TTL @clock.tick(time) @battle.isOver().should.be.true it "sends BATTLE_EXPIRED after a specific amount after battle end", -> time = Battle::ENDED_BATTLE_TTL delta = 5000 spy = @sandbox.spy(@battle, 'tell').withArgs(Protocol.BATTLE_EXPIRED) @clock.tick(delta) @battle.forfeit(@id1) @battle.isOver().should.be.true spy.withArgs(Protocol.BATTLE_EXPIRED).called.should.be.false @battle.tell.restore() spy = @sandbox.spy(@battle, 'tell').withArgs(Protocol.BATTLE_EXPIRED) @clock.tick(time) @battle.isOver().should.be.true spy.withArgs(Protocol.BATTLE_EXPIRED).calledOnce.should.be.true it "doesn't call 'expire' if expiring twice", -> firstExpire = 24 * 60 * 60 * 1000 secondExpire = 48 * 60 * 60 * 1000 spy = @sandbox.spy(@battle, 'expire') @clock.tick(firstExpire) @battle.isOver().should.be.true @clock.tick(secondExpire) spy.calledOnce.should.be.true it "doesn't call 'end' twice", -> longExpire = 48 * 60 * 60 * 1000 spy = @sandbox.spy() @battle.on('end', spy) @battle.forfeit(@id1) @battle.isOver().should.be.true @clock.tick(longExpire) spy.calledOnce.should.be.true describe "Rated battles", -> beforeEach -> shared.create.call this, team1: [Factory('HitPI:NAME:<NAME>END_PI')] team2: [Factory('Mew')] conditions: [ Conditions.RATED_BATTLE ] it "updates the winner and losers' ratings", (done) -> @battle.on "ratingsUpdated", => ratings.getPlayer @id1, (err, rating1) => ratings.getPlayer @id2, (err, rating2) => defaultPlayer = ratings.algorithm.createPlayer() rating1.rating.should.be.greaterThan(defaultPlayer.rating) rating2.rating.should.be.lessThan(defaultPlayer.rating) done() @battle.forfeit(@id2)
[ { "context": "TEAM */\n Koding, Inc.\n Contact : hello@koding.com\n Twitter : twitter.com/koding\n ", "end": 863, "score": 0.9999175667762756, "start": 847, "tag": "EMAIL", "value": "hello@koding.com" }, { "context": "ello@koding.com\n Twitter : twitter.com/koding\n Facebook : facebook.com/koding\n ", "end": 904, "score": 0.9986429214477539, "start": 898, "tag": "USERNAME", "value": "koding" }, { "context": "ter.com/koding\n Facebook : facebook.com/koding\n GitHub : github.com/koding\n L", "end": 946, "score": 0.9992072582244873, "start": 940, "tag": "USERNAME", "value": "koding" }, { "context": "ebook.com/koding\n GitHub : github.com/koding\n Location : San Francisco\n \\n\n ", "end": 986, "score": 0.9992359280586243, "start": 980, "tag": "USERNAME", "value": "koding" }, { "context": "cript, KD, MongoDB, PostgreSql, http://github.com/koding for more.\n\n\n /\\\\ \\\\ /\\\\ \\\\ ", "end": 1290, "score": 0.9993481040000916, "start": 1284, "tag": "USERNAME", "value": "koding" } ]
servers/lib/server/humanstxt.coffee
ezgikaysi/koding
1
bongo = require './bongo' generateHumanstxt = (req, res) -> { JAccount } = bongo.models JAccount.some { 'globalFlags': 'staff' }, {}, (err, accounts) -> if err or not accounts return res.status(500).end() else body = '' for acc in accounts if acc?.profile?.nickname? { firstName, lastName, nickname } = acc.profile person = '' if firstName person = "#{firstName} " person += "#{lastName}\n" if lastName else person = "#{nickname}\n" person += "Site: https://koding.com/#{nickname}\n" if acc?.locationTags? person += "Location: #{acc.locationTags}\n" person += '\n' body += person header = ''' /* TEAM */ Koding, Inc. Contact : hello@koding.com Twitter : twitter.com/koding Facebook : facebook.com/koding GitHub : github.com/koding Location : San Francisco \n ''' footer = """ /* SITE */ Last update : 2015/4/16 Language : English Standards : HTML5, CSS3 Software : Golang, NodeJS, Coffeescript, KD, MongoDB, PostgreSql, http://github.com/koding for more. /\\ \\ /\\ \\ __ \\ \\ \\/'\\ ___ \\_\\ \\/\\_\\ ___ __ \\ \\ , < / __`\\ /'_` \\/\\ \\ /' _ `\\ /'_ `\\ \\ \\ \\\\`\\ /\\ \\L\\ \\/\\ \\L\\ \\ \\ \\/\\ \\/\\ \\/\\ \\L\\ \\ \\ \\_\\ \\_\\ \\____/\\ \\___,_\\ \\_\\ \\_\\ \\_\\ \\____ \\ \\/_/\\/_/\\/___/ \\/__,_ /\\/_/\\/_/\\/_/\\/___L\\ \\ /\\____/ \\_/__/ """ content = header + body + footer res.setHeader 'Content-Type', 'text/plain' return res.status(200).send content module.exports = { generateHumanstxt }
170648
bongo = require './bongo' generateHumanstxt = (req, res) -> { JAccount } = bongo.models JAccount.some { 'globalFlags': 'staff' }, {}, (err, accounts) -> if err or not accounts return res.status(500).end() else body = '' for acc in accounts if acc?.profile?.nickname? { firstName, lastName, nickname } = acc.profile person = '' if firstName person = "#{firstName} " person += "#{lastName}\n" if lastName else person = "#{nickname}\n" person += "Site: https://koding.com/#{nickname}\n" if acc?.locationTags? person += "Location: #{acc.locationTags}\n" person += '\n' body += person header = ''' /* TEAM */ Koding, Inc. Contact : <EMAIL> Twitter : twitter.com/koding Facebook : facebook.com/koding GitHub : github.com/koding Location : San Francisco \n ''' footer = """ /* SITE */ Last update : 2015/4/16 Language : English Standards : HTML5, CSS3 Software : Golang, NodeJS, Coffeescript, KD, MongoDB, PostgreSql, http://github.com/koding for more. /\\ \\ /\\ \\ __ \\ \\ \\/'\\ ___ \\_\\ \\/\\_\\ ___ __ \\ \\ , < / __`\\ /'_` \\/\\ \\ /' _ `\\ /'_ `\\ \\ \\ \\\\`\\ /\\ \\L\\ \\/\\ \\L\\ \\ \\ \\/\\ \\/\\ \\/\\ \\L\\ \\ \\ \\_\\ \\_\\ \\____/\\ \\___,_\\ \\_\\ \\_\\ \\_\\ \\____ \\ \\/_/\\/_/\\/___/ \\/__,_ /\\/_/\\/_/\\/_/\\/___L\\ \\ /\\____/ \\_/__/ """ content = header + body + footer res.setHeader 'Content-Type', 'text/plain' return res.status(200).send content module.exports = { generateHumanstxt }
true
bongo = require './bongo' generateHumanstxt = (req, res) -> { JAccount } = bongo.models JAccount.some { 'globalFlags': 'staff' }, {}, (err, accounts) -> if err or not accounts return res.status(500).end() else body = '' for acc in accounts if acc?.profile?.nickname? { firstName, lastName, nickname } = acc.profile person = '' if firstName person = "#{firstName} " person += "#{lastName}\n" if lastName else person = "#{nickname}\n" person += "Site: https://koding.com/#{nickname}\n" if acc?.locationTags? person += "Location: #{acc.locationTags}\n" person += '\n' body += person header = ''' /* TEAM */ Koding, Inc. Contact : PI:EMAIL:<EMAIL>END_PI Twitter : twitter.com/koding Facebook : facebook.com/koding GitHub : github.com/koding Location : San Francisco \n ''' footer = """ /* SITE */ Last update : 2015/4/16 Language : English Standards : HTML5, CSS3 Software : Golang, NodeJS, Coffeescript, KD, MongoDB, PostgreSql, http://github.com/koding for more. /\\ \\ /\\ \\ __ \\ \\ \\/'\\ ___ \\_\\ \\/\\_\\ ___ __ \\ \\ , < / __`\\ /'_` \\/\\ \\ /' _ `\\ /'_ `\\ \\ \\ \\\\`\\ /\\ \\L\\ \\/\\ \\L\\ \\ \\ \\/\\ \\/\\ \\/\\ \\L\\ \\ \\ \\_\\ \\_\\ \\____/\\ \\___,_\\ \\_\\ \\_\\ \\_\\ \\____ \\ \\/_/\\/_/\\/___/ \\/__,_ /\\/_/\\/_/\\/_/\\/___L\\ \\ /\\____/ \\_/__/ """ content = header + body + footer res.setHeader 'Content-Type', 'text/plain' return res.status(200).send content module.exports = { generateHumanstxt }
[ { "context": "Person =\n name: 'string'\n email: 'string'\n chore_ids: [ ObjectId(chore_", "end": 24, "score": 0.9817655086517334, "start": 18, "tag": "NAME", "value": "string" } ]
store/_data.cson
jimbol/dashberry-pi
0
Person = name: 'string' email: 'string' chore_ids: [ ObjectId(chore_id) ] Chore = label: 'string' person_id: ObjectId( person_id ) List = person_id: ObjectId( person_id ) title: 'string' chore_ids: [ ObjectId(chore_id) ] Lists = list_ids: [ ObjectId( list_id ) ] person_id: ObjectId( person_id )
225627
Person = name: '<NAME>' email: 'string' chore_ids: [ ObjectId(chore_id) ] Chore = label: 'string' person_id: ObjectId( person_id ) List = person_id: ObjectId( person_id ) title: 'string' chore_ids: [ ObjectId(chore_id) ] Lists = list_ids: [ ObjectId( list_id ) ] person_id: ObjectId( person_id )
true
Person = name: 'PI:NAME:<NAME>END_PI' email: 'string' chore_ids: [ ObjectId(chore_id) ] Chore = label: 'string' person_id: ObjectId( person_id ) List = person_id: ObjectId( person_id ) title: 'string' chore_ids: [ ObjectId(chore_id) ] Lists = list_ids: [ ObjectId( list_id ) ] person_id: ObjectId( person_id )
[ { "context": "'base64')\n\n opt.headers[\"Authorization\"] = \"UPYUN #{@username}:#{signature}\"\n opt.headers[\"Date\"] = date\n @_u", "end": 2050, "score": 0.8638317584991455, "start": 2039, "tag": "USERNAME", "value": "#{@username" }, { "context": "xt url\n@action_share = (url)=>\n url = \"upyun://#{@username}:#{@password}@#{@bucket}#{url}\"\n msg = Messenger", "end": 11925, "score": 0.6846973896026611, "start": 11916, "tag": "USERNAME", "value": "@username" }, { "context": "ument.createElement 'a'\n .appendTo li\n .text @username\n .prepend @createIcon 'user'\n .attr 'href',", "end": 13147, "score": 0.850813627243042, "start": 13138, "tag": "USERNAME", "value": "@username" }, { "context": " Open 'editor',\n username: @username\n password: @password\n ", "end": 21887, "score": 0.999582052230835, "start": 21878, "tag": "USERNAME", "value": "@username" }, { "context": " username: @username\n password: @password\n bucket: @bucket\n e", "end": 21923, "score": 0.9988762140274048, "start": 21914, "tag": "PASSWORD", "value": "@password" }, { "context": "rmLogin').serializeObject()\n fav.password = \"MD5_\" + MD5 fav.password unless fav.password.match /^MD", "end": 23779, "score": 0.995406448841095, "start": 23775, "tag": "PASSWORD", "value": "MD5_" }, { "context": "lizeObject()\n fav.password = \"MD5_\" + MD5 fav.password unless fav.password.match /^MD5_/\n @", "end": 23790, "score": 0.6966699361801147, "start": 23790, "tag": "PASSWORD", "value": "" }, { "context": " + MD5 fav.password unless fav.password.match /^MD5_/\n @m_favs[\"#{fav.username}@#{fav.bucket}\"] ", "end": 23831, "score": 0.7951586246490479, "start": 23830, "tag": "PASSWORD", "value": "5" }, { "context": "rrentTarget).serializeObject()\n @password = \"MD5_\" + MD5 @password unless @password.match /^MD5_/\n ", "end": 24108, "score": 0.9916470646858215, "start": 24104, "tag": "PASSWORD", "value": "MD5_" }, { "context": "name)=>\n Open 'editor',\n username: @username\n password: @password\n bucket: @", "end": 26120, "score": 0.9994897842407227, "start": 26111, "tag": "USERNAME", "value": "@username" }, { "context": "\n username: @username\n password: @password\n bucket: @bucket\n editor_url: \"", "end": 26150, "score": 0.9985815286636353, "start": 26141, "tag": "PASSWORD", "value": "@password" }, { "context": " Electron.shell.openExternal \"https://github.com/layerssss/manager-for-upyun/issues\"\n $ '[title]'\n .tool", "end": 27611, "score": 0.9994949102401733, "start": 27602, "tag": "USERNAME", "value": "layerssss" } ]
source/javascripts/all.coffee
layerssss/manager-for-upyun
164
moment.locale 'zh-cn' try @m_favs = JSON.parse(localStorage.favs)||{} catch @m_favs = {} @refresh_favs = => $ '#favs' .empty() for k, fav of @m_favs fav.origin ?= "http://#{fav.bucket}.b0.upaiyun.com" $ li = document.createElement 'li' .appendTo '#favs' $ document.createElement 'a' .appendTo li .text "#{k} (#{fav.origin})" .attr href: '#' .data 'fav', fav .click (ev)=> ev.preventDefault() $(ev.currentTarget).parent().addClass('active').siblings().removeClass 'active' for k, v of $(ev.currentTarget).data 'fav' $ "#input#{_.capitalize k}" .val v $ '#formLogin' .submit() $ document.createElement 'button' .appendTo li .prepend @createIcon 'trash-o' .addClass 'btn btn-danger btn-xs' .attr 'title', '删除这条收藏记录' .tooltip placement: 'bottom' .data 'fav', fav .click (ev)=> fav = $(ev.currentTarget).data 'fav' delete @m_favs["#{fav.username}@#{fav.bucket}"] localStorage.favs = JSON.stringify @m_favs @refresh_favs() @humanFileSize = (bytes, si) -> thresh = (if si then 1000 else 1024) return bytes + " B" if bytes < thresh units = (if si then [ "kB" "MB" "GB" "TB" "PB" "EB" "ZB" "YB" ] else [ "KiB" "MiB" "GiB" "TiB" "PiB" "EiB" "ZiB" "YiB" ]) u = -1 loop bytes /= thresh ++u break unless bytes >= thresh bytes.toFixed(1) + " " + units[u] @_upyun_api = (opt, cb)=> opt.headers?= {} opt.headers["Content-Length"] = String opt.length || opt.data?.length || 0 unless opt.method in ['GET', 'HEAD'] date = new Date().toUTCString() if @password.match /^MD5_/ md5_password = @password.replace /^MD5_/, '' else md5_password = MD5 @password signature = "#{opt.method}&/#{@bucket}#{opt.url}&#{date}" signature = Crypto.createHmac('sha1', md5_password).update(signature).digest('base64') opt.headers["Authorization"] = "UPYUN #{@username}:#{signature}" opt.headers["Date"] = date @_upyun_api_req = req = CallRequest options: method: opt.method url: "http://v0.api.upyun.com/#{@bucket}#{opt.url}" headers: opt.headers body: opt.data onData: opt.onData onRequestData: opt.onRequestData pipeRequest: opt.pipeRequest pipeResponse: opt.pipeResponse onFinish: (e, res, data)=> return cb e if e if res.statusCode == 200 cb null, data else status = null try status = JSON.parse(data) if data if status && status.msg cb new Error status.msg else cb new Error "未知错误 (HTTP#{res.statusCode})" return => req.abort() cb new Error '操作已取消' @upyun_api = (opt, cb)=> start = Date.now() @_upyun_api opt, (e, data)=> console?.log "#{opt.method} #{@bucket}#{opt.url} done (+#{Date.now() - start}ms)" cb e, data Messenger.options = extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right' theme: 'future' messageDefaults: showCloseButton: true hideAfter: 10 retry: label: '重试' phrase: 'TIME秒钟后重试' auto: true delay: 5 @createIcon = (icon)=> $ document.createElement 'i' .addClass "fa fa-#{icon}" @shortOperation = (title, operation)=> @shortOperationBusy = true $ '#loadingText' .text title||'' .append '<br />' $ 'body' .addClass 'loading' $ btnCancel = document.createElement 'button' .appendTo '#loadingText' .addClass 'btn btn-default btn-xs btn-inline' .text '取消' .hide() operationDone = (e)=> @shortOperationBusy = false $ 'body' .removeClass 'loading' if e msg = Messenger().post type: 'error' message: e.message showCloseButton: true actions: ok: label: '确定' action: => msg.hide() retry: label: '重试' action: => msg.hide() @shortOperation title, operation operation operationDone, $ btnCancel @taskOperation = (title, operation)=> msg = Messenger( instance: @messengerTasks extraClasses: 'messenger-fixed messenger-on-left messenger-on-bottom' ).post hideAfter: 0 message: title actions: cancel: label: '取消' action: => $progresslabel1 = $ document.createElement 'span' .appendTo msg.$message.find('.messenger-message-inner') .addClass 'pull-right' $progressbar = $ document.createElement 'div' .appendTo msg.$message.find('.messenger-message-inner') .addClass 'progress progress-striped active' .css margin: 0 .append $(document.createElement 'div').addClass('progress-bar').width '100%' .append $(document.createElement 'div').addClass('progress-bar progress-bar-success').width '0%' $progresslabel2 = $ document.createElement 'div' .appendTo msg.$message.find('.messenger-message-inner') operationProgress = (progress, progresstext)=> $progresslabel2.text progresstext if progresstext $progresslabel1.text "#{progress}%" if progress? $progressbar .toggleClass 'active', !progress? $progressbar.children ':not(.progress-bar-success)' .toggle !progress? $progressbar.children '.progress-bar-success' .toggle progress? .width "#{progress}%" operationDone = (e)=> return unless msg if e msg.update type: 'error' message: e.message showCloseButton: true actions: ok: label: '确定' action: => msg.hide() retry: label: '重试' action: => msg.hide() @taskOperation title, operation else msg.hide() operationProgress null operation operationProgress, operationDone, msg.$message.find('[data-action="cancel"] a') @upyun_readdir = (url, cb)=> @upyun_api method: "GET" url: url , (e, data)=> return cb e if e files = data.split('\n').map (line)-> line = line.split '\t' return null unless line.length == 4 return ( filename: line[0] url: url + encodeURIComponent line[0] isDirectory: line[1]=='F' length: Number line[2] mtime: 1000 * Number line[3] ) cb null, files.filter (file)-> file? @upyun_find_abort = -> @upyun_find = (url, cb)=> results = [] @upyun_find_abort = @upyun_readdir url, (e, files)=> return cb e if e async.eachSeries files, (file, doneEach)=> if file.isDirectory @upyun_find file.url + '/', (e, tmp)=> return doneEach e if e results.push item for item in tmp results.push file doneEach null else results.push file _.defer => doneEach null , (e)=> @upyun_find_abort = -> cb e, results @upyun_upload = (url, files, onProgress, cb)=> aborted = false api_aborting = null aborting = => aborted = true api_aborting?() status = total_files: files.length total_bytes: files.reduce ((a, b)-> a + b.length), 0 current_files: 0 current_bytes: 0 async.eachSeries files, (file, doneEach)=> Fs.stat file.path, (e, stats)=> return doneEach (new Error '操作已取消') if aborted return doneEach e if e api_aborting = @upyun_api pipeRequest: file.path method: "PUT" headers: 'mkdir': 'true', length: stats.size url: url + file.url onRequestData: (data)=> status.current_bytes+= data.length onProgress status , (e)=> status.current_files+= 1 onProgress status doneEach e , (e)=> cb e return aborting @action_downloadFolder = (filename, url)=> unless filename || filename = url.match(/([^\/]+)\/$/)?[1] filename = @bucket @shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=> $btnCancelFind.show().click => @upyun_find_abort() @upyun_find url, (e, files)=> doneFind e unless e SelectFolder (savepath)=> @taskOperation "正在下载目录 #{filename} ...", (progressTransfer, doneTransfer, $btnCancelTransfer)=> total_files = files.length total_bytes = files.reduce ((a, b)-> a + b.length), 0 current_files = 0 current_bytes = 0 aborting = null $btnCancelTransfer.click => aborting() if aborting? async.eachSeries files, ((file, doneEach)=> return (_.defer => doneEach null) if file.isDirectory segs = file.url.substring(url.length).split '/' segs = segs.map decodeURIComponent destpath = Path.join savepath, filename, Path.join.apply Path, segs Mkdirp Path.dirname(destpath), (e)=> return doneEach e if e _.defer => bytesWritten = 0 current_files+= 1 aborting = @upyun_api method: 'GET' url: file.url pipeResponse: destpath onData: (data)=> bytesWritten += data.length progressTransfer (Math.floor 100 * (current_bytes + bytesWritten) / total_bytes), "已下载:#{current_files} / #{total_files} (#{@humanFileSize current_bytes + bytesWritten} / #{@humanFileSize total_bytes})" , (e)=> current_bytes+= file.length unless e doneEach e ), (e)=> aborting = null doneTransfer e unless e msg = Messenger().post message: "目录 #{filename} 下载完毕" actions: ok: label: '确定' action: => msg.hide() open: label: "打开" action: => msg.hide() Electron.shell.openItem savepath @action_uploadFile = (filepath, filename, destpath)=> @taskOperation "正在上传 #{filename}", (progressTransfer, doneTransfer, $btnCancelTransfer)=> files = [] loadfileSync = (file)=> stat = Fs.statSync(file.path) if stat.isFile() file.length = stat.size files.push file if stat.isDirectory() for filename in Fs.readdirSync file.path loadfileSync path: Path.join(file.path, filename) url: file.url + '/' + encodeURIComponent filename try loadfileSync path: filepath, url: '' catch e return doneTransfer e if e $btnCancelTransfer.show().click @upyun_upload destpath, files, (status)=> progressTransfer (Math.floor 100 * status.current_bytes / status.total_bytes), "已上传:#{status.current_files} / #{status.total_files} (#{@humanFileSize status.current_bytes} / #{@humanFileSize status.total_bytes})" , (e)=> doneTransfer e unless e @m_changed_path = destpath.replace /[^\/]+$/, '' msg = Messenger().post message: "文件 #{filename} 上传完毕" actions: ok: label: '确定' action: => msg.hide() @action_show_url = (title, url)=> msg = Messenger().post message: "#{title}<pre>#{url}</pre>" actions: ok: label: '确定' action: => msg.hide() copy: label: '将该地址复制到剪切版' action: (ev)=> $(ev.currentTarget).text '已复制到剪切版' Electron.clipboard.writeText url @action_share = (url)=> url = "upyun://#{@username}:#{@password}@#{@bucket}#{url}" msg = Messenger().post message: """ 您可以通过以下地址向其他人分享该目录: <pre>#{url}</pre> 注意:<ol> <li>该地址中包含了当前操作员的授权信息,向他人分享该地址的同时,也同时分享了该操作员的身份。</li> <li>当他人安装了“又拍云管理器时”后,便可以直接点击该链接以打开。</li> </ol> """ actions: ok: label: '确定' action: => msg.hide() copy: label: '将该地址复制到剪切版' action: (ev)=> $(ev.currentTarget).text '已复制到剪切版' Electron.clipboard.writeText url, 'text' @jump_login = => @m_path = '/' @m_active = false @refresh_favs() $ '#filelist, #editor' .hide() $ '#login' .fadeIn() @jump_filelist = => @jump_path '/' @jump_path = (path)=> @m_path = path @m_changed_path = path @m_active = true @m_files = null $ '#filelist .preloader' .css opacity: 1 $ '#inputFilter' .val '' $ '#login, #editor' .hide() $ '#filelist' .fadeIn() segs = $.makeArray(@m_path.match /\/[^\/]+/g).map (match)-> String(match).replace /^\//, '' segs = segs.map decodeURIComponent $ '#path' .empty() $ li = document.createElement 'li' .appendTo '#path' $ document.createElement 'a' .appendTo li .text @username .prepend @createIcon 'user' .attr 'href', '#' .click (ev)=> ev.preventDefault() @jump_login() $ li = document.createElement 'li' .toggleClass 'active', !segs.length .appendTo '#path' $ document.createElement 'a' .appendTo li .text "#{@bucket} (#{@origin})" .prepend @createIcon 'cloud' .attr 'href', "#{@origin}/" .data 'url', '/' for seg, i in segs url = '/' + segs[0..i].map(encodeURIComponent).join('/') + '/' $ li = document.createElement 'li' .toggleClass 'active', i == segs.length - 1 .appendTo '#path' $ document.createElement 'a' .appendTo li .text seg .prepend @createIcon 'folder' .attr 'href', "#{@origin}#{url}" .data 'url', url $ '#path li:not(:first-child)>a' .click (ev)=> ev.preventDefault() @jump_path $(ev.currentTarget).data 'url' @refresh_filelist = (cb)=> cur_path = @m_path @upyun_readdir cur_path, (e, files)=> return cb e if e if @m_path == cur_path && JSON.stringify(@m_files) != JSON.stringify(files) $('#filelist tbody').empty() $('#filelist .preloader').css opacity: 0 for file in @m_files = files $ tr = document.createElement 'tr' .appendTo '#filelist tbody' $ td = document.createElement 'td' .appendTo tr if file.isDirectory $ a = document.createElement 'a' .appendTo td .text file.filename .prepend @createIcon 'folder' .attr 'href', "#" .data 'url', file.url + '/' .click (ev)=> ev.preventDefault() @jump_path $(ev.currentTarget).data('url') else $ td .text file.filename .prepend @createIcon 'file' $ document.createElement 'td' .appendTo tr .text if file.isDirectory then '' else @humanFileSize file.length $ document.createElement 'td' .appendTo tr .text moment(file.mtime).format 'LLL' $ td = document.createElement 'td' .appendTo tr if file.isDirectory $ document.createElement 'button' .appendTo td .attr title: '删除该目录' .addClass 'btn btn-danger btn-xs' .data 'url', file.url + '/' .data 'filename', file.filename .prepend @createIcon 'trash-o' .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' @shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=> $btnCancelFind.show().click => @upyun_find_abort() @upyun_find url, (e, files)=> doneFind e unless e files_deleting = 0 async.eachSeries files, (file, doneEach)=> files_deleting+= 1 @shortOperation "正在删除(#{files_deleting}/#{files.length}) #{file.filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: file.url , (e)=> operationDone e doneEach e , (e)=> unless e @shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: url , (e)=> @m_changed_path = url.replace /[^\/]+\/$/, '' operationDone e else $ document.createElement 'button' .appendTo td .attr title: '删除该文件' .addClass 'btn btn-danger btn-xs' .data 'url', file.url .data 'filename', file.filename .prepend @createIcon 'trash-o' .click (ev)=> url = $(ev.currentTarget).data('url') filename = $(ev.currentTarget).data('filename') @shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: url , (e)=> @m_changed_path = url.replace /\/[^\/]+$/, '/' operationDone e if file.isDirectory $ document.createElement 'button' .appendTo td .attr title: '下载该目录' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'download' .data 'url', file.url + '/' .data 'filename', file.filename .click (ev)=> @action_downloadFolder $(ev.currentTarget).data('filename'), $(ev.currentTarget).data('url') $ document.createElement 'button' .appendTo td .attr title: '向其他人分享该目录' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'share' .data 'url', file.url + '/' .click (ev)=> url = $(ev.currentTarget).data 'url' @action_share url else $ document.createElement 'button' .appendTo td .attr title: '下载该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'download' .data 'url', file.url .data 'filename', file.filename .data 'length', file.length .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' length = $(ev.currentTarget).data 'length' SaveAsFile filename, (savepath)=> @taskOperation "正在下载文件 #{filename} ..", (progressTransfer, doneTransfer, $btnCancelTransfer)=> aborting = null $btnCancelTransfer.click => aborting() if aborting? _.defer => bytesWritten = 0 aborting = @upyun_api method: "GET" url: url pipeResponse: savepath onData: (data)=> bytesWritten += data.length progressTransfer (Math.floor 100 * bytesWritten / length), "#{@humanFileSize bytesWritten} / #{@humanFileSize length}" , (e, data)=> doneTransfer e unless e msg = Messenger().post message: "文件 #{filename} 下载完毕" actions: ok: label: '确定' action: => msg.hide() open: label: "打开" action: => msg.hide() Electron.shell.openItem savepath showItemInFolder: label: "打开目录" action: => msg.hide() Electron.shell.showItemInFolder savepath $ document.createElement 'button' .appendTo td .attr title: '在浏览器中访问该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'globe' .data 'url', "#{@origin}#{file.url}" .click (ev)=> url = $(ev.currentTarget).data 'url' Electron.shell.openExternal url $ document.createElement 'button' .appendTo td .attr title: '公共地址' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'code' .data 'url', "#{@origin}#{file.url}" .data 'filename', file.filename .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' @action_show_url "文件 #{filename} 的公共地址(URL)", url $ document.createElement 'button' .appendTo td .attr title: '用文本编辑器打开该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'edit' .data 'url', file.url .data 'filename', file.filename .click (ev)=> Open 'editor', username: @username password: @password bucket: @bucket editor_url: $(ev.currentTarget).data 'url' editor_filename: $(ev.currentTarget).data 'filename' $('#filelist tbody [title]') .tooltip placement: 'bottom' trigger: 'hover' cb null @jump_editor = => $ '#login, #filelist' .hide() $ '#editor' .show() window.document.title = @editor_filename @editor = Ace.edit $('#editor .editor')[0] $('#btnReloadEditor').click() window.ondragover = window.ondrop = (ev)-> ev.preventDefault() return false $ => @messengerTasks = $ document.createElement 'ul' .appendTo 'body' .messenger() forverCounter = 0 async.forever (doneForever)=> if @m_active && !@shortOperationBusy forverCounter += 1 if forverCounter == 20 || @m_changed_path == @m_path forverCounter = 0 @m_changed_path = null return @refresh_filelist (e)=> if e msg = Messenger().post message: e.message type: 'error' actions: ok: label: '确定' action: => msg.hide() @jump_login() setTimeout (=>doneForever null), 100 setTimeout (=>doneForever null), 100 , (e)=> throw e $ '#inputBucket' .on 'input', (event)=> origin = $('#inputOrigin').val() return unless origin.endsWith('.b0.upaiyun.com') $('#inputOrigin').val("http://#{event.currentTarget.value}.b0.upaiyun.com") $ '#inputOrigin' .on 'change', (event)=> if !event.currentTarget.value.trim() $(event.currentTarget).val("http://#{$('#inputBucket').val()}.b0.upaiyun.com") $ '#btnAddFav' .click => fav = $('#formLogin').serializeObject() fav.password = "MD5_" + MD5 fav.password unless fav.password.match /^MD5_/ @m_favs["#{fav.username}@#{fav.bucket}"] = fav localStorage.favs = JSON.stringify @m_favs @refresh_favs() $ '#formLogin' .submit (ev)=> ev.preventDefault() @[k] = v for k, v of $(ev.currentTarget).serializeObject() @password = "MD5_" + MD5 @password unless @password.match /^MD5_/ $ '#filelist tbody' .empty() @jump_filelist() $ window .on 'dragover', -> $('body').addClass 'drag_hover' .on 'dragleave', -> $('body').removeClass 'drag_hover' .on 'dragend', -> $('body').removeClass 'drag_hover' .on 'drop', (ev)=> $('body').removeClass 'drag_hover' ev.preventDefault() for file in ev.originalEvent.dataTransfer.files @action_uploadFile file.path, file.name, "#{@m_path}#{encodeURIComponent file.name}" $ '#inputFilter' .keydown => _.defer => val = String $('#inputFilter').val() $ "#filelist tbody tr:contains(#{JSON.stringify val})" .removeClass 'filtered' $ "#filelist tbody tr:not(:contains(#{JSON.stringify val}))" .addClass 'filtered' $ '#btnDownloadFolder' .click (ev)=> ev.preventDefault() @action_downloadFolder null, @m_path $ '#btnUploadFiles' .click (ev)=> ev.preventDefault() SelectFiles (files)=> for filepath in files filename = Path.basename filepath @action_uploadFile filepath, filename, "#{@m_path}#{encodeURIComponent filename}" $ '#btnUploadFolder' .click (ev)=> ev.preventDefault() SelectFolder (dirpath)=> @action_uploadFile dirpath, Path.basename(dirpath), @m_path $ '#btnCreateFolder' .click (ev)=> ev.preventDefault() Prompt "请输入新目录的名称", (filename)=> @shortOperation "正在新建目录 #{filename} ...", (doneCreating, $btnCancelCreateing)=> cur_path = @m_path $btnCancelCreateing.click @upyun_api url: "#{cur_path}#{filename}" method: "POST" headers: 'Folder': 'true' , (e, data)=> doneCreating e @m_changed_path = cur_path $ '#btnCreateFile' .click (ev)=> ev.preventDefault() Prompt "请输入新文件的文件名", (filename)=> Open 'editor', username: @username password: @password bucket: @bucket editor_url: "#{@m_path}#{filename}" editor_filename: filename $ '#btnReloadEditor' .click (ev)=> ev.preventDefault() @shortOperation "正在加载文件 #{@editor_filename} ...", (doneReloading, $btnCancelReloading)=> $btnCancelReloading.click @upyun_api url: @editor_url method: 'GET' , (e, data)=> if e data = '' else data = data.toString 'utf8' doneReloading null unless e @editor.setValue data $ '#btnShareFolder' .click (ev)=> @action_share @m_path $ '#btnSaveEditor' .click (ev)=> ev.preventDefault() @shortOperation "正在保存文件 #{@editor_filename} ...", (doneSaving, $btnCancelSaving)=> $btnCancelSaving.click @upyun_api url: @editor_url method: 'PUT' data: new Buffer @editor.getValue(), 'utf8' , (e)=> doneSaving e unless e msg = Messenger().post message: "成功保存文件 #{@editor_filename}" actions: ok: label: '确定' action: => msg.hide() $ '#btnLogout' .click (ev)=> ev.preventDefault() @jump_login() $ '#btnIssues' .click (ev)=> ev.preventDefault() Electron.shell.openExternal "https://github.com/layerssss/manager-for-upyun/issues" $ '[title]' .tooltip placement: 'bottom' trigger: 'hover' window.Init = (action, params) => for key, value of params @[key] = value @["jump_#{action}"]()
53432
moment.locale 'zh-cn' try @m_favs = JSON.parse(localStorage.favs)||{} catch @m_favs = {} @refresh_favs = => $ '#favs' .empty() for k, fav of @m_favs fav.origin ?= "http://#{fav.bucket}.b0.upaiyun.com" $ li = document.createElement 'li' .appendTo '#favs' $ document.createElement 'a' .appendTo li .text "#{k} (#{fav.origin})" .attr href: '#' .data 'fav', fav .click (ev)=> ev.preventDefault() $(ev.currentTarget).parent().addClass('active').siblings().removeClass 'active' for k, v of $(ev.currentTarget).data 'fav' $ "#input#{_.capitalize k}" .val v $ '#formLogin' .submit() $ document.createElement 'button' .appendTo li .prepend @createIcon 'trash-o' .addClass 'btn btn-danger btn-xs' .attr 'title', '删除这条收藏记录' .tooltip placement: 'bottom' .data 'fav', fav .click (ev)=> fav = $(ev.currentTarget).data 'fav' delete @m_favs["#{fav.username}@#{fav.bucket}"] localStorage.favs = JSON.stringify @m_favs @refresh_favs() @humanFileSize = (bytes, si) -> thresh = (if si then 1000 else 1024) return bytes + " B" if bytes < thresh units = (if si then [ "kB" "MB" "GB" "TB" "PB" "EB" "ZB" "YB" ] else [ "KiB" "MiB" "GiB" "TiB" "PiB" "EiB" "ZiB" "YiB" ]) u = -1 loop bytes /= thresh ++u break unless bytes >= thresh bytes.toFixed(1) + " " + units[u] @_upyun_api = (opt, cb)=> opt.headers?= {} opt.headers["Content-Length"] = String opt.length || opt.data?.length || 0 unless opt.method in ['GET', 'HEAD'] date = new Date().toUTCString() if @password.match /^MD5_/ md5_password = @password.replace /^MD5_/, '' else md5_password = MD5 @password signature = "#{opt.method}&/#{@bucket}#{opt.url}&#{date}" signature = Crypto.createHmac('sha1', md5_password).update(signature).digest('base64') opt.headers["Authorization"] = "UPYUN #{@username}:#{signature}" opt.headers["Date"] = date @_upyun_api_req = req = CallRequest options: method: opt.method url: "http://v0.api.upyun.com/#{@bucket}#{opt.url}" headers: opt.headers body: opt.data onData: opt.onData onRequestData: opt.onRequestData pipeRequest: opt.pipeRequest pipeResponse: opt.pipeResponse onFinish: (e, res, data)=> return cb e if e if res.statusCode == 200 cb null, data else status = null try status = JSON.parse(data) if data if status && status.msg cb new Error status.msg else cb new Error "未知错误 (HTTP#{res.statusCode})" return => req.abort() cb new Error '操作已取消' @upyun_api = (opt, cb)=> start = Date.now() @_upyun_api opt, (e, data)=> console?.log "#{opt.method} #{@bucket}#{opt.url} done (+#{Date.now() - start}ms)" cb e, data Messenger.options = extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right' theme: 'future' messageDefaults: showCloseButton: true hideAfter: 10 retry: label: '重试' phrase: 'TIME秒钟后重试' auto: true delay: 5 @createIcon = (icon)=> $ document.createElement 'i' .addClass "fa fa-#{icon}" @shortOperation = (title, operation)=> @shortOperationBusy = true $ '#loadingText' .text title||'' .append '<br />' $ 'body' .addClass 'loading' $ btnCancel = document.createElement 'button' .appendTo '#loadingText' .addClass 'btn btn-default btn-xs btn-inline' .text '取消' .hide() operationDone = (e)=> @shortOperationBusy = false $ 'body' .removeClass 'loading' if e msg = Messenger().post type: 'error' message: e.message showCloseButton: true actions: ok: label: '确定' action: => msg.hide() retry: label: '重试' action: => msg.hide() @shortOperation title, operation operation operationDone, $ btnCancel @taskOperation = (title, operation)=> msg = Messenger( instance: @messengerTasks extraClasses: 'messenger-fixed messenger-on-left messenger-on-bottom' ).post hideAfter: 0 message: title actions: cancel: label: '取消' action: => $progresslabel1 = $ document.createElement 'span' .appendTo msg.$message.find('.messenger-message-inner') .addClass 'pull-right' $progressbar = $ document.createElement 'div' .appendTo msg.$message.find('.messenger-message-inner') .addClass 'progress progress-striped active' .css margin: 0 .append $(document.createElement 'div').addClass('progress-bar').width '100%' .append $(document.createElement 'div').addClass('progress-bar progress-bar-success').width '0%' $progresslabel2 = $ document.createElement 'div' .appendTo msg.$message.find('.messenger-message-inner') operationProgress = (progress, progresstext)=> $progresslabel2.text progresstext if progresstext $progresslabel1.text "#{progress}%" if progress? $progressbar .toggleClass 'active', !progress? $progressbar.children ':not(.progress-bar-success)' .toggle !progress? $progressbar.children '.progress-bar-success' .toggle progress? .width "#{progress}%" operationDone = (e)=> return unless msg if e msg.update type: 'error' message: e.message showCloseButton: true actions: ok: label: '确定' action: => msg.hide() retry: label: '重试' action: => msg.hide() @taskOperation title, operation else msg.hide() operationProgress null operation operationProgress, operationDone, msg.$message.find('[data-action="cancel"] a') @upyun_readdir = (url, cb)=> @upyun_api method: "GET" url: url , (e, data)=> return cb e if e files = data.split('\n').map (line)-> line = line.split '\t' return null unless line.length == 4 return ( filename: line[0] url: url + encodeURIComponent line[0] isDirectory: line[1]=='F' length: Number line[2] mtime: 1000 * Number line[3] ) cb null, files.filter (file)-> file? @upyun_find_abort = -> @upyun_find = (url, cb)=> results = [] @upyun_find_abort = @upyun_readdir url, (e, files)=> return cb e if e async.eachSeries files, (file, doneEach)=> if file.isDirectory @upyun_find file.url + '/', (e, tmp)=> return doneEach e if e results.push item for item in tmp results.push file doneEach null else results.push file _.defer => doneEach null , (e)=> @upyun_find_abort = -> cb e, results @upyun_upload = (url, files, onProgress, cb)=> aborted = false api_aborting = null aborting = => aborted = true api_aborting?() status = total_files: files.length total_bytes: files.reduce ((a, b)-> a + b.length), 0 current_files: 0 current_bytes: 0 async.eachSeries files, (file, doneEach)=> Fs.stat file.path, (e, stats)=> return doneEach (new Error '操作已取消') if aborted return doneEach e if e api_aborting = @upyun_api pipeRequest: file.path method: "PUT" headers: 'mkdir': 'true', length: stats.size url: url + file.url onRequestData: (data)=> status.current_bytes+= data.length onProgress status , (e)=> status.current_files+= 1 onProgress status doneEach e , (e)=> cb e return aborting @action_downloadFolder = (filename, url)=> unless filename || filename = url.match(/([^\/]+)\/$/)?[1] filename = @bucket @shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=> $btnCancelFind.show().click => @upyun_find_abort() @upyun_find url, (e, files)=> doneFind e unless e SelectFolder (savepath)=> @taskOperation "正在下载目录 #{filename} ...", (progressTransfer, doneTransfer, $btnCancelTransfer)=> total_files = files.length total_bytes = files.reduce ((a, b)-> a + b.length), 0 current_files = 0 current_bytes = 0 aborting = null $btnCancelTransfer.click => aborting() if aborting? async.eachSeries files, ((file, doneEach)=> return (_.defer => doneEach null) if file.isDirectory segs = file.url.substring(url.length).split '/' segs = segs.map decodeURIComponent destpath = Path.join savepath, filename, Path.join.apply Path, segs Mkdirp Path.dirname(destpath), (e)=> return doneEach e if e _.defer => bytesWritten = 0 current_files+= 1 aborting = @upyun_api method: 'GET' url: file.url pipeResponse: destpath onData: (data)=> bytesWritten += data.length progressTransfer (Math.floor 100 * (current_bytes + bytesWritten) / total_bytes), "已下载:#{current_files} / #{total_files} (#{@humanFileSize current_bytes + bytesWritten} / #{@humanFileSize total_bytes})" , (e)=> current_bytes+= file.length unless e doneEach e ), (e)=> aborting = null doneTransfer e unless e msg = Messenger().post message: "目录 #{filename} 下载完毕" actions: ok: label: '确定' action: => msg.hide() open: label: "打开" action: => msg.hide() Electron.shell.openItem savepath @action_uploadFile = (filepath, filename, destpath)=> @taskOperation "正在上传 #{filename}", (progressTransfer, doneTransfer, $btnCancelTransfer)=> files = [] loadfileSync = (file)=> stat = Fs.statSync(file.path) if stat.isFile() file.length = stat.size files.push file if stat.isDirectory() for filename in Fs.readdirSync file.path loadfileSync path: Path.join(file.path, filename) url: file.url + '/' + encodeURIComponent filename try loadfileSync path: filepath, url: '' catch e return doneTransfer e if e $btnCancelTransfer.show().click @upyun_upload destpath, files, (status)=> progressTransfer (Math.floor 100 * status.current_bytes / status.total_bytes), "已上传:#{status.current_files} / #{status.total_files} (#{@humanFileSize status.current_bytes} / #{@humanFileSize status.total_bytes})" , (e)=> doneTransfer e unless e @m_changed_path = destpath.replace /[^\/]+$/, '' msg = Messenger().post message: "文件 #{filename} 上传完毕" actions: ok: label: '确定' action: => msg.hide() @action_show_url = (title, url)=> msg = Messenger().post message: "#{title}<pre>#{url}</pre>" actions: ok: label: '确定' action: => msg.hide() copy: label: '将该地址复制到剪切版' action: (ev)=> $(ev.currentTarget).text '已复制到剪切版' Electron.clipboard.writeText url @action_share = (url)=> url = "upyun://#{@username}:#{@password}@#{@bucket}#{url}" msg = Messenger().post message: """ 您可以通过以下地址向其他人分享该目录: <pre>#{url}</pre> 注意:<ol> <li>该地址中包含了当前操作员的授权信息,向他人分享该地址的同时,也同时分享了该操作员的身份。</li> <li>当他人安装了“又拍云管理器时”后,便可以直接点击该链接以打开。</li> </ol> """ actions: ok: label: '确定' action: => msg.hide() copy: label: '将该地址复制到剪切版' action: (ev)=> $(ev.currentTarget).text '已复制到剪切版' Electron.clipboard.writeText url, 'text' @jump_login = => @m_path = '/' @m_active = false @refresh_favs() $ '#filelist, #editor' .hide() $ '#login' .fadeIn() @jump_filelist = => @jump_path '/' @jump_path = (path)=> @m_path = path @m_changed_path = path @m_active = true @m_files = null $ '#filelist .preloader' .css opacity: 1 $ '#inputFilter' .val '' $ '#login, #editor' .hide() $ '#filelist' .fadeIn() segs = $.makeArray(@m_path.match /\/[^\/]+/g).map (match)-> String(match).replace /^\//, '' segs = segs.map decodeURIComponent $ '#path' .empty() $ li = document.createElement 'li' .appendTo '#path' $ document.createElement 'a' .appendTo li .text @username .prepend @createIcon 'user' .attr 'href', '#' .click (ev)=> ev.preventDefault() @jump_login() $ li = document.createElement 'li' .toggleClass 'active', !segs.length .appendTo '#path' $ document.createElement 'a' .appendTo li .text "#{@bucket} (#{@origin})" .prepend @createIcon 'cloud' .attr 'href', "#{@origin}/" .data 'url', '/' for seg, i in segs url = '/' + segs[0..i].map(encodeURIComponent).join('/') + '/' $ li = document.createElement 'li' .toggleClass 'active', i == segs.length - 1 .appendTo '#path' $ document.createElement 'a' .appendTo li .text seg .prepend @createIcon 'folder' .attr 'href', "#{@origin}#{url}" .data 'url', url $ '#path li:not(:first-child)>a' .click (ev)=> ev.preventDefault() @jump_path $(ev.currentTarget).data 'url' @refresh_filelist = (cb)=> cur_path = @m_path @upyun_readdir cur_path, (e, files)=> return cb e if e if @m_path == cur_path && JSON.stringify(@m_files) != JSON.stringify(files) $('#filelist tbody').empty() $('#filelist .preloader').css opacity: 0 for file in @m_files = files $ tr = document.createElement 'tr' .appendTo '#filelist tbody' $ td = document.createElement 'td' .appendTo tr if file.isDirectory $ a = document.createElement 'a' .appendTo td .text file.filename .prepend @createIcon 'folder' .attr 'href', "#" .data 'url', file.url + '/' .click (ev)=> ev.preventDefault() @jump_path $(ev.currentTarget).data('url') else $ td .text file.filename .prepend @createIcon 'file' $ document.createElement 'td' .appendTo tr .text if file.isDirectory then '' else @humanFileSize file.length $ document.createElement 'td' .appendTo tr .text moment(file.mtime).format 'LLL' $ td = document.createElement 'td' .appendTo tr if file.isDirectory $ document.createElement 'button' .appendTo td .attr title: '删除该目录' .addClass 'btn btn-danger btn-xs' .data 'url', file.url + '/' .data 'filename', file.filename .prepend @createIcon 'trash-o' .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' @shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=> $btnCancelFind.show().click => @upyun_find_abort() @upyun_find url, (e, files)=> doneFind e unless e files_deleting = 0 async.eachSeries files, (file, doneEach)=> files_deleting+= 1 @shortOperation "正在删除(#{files_deleting}/#{files.length}) #{file.filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: file.url , (e)=> operationDone e doneEach e , (e)=> unless e @shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: url , (e)=> @m_changed_path = url.replace /[^\/]+\/$/, '' operationDone e else $ document.createElement 'button' .appendTo td .attr title: '删除该文件' .addClass 'btn btn-danger btn-xs' .data 'url', file.url .data 'filename', file.filename .prepend @createIcon 'trash-o' .click (ev)=> url = $(ev.currentTarget).data('url') filename = $(ev.currentTarget).data('filename') @shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: url , (e)=> @m_changed_path = url.replace /\/[^\/]+$/, '/' operationDone e if file.isDirectory $ document.createElement 'button' .appendTo td .attr title: '下载该目录' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'download' .data 'url', file.url + '/' .data 'filename', file.filename .click (ev)=> @action_downloadFolder $(ev.currentTarget).data('filename'), $(ev.currentTarget).data('url') $ document.createElement 'button' .appendTo td .attr title: '向其他人分享该目录' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'share' .data 'url', file.url + '/' .click (ev)=> url = $(ev.currentTarget).data 'url' @action_share url else $ document.createElement 'button' .appendTo td .attr title: '下载该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'download' .data 'url', file.url .data 'filename', file.filename .data 'length', file.length .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' length = $(ev.currentTarget).data 'length' SaveAsFile filename, (savepath)=> @taskOperation "正在下载文件 #{filename} ..", (progressTransfer, doneTransfer, $btnCancelTransfer)=> aborting = null $btnCancelTransfer.click => aborting() if aborting? _.defer => bytesWritten = 0 aborting = @upyun_api method: "GET" url: url pipeResponse: savepath onData: (data)=> bytesWritten += data.length progressTransfer (Math.floor 100 * bytesWritten / length), "#{@humanFileSize bytesWritten} / #{@humanFileSize length}" , (e, data)=> doneTransfer e unless e msg = Messenger().post message: "文件 #{filename} 下载完毕" actions: ok: label: '确定' action: => msg.hide() open: label: "打开" action: => msg.hide() Electron.shell.openItem savepath showItemInFolder: label: "打开目录" action: => msg.hide() Electron.shell.showItemInFolder savepath $ document.createElement 'button' .appendTo td .attr title: '在浏览器中访问该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'globe' .data 'url', "#{@origin}#{file.url}" .click (ev)=> url = $(ev.currentTarget).data 'url' Electron.shell.openExternal url $ document.createElement 'button' .appendTo td .attr title: '公共地址' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'code' .data 'url', "#{@origin}#{file.url}" .data 'filename', file.filename .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' @action_show_url "文件 #{filename} 的公共地址(URL)", url $ document.createElement 'button' .appendTo td .attr title: '用文本编辑器打开该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'edit' .data 'url', file.url .data 'filename', file.filename .click (ev)=> Open 'editor', username: @username password: <PASSWORD> bucket: @bucket editor_url: $(ev.currentTarget).data 'url' editor_filename: $(ev.currentTarget).data 'filename' $('#filelist tbody [title]') .tooltip placement: 'bottom' trigger: 'hover' cb null @jump_editor = => $ '#login, #filelist' .hide() $ '#editor' .show() window.document.title = @editor_filename @editor = Ace.edit $('#editor .editor')[0] $('#btnReloadEditor').click() window.ondragover = window.ondrop = (ev)-> ev.preventDefault() return false $ => @messengerTasks = $ document.createElement 'ul' .appendTo 'body' .messenger() forverCounter = 0 async.forever (doneForever)=> if @m_active && !@shortOperationBusy forverCounter += 1 if forverCounter == 20 || @m_changed_path == @m_path forverCounter = 0 @m_changed_path = null return @refresh_filelist (e)=> if e msg = Messenger().post message: e.message type: 'error' actions: ok: label: '确定' action: => msg.hide() @jump_login() setTimeout (=>doneForever null), 100 setTimeout (=>doneForever null), 100 , (e)=> throw e $ '#inputBucket' .on 'input', (event)=> origin = $('#inputOrigin').val() return unless origin.endsWith('.b0.upaiyun.com') $('#inputOrigin').val("http://#{event.currentTarget.value}.b0.upaiyun.com") $ '#inputOrigin' .on 'change', (event)=> if !event.currentTarget.value.trim() $(event.currentTarget).val("http://#{$('#inputBucket').val()}.b0.upaiyun.com") $ '#btnAddFav' .click => fav = $('#formLogin').serializeObject() fav.password = "<PASSWORD>" + MD5 fav<PASSWORD>.password unless fav.password.match /^MD<PASSWORD>_/ @m_favs["#{fav.username}@#{fav.bucket}"] = fav localStorage.favs = JSON.stringify @m_favs @refresh_favs() $ '#formLogin' .submit (ev)=> ev.preventDefault() @[k] = v for k, v of $(ev.currentTarget).serializeObject() @password = "<PASSWORD>" + MD5 @password unless @password.match /^MD5_/ $ '#filelist tbody' .empty() @jump_filelist() $ window .on 'dragover', -> $('body').addClass 'drag_hover' .on 'dragleave', -> $('body').removeClass 'drag_hover' .on 'dragend', -> $('body').removeClass 'drag_hover' .on 'drop', (ev)=> $('body').removeClass 'drag_hover' ev.preventDefault() for file in ev.originalEvent.dataTransfer.files @action_uploadFile file.path, file.name, "#{@m_path}#{encodeURIComponent file.name}" $ '#inputFilter' .keydown => _.defer => val = String $('#inputFilter').val() $ "#filelist tbody tr:contains(#{JSON.stringify val})" .removeClass 'filtered' $ "#filelist tbody tr:not(:contains(#{JSON.stringify val}))" .addClass 'filtered' $ '#btnDownloadFolder' .click (ev)=> ev.preventDefault() @action_downloadFolder null, @m_path $ '#btnUploadFiles' .click (ev)=> ev.preventDefault() SelectFiles (files)=> for filepath in files filename = Path.basename filepath @action_uploadFile filepath, filename, "#{@m_path}#{encodeURIComponent filename}" $ '#btnUploadFolder' .click (ev)=> ev.preventDefault() SelectFolder (dirpath)=> @action_uploadFile dirpath, Path.basename(dirpath), @m_path $ '#btnCreateFolder' .click (ev)=> ev.preventDefault() Prompt "请输入新目录的名称", (filename)=> @shortOperation "正在新建目录 #{filename} ...", (doneCreating, $btnCancelCreateing)=> cur_path = @m_path $btnCancelCreateing.click @upyun_api url: "#{cur_path}#{filename}" method: "POST" headers: 'Folder': 'true' , (e, data)=> doneCreating e @m_changed_path = cur_path $ '#btnCreateFile' .click (ev)=> ev.preventDefault() Prompt "请输入新文件的文件名", (filename)=> Open 'editor', username: @username password: <PASSWORD> bucket: @bucket editor_url: "#{@m_path}#{filename}" editor_filename: filename $ '#btnReloadEditor' .click (ev)=> ev.preventDefault() @shortOperation "正在加载文件 #{@editor_filename} ...", (doneReloading, $btnCancelReloading)=> $btnCancelReloading.click @upyun_api url: @editor_url method: 'GET' , (e, data)=> if e data = '' else data = data.toString 'utf8' doneReloading null unless e @editor.setValue data $ '#btnShareFolder' .click (ev)=> @action_share @m_path $ '#btnSaveEditor' .click (ev)=> ev.preventDefault() @shortOperation "正在保存文件 #{@editor_filename} ...", (doneSaving, $btnCancelSaving)=> $btnCancelSaving.click @upyun_api url: @editor_url method: 'PUT' data: new Buffer @editor.getValue(), 'utf8' , (e)=> doneSaving e unless e msg = Messenger().post message: "成功保存文件 #{@editor_filename}" actions: ok: label: '确定' action: => msg.hide() $ '#btnLogout' .click (ev)=> ev.preventDefault() @jump_login() $ '#btnIssues' .click (ev)=> ev.preventDefault() Electron.shell.openExternal "https://github.com/layerssss/manager-for-upyun/issues" $ '[title]' .tooltip placement: 'bottom' trigger: 'hover' window.Init = (action, params) => for key, value of params @[key] = value @["jump_#{action}"]()
true
moment.locale 'zh-cn' try @m_favs = JSON.parse(localStorage.favs)||{} catch @m_favs = {} @refresh_favs = => $ '#favs' .empty() for k, fav of @m_favs fav.origin ?= "http://#{fav.bucket}.b0.upaiyun.com" $ li = document.createElement 'li' .appendTo '#favs' $ document.createElement 'a' .appendTo li .text "#{k} (#{fav.origin})" .attr href: '#' .data 'fav', fav .click (ev)=> ev.preventDefault() $(ev.currentTarget).parent().addClass('active').siblings().removeClass 'active' for k, v of $(ev.currentTarget).data 'fav' $ "#input#{_.capitalize k}" .val v $ '#formLogin' .submit() $ document.createElement 'button' .appendTo li .prepend @createIcon 'trash-o' .addClass 'btn btn-danger btn-xs' .attr 'title', '删除这条收藏记录' .tooltip placement: 'bottom' .data 'fav', fav .click (ev)=> fav = $(ev.currentTarget).data 'fav' delete @m_favs["#{fav.username}@#{fav.bucket}"] localStorage.favs = JSON.stringify @m_favs @refresh_favs() @humanFileSize = (bytes, si) -> thresh = (if si then 1000 else 1024) return bytes + " B" if bytes < thresh units = (if si then [ "kB" "MB" "GB" "TB" "PB" "EB" "ZB" "YB" ] else [ "KiB" "MiB" "GiB" "TiB" "PiB" "EiB" "ZiB" "YiB" ]) u = -1 loop bytes /= thresh ++u break unless bytes >= thresh bytes.toFixed(1) + " " + units[u] @_upyun_api = (opt, cb)=> opt.headers?= {} opt.headers["Content-Length"] = String opt.length || opt.data?.length || 0 unless opt.method in ['GET', 'HEAD'] date = new Date().toUTCString() if @password.match /^MD5_/ md5_password = @password.replace /^MD5_/, '' else md5_password = MD5 @password signature = "#{opt.method}&/#{@bucket}#{opt.url}&#{date}" signature = Crypto.createHmac('sha1', md5_password).update(signature).digest('base64') opt.headers["Authorization"] = "UPYUN #{@username}:#{signature}" opt.headers["Date"] = date @_upyun_api_req = req = CallRequest options: method: opt.method url: "http://v0.api.upyun.com/#{@bucket}#{opt.url}" headers: opt.headers body: opt.data onData: opt.onData onRequestData: opt.onRequestData pipeRequest: opt.pipeRequest pipeResponse: opt.pipeResponse onFinish: (e, res, data)=> return cb e if e if res.statusCode == 200 cb null, data else status = null try status = JSON.parse(data) if data if status && status.msg cb new Error status.msg else cb new Error "未知错误 (HTTP#{res.statusCode})" return => req.abort() cb new Error '操作已取消' @upyun_api = (opt, cb)=> start = Date.now() @_upyun_api opt, (e, data)=> console?.log "#{opt.method} #{@bucket}#{opt.url} done (+#{Date.now() - start}ms)" cb e, data Messenger.options = extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right' theme: 'future' messageDefaults: showCloseButton: true hideAfter: 10 retry: label: '重试' phrase: 'TIME秒钟后重试' auto: true delay: 5 @createIcon = (icon)=> $ document.createElement 'i' .addClass "fa fa-#{icon}" @shortOperation = (title, operation)=> @shortOperationBusy = true $ '#loadingText' .text title||'' .append '<br />' $ 'body' .addClass 'loading' $ btnCancel = document.createElement 'button' .appendTo '#loadingText' .addClass 'btn btn-default btn-xs btn-inline' .text '取消' .hide() operationDone = (e)=> @shortOperationBusy = false $ 'body' .removeClass 'loading' if e msg = Messenger().post type: 'error' message: e.message showCloseButton: true actions: ok: label: '确定' action: => msg.hide() retry: label: '重试' action: => msg.hide() @shortOperation title, operation operation operationDone, $ btnCancel @taskOperation = (title, operation)=> msg = Messenger( instance: @messengerTasks extraClasses: 'messenger-fixed messenger-on-left messenger-on-bottom' ).post hideAfter: 0 message: title actions: cancel: label: '取消' action: => $progresslabel1 = $ document.createElement 'span' .appendTo msg.$message.find('.messenger-message-inner') .addClass 'pull-right' $progressbar = $ document.createElement 'div' .appendTo msg.$message.find('.messenger-message-inner') .addClass 'progress progress-striped active' .css margin: 0 .append $(document.createElement 'div').addClass('progress-bar').width '100%' .append $(document.createElement 'div').addClass('progress-bar progress-bar-success').width '0%' $progresslabel2 = $ document.createElement 'div' .appendTo msg.$message.find('.messenger-message-inner') operationProgress = (progress, progresstext)=> $progresslabel2.text progresstext if progresstext $progresslabel1.text "#{progress}%" if progress? $progressbar .toggleClass 'active', !progress? $progressbar.children ':not(.progress-bar-success)' .toggle !progress? $progressbar.children '.progress-bar-success' .toggle progress? .width "#{progress}%" operationDone = (e)=> return unless msg if e msg.update type: 'error' message: e.message showCloseButton: true actions: ok: label: '确定' action: => msg.hide() retry: label: '重试' action: => msg.hide() @taskOperation title, operation else msg.hide() operationProgress null operation operationProgress, operationDone, msg.$message.find('[data-action="cancel"] a') @upyun_readdir = (url, cb)=> @upyun_api method: "GET" url: url , (e, data)=> return cb e if e files = data.split('\n').map (line)-> line = line.split '\t' return null unless line.length == 4 return ( filename: line[0] url: url + encodeURIComponent line[0] isDirectory: line[1]=='F' length: Number line[2] mtime: 1000 * Number line[3] ) cb null, files.filter (file)-> file? @upyun_find_abort = -> @upyun_find = (url, cb)=> results = [] @upyun_find_abort = @upyun_readdir url, (e, files)=> return cb e if e async.eachSeries files, (file, doneEach)=> if file.isDirectory @upyun_find file.url + '/', (e, tmp)=> return doneEach e if e results.push item for item in tmp results.push file doneEach null else results.push file _.defer => doneEach null , (e)=> @upyun_find_abort = -> cb e, results @upyun_upload = (url, files, onProgress, cb)=> aborted = false api_aborting = null aborting = => aborted = true api_aborting?() status = total_files: files.length total_bytes: files.reduce ((a, b)-> a + b.length), 0 current_files: 0 current_bytes: 0 async.eachSeries files, (file, doneEach)=> Fs.stat file.path, (e, stats)=> return doneEach (new Error '操作已取消') if aborted return doneEach e if e api_aborting = @upyun_api pipeRequest: file.path method: "PUT" headers: 'mkdir': 'true', length: stats.size url: url + file.url onRequestData: (data)=> status.current_bytes+= data.length onProgress status , (e)=> status.current_files+= 1 onProgress status doneEach e , (e)=> cb e return aborting @action_downloadFolder = (filename, url)=> unless filename || filename = url.match(/([^\/]+)\/$/)?[1] filename = @bucket @shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=> $btnCancelFind.show().click => @upyun_find_abort() @upyun_find url, (e, files)=> doneFind e unless e SelectFolder (savepath)=> @taskOperation "正在下载目录 #{filename} ...", (progressTransfer, doneTransfer, $btnCancelTransfer)=> total_files = files.length total_bytes = files.reduce ((a, b)-> a + b.length), 0 current_files = 0 current_bytes = 0 aborting = null $btnCancelTransfer.click => aborting() if aborting? async.eachSeries files, ((file, doneEach)=> return (_.defer => doneEach null) if file.isDirectory segs = file.url.substring(url.length).split '/' segs = segs.map decodeURIComponent destpath = Path.join savepath, filename, Path.join.apply Path, segs Mkdirp Path.dirname(destpath), (e)=> return doneEach e if e _.defer => bytesWritten = 0 current_files+= 1 aborting = @upyun_api method: 'GET' url: file.url pipeResponse: destpath onData: (data)=> bytesWritten += data.length progressTransfer (Math.floor 100 * (current_bytes + bytesWritten) / total_bytes), "已下载:#{current_files} / #{total_files} (#{@humanFileSize current_bytes + bytesWritten} / #{@humanFileSize total_bytes})" , (e)=> current_bytes+= file.length unless e doneEach e ), (e)=> aborting = null doneTransfer e unless e msg = Messenger().post message: "目录 #{filename} 下载完毕" actions: ok: label: '确定' action: => msg.hide() open: label: "打开" action: => msg.hide() Electron.shell.openItem savepath @action_uploadFile = (filepath, filename, destpath)=> @taskOperation "正在上传 #{filename}", (progressTransfer, doneTransfer, $btnCancelTransfer)=> files = [] loadfileSync = (file)=> stat = Fs.statSync(file.path) if stat.isFile() file.length = stat.size files.push file if stat.isDirectory() for filename in Fs.readdirSync file.path loadfileSync path: Path.join(file.path, filename) url: file.url + '/' + encodeURIComponent filename try loadfileSync path: filepath, url: '' catch e return doneTransfer e if e $btnCancelTransfer.show().click @upyun_upload destpath, files, (status)=> progressTransfer (Math.floor 100 * status.current_bytes / status.total_bytes), "已上传:#{status.current_files} / #{status.total_files} (#{@humanFileSize status.current_bytes} / #{@humanFileSize status.total_bytes})" , (e)=> doneTransfer e unless e @m_changed_path = destpath.replace /[^\/]+$/, '' msg = Messenger().post message: "文件 #{filename} 上传完毕" actions: ok: label: '确定' action: => msg.hide() @action_show_url = (title, url)=> msg = Messenger().post message: "#{title}<pre>#{url}</pre>" actions: ok: label: '确定' action: => msg.hide() copy: label: '将该地址复制到剪切版' action: (ev)=> $(ev.currentTarget).text '已复制到剪切版' Electron.clipboard.writeText url @action_share = (url)=> url = "upyun://#{@username}:#{@password}@#{@bucket}#{url}" msg = Messenger().post message: """ 您可以通过以下地址向其他人分享该目录: <pre>#{url}</pre> 注意:<ol> <li>该地址中包含了当前操作员的授权信息,向他人分享该地址的同时,也同时分享了该操作员的身份。</li> <li>当他人安装了“又拍云管理器时”后,便可以直接点击该链接以打开。</li> </ol> """ actions: ok: label: '确定' action: => msg.hide() copy: label: '将该地址复制到剪切版' action: (ev)=> $(ev.currentTarget).text '已复制到剪切版' Electron.clipboard.writeText url, 'text' @jump_login = => @m_path = '/' @m_active = false @refresh_favs() $ '#filelist, #editor' .hide() $ '#login' .fadeIn() @jump_filelist = => @jump_path '/' @jump_path = (path)=> @m_path = path @m_changed_path = path @m_active = true @m_files = null $ '#filelist .preloader' .css opacity: 1 $ '#inputFilter' .val '' $ '#login, #editor' .hide() $ '#filelist' .fadeIn() segs = $.makeArray(@m_path.match /\/[^\/]+/g).map (match)-> String(match).replace /^\//, '' segs = segs.map decodeURIComponent $ '#path' .empty() $ li = document.createElement 'li' .appendTo '#path' $ document.createElement 'a' .appendTo li .text @username .prepend @createIcon 'user' .attr 'href', '#' .click (ev)=> ev.preventDefault() @jump_login() $ li = document.createElement 'li' .toggleClass 'active', !segs.length .appendTo '#path' $ document.createElement 'a' .appendTo li .text "#{@bucket} (#{@origin})" .prepend @createIcon 'cloud' .attr 'href', "#{@origin}/" .data 'url', '/' for seg, i in segs url = '/' + segs[0..i].map(encodeURIComponent).join('/') + '/' $ li = document.createElement 'li' .toggleClass 'active', i == segs.length - 1 .appendTo '#path' $ document.createElement 'a' .appendTo li .text seg .prepend @createIcon 'folder' .attr 'href', "#{@origin}#{url}" .data 'url', url $ '#path li:not(:first-child)>a' .click (ev)=> ev.preventDefault() @jump_path $(ev.currentTarget).data 'url' @refresh_filelist = (cb)=> cur_path = @m_path @upyun_readdir cur_path, (e, files)=> return cb e if e if @m_path == cur_path && JSON.stringify(@m_files) != JSON.stringify(files) $('#filelist tbody').empty() $('#filelist .preloader').css opacity: 0 for file in @m_files = files $ tr = document.createElement 'tr' .appendTo '#filelist tbody' $ td = document.createElement 'td' .appendTo tr if file.isDirectory $ a = document.createElement 'a' .appendTo td .text file.filename .prepend @createIcon 'folder' .attr 'href', "#" .data 'url', file.url + '/' .click (ev)=> ev.preventDefault() @jump_path $(ev.currentTarget).data('url') else $ td .text file.filename .prepend @createIcon 'file' $ document.createElement 'td' .appendTo tr .text if file.isDirectory then '' else @humanFileSize file.length $ document.createElement 'td' .appendTo tr .text moment(file.mtime).format 'LLL' $ td = document.createElement 'td' .appendTo tr if file.isDirectory $ document.createElement 'button' .appendTo td .attr title: '删除该目录' .addClass 'btn btn-danger btn-xs' .data 'url', file.url + '/' .data 'filename', file.filename .prepend @createIcon 'trash-o' .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' @shortOperation "正在列出目录 #{filename} 下的所有文件", (doneFind, $btnCancelFind)=> $btnCancelFind.show().click => @upyun_find_abort() @upyun_find url, (e, files)=> doneFind e unless e files_deleting = 0 async.eachSeries files, (file, doneEach)=> files_deleting+= 1 @shortOperation "正在删除(#{files_deleting}/#{files.length}) #{file.filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: file.url , (e)=> operationDone e doneEach e , (e)=> unless e @shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: url , (e)=> @m_changed_path = url.replace /[^\/]+\/$/, '' operationDone e else $ document.createElement 'button' .appendTo td .attr title: '删除该文件' .addClass 'btn btn-danger btn-xs' .data 'url', file.url .data 'filename', file.filename .prepend @createIcon 'trash-o' .click (ev)=> url = $(ev.currentTarget).data('url') filename = $(ev.currentTarget).data('filename') @shortOperation "正在删除 #{filename}", (operationDone, $btnCancelDel)=> $btnCancelDel.show().click @upyun_api method: "DELETE" url: url , (e)=> @m_changed_path = url.replace /\/[^\/]+$/, '/' operationDone e if file.isDirectory $ document.createElement 'button' .appendTo td .attr title: '下载该目录' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'download' .data 'url', file.url + '/' .data 'filename', file.filename .click (ev)=> @action_downloadFolder $(ev.currentTarget).data('filename'), $(ev.currentTarget).data('url') $ document.createElement 'button' .appendTo td .attr title: '向其他人分享该目录' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'share' .data 'url', file.url + '/' .click (ev)=> url = $(ev.currentTarget).data 'url' @action_share url else $ document.createElement 'button' .appendTo td .attr title: '下载该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'download' .data 'url', file.url .data 'filename', file.filename .data 'length', file.length .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' length = $(ev.currentTarget).data 'length' SaveAsFile filename, (savepath)=> @taskOperation "正在下载文件 #{filename} ..", (progressTransfer, doneTransfer, $btnCancelTransfer)=> aborting = null $btnCancelTransfer.click => aborting() if aborting? _.defer => bytesWritten = 0 aborting = @upyun_api method: "GET" url: url pipeResponse: savepath onData: (data)=> bytesWritten += data.length progressTransfer (Math.floor 100 * bytesWritten / length), "#{@humanFileSize bytesWritten} / #{@humanFileSize length}" , (e, data)=> doneTransfer e unless e msg = Messenger().post message: "文件 #{filename} 下载完毕" actions: ok: label: '确定' action: => msg.hide() open: label: "打开" action: => msg.hide() Electron.shell.openItem savepath showItemInFolder: label: "打开目录" action: => msg.hide() Electron.shell.showItemInFolder savepath $ document.createElement 'button' .appendTo td .attr title: '在浏览器中访问该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'globe' .data 'url', "#{@origin}#{file.url}" .click (ev)=> url = $(ev.currentTarget).data 'url' Electron.shell.openExternal url $ document.createElement 'button' .appendTo td .attr title: '公共地址' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'code' .data 'url', "#{@origin}#{file.url}" .data 'filename', file.filename .click (ev)=> filename = $(ev.currentTarget).data 'filename' url = $(ev.currentTarget).data 'url' @action_show_url "文件 #{filename} 的公共地址(URL)", url $ document.createElement 'button' .appendTo td .attr title: '用文本编辑器打开该文件' .addClass 'btn btn-info btn-xs' .prepend @createIcon 'edit' .data 'url', file.url .data 'filename', file.filename .click (ev)=> Open 'editor', username: @username password: PI:PASSWORD:<PASSWORD>END_PI bucket: @bucket editor_url: $(ev.currentTarget).data 'url' editor_filename: $(ev.currentTarget).data 'filename' $('#filelist tbody [title]') .tooltip placement: 'bottom' trigger: 'hover' cb null @jump_editor = => $ '#login, #filelist' .hide() $ '#editor' .show() window.document.title = @editor_filename @editor = Ace.edit $('#editor .editor')[0] $('#btnReloadEditor').click() window.ondragover = window.ondrop = (ev)-> ev.preventDefault() return false $ => @messengerTasks = $ document.createElement 'ul' .appendTo 'body' .messenger() forverCounter = 0 async.forever (doneForever)=> if @m_active && !@shortOperationBusy forverCounter += 1 if forverCounter == 20 || @m_changed_path == @m_path forverCounter = 0 @m_changed_path = null return @refresh_filelist (e)=> if e msg = Messenger().post message: e.message type: 'error' actions: ok: label: '确定' action: => msg.hide() @jump_login() setTimeout (=>doneForever null), 100 setTimeout (=>doneForever null), 100 , (e)=> throw e $ '#inputBucket' .on 'input', (event)=> origin = $('#inputOrigin').val() return unless origin.endsWith('.b0.upaiyun.com') $('#inputOrigin').val("http://#{event.currentTarget.value}.b0.upaiyun.com") $ '#inputOrigin' .on 'change', (event)=> if !event.currentTarget.value.trim() $(event.currentTarget).val("http://#{$('#inputBucket').val()}.b0.upaiyun.com") $ '#btnAddFav' .click => fav = $('#formLogin').serializeObject() fav.password = "PI:PASSWORD:<PASSWORD>END_PI" + MD5 favPI:PASSWORD:<PASSWORD>END_PI.password unless fav.password.match /^MDPI:PASSWORD:<PASSWORD>END_PI_/ @m_favs["#{fav.username}@#{fav.bucket}"] = fav localStorage.favs = JSON.stringify @m_favs @refresh_favs() $ '#formLogin' .submit (ev)=> ev.preventDefault() @[k] = v for k, v of $(ev.currentTarget).serializeObject() @password = "PI:PASSWORD:<PASSWORD>END_PI" + MD5 @password unless @password.match /^MD5_/ $ '#filelist tbody' .empty() @jump_filelist() $ window .on 'dragover', -> $('body').addClass 'drag_hover' .on 'dragleave', -> $('body').removeClass 'drag_hover' .on 'dragend', -> $('body').removeClass 'drag_hover' .on 'drop', (ev)=> $('body').removeClass 'drag_hover' ev.preventDefault() for file in ev.originalEvent.dataTransfer.files @action_uploadFile file.path, file.name, "#{@m_path}#{encodeURIComponent file.name}" $ '#inputFilter' .keydown => _.defer => val = String $('#inputFilter').val() $ "#filelist tbody tr:contains(#{JSON.stringify val})" .removeClass 'filtered' $ "#filelist tbody tr:not(:contains(#{JSON.stringify val}))" .addClass 'filtered' $ '#btnDownloadFolder' .click (ev)=> ev.preventDefault() @action_downloadFolder null, @m_path $ '#btnUploadFiles' .click (ev)=> ev.preventDefault() SelectFiles (files)=> for filepath in files filename = Path.basename filepath @action_uploadFile filepath, filename, "#{@m_path}#{encodeURIComponent filename}" $ '#btnUploadFolder' .click (ev)=> ev.preventDefault() SelectFolder (dirpath)=> @action_uploadFile dirpath, Path.basename(dirpath), @m_path $ '#btnCreateFolder' .click (ev)=> ev.preventDefault() Prompt "请输入新目录的名称", (filename)=> @shortOperation "正在新建目录 #{filename} ...", (doneCreating, $btnCancelCreateing)=> cur_path = @m_path $btnCancelCreateing.click @upyun_api url: "#{cur_path}#{filename}" method: "POST" headers: 'Folder': 'true' , (e, data)=> doneCreating e @m_changed_path = cur_path $ '#btnCreateFile' .click (ev)=> ev.preventDefault() Prompt "请输入新文件的文件名", (filename)=> Open 'editor', username: @username password: PI:PASSWORD:<PASSWORD>END_PI bucket: @bucket editor_url: "#{@m_path}#{filename}" editor_filename: filename $ '#btnReloadEditor' .click (ev)=> ev.preventDefault() @shortOperation "正在加载文件 #{@editor_filename} ...", (doneReloading, $btnCancelReloading)=> $btnCancelReloading.click @upyun_api url: @editor_url method: 'GET' , (e, data)=> if e data = '' else data = data.toString 'utf8' doneReloading null unless e @editor.setValue data $ '#btnShareFolder' .click (ev)=> @action_share @m_path $ '#btnSaveEditor' .click (ev)=> ev.preventDefault() @shortOperation "正在保存文件 #{@editor_filename} ...", (doneSaving, $btnCancelSaving)=> $btnCancelSaving.click @upyun_api url: @editor_url method: 'PUT' data: new Buffer @editor.getValue(), 'utf8' , (e)=> doneSaving e unless e msg = Messenger().post message: "成功保存文件 #{@editor_filename}" actions: ok: label: '确定' action: => msg.hide() $ '#btnLogout' .click (ev)=> ev.preventDefault() @jump_login() $ '#btnIssues' .click (ev)=> ev.preventDefault() Electron.shell.openExternal "https://github.com/layerssss/manager-for-upyun/issues" $ '[title]' .tooltip placement: 'bottom' trigger: 'hover' window.Init = (action, params) => for key, value of params @[key] = value @["jump_#{action}"]()
[ { "context": "###*\n@author Mat Groves http://matgroves.com/\n###\n\ndefine 'Coffixi/extras", "end": 23, "score": 0.9998831748962402, "start": 13, "tag": "NAME", "value": "Mat Groves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/\n###\n\ndefine 'Coffixi/extras/Strip', [\n 'Cof", "end": 40, "score": 0.9073391556739807, "start": 31, "tag": "USERNAME", "value": "matgroves" } ]
src/Coffixi/extras/Strip.coffee
namuol/Coffixi
1
###* @author Mat Groves http://matgroves.com/ ### define 'Coffixi/extras/Strip', [ 'Coffixi/display/DisplayObjectContainer' 'Coffixi/display/Sprite' 'Coffixi/utils/Utils' 'Coffixi/core/RenderTypes' ], ( DisplayObjectContainer Sprite Utils RenderTypes ) -> class Strip extends DisplayObjectContainer __renderType: RenderTypes.STRIP constructor: (texture, width, height) -> super @texture = texture @blendMode = Sprite.blendModes.NORMAL try @uvs = new Utils.Float32Array([0, 1, 1, 1, 1, 0, 0, 1]) @verticies = new Utils.Float32Array([0, 0, 0, 0, 0, 0, 0, 0, 0]) @colors = new Utils.Float32Array([1, 1, 1, 1]) @indices = new Utils.Uint16Array([0, 1, 2, 3]) catch error @uvs = [0, 1, 1, 1, 1, 0, 0, 1] @verticies = [0, 0, 0, 0, 0, 0, 0, 0, 0] @colors = [1, 1, 1, 1] @indices = [0, 1, 2, 3] # # this.uvs = new Utils.Float32Array() # this.verticies = new Utils.Float32Array() # this.colors = new Utils.Float32Array() # this.indices = new Utils.Uint16Array() # @width = width @height = height # load the texture! if texture.baseTexture.hasLoaded @width = @texture.frame.width @height = @texture.frame.height @updateFrame = true else @onTextureUpdateBind = @onTextureUpdate.bind(this) @texture.on 'update', @onTextureUpdateBind @renderable = true ###* The texture used by this `Strip`. @property texture ### Object.defineProperty @::, 'texture', get: -> @_texture set: (texture) -> #TODO SET THE TEXTURES #TODO VISIBILITY # stop current texture @_texture = texture @width = texture.frame.width @height = texture.frame.height @updateFrame = true onTextureUpdate: (event) -> @updateFrame = true
209182
###* @author <NAME> http://matgroves.com/ ### define 'Coffixi/extras/Strip', [ 'Coffixi/display/DisplayObjectContainer' 'Coffixi/display/Sprite' 'Coffixi/utils/Utils' 'Coffixi/core/RenderTypes' ], ( DisplayObjectContainer Sprite Utils RenderTypes ) -> class Strip extends DisplayObjectContainer __renderType: RenderTypes.STRIP constructor: (texture, width, height) -> super @texture = texture @blendMode = Sprite.blendModes.NORMAL try @uvs = new Utils.Float32Array([0, 1, 1, 1, 1, 0, 0, 1]) @verticies = new Utils.Float32Array([0, 0, 0, 0, 0, 0, 0, 0, 0]) @colors = new Utils.Float32Array([1, 1, 1, 1]) @indices = new Utils.Uint16Array([0, 1, 2, 3]) catch error @uvs = [0, 1, 1, 1, 1, 0, 0, 1] @verticies = [0, 0, 0, 0, 0, 0, 0, 0, 0] @colors = [1, 1, 1, 1] @indices = [0, 1, 2, 3] # # this.uvs = new Utils.Float32Array() # this.verticies = new Utils.Float32Array() # this.colors = new Utils.Float32Array() # this.indices = new Utils.Uint16Array() # @width = width @height = height # load the texture! if texture.baseTexture.hasLoaded @width = @texture.frame.width @height = @texture.frame.height @updateFrame = true else @onTextureUpdateBind = @onTextureUpdate.bind(this) @texture.on 'update', @onTextureUpdateBind @renderable = true ###* The texture used by this `Strip`. @property texture ### Object.defineProperty @::, 'texture', get: -> @_texture set: (texture) -> #TODO SET THE TEXTURES #TODO VISIBILITY # stop current texture @_texture = texture @width = texture.frame.width @height = texture.frame.height @updateFrame = true onTextureUpdate: (event) -> @updateFrame = true
true
###* @author PI:NAME:<NAME>END_PI http://matgroves.com/ ### define 'Coffixi/extras/Strip', [ 'Coffixi/display/DisplayObjectContainer' 'Coffixi/display/Sprite' 'Coffixi/utils/Utils' 'Coffixi/core/RenderTypes' ], ( DisplayObjectContainer Sprite Utils RenderTypes ) -> class Strip extends DisplayObjectContainer __renderType: RenderTypes.STRIP constructor: (texture, width, height) -> super @texture = texture @blendMode = Sprite.blendModes.NORMAL try @uvs = new Utils.Float32Array([0, 1, 1, 1, 1, 0, 0, 1]) @verticies = new Utils.Float32Array([0, 0, 0, 0, 0, 0, 0, 0, 0]) @colors = new Utils.Float32Array([1, 1, 1, 1]) @indices = new Utils.Uint16Array([0, 1, 2, 3]) catch error @uvs = [0, 1, 1, 1, 1, 0, 0, 1] @verticies = [0, 0, 0, 0, 0, 0, 0, 0, 0] @colors = [1, 1, 1, 1] @indices = [0, 1, 2, 3] # # this.uvs = new Utils.Float32Array() # this.verticies = new Utils.Float32Array() # this.colors = new Utils.Float32Array() # this.indices = new Utils.Uint16Array() # @width = width @height = height # load the texture! if texture.baseTexture.hasLoaded @width = @texture.frame.width @height = @texture.frame.height @updateFrame = true else @onTextureUpdateBind = @onTextureUpdate.bind(this) @texture.on 'update', @onTextureUpdateBind @renderable = true ###* The texture used by this `Strip`. @property texture ### Object.defineProperty @::, 'texture', get: -> @_texture set: (texture) -> #TODO SET THE TEXTURES #TODO VISIBILITY # stop current texture @_texture = texture @width = texture.frame.width @height = texture.frame.height @updateFrame = true onTextureUpdate: (event) -> @updateFrame = true
[ { "context": "###\n turing-tape.coffee\n Fionan Haralddottir\n Spring 2015\n This program is published under t", "end": 46, "score": 0.9998840093612671, "start": 27, "tag": "NAME", "value": "Fionan Haralddottir" } ]
src/turing-tape.coffee
Lokidottir/coffeescript-turing-machine
0
### turing-tape.coffee Fionan Haralddottir Spring 2015 This program is published under the MIT licence ### class TuringTape ### A class that represents an infinite bi-directional tape ### defaultSymbol: null # The default symbol written to the tape symbols: null # The number of symbols supported by the tape () postape: [] # The positive tape, indexes >= 0 negtape: [] # The negative tape, indexes <= -1 constructor: (@symbols, @defaultSymbol = 0) -> read: (index) -> if index >= 0 then TuringTape.readAbstract(@postape, index) else TuringTape.readAbstract(@negtape, Math.abs(index) - 1) @readAbstract: (tape, index) -> return if index < tape.length then tape[index] else @defaultSymbol write: (index, symbol, log = console.log) -> if symbol < 0 or symbol >= @symbols log("[TuringTape] could not write symbol '#{symbol}' to tape, not within tape's symbol range") else @writeAbstract((if index >= 0 then @postape else @negtape), Math.abs(index - (if index >= 0 then 0 else 1)), parseInt(symbol)) @writeAbstract: (tape, index, symbol) -> tape.push(@defaultSymbol) while tape.length < index tape[index] = symbol module.exports = {TuringTape}
210058
### turing-tape.coffee <NAME> Spring 2015 This program is published under the MIT licence ### class TuringTape ### A class that represents an infinite bi-directional tape ### defaultSymbol: null # The default symbol written to the tape symbols: null # The number of symbols supported by the tape () postape: [] # The positive tape, indexes >= 0 negtape: [] # The negative tape, indexes <= -1 constructor: (@symbols, @defaultSymbol = 0) -> read: (index) -> if index >= 0 then TuringTape.readAbstract(@postape, index) else TuringTape.readAbstract(@negtape, Math.abs(index) - 1) @readAbstract: (tape, index) -> return if index < tape.length then tape[index] else @defaultSymbol write: (index, symbol, log = console.log) -> if symbol < 0 or symbol >= @symbols log("[TuringTape] could not write symbol '#{symbol}' to tape, not within tape's symbol range") else @writeAbstract((if index >= 0 then @postape else @negtape), Math.abs(index - (if index >= 0 then 0 else 1)), parseInt(symbol)) @writeAbstract: (tape, index, symbol) -> tape.push(@defaultSymbol) while tape.length < index tape[index] = symbol module.exports = {TuringTape}
true
### turing-tape.coffee PI:NAME:<NAME>END_PI Spring 2015 This program is published under the MIT licence ### class TuringTape ### A class that represents an infinite bi-directional tape ### defaultSymbol: null # The default symbol written to the tape symbols: null # The number of symbols supported by the tape () postape: [] # The positive tape, indexes >= 0 negtape: [] # The negative tape, indexes <= -1 constructor: (@symbols, @defaultSymbol = 0) -> read: (index) -> if index >= 0 then TuringTape.readAbstract(@postape, index) else TuringTape.readAbstract(@negtape, Math.abs(index) - 1) @readAbstract: (tape, index) -> return if index < tape.length then tape[index] else @defaultSymbol write: (index, symbol, log = console.log) -> if symbol < 0 or symbol >= @symbols log("[TuringTape] could not write symbol '#{symbol}' to tape, not within tape's symbol range") else @writeAbstract((if index >= 0 then @postape else @negtape), Math.abs(index - (if index >= 0 then 0 else 1)), parseInt(symbol)) @writeAbstract: (tape, index, symbol) -> tape.push(@defaultSymbol) while tape.length < index tape[index] = symbol module.exports = {TuringTape}
[ { "context": "/artwork/foo-bar-id\",\n \"partner\": {\n \"name\": \"Galerie Foo Bar\"\n },\n \"artist_names\": \"John Doe\",\n \"image\": {\n", "end": 211, "score": 0.9998782277107239, "start": 196, "tag": "NAME", "value": "Galerie Foo Bar" }, { "context": "\"name\": \"Galerie Foo Bar\"\n },\n \"artist_names\": \"John Doe\",\n \"image\": {\n \"url\": \"foo-bar.jpg\"\n }\n}", "end": 245, "score": 0.9998602867126465, "start": 237, "tag": "NAME", "value": "John Doe" } ]
apps/artwork_purchase/test/artwork_json.coffee
l2succes/force
0
module.exports = { "id": "foo-bar-id", "is_purchasable": true, "title": "Foo Bar", "date": "2011", "sale_message": "€9,500", "href": "/artwork/foo-bar-id", "partner": { "name": "Galerie Foo Bar" }, "artist_names": "John Doe", "image": { "url": "foo-bar.jpg" } }
37943
module.exports = { "id": "foo-bar-id", "is_purchasable": true, "title": "Foo Bar", "date": "2011", "sale_message": "€9,500", "href": "/artwork/foo-bar-id", "partner": { "name": "<NAME>" }, "artist_names": "<NAME>", "image": { "url": "foo-bar.jpg" } }
true
module.exports = { "id": "foo-bar-id", "is_purchasable": true, "title": "Foo Bar", "date": "2011", "sale_message": "€9,500", "href": "/artwork/foo-bar-id", "partner": { "name": "PI:NAME:<NAME>END_PI" }, "artist_names": "PI:NAME:<NAME>END_PI", "image": { "url": "foo-bar.jpg" } }
[ { "context": " create an auction\nauction = new Auction({ item: 'Mars Bar', description: 'chocolate bar'})\n# until we have ", "end": 5662, "score": 0.9863173961639404, "start": 5654, "tag": "NAME", "value": "Mars Bar" } ]
auction.coffee
kartikmenda/livebids
0
StateMachine = require('./sm').StateMachine Collection = require('./collection').Collection states = start: full_name: 'Waiting for Bidders' active: full_name: 'Auction happening now!' complete: full_name: 'Auction Finished' payment_pending: full_name: 'Waiting for Payment' payment_collected: full_name: 'Payment Completed' finished: full_name: 'End State' events = bidder_joined: transitions: start: 'start' active: 'active' complete: 'complete' payment_pending: 'payment_pending' payment_collected: 'payment_collected' callback: (bidder) -> # todo , regisiter a 'disconnect' handler? @bidders.push bidder @bidderemit bidder, 'startup' @bidderemit bidder, "newbid", @current_bid @broadcast "new bidder! #{bidder.name}" @broademit "bidder_joined", bidders: (p.id for p in @bidders) true bidder_left: transitions: start: 'start' active: 'active' complete: 'complete' payment_pending: 'payment_pending' payment_collected: 'payment_collected' callback: (bidder) -> @bidders = (p for p in @bidders when p != bidder) @broadcast "bidder left! #{bidder.name}" @broademit "bidder_left", bidders: (p.id for p in @bidders) true start_auction: transitions: start: 'active' callback: () -> @broadcast "auction started " @broademit "started" stop_auction: transitions: active: 'complete' callback: (admin) -> @broadcast "auction stopped" @broademit "stopped" auction_over: transitions: active: 'complete' callback: () -> @broadcast "auction over. Sold!" @broademit "over", name: @current_bid.name, value: @current_bid.value if @current_bidder? @biddercast @current_bidder, "You've won and it's now time to pay" @bidderemit @current_bidder, "winner", value: @current_bid.value, auction_name: @name restart_auction: transitions: start: 'active' active: 'active' complete: 'active' payment_pending: 'active' payment_collected: 'active' active: 'active' callback: (admin) -> @broadcast "auction restarted" @broademit "restarted" @bids = [] @current_bidder = null @current_bid = { value: 0, name: admin.name, image: admin.image } @broademit "newbid", @current_bid going_auction: transitions: active: 'active' callback: (admin) -> @going1() bid: transitions: active: 'active' callback: (bid, bidder) -> if @going? clearTimeout @going @going = null bid.name = bidder.name bid.image = bidder.image # auction logic console.log "auction #{@item} got bid #{bid.value} from #{bidder.name}" if !@current_bid? console.log "first bid accepted #{bid.value} from #{bidder.name}" @bids.push bid @current_bid = bid @current_bidder = bidder @broadcast "first bid from #{bidder.name}" @biddercast bidder, "bid accepted" @broademit "newbid", bid @bidderemit bidder, "bidstatus", accepted: true if bid.value > @current_bid.value console.log "bid accepted" @bids.push bid @current_bid = bid @current_bidder = bidder @broadcast "new bid from #{bidder.name}" @biddercast bidder, "bid accepted" @broademit "newbid", bid @bidderemit bidder, "bidstatus", accepted: true else console.log "bid rejected" @biddercast bidder, "sorry, you've been out bid already" @bidderemit bidder, "bidstatus", accepted: false @bidderemit bidder, "newbid", @current_bid class Auction extends StateMachine constructor: (item: @item, description: @description ) -> super('start', states, events) @bidders = [] @current_bid = null @current_bidder = null @bids = [] @name = "#{Math.floor(Math.random() * 1000000000000)}" #TODO make unique @on 'moved_state', (state_name) => @broadcast "auction moved to #{state_name}" @getState('finished').on 'enter', => p.sm.trigger 'auction_over' for p in @bidders # todo: move this cleanup to sm special 'finished' state or event Auction.collection.remove @id Auction.finished_collection.remove @id bidderemit: (b, event, args...) -> console.log "auction #{@item} bidderemit: #{b.name} #{event}", args... b.emit(event, args...) biddercast: (b, message) -> console.log "auction #{@item} biddercast: #{b.name} #{message}" b.emit("broadcast", message: message) b.send(message) broademit: (event, args...) -> console.log "auction #{@item} broademit: #{event}", args... b.emit(event, args...) for b in @bidders broadcast: (message) -> console.log "auction #{@item} broadcast: #{message}" b.emit("broadcast", message: message) for b in @bidders b.send(message) for b in @bidders going1: -> @broadcast 'going once' @broademit 'going', left: 3, message: 'Going once!' a = @ @going = setTimeout -> a.broadcast 'going twice' a.broademit 'going', left: 2, message: 'Going twice!' a.going = setTimeout -> a.broadcast 'going three times' a.broademit 'going', left: 1, message: 'Going three times...!' a.going = setTimeout -> a.trigger 'auction_over' a.broadcast 'Sold' a.broademit 'going', left: 0, message: 'Sold!' , 3500 , 3000 , 2500 # create an auction auction = new Auction({ item: 'Mars Bar', description: 'chocolate bar'}) # until we have admin, make it the global live auction global.live_auction = auction # until we have admin, start the auction auction.trigger('start_auction') (exports ? window).Auction = Auction
164122
StateMachine = require('./sm').StateMachine Collection = require('./collection').Collection states = start: full_name: 'Waiting for Bidders' active: full_name: 'Auction happening now!' complete: full_name: 'Auction Finished' payment_pending: full_name: 'Waiting for Payment' payment_collected: full_name: 'Payment Completed' finished: full_name: 'End State' events = bidder_joined: transitions: start: 'start' active: 'active' complete: 'complete' payment_pending: 'payment_pending' payment_collected: 'payment_collected' callback: (bidder) -> # todo , regisiter a 'disconnect' handler? @bidders.push bidder @bidderemit bidder, 'startup' @bidderemit bidder, "newbid", @current_bid @broadcast "new bidder! #{bidder.name}" @broademit "bidder_joined", bidders: (p.id for p in @bidders) true bidder_left: transitions: start: 'start' active: 'active' complete: 'complete' payment_pending: 'payment_pending' payment_collected: 'payment_collected' callback: (bidder) -> @bidders = (p for p in @bidders when p != bidder) @broadcast "bidder left! #{bidder.name}" @broademit "bidder_left", bidders: (p.id for p in @bidders) true start_auction: transitions: start: 'active' callback: () -> @broadcast "auction started " @broademit "started" stop_auction: transitions: active: 'complete' callback: (admin) -> @broadcast "auction stopped" @broademit "stopped" auction_over: transitions: active: 'complete' callback: () -> @broadcast "auction over. Sold!" @broademit "over", name: @current_bid.name, value: @current_bid.value if @current_bidder? @biddercast @current_bidder, "You've won and it's now time to pay" @bidderemit @current_bidder, "winner", value: @current_bid.value, auction_name: @name restart_auction: transitions: start: 'active' active: 'active' complete: 'active' payment_pending: 'active' payment_collected: 'active' active: 'active' callback: (admin) -> @broadcast "auction restarted" @broademit "restarted" @bids = [] @current_bidder = null @current_bid = { value: 0, name: admin.name, image: admin.image } @broademit "newbid", @current_bid going_auction: transitions: active: 'active' callback: (admin) -> @going1() bid: transitions: active: 'active' callback: (bid, bidder) -> if @going? clearTimeout @going @going = null bid.name = bidder.name bid.image = bidder.image # auction logic console.log "auction #{@item} got bid #{bid.value} from #{bidder.name}" if !@current_bid? console.log "first bid accepted #{bid.value} from #{bidder.name}" @bids.push bid @current_bid = bid @current_bidder = bidder @broadcast "first bid from #{bidder.name}" @biddercast bidder, "bid accepted" @broademit "newbid", bid @bidderemit bidder, "bidstatus", accepted: true if bid.value > @current_bid.value console.log "bid accepted" @bids.push bid @current_bid = bid @current_bidder = bidder @broadcast "new bid from #{bidder.name}" @biddercast bidder, "bid accepted" @broademit "newbid", bid @bidderemit bidder, "bidstatus", accepted: true else console.log "bid rejected" @biddercast bidder, "sorry, you've been out bid already" @bidderemit bidder, "bidstatus", accepted: false @bidderemit bidder, "newbid", @current_bid class Auction extends StateMachine constructor: (item: @item, description: @description ) -> super('start', states, events) @bidders = [] @current_bid = null @current_bidder = null @bids = [] @name = "#{Math.floor(Math.random() * 1000000000000)}" #TODO make unique @on 'moved_state', (state_name) => @broadcast "auction moved to #{state_name}" @getState('finished').on 'enter', => p.sm.trigger 'auction_over' for p in @bidders # todo: move this cleanup to sm special 'finished' state or event Auction.collection.remove @id Auction.finished_collection.remove @id bidderemit: (b, event, args...) -> console.log "auction #{@item} bidderemit: #{b.name} #{event}", args... b.emit(event, args...) biddercast: (b, message) -> console.log "auction #{@item} biddercast: #{b.name} #{message}" b.emit("broadcast", message: message) b.send(message) broademit: (event, args...) -> console.log "auction #{@item} broademit: #{event}", args... b.emit(event, args...) for b in @bidders broadcast: (message) -> console.log "auction #{@item} broadcast: #{message}" b.emit("broadcast", message: message) for b in @bidders b.send(message) for b in @bidders going1: -> @broadcast 'going once' @broademit 'going', left: 3, message: 'Going once!' a = @ @going = setTimeout -> a.broadcast 'going twice' a.broademit 'going', left: 2, message: 'Going twice!' a.going = setTimeout -> a.broadcast 'going three times' a.broademit 'going', left: 1, message: 'Going three times...!' a.going = setTimeout -> a.trigger 'auction_over' a.broadcast 'Sold' a.broademit 'going', left: 0, message: 'Sold!' , 3500 , 3000 , 2500 # create an auction auction = new Auction({ item: '<NAME>', description: 'chocolate bar'}) # until we have admin, make it the global live auction global.live_auction = auction # until we have admin, start the auction auction.trigger('start_auction') (exports ? window).Auction = Auction
true
StateMachine = require('./sm').StateMachine Collection = require('./collection').Collection states = start: full_name: 'Waiting for Bidders' active: full_name: 'Auction happening now!' complete: full_name: 'Auction Finished' payment_pending: full_name: 'Waiting for Payment' payment_collected: full_name: 'Payment Completed' finished: full_name: 'End State' events = bidder_joined: transitions: start: 'start' active: 'active' complete: 'complete' payment_pending: 'payment_pending' payment_collected: 'payment_collected' callback: (bidder) -> # todo , regisiter a 'disconnect' handler? @bidders.push bidder @bidderemit bidder, 'startup' @bidderemit bidder, "newbid", @current_bid @broadcast "new bidder! #{bidder.name}" @broademit "bidder_joined", bidders: (p.id for p in @bidders) true bidder_left: transitions: start: 'start' active: 'active' complete: 'complete' payment_pending: 'payment_pending' payment_collected: 'payment_collected' callback: (bidder) -> @bidders = (p for p in @bidders when p != bidder) @broadcast "bidder left! #{bidder.name}" @broademit "bidder_left", bidders: (p.id for p in @bidders) true start_auction: transitions: start: 'active' callback: () -> @broadcast "auction started " @broademit "started" stop_auction: transitions: active: 'complete' callback: (admin) -> @broadcast "auction stopped" @broademit "stopped" auction_over: transitions: active: 'complete' callback: () -> @broadcast "auction over. Sold!" @broademit "over", name: @current_bid.name, value: @current_bid.value if @current_bidder? @biddercast @current_bidder, "You've won and it's now time to pay" @bidderemit @current_bidder, "winner", value: @current_bid.value, auction_name: @name restart_auction: transitions: start: 'active' active: 'active' complete: 'active' payment_pending: 'active' payment_collected: 'active' active: 'active' callback: (admin) -> @broadcast "auction restarted" @broademit "restarted" @bids = [] @current_bidder = null @current_bid = { value: 0, name: admin.name, image: admin.image } @broademit "newbid", @current_bid going_auction: transitions: active: 'active' callback: (admin) -> @going1() bid: transitions: active: 'active' callback: (bid, bidder) -> if @going? clearTimeout @going @going = null bid.name = bidder.name bid.image = bidder.image # auction logic console.log "auction #{@item} got bid #{bid.value} from #{bidder.name}" if !@current_bid? console.log "first bid accepted #{bid.value} from #{bidder.name}" @bids.push bid @current_bid = bid @current_bidder = bidder @broadcast "first bid from #{bidder.name}" @biddercast bidder, "bid accepted" @broademit "newbid", bid @bidderemit bidder, "bidstatus", accepted: true if bid.value > @current_bid.value console.log "bid accepted" @bids.push bid @current_bid = bid @current_bidder = bidder @broadcast "new bid from #{bidder.name}" @biddercast bidder, "bid accepted" @broademit "newbid", bid @bidderemit bidder, "bidstatus", accepted: true else console.log "bid rejected" @biddercast bidder, "sorry, you've been out bid already" @bidderemit bidder, "bidstatus", accepted: false @bidderemit bidder, "newbid", @current_bid class Auction extends StateMachine constructor: (item: @item, description: @description ) -> super('start', states, events) @bidders = [] @current_bid = null @current_bidder = null @bids = [] @name = "#{Math.floor(Math.random() * 1000000000000)}" #TODO make unique @on 'moved_state', (state_name) => @broadcast "auction moved to #{state_name}" @getState('finished').on 'enter', => p.sm.trigger 'auction_over' for p in @bidders # todo: move this cleanup to sm special 'finished' state or event Auction.collection.remove @id Auction.finished_collection.remove @id bidderemit: (b, event, args...) -> console.log "auction #{@item} bidderemit: #{b.name} #{event}", args... b.emit(event, args...) biddercast: (b, message) -> console.log "auction #{@item} biddercast: #{b.name} #{message}" b.emit("broadcast", message: message) b.send(message) broademit: (event, args...) -> console.log "auction #{@item} broademit: #{event}", args... b.emit(event, args...) for b in @bidders broadcast: (message) -> console.log "auction #{@item} broadcast: #{message}" b.emit("broadcast", message: message) for b in @bidders b.send(message) for b in @bidders going1: -> @broadcast 'going once' @broademit 'going', left: 3, message: 'Going once!' a = @ @going = setTimeout -> a.broadcast 'going twice' a.broademit 'going', left: 2, message: 'Going twice!' a.going = setTimeout -> a.broadcast 'going three times' a.broademit 'going', left: 1, message: 'Going three times...!' a.going = setTimeout -> a.trigger 'auction_over' a.broadcast 'Sold' a.broademit 'going', left: 0, message: 'Sold!' , 3500 , 3000 , 2500 # create an auction auction = new Auction({ item: 'PI:NAME:<NAME>END_PI', description: 'chocolate bar'}) # until we have admin, make it the global live auction global.live_auction = auction # until we have admin, start the auction auction.trigger('start_auction') (exports ? window).Auction = Auction
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999122619628906, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/profile-page/detail.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { DetailBar } from './detail-bar' import { MedalsCount } from './medals-count' import { PlayTime } from './play-time' import { Pp } from './pp' import { Rank } from './rank' import { RankChart } from './rank-chart' import { RankCount } from './rank-count' import * as React from 'react' import { div } from 'react-dom-factories' el = React.createElement bn = 'profile-detail' export class Detail extends React.PureComponent constructor: (props) -> super props @state = expanded: if currentUser.id? then currentUser.user_preferences.ranking_expanded else true render: => div className: bn, div className: "#{bn}__bar", el DetailBar, stats: @props.stats toggleExtend: @toggleExtend expanded: @state.expanded user: @props.user div className: if @state.expanded then '' else 'hidden' div className: "#{bn}__row #{bn}__row--top", div className: "#{bn}__col #{bn}__col--top-left", div className: "#{bn}__top-left-item", el PlayTime, stats: @props.stats div className: "#{bn}__top-left-item", el MedalsCount, userAchievements: @props.userAchievements div className: "#{bn}__top-left-item", el Pp, stats: @props.stats div className: "#{bn}__col", el RankCount, stats: @props.stats div className: "#{bn}__row", div className: "#{bn}__col #{bn}__col--bottom-left", if @props.stats.is_ranked el RankChart, rankHistory: @props.user.rankHistory stats: @props.stats else div className: "#{bn}__empty-chart", osu.trans('users.show.extra.unranked') div className: "#{bn}__col #{bn}__col--bottom-right", div className: "#{bn}__bottom-right-item", el Rank, modifiers: ['large'] type: 'global' stats: @props.stats div className: "#{bn}__bottom-right-item", el Rank, type: 'country' stats: @props.stats toggleExtend: => if currentUser.id? $.ajax laroute.route('account.options'), method: 'put', dataType: 'json', data: user_profile_customization: ranking_expanded: !@state.expanded @setState expanded: !@state.expanded
180529
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { DetailBar } from './detail-bar' import { MedalsCount } from './medals-count' import { PlayTime } from './play-time' import { Pp } from './pp' import { Rank } from './rank' import { RankChart } from './rank-chart' import { RankCount } from './rank-count' import * as React from 'react' import { div } from 'react-dom-factories' el = React.createElement bn = 'profile-detail' export class Detail extends React.PureComponent constructor: (props) -> super props @state = expanded: if currentUser.id? then currentUser.user_preferences.ranking_expanded else true render: => div className: bn, div className: "#{bn}__bar", el DetailBar, stats: @props.stats toggleExtend: @toggleExtend expanded: @state.expanded user: @props.user div className: if @state.expanded then '' else 'hidden' div className: "#{bn}__row #{bn}__row--top", div className: "#{bn}__col #{bn}__col--top-left", div className: "#{bn}__top-left-item", el PlayTime, stats: @props.stats div className: "#{bn}__top-left-item", el MedalsCount, userAchievements: @props.userAchievements div className: "#{bn}__top-left-item", el Pp, stats: @props.stats div className: "#{bn}__col", el RankCount, stats: @props.stats div className: "#{bn}__row", div className: "#{bn}__col #{bn}__col--bottom-left", if @props.stats.is_ranked el RankChart, rankHistory: @props.user.rankHistory stats: @props.stats else div className: "#{bn}__empty-chart", osu.trans('users.show.extra.unranked') div className: "#{bn}__col #{bn}__col--bottom-right", div className: "#{bn}__bottom-right-item", el Rank, modifiers: ['large'] type: 'global' stats: @props.stats div className: "#{bn}__bottom-right-item", el Rank, type: 'country' stats: @props.stats toggleExtend: => if currentUser.id? $.ajax laroute.route('account.options'), method: 'put', dataType: 'json', data: user_profile_customization: ranking_expanded: !@state.expanded @setState expanded: !@state.expanded
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import { DetailBar } from './detail-bar' import { MedalsCount } from './medals-count' import { PlayTime } from './play-time' import { Pp } from './pp' import { Rank } from './rank' import { RankChart } from './rank-chart' import { RankCount } from './rank-count' import * as React from 'react' import { div } from 'react-dom-factories' el = React.createElement bn = 'profile-detail' export class Detail extends React.PureComponent constructor: (props) -> super props @state = expanded: if currentUser.id? then currentUser.user_preferences.ranking_expanded else true render: => div className: bn, div className: "#{bn}__bar", el DetailBar, stats: @props.stats toggleExtend: @toggleExtend expanded: @state.expanded user: @props.user div className: if @state.expanded then '' else 'hidden' div className: "#{bn}__row #{bn}__row--top", div className: "#{bn}__col #{bn}__col--top-left", div className: "#{bn}__top-left-item", el PlayTime, stats: @props.stats div className: "#{bn}__top-left-item", el MedalsCount, userAchievements: @props.userAchievements div className: "#{bn}__top-left-item", el Pp, stats: @props.stats div className: "#{bn}__col", el RankCount, stats: @props.stats div className: "#{bn}__row", div className: "#{bn}__col #{bn}__col--bottom-left", if @props.stats.is_ranked el RankChart, rankHistory: @props.user.rankHistory stats: @props.stats else div className: "#{bn}__empty-chart", osu.trans('users.show.extra.unranked') div className: "#{bn}__col #{bn}__col--bottom-right", div className: "#{bn}__bottom-right-item", el Rank, modifiers: ['large'] type: 'global' stats: @props.stats div className: "#{bn}__bottom-right-item", el Rank, type: 'country' stats: @props.stats toggleExtend: => if currentUser.id? $.ajax laroute.route('account.options'), method: 'put', dataType: 'json', data: user_profile_customization: ranking_expanded: !@state.expanded @setState expanded: !@state.expanded
[ { "context": "ery plugin v<%= pkg.version %>\\nCopyright (c) 2015 Ivan Prignano\\nReleased under the MIT License\\n*/'\n file", "end": 327, "score": 0.9998878240585327, "start": 314, "tag": "NAME", "value": "Ivan Prignano" } ]
Gruntfile.coffee
iprignano/tendina
77
module.exports = (grunt)-> grunt.initConfig pkg: grunt.file.readJSON("package.json") coffee: compile: files: "dist/tendina.js": "src/tendina.coffee" uglify: target: options: banner: '/*!\nTendina jQuery plugin v<%= pkg.version %>\nCopyright (c) 2015 Ivan Prignano\nReleased under the MIT License\n*/' files: "dist/tendina.min.js": "dist/tendina.js" watch: coffee: files: ["src/*.coffee"] tasks: ["coffee:compile"] uglify: files: ["dist/tendina.js"] tasks: ["uglify:target"] grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-contrib-watch" grunt.registerTask "default", ["coffee", "uglify"]
92390
module.exports = (grunt)-> grunt.initConfig pkg: grunt.file.readJSON("package.json") coffee: compile: files: "dist/tendina.js": "src/tendina.coffee" uglify: target: options: banner: '/*!\nTendina jQuery plugin v<%= pkg.version %>\nCopyright (c) 2015 <NAME>\nReleased under the MIT License\n*/' files: "dist/tendina.min.js": "dist/tendina.js" watch: coffee: files: ["src/*.coffee"] tasks: ["coffee:compile"] uglify: files: ["dist/tendina.js"] tasks: ["uglify:target"] grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-contrib-watch" grunt.registerTask "default", ["coffee", "uglify"]
true
module.exports = (grunt)-> grunt.initConfig pkg: grunt.file.readJSON("package.json") coffee: compile: files: "dist/tendina.js": "src/tendina.coffee" uglify: target: options: banner: '/*!\nTendina jQuery plugin v<%= pkg.version %>\nCopyright (c) 2015 PI:NAME:<NAME>END_PI\nReleased under the MIT License\n*/' files: "dist/tendina.min.js": "dist/tendina.js" watch: coffee: files: ["src/*.coffee"] tasks: ["coffee:compile"] uglify: files: ["dist/tendina.js"] tasks: ["uglify:target"] grunt.loadNpmTasks "grunt-contrib-coffee" grunt.loadNpmTasks "grunt-contrib-uglify" grunt.loadNpmTasks "grunt-contrib-watch" grunt.registerTask "default", ["coffee", "uglify"]
[ { "context": " yield utils.clearModels([User, Classroom])\n @user1 = yield utils.initUser()\n yield utils.loginUs", "end": 492, "score": 0.5070427060127258, "start": 488, "tag": "USERNAME", "value": "user" }, { "context": "= yield utils.initUser()\n yield utils.loginUser(@user1)\n @classroom1 = yield new Classroom({name: 'Cl", "end": 551, "score": 0.9983108043670654, "start": 545, "tag": "USERNAME", "value": "@user1" }, { "context": "yield new Classroom({name: 'Classroom 1', ownerID: @user1.get('_id') }).save()\n @user2 = yield utils.ini", "end": 628, "score": 0.7424508929252625, "start": 622, "tag": "USERNAME", "value": "@user1" }, { "context": "= yield utils.initUser()\n yield utils.loginUser(@user2)\n @classroom2 = yield new Classroom({name: 'Cl", "end": 718, "score": 0.9992249608039856, "start": 712, "tag": "USERNAME", "value": "@user2" }, { "context": "yield new Classroom({name: 'Classroom 2', ownerID: @user2.get('_id') }).save()\n done()\n \n it 'ret", "end": 794, "score": 0.7413321137428284, "start": 789, "tag": "USERNAME", "value": "@user" }, { "context": " request.getAsync getURL('/db/classroom?ownerID='+@user2.id), { json: true }\n expect(res.statusCode).to", "end": 996, "score": 0.9025372862815857, "start": 990, "tag": "USERNAME", "value": "@user2" }, { "context": " request.getAsync getURL('/db/classroom?ownerID='+@user1.id), { json: true }\n expect(res.statusCode).to", "end": 1336, "score": 0.9529070854187012, "start": 1330, "tag": "USERNAME", "value": "@user1" }, { "context": " + '/invite-members'\n data = { emails: ['test@test.com'] }\n request.post { uri: url, json: data", "end": 9346, "score": 0.9998817443847656, "start": 9333, "tag": "EMAIL", "value": "test@test.com" }, { "context": "e: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save()\n @session1A = yi", "end": 10261, "score": 0.8625207543373108, "start": 10253, "tag": "USERNAME", "value": "student1" }, { "context": "\n @session1A = yield new LevelSession({creator: @student1.id, state: { complete: true }, level: {or", "end": 10341, "score": 0.5363510251045227, "start": 10341, "tag": "USERNAME", "value": "" }, { "context": "l: {original: @levelA._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save()\n @sess", "end": 10814, "score": 0.7167325615882874, "start": 10814, "tag": "USERNAME", "value": "" }, { "context": "\n @session2B = yield new LevelSession({creator: @student2.id, state: { complete: false }, level: {original: @l", "end": 10919, "score": 0.9700194597244263, "start": 10907, "tag": "USERNAME", "value": "@student2.id" }, { "context": "l: {original: @levelB._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save()\n done(", "end": 11003, "score": 0.5141444802284241, "start": 11003, "tag": "USERNAME", "value": "" }, { "context": "e', utils.wrap (done) ->\n yield utils.loginUser(@teacher)\n [res, body] = yield request.getAsync getURL", "end": 11230, "score": 0.9994213581085205, "start": 11222, "tag": "USERNAME", "value": "@teacher" }, { "context": "m', utils.wrap (done) ->\n yield utils.loginUser(@student1)\n [res, body] = yield request.getAsync getURL", "end": 11552, "score": 0.9996725916862488, "start": 11543, "tag": "USERNAME", "value": "@student1" }, { "context": "s', utils.wrap (done) ->\n yield utils.loginUser(@teacher)\n [res, body] = yield request.getAsync getURL", "end": 12071, "score": 0.9995694160461426, "start": 12063, "tag": "USERNAME", "value": "@teacher" }, { "context": "y.length).toBe(2)\n expect(session.creator).toBe(@student1.id) for session in body\n [res, body] = yield req", "end": 12316, "score": 0.9926844835281372, "start": 12304, "tag": "USERNAME", "value": "@student1.id" }, { "context": "length).toBe(2)\n expect(session.creator).toBe(@student2.id) for session in body\n done()\n \ndescribe ", "end": 12577, "score": 0.7966053485870361, "start": 12569, "tag": "USERNAME", "value": "student2" }, { "context": "r()\n @student1 = yield utils.initUser({ name: \"Firstname Lastname\" })\n @student2 = yield utils.initUser({ name: ", "end": 12853, "score": 0.9142396450042725, "start": 12835, "tag": "NAME", "value": "Firstname Lastname" }, { "context": " })\n @student2 = yield utils.initUser({ name: \"Student Nameynamington\" })\n @classroom = yield new Classroom({name: '", "end": 12926, "score": 0.9659972190856934, "start": 12904, "tag": "NAME", "value": "Student Nameynamington" }, { "context": "e: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save()\n @emptyClassroom", "end": 13030, "score": 0.9445960521697998, "start": 13022, "tag": "USERNAME", "value": "student1" }, { "context": "D: @teacher._id, members: [@student1._id, @student2._id] }).save()\n @emptyClassroom = yield new Cl", "end": 13045, "score": 0.5148389935493469, "start": 13044, "tag": "USERNAME", "value": "2" }, { "context": "m', utils.wrap (done) ->\n yield utils.loginUser(@student1)\n [res, body] = yield request.getAsync getURL", "end": 13310, "score": 0.9987642765045166, "start": 13301, "tag": "USERNAME", "value": "@student1" }, { "context": "m', utils.wrap (done) ->\n yield utils.loginUser(@teacher)\n [res, body] = yield request.getAsync getURL(", "end": 13805, "score": 0.9933010935783386, "start": 13797, "tag": "USERNAME", "value": "@teacher" }, { "context": "l', utils.wrap (done) ->\n yield utils.loginUser(@teacher)\n [res, body] = yield request.getAsync getURL(", "end": 14124, "score": 0.9816808700561523, "start": 14116, "tag": "USERNAME", "value": "@teacher" } ]
spec/server/functional/classrooms.spec.coffee
differentmatt/codecombat
0
config = require '../../../server_config' require '../common' clientUtils = require '../../../app/core/utils' # Must come after require /common mongoose = require 'mongoose' utils = require '../utils' _ = require 'lodash' Promise = require 'bluebird' requestAsync = Promise.promisify(request, {multiArgs: true}) classroomsURL = getURL('/db/classroom') describe 'GET /db/classroom?ownerID=:id', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @user1 = yield utils.initUser() yield utils.loginUser(@user1) @classroom1 = yield new Classroom({name: 'Classroom 1', ownerID: @user1.get('_id') }).save() @user2 = yield utils.initUser() yield utils.loginUser(@user2) @classroom2 = yield new Classroom({name: 'Classroom 2', ownerID: @user2.get('_id') }).save() done() it 'returns an array of classrooms with the given owner', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user2.id), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(body[0].name).toBe('Classroom 2') done() it 'returns 403 when a non-admin tries to get classrooms for another user', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user1.id), { json: true } expect(res.statusCode).toBe(403) done() describe 'GET /db/classroom/:id', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'returns the classroom for the given id', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) classroomID = body._id request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body._id).toBe(classroomID = body._id) done() describe 'POST /db/classroom', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'creates a new classroom for the given user', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.name).toBe('Classroom 1') expect(body.members.length).toBe(0) expect(body.ownerID).toBe(user1.id) done() it 'does not work for anonymous users', (done) -> logoutUser -> data = { name: 'Classroom 2' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(401) done() it 'does not work for non-teacher users', (done) -> loginNewUser (user1) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'PUT /db/classroom', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'edits name and description', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 2' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) data = { name: 'Classroom 3', description: 'New Description' } url = classroomsURL + '/' + body._id request.put { uri: url, json: data }, (err, res, body) -> expect(body.name).toBe('Classroom 3') expect(body.description).toBe('New Description') done() it 'is not allowed if you are just a member', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 4' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) classroomCode = body.code loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) url = classroomsURL + '/' + body._id request.put { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'POST /db/classroom/~/members', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'adds the signed in user to the list of members in the classroom', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 5' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')?[0]?.equals(user2.get('_id'))).toBe(true) User.findById user2.get('_id'), (err, user2) -> expect(user2.get('role')).toBe('student') done() it 'does not work if the user is a teacher', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 5' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> user2.set('role', 'teacher') user2.save (err, user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(0) done() it 'does not work if the user is anonymous', utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) [res, body] = yield request.postAsync {uri: classroomsURL, json: { name: 'Classroom' } } expect(res.statusCode).toBe(200) classroomCode = body.code yield utils.becomeAnonymous() [res, body] = yield request.postAsync { uri: getURL("/db/classroom/~/members"), json: { code: classroomCode } } expect(res.statusCode).toBe(401) done() describe 'DELETE /db/classroom/:id/members', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'removes the given user from the list of members in the classroom', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 6' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(1) url = getURL("/db/classroom/#{classroom.id}/members") data = { userID: user2.id } request.del { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(0) done() describe 'POST /db/classroom/:id/invite-members', -> it 'takes a list of emails and sends invites', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 6' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) url = classroomsURL + '/' + body._id + '/invite-members' data = { emails: ['test@test.com'] } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) done() describe 'GET /db/classroom/:handle/member-sessions', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, LevelSession, Level]) @artisan = yield utils.initUser() @teacher = yield utils.initUser() @student1 = yield utils.initUser() @student2 = yield utils.initUser() @levelA = new Level({name: 'Level A', permissions: [{target: @artisan._id, access: 'owner'}]}) @levelA.set('original', @levelA._id) @levelA = yield @levelA.save() @levelB = new Level({name: 'Level B', permissions: [{target: @artisan._id, access: 'owner'}]}) @levelB.set('original', @levelB._id) @levelB = yield @levelB.save() @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @session1A = yield new LevelSession({creator: @student1.id, state: { complete: true }, level: {original: @levelA._id}, permissions: [{target: @student1._id, access: 'owner'}]}).save() @session1B = yield new LevelSession({creator: @student1.id, state: { complete: false }, level: {original: @levelB._id}, permissions: [{target: @student1._id, access: 'owner'}]}).save() @session2A = yield new LevelSession({creator: @student2.id, state: { complete: true }, level: {original: @levelA._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save() @session2B = yield new LevelSession({creator: @student2.id, state: { complete: false }, level: {original: @levelB._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save() done() it 'returns all sessions for all members in the classroom with only properties level, creator and state.complete', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(4) done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'accepts memberSkip and memberLimit GET parameters', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberLimit=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student1.id) for session in body [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberSkip=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student2.id) for session in body done() describe 'GET /db/classroom/:handle/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser() @student1 = yield utils.initUser({ name: "Firstname Lastname" }) @student2 = yield utils.initUser({ name: "Student Nameynamington" }) @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @emptyClassroom = yield new Classroom({name: 'Empty Classroom', ownerID: @teacher._id, members: [] }).save() done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'works on an empty classroom', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@emptyClassroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body).toEqual([]) done() it 'returns all members with name and email', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) for user in body expect(user.name).toBeDefined() expect(user.email).toBeDefined() expect(user.passwordHash).toBeUndefined() done()
68003
config = require '../../../server_config' require '../common' clientUtils = require '../../../app/core/utils' # Must come after require /common mongoose = require 'mongoose' utils = require '../utils' _ = require 'lodash' Promise = require 'bluebird' requestAsync = Promise.promisify(request, {multiArgs: true}) classroomsURL = getURL('/db/classroom') describe 'GET /db/classroom?ownerID=:id', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @user1 = yield utils.initUser() yield utils.loginUser(@user1) @classroom1 = yield new Classroom({name: 'Classroom 1', ownerID: @user1.get('_id') }).save() @user2 = yield utils.initUser() yield utils.loginUser(@user2) @classroom2 = yield new Classroom({name: 'Classroom 2', ownerID: @user2.get('_id') }).save() done() it 'returns an array of classrooms with the given owner', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user2.id), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(body[0].name).toBe('Classroom 2') done() it 'returns 403 when a non-admin tries to get classrooms for another user', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user1.id), { json: true } expect(res.statusCode).toBe(403) done() describe 'GET /db/classroom/:id', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'returns the classroom for the given id', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) classroomID = body._id request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body._id).toBe(classroomID = body._id) done() describe 'POST /db/classroom', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'creates a new classroom for the given user', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.name).toBe('Classroom 1') expect(body.members.length).toBe(0) expect(body.ownerID).toBe(user1.id) done() it 'does not work for anonymous users', (done) -> logoutUser -> data = { name: 'Classroom 2' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(401) done() it 'does not work for non-teacher users', (done) -> loginNewUser (user1) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'PUT /db/classroom', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'edits name and description', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 2' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) data = { name: 'Classroom 3', description: 'New Description' } url = classroomsURL + '/' + body._id request.put { uri: url, json: data }, (err, res, body) -> expect(body.name).toBe('Classroom 3') expect(body.description).toBe('New Description') done() it 'is not allowed if you are just a member', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 4' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) classroomCode = body.code loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) url = classroomsURL + '/' + body._id request.put { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'POST /db/classroom/~/members', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'adds the signed in user to the list of members in the classroom', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 5' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')?[0]?.equals(user2.get('_id'))).toBe(true) User.findById user2.get('_id'), (err, user2) -> expect(user2.get('role')).toBe('student') done() it 'does not work if the user is a teacher', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 5' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> user2.set('role', 'teacher') user2.save (err, user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(0) done() it 'does not work if the user is anonymous', utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) [res, body] = yield request.postAsync {uri: classroomsURL, json: { name: 'Classroom' } } expect(res.statusCode).toBe(200) classroomCode = body.code yield utils.becomeAnonymous() [res, body] = yield request.postAsync { uri: getURL("/db/classroom/~/members"), json: { code: classroomCode } } expect(res.statusCode).toBe(401) done() describe 'DELETE /db/classroom/:id/members', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'removes the given user from the list of members in the classroom', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 6' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(1) url = getURL("/db/classroom/#{classroom.id}/members") data = { userID: user2.id } request.del { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(0) done() describe 'POST /db/classroom/:id/invite-members', -> it 'takes a list of emails and sends invites', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 6' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) url = classroomsURL + '/' + body._id + '/invite-members' data = { emails: ['<EMAIL>'] } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) done() describe 'GET /db/classroom/:handle/member-sessions', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, LevelSession, Level]) @artisan = yield utils.initUser() @teacher = yield utils.initUser() @student1 = yield utils.initUser() @student2 = yield utils.initUser() @levelA = new Level({name: 'Level A', permissions: [{target: @artisan._id, access: 'owner'}]}) @levelA.set('original', @levelA._id) @levelA = yield @levelA.save() @levelB = new Level({name: 'Level B', permissions: [{target: @artisan._id, access: 'owner'}]}) @levelB.set('original', @levelB._id) @levelB = yield @levelB.save() @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @session1A = yield new LevelSession({creator: @student1.id, state: { complete: true }, level: {original: @levelA._id}, permissions: [{target: @student1._id, access: 'owner'}]}).save() @session1B = yield new LevelSession({creator: @student1.id, state: { complete: false }, level: {original: @levelB._id}, permissions: [{target: @student1._id, access: 'owner'}]}).save() @session2A = yield new LevelSession({creator: @student2.id, state: { complete: true }, level: {original: @levelA._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save() @session2B = yield new LevelSession({creator: @student2.id, state: { complete: false }, level: {original: @levelB._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save() done() it 'returns all sessions for all members in the classroom with only properties level, creator and state.complete', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(4) done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'accepts memberSkip and memberLimit GET parameters', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberLimit=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student1.id) for session in body [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberSkip=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student2.id) for session in body done() describe 'GET /db/classroom/:handle/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser() @student1 = yield utils.initUser({ name: "<NAME>" }) @student2 = yield utils.initUser({ name: "<NAME>" }) @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @emptyClassroom = yield new Classroom({name: 'Empty Classroom', ownerID: @teacher._id, members: [] }).save() done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'works on an empty classroom', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@emptyClassroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body).toEqual([]) done() it 'returns all members with name and email', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) for user in body expect(user.name).toBeDefined() expect(user.email).toBeDefined() expect(user.passwordHash).toBeUndefined() done()
true
config = require '../../../server_config' require '../common' clientUtils = require '../../../app/core/utils' # Must come after require /common mongoose = require 'mongoose' utils = require '../utils' _ = require 'lodash' Promise = require 'bluebird' requestAsync = Promise.promisify(request, {multiArgs: true}) classroomsURL = getURL('/db/classroom') describe 'GET /db/classroom?ownerID=:id', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @user1 = yield utils.initUser() yield utils.loginUser(@user1) @classroom1 = yield new Classroom({name: 'Classroom 1', ownerID: @user1.get('_id') }).save() @user2 = yield utils.initUser() yield utils.loginUser(@user2) @classroom2 = yield new Classroom({name: 'Classroom 2', ownerID: @user2.get('_id') }).save() done() it 'returns an array of classrooms with the given owner', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user2.id), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(1) expect(body[0].name).toBe('Classroom 2') done() it 'returns 403 when a non-admin tries to get classrooms for another user', utils.wrap (done) -> [res, body] = yield request.getAsync getURL('/db/classroom?ownerID='+@user1.id), { json: true } expect(res.statusCode).toBe(403) done() describe 'GET /db/classroom/:id', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'returns the classroom for the given id', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) classroomID = body._id request.get {uri: classroomsURL + '/' + body._id }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body._id).toBe(classroomID = body._id) done() describe 'POST /db/classroom', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'creates a new classroom for the given user', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.name).toBe('Classroom 1') expect(body.members.length).toBe(0) expect(body.ownerID).toBe(user1.id) done() it 'does not work for anonymous users', (done) -> logoutUser -> data = { name: 'Classroom 2' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(401) done() it 'does not work for non-teacher users', (done) -> loginNewUser (user1) -> data = { name: 'Classroom 1' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'PUT /db/classroom', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'edits name and description', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 2' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) data = { name: 'Classroom 3', description: 'New Description' } url = classroomsURL + '/' + body._id request.put { uri: url, json: data }, (err, res, body) -> expect(body.name).toBe('Classroom 3') expect(body.description).toBe('New Description') done() it 'is not allowed if you are just a member', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 4' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) classroomCode = body.code loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) url = classroomsURL + '/' + body._id request.put { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'POST /db/classroom/~/members', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'adds the signed in user to the list of members in the classroom', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 5' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(1) expect(classroom.get('members')?[0]?.equals(user2.get('_id'))).toBe(true) User.findById user2.get('_id'), (err, user2) -> expect(user2.get('role')).toBe('student') done() it 'does not work if the user is a teacher', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 5' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> user2.set('role', 'teacher') user2.save (err, user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(403) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(0) done() it 'does not work if the user is anonymous', utils.wrap (done) -> yield utils.clearModels([User, Classroom]) teacher = yield utils.initUser({role: 'teacher'}) yield utils.loginUser(teacher) [res, body] = yield request.postAsync {uri: classroomsURL, json: { name: 'Classroom' } } expect(res.statusCode).toBe(200) classroomCode = body.code yield utils.becomeAnonymous() [res, body] = yield request.postAsync { uri: getURL("/db/classroom/~/members"), json: { code: classroomCode } } expect(res.statusCode).toBe(401) done() describe 'DELETE /db/classroom/:id/members', -> it 'clears database users and classrooms', (done) -> clearModels [User, Classroom], (err) -> throw err if err done() it 'removes the given user from the list of members in the classroom', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 6' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> classroomCode = body.code classroomID = body._id expect(res.statusCode).toBe(200) loginNewUser (user2) -> url = getURL("/db/classroom/~/members") data = { code: classroomCode } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(1) url = getURL("/db/classroom/#{classroom.id}/members") data = { userID: user2.id } request.del { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) Classroom.findById classroomID, (err, classroom) -> expect(classroom.get('members').length).toBe(0) done() describe 'POST /db/classroom/:id/invite-members', -> it 'takes a list of emails and sends invites', (done) -> loginNewUser (user1) -> user1.set('role', 'teacher') user1.save (err) -> data = { name: 'Classroom 6' } request.post {uri: classroomsURL, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) url = classroomsURL + '/' + body._id + '/invite-members' data = { emails: ['PI:EMAIL:<EMAIL>END_PI'] } request.post { uri: url, json: data }, (err, res, body) -> expect(res.statusCode).toBe(200) done() describe 'GET /db/classroom/:handle/member-sessions', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom, LevelSession, Level]) @artisan = yield utils.initUser() @teacher = yield utils.initUser() @student1 = yield utils.initUser() @student2 = yield utils.initUser() @levelA = new Level({name: 'Level A', permissions: [{target: @artisan._id, access: 'owner'}]}) @levelA.set('original', @levelA._id) @levelA = yield @levelA.save() @levelB = new Level({name: 'Level B', permissions: [{target: @artisan._id, access: 'owner'}]}) @levelB.set('original', @levelB._id) @levelB = yield @levelB.save() @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @session1A = yield new LevelSession({creator: @student1.id, state: { complete: true }, level: {original: @levelA._id}, permissions: [{target: @student1._id, access: 'owner'}]}).save() @session1B = yield new LevelSession({creator: @student1.id, state: { complete: false }, level: {original: @levelB._id}, permissions: [{target: @student1._id, access: 'owner'}]}).save() @session2A = yield new LevelSession({creator: @student2.id, state: { complete: true }, level: {original: @levelA._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save() @session2B = yield new LevelSession({creator: @student2.id, state: { complete: false }, level: {original: @levelB._id}, permissions: [{target: @student2._id, access: 'owner'}]}).save() done() it 'returns all sessions for all members in the classroom with only properties level, creator and state.complete', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(4) done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'accepts memberSkip and memberLimit GET parameters', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberLimit=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student1.id) for session in body [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions?memberSkip=1"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) expect(session.creator).toBe(@student2.id) for session in body done() describe 'GET /db/classroom/:handle/members', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User, Classroom]) @teacher = yield utils.initUser() @student1 = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI" }) @student2 = yield utils.initUser({ name: "PI:NAME:<NAME>END_PI" }) @classroom = yield new Classroom({name: 'Classroom', ownerID: @teacher._id, members: [@student1._id, @student2._id] }).save() @emptyClassroom = yield new Classroom({name: 'Empty Classroom', ownerID: @teacher._id, members: [] }).save() done() it 'does not work if you are not the owner of the classroom', utils.wrap (done) -> yield utils.loginUser(@student1) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(403) done() it 'does not work if you are not logged in', utils.wrap (done) -> [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/member-sessions"), { json: true } expect(res.statusCode).toBe(401) done() it 'works on an empty classroom', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@emptyClassroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body).toEqual([]) done() it 'returns all members with name and email', utils.wrap (done) -> yield utils.loginUser(@teacher) [res, body] = yield request.getAsync getURL("/db/classroom/#{@classroom.id}/members?name=true&email=true"), { json: true } expect(res.statusCode).toBe(200) expect(body.length).toBe(2) for user in body expect(user.name).toBeDefined() expect(user.email).toBeDefined() expect(user.passwordHash).toBeUndefined() done()
[ { "context": "a-11e5-a51a-f5a1e8cbbcce'\nGITHUB_CLIENT_SECRET = 'f01b0f2f-947a-467b-ad41-dcae8fe6ed7c'\n# Passport session setup.\n# To support persist", "end": 245, "score": 0.9945878386497498, "start": 209, "tag": "KEY", "value": "f01b0f2f-947a-467b-ad41-dcae8fe6ed7c" }, { "context": "ck\napp.get '/auth/github', passport.authenticate('teambition'), (req, res) ->\n # The request will be redirect", "end": 3243, "score": 0.9343981146812439, "start": 3233, "tag": "USERNAME", "value": "teambition" }, { "context": "t '/auth/github/callback', passport.authenticate('teambition', failureRedirect: '/login'), (req, res) ->\n res", "end": 3770, "score": 0.9088348746299744, "start": 3760, "tag": "USERNAME", "value": "teambition" } ]
example/app.coffee
trevorwang/passport-teambition
0
express = require('express') passport = require('passport') util = require('util') GitHubStrategy = require('../src').Strategy GITHUB_CLIENT_ID = '88fc4f30-983a-11e5-a51a-f5a1e8cbbcce' GITHUB_CLIENT_SECRET = 'f01b0f2f-947a-467b-ad41-dcae8fe6ed7c' # Passport session setup. # To support persistent login sessions, Passport needs to be able to # serialize users into and deserialize users out of the session. Typically, # this will be as simple as storing the user ID when serializing, and finding # the user by ID when deserializing. However, since this example does not # have a database of user records, the complete GitHub profile is serialized # and deserialized. # Simple route middleware to ensure user is authenticated. # Use this route middleware on any resource that needs to be protected. If # the request is authenticated (typically via a persistent login session), # the request will proceed. Otherwise, the user will be redirected to the # login page. ensureAuthenticated = (req, res, next) -> if req.isAuthenticated() return next() res.redirect '/login' return passport.serializeUser (user, done) -> done null, user return passport.deserializeUser (obj, done) -> done null, obj return # Use the GitHubStrategy within Passport. # Strategies in Passport require a `verify` function, which accept # credentials (in this case, an accessToken, refreshToken, and GitHub # profile), and invoke a callback with a user object. passport.use new GitHubStrategy({ clientID: GITHUB_CLIENT_ID clientSecret: GITHUB_CLIENT_SECRET callbackURL: 'http://localhost:3000/auth/github/callback' }, (accessToken, refreshToken, profile, done) -> # asynchronous verification, for effect... process.nextTick -> # To keep the example simple, the user's GitHub profile is returned to # represent the logged-in user. In a typical application, you would want # to associate the GitHub account with a user record in your database, # and return that user instead. done null, profile return ) app = express.createServer() # configure Express app.configure -> app.set 'views', __dirname + '/views' app.set 'view engine', 'ejs' app.use express.logger() app.use express.cookieParser() app.use express.bodyParser() app.use express.methodOverride() app.use express.session(secret: 'keyboard cat') # Initialize Passport! Also use passport.session() middleware, to support # persistent login sessions (recommended). app.use passport.initialize() app.use passport.session() app.use app.router app.use express.static(__dirname + '/public') return app.get '/', (req, res) -> res.render 'index', user: req.user return app.get '/account', ensureAuthenticated, (req, res) -> res.render 'account', user: req.user return app.get '/login', (req, res) -> res.render 'login', user: req.user return # GET /auth/github # Use passport.authenticate() as route middleware to authenticate the # request. The first step in GitHub authentication will involve redirecting # the user to github.com. After authorization, GitHubwill redirect the user # back to this application at /auth/github/callback app.get '/auth/github', passport.authenticate('teambition'), (req, res) -> # The request will be redirected to GitHub for authentication, so this # function will not be called. return # GET /auth/github/callback # Use passport.authenticate() as route middleware to authenticate the # request. If authentication fails, the user will be redirected back to the # login page. Otherwise, the primary route function function will be called, # which, in this example, will redirect the user to the home page. app.get '/auth/github/callback', passport.authenticate('teambition', failureRedirect: '/login'), (req, res) -> res.redirect '/' return app.get '/logout', (req, res) -> req.logout() res.redirect '/' return app.listen 3000
45227
express = require('express') passport = require('passport') util = require('util') GitHubStrategy = require('../src').Strategy GITHUB_CLIENT_ID = '88fc4f30-983a-11e5-a51a-f5a1e8cbbcce' GITHUB_CLIENT_SECRET = '<KEY>' # Passport session setup. # To support persistent login sessions, Passport needs to be able to # serialize users into and deserialize users out of the session. Typically, # this will be as simple as storing the user ID when serializing, and finding # the user by ID when deserializing. However, since this example does not # have a database of user records, the complete GitHub profile is serialized # and deserialized. # Simple route middleware to ensure user is authenticated. # Use this route middleware on any resource that needs to be protected. If # the request is authenticated (typically via a persistent login session), # the request will proceed. Otherwise, the user will be redirected to the # login page. ensureAuthenticated = (req, res, next) -> if req.isAuthenticated() return next() res.redirect '/login' return passport.serializeUser (user, done) -> done null, user return passport.deserializeUser (obj, done) -> done null, obj return # Use the GitHubStrategy within Passport. # Strategies in Passport require a `verify` function, which accept # credentials (in this case, an accessToken, refreshToken, and GitHub # profile), and invoke a callback with a user object. passport.use new GitHubStrategy({ clientID: GITHUB_CLIENT_ID clientSecret: GITHUB_CLIENT_SECRET callbackURL: 'http://localhost:3000/auth/github/callback' }, (accessToken, refreshToken, profile, done) -> # asynchronous verification, for effect... process.nextTick -> # To keep the example simple, the user's GitHub profile is returned to # represent the logged-in user. In a typical application, you would want # to associate the GitHub account with a user record in your database, # and return that user instead. done null, profile return ) app = express.createServer() # configure Express app.configure -> app.set 'views', __dirname + '/views' app.set 'view engine', 'ejs' app.use express.logger() app.use express.cookieParser() app.use express.bodyParser() app.use express.methodOverride() app.use express.session(secret: 'keyboard cat') # Initialize Passport! Also use passport.session() middleware, to support # persistent login sessions (recommended). app.use passport.initialize() app.use passport.session() app.use app.router app.use express.static(__dirname + '/public') return app.get '/', (req, res) -> res.render 'index', user: req.user return app.get '/account', ensureAuthenticated, (req, res) -> res.render 'account', user: req.user return app.get '/login', (req, res) -> res.render 'login', user: req.user return # GET /auth/github # Use passport.authenticate() as route middleware to authenticate the # request. The first step in GitHub authentication will involve redirecting # the user to github.com. After authorization, GitHubwill redirect the user # back to this application at /auth/github/callback app.get '/auth/github', passport.authenticate('teambition'), (req, res) -> # The request will be redirected to GitHub for authentication, so this # function will not be called. return # GET /auth/github/callback # Use passport.authenticate() as route middleware to authenticate the # request. If authentication fails, the user will be redirected back to the # login page. Otherwise, the primary route function function will be called, # which, in this example, will redirect the user to the home page. app.get '/auth/github/callback', passport.authenticate('teambition', failureRedirect: '/login'), (req, res) -> res.redirect '/' return app.get '/logout', (req, res) -> req.logout() res.redirect '/' return app.listen 3000
true
express = require('express') passport = require('passport') util = require('util') GitHubStrategy = require('../src').Strategy GITHUB_CLIENT_ID = '88fc4f30-983a-11e5-a51a-f5a1e8cbbcce' GITHUB_CLIENT_SECRET = 'PI:KEY:<KEY>END_PI' # Passport session setup. # To support persistent login sessions, Passport needs to be able to # serialize users into and deserialize users out of the session. Typically, # this will be as simple as storing the user ID when serializing, and finding # the user by ID when deserializing. However, since this example does not # have a database of user records, the complete GitHub profile is serialized # and deserialized. # Simple route middleware to ensure user is authenticated. # Use this route middleware on any resource that needs to be protected. If # the request is authenticated (typically via a persistent login session), # the request will proceed. Otherwise, the user will be redirected to the # login page. ensureAuthenticated = (req, res, next) -> if req.isAuthenticated() return next() res.redirect '/login' return passport.serializeUser (user, done) -> done null, user return passport.deserializeUser (obj, done) -> done null, obj return # Use the GitHubStrategy within Passport. # Strategies in Passport require a `verify` function, which accept # credentials (in this case, an accessToken, refreshToken, and GitHub # profile), and invoke a callback with a user object. passport.use new GitHubStrategy({ clientID: GITHUB_CLIENT_ID clientSecret: GITHUB_CLIENT_SECRET callbackURL: 'http://localhost:3000/auth/github/callback' }, (accessToken, refreshToken, profile, done) -> # asynchronous verification, for effect... process.nextTick -> # To keep the example simple, the user's GitHub profile is returned to # represent the logged-in user. In a typical application, you would want # to associate the GitHub account with a user record in your database, # and return that user instead. done null, profile return ) app = express.createServer() # configure Express app.configure -> app.set 'views', __dirname + '/views' app.set 'view engine', 'ejs' app.use express.logger() app.use express.cookieParser() app.use express.bodyParser() app.use express.methodOverride() app.use express.session(secret: 'keyboard cat') # Initialize Passport! Also use passport.session() middleware, to support # persistent login sessions (recommended). app.use passport.initialize() app.use passport.session() app.use app.router app.use express.static(__dirname + '/public') return app.get '/', (req, res) -> res.render 'index', user: req.user return app.get '/account', ensureAuthenticated, (req, res) -> res.render 'account', user: req.user return app.get '/login', (req, res) -> res.render 'login', user: req.user return # GET /auth/github # Use passport.authenticate() as route middleware to authenticate the # request. The first step in GitHub authentication will involve redirecting # the user to github.com. After authorization, GitHubwill redirect the user # back to this application at /auth/github/callback app.get '/auth/github', passport.authenticate('teambition'), (req, res) -> # The request will be redirected to GitHub for authentication, so this # function will not be called. return # GET /auth/github/callback # Use passport.authenticate() as route middleware to authenticate the # request. If authentication fails, the user will be redirected back to the # login page. Otherwise, the primary route function function will be called, # which, in this example, will redirect the user to the home page. app.get '/auth/github/callback', passport.authenticate('teambition', failureRedirect: '/login'), (req, res) -> res.redirect '/' return app.get '/logout', (req, res) -> req.logout() res.redirect '/' return app.listen 3000
[ { "context": "d @, card._id\n card: card,\n key: card._id\n ,\n (Editing\n cardid: ", "end": 1868, "score": 0.934030294418335, "start": 1860, "tag": "KEY", "value": "card._id" } ]
main.coffee
fiatjaf/youfle
1
YAML = require './yaml.coffee' cardStore = require './cardStore.coffee' dispatcher = require './dispatcher.coffee' {div, span, pre, small, i, p, a, button, h1, h2, h3, h4, form, legend, fieldset, input, textarea, select ul, li} = React.DOM Board = React.createClass displayName: 'Board' getInitialState: -> cardsByType: {} editingCardId: null viewingCardId: null componentDidMount: -> @fetchCards() cardStore.on 'CHANGE', @fetchCards componentWillUnmount: -> cardStore.off 'CHANGE', @fetchCards fetchCards: -> cardStore.allCards().then (cardsByType) => @setState cardsByType: cardsByType i: 0 # trello-like scrolling dragStart: (e) -> if e.target == @getDOMNode() @setState dragging: true startCoords: pageX: e.pageX pageY: e.pageY clientX: e.clientX clientY: e.clientY drag: (e) -> if @state.dragging e.preventDefault() @i++ if @i % 3 == 0 dx = @state.startCoords.pageX - e.pageX dy = @state.startCoords.pageY - e.pageY ax = window.pageXOffset || document.documentElement.scrollLeft ay = window.pageYOffset || document.documentElement.scrollTop window.scrollTo ax+dx, ay+dy dragEnd: -> if @state.dragging @setState dragging: false render: -> (div id: 'board' style: width: 310 * (Object.keys(@state.cardsByType).length + 1) + 400 onMouseDown: @dragStart onMouseMove: @drag onMouseUp: @dragEnd onMouseOut: @dragEnd , (List key: type onDropCard: @handleCardDropped.bind @, type , (Card editing: (@state.editingCardId == card._id) onView: @viewCard.bind @, card._id onEdit: @editCard.bind @, card._id card: card, key: card._id , (Editing cardid: card._id onCancel: @editCard.bind @, null ) ) for card in cards (div className: 'card', (Editing type: type template: @templates[type] if @templates ) ) ) for type, cards of @state.cardsByType (button onClick: @addCard , 'Add card') (View cardid: @state.viewingCardId onStopViewing: @viewCard.bind @, null onView: @viewCard ) if @state.viewingCardId ) viewCard: (cardid) -> @setState viewingCardId: cardid editCard: (cardid) -> @setState editingCardId: cardid handleCardDropped: (listName, e) -> cardStore.get(e.dataTransfer.getData 'cardId').then (draggedCard) => draggedCard.type = listName cardStore.save(draggedCard) addCard: -> type = prompt 'Which type?' cardStore.save({type: type}) List = React.createClass displayName: 'List' getInitialState: -> height: '' onCardBeingDragged: (cardType) -> if cardType and cardType == @props.key return @setState height: "#{@getDOMNode().offsetHeight + 200}px" onCardNotBeingDraggedAnymore: -> @setState height: '' componentDidMount: -> dispatcher.on 'card.dragstart', @onCardBeingDragged dispatcher.on 'card.dragend', @onCardNotBeingDraggedAnymore componentWillUnmount: -> dispatcher.off 'card.dragstart', @onCardBeingDragged dispatcher.off 'card.dragend', @onCardNotBeingDraggedAnymore dragOver: (e) -> e.preventDefault() drop: (e) -> e.stopPropagation() draggedCardId = e.dataTransfer.getData 'cardId' @props.onDropCard e @setState height: '' render: -> (div className: "list" onDragOver: @dragOver onDragEnter: @dragEnter onDragLeave: @dragLeave onDrop: @drop style: height: @state.height , (h3 {}, @props.key) @props.children ) Card = React.createClass displayName: 'Card' getInitialState: -> {} dragStart: (e) -> dispatcher.emit 'card.dragstart', @props.card.type e.dataTransfer.setData 'cardId', @props.card._id @setState dragging: true dragEnd: -> dispatcher.emit 'card.dragend' render: -> yamlString = YAML.stringifyCard @props.card if @props.editing content = @props.children else content = (div className: 'listed' onClick: @handleClick , (pre className: if @state.dragging then 'dragging' else '' onClick: @props.onView draggable: true onDragStart: @dragStart onDragEnd: @dragEnd ref: 'pre' , yamlString) ) (div className: 'card' , (h4 {onDoubleClick: @props.onEdit}, @props.card._id) content ) View = React.createClass displayName: 'View' getInitialState: -> card: {} referred: {} referring: {} loadCard: -> cardStore.getWithRefs(@props.cardid).then (result) => {card, referred, referring} = result @setState card: card referred: referred referring: referring componentDidMount: -> @loadCard() componentDidUpdate: (prevProps) -> if @props.cardid != prevProps.cardid @loadCard() render: -> (div onClick: @props.onStopViewing className: 'view overlay', , (div className: 'referring', (div {}, (h3 {}, at) (pre key: card._id onClick: @jumpToCard.bind @, card._id , YAML.stringifyCard card) for card in cards ) for at, cards of @state.referring ) (div className: 'focus', (div onClick: @nothing, (pre {}, YAML.stringifyCard @state.card) ) ) (div className: 'referred', (div {}, (h3 {}, at) (pre key: card._id onClick: @jumpToCard.bind @, card._id , YAML.stringifyCard card) for card in cards ) for at, cards of @state.referred ) ) jumpToCard: (id, e) -> @nothing e @props.onView id nothing: (e) -> e.preventDefault() e.stopPropagation() Editing = React.createClass displayName: 'Editing' getInitialState: -> textareaSize: 100 componentWillMount: -> if @props.cardid @loadCard @props.cardid loadCard: (cardid) -> cardStore.get(cardid).then (card) => @setState card: card yamlString: YAML.stringifyCard card save: (e) -> e.preventDefault() card = YAML.parseCard @state.yamlString, @state.card cardStore.save(card) delete: (e) -> e.preventDefault() if confirm 'Are you sure you want to delete ' + @state.card._id + '?' cardStore.delete(@state.card) handleClickAddNewCard: (e) -> e.preventDefault() card = @props.template or {type: @props.type} card.type = @props.type @setState card: card yamlString: YAML.stringifyCard card handleChange: (e) -> @setState yamlString: e.target.value handleCancel: (e) -> e.preventDefault() if @props.onCancel @props.onCancel() else @setState card: null render: -> if not @state.card and not @props.cardid return (button className: 'pure-button new-card' onClick: @handleClickAddNewCard , "create new #{@props.type} card") else if @state.card textareaHeight = @state.yamlString.split('\n').length * 18 return (div className: 'editing', (form className: 'pure-form pure-form-stacked', (fieldset className: 'main', (h3 {}, if not @state.card._id then "new #{@state.card.type} card" else 'new') (textarea value: @state.yamlString onChange: @handleChange style: minHeight: if textareaHeight < 100 then 100 else textareaHeight ) ) (fieldset {}, (button className: 'pure-button cancel' onClick: @handleCancel , 'Cancel') (button className: 'pure-button delete' onClick: @delete , 'Delete') if @props.cardid (button className: 'pure-button save' onClick: @save , 'Save') ) ) ) else return (div {}) Main = React.createClass displayName: 'Main' reset: (e) -> e.preventDefault() cardStore.reset().then(location.reload) render: -> (div {id: 'main'}, (button className: 'pure-button' onClick: @reset , 'RESET') (Board {}) ) React.renderComponent Main(), document.body
159466
YAML = require './yaml.coffee' cardStore = require './cardStore.coffee' dispatcher = require './dispatcher.coffee' {div, span, pre, small, i, p, a, button, h1, h2, h3, h4, form, legend, fieldset, input, textarea, select ul, li} = React.DOM Board = React.createClass displayName: 'Board' getInitialState: -> cardsByType: {} editingCardId: null viewingCardId: null componentDidMount: -> @fetchCards() cardStore.on 'CHANGE', @fetchCards componentWillUnmount: -> cardStore.off 'CHANGE', @fetchCards fetchCards: -> cardStore.allCards().then (cardsByType) => @setState cardsByType: cardsByType i: 0 # trello-like scrolling dragStart: (e) -> if e.target == @getDOMNode() @setState dragging: true startCoords: pageX: e.pageX pageY: e.pageY clientX: e.clientX clientY: e.clientY drag: (e) -> if @state.dragging e.preventDefault() @i++ if @i % 3 == 0 dx = @state.startCoords.pageX - e.pageX dy = @state.startCoords.pageY - e.pageY ax = window.pageXOffset || document.documentElement.scrollLeft ay = window.pageYOffset || document.documentElement.scrollTop window.scrollTo ax+dx, ay+dy dragEnd: -> if @state.dragging @setState dragging: false render: -> (div id: 'board' style: width: 310 * (Object.keys(@state.cardsByType).length + 1) + 400 onMouseDown: @dragStart onMouseMove: @drag onMouseUp: @dragEnd onMouseOut: @dragEnd , (List key: type onDropCard: @handleCardDropped.bind @, type , (Card editing: (@state.editingCardId == card._id) onView: @viewCard.bind @, card._id onEdit: @editCard.bind @, card._id card: card, key: <KEY> , (Editing cardid: card._id onCancel: @editCard.bind @, null ) ) for card in cards (div className: 'card', (Editing type: type template: @templates[type] if @templates ) ) ) for type, cards of @state.cardsByType (button onClick: @addCard , 'Add card') (View cardid: @state.viewingCardId onStopViewing: @viewCard.bind @, null onView: @viewCard ) if @state.viewingCardId ) viewCard: (cardid) -> @setState viewingCardId: cardid editCard: (cardid) -> @setState editingCardId: cardid handleCardDropped: (listName, e) -> cardStore.get(e.dataTransfer.getData 'cardId').then (draggedCard) => draggedCard.type = listName cardStore.save(draggedCard) addCard: -> type = prompt 'Which type?' cardStore.save({type: type}) List = React.createClass displayName: 'List' getInitialState: -> height: '' onCardBeingDragged: (cardType) -> if cardType and cardType == @props.key return @setState height: "#{@getDOMNode().offsetHeight + 200}px" onCardNotBeingDraggedAnymore: -> @setState height: '' componentDidMount: -> dispatcher.on 'card.dragstart', @onCardBeingDragged dispatcher.on 'card.dragend', @onCardNotBeingDraggedAnymore componentWillUnmount: -> dispatcher.off 'card.dragstart', @onCardBeingDragged dispatcher.off 'card.dragend', @onCardNotBeingDraggedAnymore dragOver: (e) -> e.preventDefault() drop: (e) -> e.stopPropagation() draggedCardId = e.dataTransfer.getData 'cardId' @props.onDropCard e @setState height: '' render: -> (div className: "list" onDragOver: @dragOver onDragEnter: @dragEnter onDragLeave: @dragLeave onDrop: @drop style: height: @state.height , (h3 {}, @props.key) @props.children ) Card = React.createClass displayName: 'Card' getInitialState: -> {} dragStart: (e) -> dispatcher.emit 'card.dragstart', @props.card.type e.dataTransfer.setData 'cardId', @props.card._id @setState dragging: true dragEnd: -> dispatcher.emit 'card.dragend' render: -> yamlString = YAML.stringifyCard @props.card if @props.editing content = @props.children else content = (div className: 'listed' onClick: @handleClick , (pre className: if @state.dragging then 'dragging' else '' onClick: @props.onView draggable: true onDragStart: @dragStart onDragEnd: @dragEnd ref: 'pre' , yamlString) ) (div className: 'card' , (h4 {onDoubleClick: @props.onEdit}, @props.card._id) content ) View = React.createClass displayName: 'View' getInitialState: -> card: {} referred: {} referring: {} loadCard: -> cardStore.getWithRefs(@props.cardid).then (result) => {card, referred, referring} = result @setState card: card referred: referred referring: referring componentDidMount: -> @loadCard() componentDidUpdate: (prevProps) -> if @props.cardid != prevProps.cardid @loadCard() render: -> (div onClick: @props.onStopViewing className: 'view overlay', , (div className: 'referring', (div {}, (h3 {}, at) (pre key: card._id onClick: @jumpToCard.bind @, card._id , YAML.stringifyCard card) for card in cards ) for at, cards of @state.referring ) (div className: 'focus', (div onClick: @nothing, (pre {}, YAML.stringifyCard @state.card) ) ) (div className: 'referred', (div {}, (h3 {}, at) (pre key: card._id onClick: @jumpToCard.bind @, card._id , YAML.stringifyCard card) for card in cards ) for at, cards of @state.referred ) ) jumpToCard: (id, e) -> @nothing e @props.onView id nothing: (e) -> e.preventDefault() e.stopPropagation() Editing = React.createClass displayName: 'Editing' getInitialState: -> textareaSize: 100 componentWillMount: -> if @props.cardid @loadCard @props.cardid loadCard: (cardid) -> cardStore.get(cardid).then (card) => @setState card: card yamlString: YAML.stringifyCard card save: (e) -> e.preventDefault() card = YAML.parseCard @state.yamlString, @state.card cardStore.save(card) delete: (e) -> e.preventDefault() if confirm 'Are you sure you want to delete ' + @state.card._id + '?' cardStore.delete(@state.card) handleClickAddNewCard: (e) -> e.preventDefault() card = @props.template or {type: @props.type} card.type = @props.type @setState card: card yamlString: YAML.stringifyCard card handleChange: (e) -> @setState yamlString: e.target.value handleCancel: (e) -> e.preventDefault() if @props.onCancel @props.onCancel() else @setState card: null render: -> if not @state.card and not @props.cardid return (button className: 'pure-button new-card' onClick: @handleClickAddNewCard , "create new #{@props.type} card") else if @state.card textareaHeight = @state.yamlString.split('\n').length * 18 return (div className: 'editing', (form className: 'pure-form pure-form-stacked', (fieldset className: 'main', (h3 {}, if not @state.card._id then "new #{@state.card.type} card" else 'new') (textarea value: @state.yamlString onChange: @handleChange style: minHeight: if textareaHeight < 100 then 100 else textareaHeight ) ) (fieldset {}, (button className: 'pure-button cancel' onClick: @handleCancel , 'Cancel') (button className: 'pure-button delete' onClick: @delete , 'Delete') if @props.cardid (button className: 'pure-button save' onClick: @save , 'Save') ) ) ) else return (div {}) Main = React.createClass displayName: 'Main' reset: (e) -> e.preventDefault() cardStore.reset().then(location.reload) render: -> (div {id: 'main'}, (button className: 'pure-button' onClick: @reset , 'RESET') (Board {}) ) React.renderComponent Main(), document.body
true
YAML = require './yaml.coffee' cardStore = require './cardStore.coffee' dispatcher = require './dispatcher.coffee' {div, span, pre, small, i, p, a, button, h1, h2, h3, h4, form, legend, fieldset, input, textarea, select ul, li} = React.DOM Board = React.createClass displayName: 'Board' getInitialState: -> cardsByType: {} editingCardId: null viewingCardId: null componentDidMount: -> @fetchCards() cardStore.on 'CHANGE', @fetchCards componentWillUnmount: -> cardStore.off 'CHANGE', @fetchCards fetchCards: -> cardStore.allCards().then (cardsByType) => @setState cardsByType: cardsByType i: 0 # trello-like scrolling dragStart: (e) -> if e.target == @getDOMNode() @setState dragging: true startCoords: pageX: e.pageX pageY: e.pageY clientX: e.clientX clientY: e.clientY drag: (e) -> if @state.dragging e.preventDefault() @i++ if @i % 3 == 0 dx = @state.startCoords.pageX - e.pageX dy = @state.startCoords.pageY - e.pageY ax = window.pageXOffset || document.documentElement.scrollLeft ay = window.pageYOffset || document.documentElement.scrollTop window.scrollTo ax+dx, ay+dy dragEnd: -> if @state.dragging @setState dragging: false render: -> (div id: 'board' style: width: 310 * (Object.keys(@state.cardsByType).length + 1) + 400 onMouseDown: @dragStart onMouseMove: @drag onMouseUp: @dragEnd onMouseOut: @dragEnd , (List key: type onDropCard: @handleCardDropped.bind @, type , (Card editing: (@state.editingCardId == card._id) onView: @viewCard.bind @, card._id onEdit: @editCard.bind @, card._id card: card, key: PI:KEY:<KEY>END_PI , (Editing cardid: card._id onCancel: @editCard.bind @, null ) ) for card in cards (div className: 'card', (Editing type: type template: @templates[type] if @templates ) ) ) for type, cards of @state.cardsByType (button onClick: @addCard , 'Add card') (View cardid: @state.viewingCardId onStopViewing: @viewCard.bind @, null onView: @viewCard ) if @state.viewingCardId ) viewCard: (cardid) -> @setState viewingCardId: cardid editCard: (cardid) -> @setState editingCardId: cardid handleCardDropped: (listName, e) -> cardStore.get(e.dataTransfer.getData 'cardId').then (draggedCard) => draggedCard.type = listName cardStore.save(draggedCard) addCard: -> type = prompt 'Which type?' cardStore.save({type: type}) List = React.createClass displayName: 'List' getInitialState: -> height: '' onCardBeingDragged: (cardType) -> if cardType and cardType == @props.key return @setState height: "#{@getDOMNode().offsetHeight + 200}px" onCardNotBeingDraggedAnymore: -> @setState height: '' componentDidMount: -> dispatcher.on 'card.dragstart', @onCardBeingDragged dispatcher.on 'card.dragend', @onCardNotBeingDraggedAnymore componentWillUnmount: -> dispatcher.off 'card.dragstart', @onCardBeingDragged dispatcher.off 'card.dragend', @onCardNotBeingDraggedAnymore dragOver: (e) -> e.preventDefault() drop: (e) -> e.stopPropagation() draggedCardId = e.dataTransfer.getData 'cardId' @props.onDropCard e @setState height: '' render: -> (div className: "list" onDragOver: @dragOver onDragEnter: @dragEnter onDragLeave: @dragLeave onDrop: @drop style: height: @state.height , (h3 {}, @props.key) @props.children ) Card = React.createClass displayName: 'Card' getInitialState: -> {} dragStart: (e) -> dispatcher.emit 'card.dragstart', @props.card.type e.dataTransfer.setData 'cardId', @props.card._id @setState dragging: true dragEnd: -> dispatcher.emit 'card.dragend' render: -> yamlString = YAML.stringifyCard @props.card if @props.editing content = @props.children else content = (div className: 'listed' onClick: @handleClick , (pre className: if @state.dragging then 'dragging' else '' onClick: @props.onView draggable: true onDragStart: @dragStart onDragEnd: @dragEnd ref: 'pre' , yamlString) ) (div className: 'card' , (h4 {onDoubleClick: @props.onEdit}, @props.card._id) content ) View = React.createClass displayName: 'View' getInitialState: -> card: {} referred: {} referring: {} loadCard: -> cardStore.getWithRefs(@props.cardid).then (result) => {card, referred, referring} = result @setState card: card referred: referred referring: referring componentDidMount: -> @loadCard() componentDidUpdate: (prevProps) -> if @props.cardid != prevProps.cardid @loadCard() render: -> (div onClick: @props.onStopViewing className: 'view overlay', , (div className: 'referring', (div {}, (h3 {}, at) (pre key: card._id onClick: @jumpToCard.bind @, card._id , YAML.stringifyCard card) for card in cards ) for at, cards of @state.referring ) (div className: 'focus', (div onClick: @nothing, (pre {}, YAML.stringifyCard @state.card) ) ) (div className: 'referred', (div {}, (h3 {}, at) (pre key: card._id onClick: @jumpToCard.bind @, card._id , YAML.stringifyCard card) for card in cards ) for at, cards of @state.referred ) ) jumpToCard: (id, e) -> @nothing e @props.onView id nothing: (e) -> e.preventDefault() e.stopPropagation() Editing = React.createClass displayName: 'Editing' getInitialState: -> textareaSize: 100 componentWillMount: -> if @props.cardid @loadCard @props.cardid loadCard: (cardid) -> cardStore.get(cardid).then (card) => @setState card: card yamlString: YAML.stringifyCard card save: (e) -> e.preventDefault() card = YAML.parseCard @state.yamlString, @state.card cardStore.save(card) delete: (e) -> e.preventDefault() if confirm 'Are you sure you want to delete ' + @state.card._id + '?' cardStore.delete(@state.card) handleClickAddNewCard: (e) -> e.preventDefault() card = @props.template or {type: @props.type} card.type = @props.type @setState card: card yamlString: YAML.stringifyCard card handleChange: (e) -> @setState yamlString: e.target.value handleCancel: (e) -> e.preventDefault() if @props.onCancel @props.onCancel() else @setState card: null render: -> if not @state.card and not @props.cardid return (button className: 'pure-button new-card' onClick: @handleClickAddNewCard , "create new #{@props.type} card") else if @state.card textareaHeight = @state.yamlString.split('\n').length * 18 return (div className: 'editing', (form className: 'pure-form pure-form-stacked', (fieldset className: 'main', (h3 {}, if not @state.card._id then "new #{@state.card.type} card" else 'new') (textarea value: @state.yamlString onChange: @handleChange style: minHeight: if textareaHeight < 100 then 100 else textareaHeight ) ) (fieldset {}, (button className: 'pure-button cancel' onClick: @handleCancel , 'Cancel') (button className: 'pure-button delete' onClick: @delete , 'Delete') if @props.cardid (button className: 'pure-button save' onClick: @save , 'Save') ) ) ) else return (div {}) Main = React.createClass displayName: 'Main' reset: (e) -> e.preventDefault() cardStore.reset().then(location.reload) render: -> (div {id: 'main'}, (button className: 'pure-button' onClick: @reset , 'RESET') (Board {}) ) React.renderComponent Main(), document.body
[ { "context": "ieldView\n role: RoleFieldView\n username: UsernameFieldView\n password: UserPasswordFieldView\n passw", "end": 2324, "score": 0.9987092018127441, "start": 2307, "tag": "USERNAME", "value": "UsernameFieldView" }, { "context": "\n username: UsernameFieldView\n password: UserPasswordFieldView\n password_confirm: UserPasswordConfirmFieldV", "end": 2362, "score": 0.9992294907569885, "start": 2341, "tag": "PASSWORD", "value": "UserPasswordFieldView" }, { "context": " 'last_name'\n 'email'\n 'role'\n 'username'\n 'password'\n 'password_confirm'\n ]\n", "end": 2521, "score": 0.9993563294410706, "start": 2513, "tag": "USERNAME", "value": "username" } ]
app/scripts/views/user-add-widget.coffee
OpenSourceFieldlinguistics/dative
7
define [ './resource-add-widget' './textarea-field' './password-field' './select-field' './relational-select-field' './script-field' './../models/user' './../utils/globals' ], (ResourceAddWidgetView, TextareaFieldView, PasswordFieldView, SelectFieldView, RelationalSelectFieldView, ScriptFieldView, UserModel, globals) -> imAdmin = -> try globals.applicationSettings.get('loggedInUser').role is 'administrator' catch false class TextareaFieldView255 extends TextareaFieldView initialize: (options) -> options.domAttributes = maxlength: 255 super options # A <select>-based field view for the markup language select field. class MarkupLanguageFieldView extends SelectFieldView initialize: (options) -> options.required = true options.selectValueGetter = (o) -> o options.selectTextGetter = (o) -> o super options class UsernameFieldView extends TextareaFieldView255 visibilityCondition: -> imAdmin() # A <select>-based field view for the markup language select field. class RoleFieldView extends SelectFieldView initialize: (options) -> options.required = true options.selectValueGetter = (o) -> o options.selectTextGetter = (o) -> o super options visibilityCondition: -> imAdmin() class UserPasswordFieldView extends PasswordFieldView visibilityCondition: -> @imAdminOrImResource() class UserPasswordConfirmFieldView extends UserPasswordFieldView visibilityCondition: -> @imAdminOrImResource() initialize: (options={}) -> options.confirmField = true super options # User Add Widget View # -------------------------- # # View for a widget containing inputs and controls for creating a new # user and updating an existing one. ############################################################################## # User Add Widget ############################################################################## class UserAddWidgetView extends ResourceAddWidgetView resourceName: 'user' resourceModel: UserModel attribute2fieldView: name: TextareaFieldView255 page_content: ScriptFieldView markup_language: MarkupLanguageFieldView role: RoleFieldView username: UsernameFieldView password: UserPasswordFieldView password_confirm: UserPasswordConfirmFieldView primaryAttributes: [ 'first_name' 'last_name' 'email' 'role' 'username' 'password' 'password_confirm' ] editableSecondaryAttributes: [ 'affiliation' 'markup_language' 'page_content' ] getNewResourceData: -> console.log 'in getNewResourceData' super
38682
define [ './resource-add-widget' './textarea-field' './password-field' './select-field' './relational-select-field' './script-field' './../models/user' './../utils/globals' ], (ResourceAddWidgetView, TextareaFieldView, PasswordFieldView, SelectFieldView, RelationalSelectFieldView, ScriptFieldView, UserModel, globals) -> imAdmin = -> try globals.applicationSettings.get('loggedInUser').role is 'administrator' catch false class TextareaFieldView255 extends TextareaFieldView initialize: (options) -> options.domAttributes = maxlength: 255 super options # A <select>-based field view for the markup language select field. class MarkupLanguageFieldView extends SelectFieldView initialize: (options) -> options.required = true options.selectValueGetter = (o) -> o options.selectTextGetter = (o) -> o super options class UsernameFieldView extends TextareaFieldView255 visibilityCondition: -> imAdmin() # A <select>-based field view for the markup language select field. class RoleFieldView extends SelectFieldView initialize: (options) -> options.required = true options.selectValueGetter = (o) -> o options.selectTextGetter = (o) -> o super options visibilityCondition: -> imAdmin() class UserPasswordFieldView extends PasswordFieldView visibilityCondition: -> @imAdminOrImResource() class UserPasswordConfirmFieldView extends UserPasswordFieldView visibilityCondition: -> @imAdminOrImResource() initialize: (options={}) -> options.confirmField = true super options # User Add Widget View # -------------------------- # # View for a widget containing inputs and controls for creating a new # user and updating an existing one. ############################################################################## # User Add Widget ############################################################################## class UserAddWidgetView extends ResourceAddWidgetView resourceName: 'user' resourceModel: UserModel attribute2fieldView: name: TextareaFieldView255 page_content: ScriptFieldView markup_language: MarkupLanguageFieldView role: RoleFieldView username: UsernameFieldView password: <PASSWORD> password_confirm: UserPasswordConfirmFieldView primaryAttributes: [ 'first_name' 'last_name' 'email' 'role' 'username' 'password' 'password_confirm' ] editableSecondaryAttributes: [ 'affiliation' 'markup_language' 'page_content' ] getNewResourceData: -> console.log 'in getNewResourceData' super
true
define [ './resource-add-widget' './textarea-field' './password-field' './select-field' './relational-select-field' './script-field' './../models/user' './../utils/globals' ], (ResourceAddWidgetView, TextareaFieldView, PasswordFieldView, SelectFieldView, RelationalSelectFieldView, ScriptFieldView, UserModel, globals) -> imAdmin = -> try globals.applicationSettings.get('loggedInUser').role is 'administrator' catch false class TextareaFieldView255 extends TextareaFieldView initialize: (options) -> options.domAttributes = maxlength: 255 super options # A <select>-based field view for the markup language select field. class MarkupLanguageFieldView extends SelectFieldView initialize: (options) -> options.required = true options.selectValueGetter = (o) -> o options.selectTextGetter = (o) -> o super options class UsernameFieldView extends TextareaFieldView255 visibilityCondition: -> imAdmin() # A <select>-based field view for the markup language select field. class RoleFieldView extends SelectFieldView initialize: (options) -> options.required = true options.selectValueGetter = (o) -> o options.selectTextGetter = (o) -> o super options visibilityCondition: -> imAdmin() class UserPasswordFieldView extends PasswordFieldView visibilityCondition: -> @imAdminOrImResource() class UserPasswordConfirmFieldView extends UserPasswordFieldView visibilityCondition: -> @imAdminOrImResource() initialize: (options={}) -> options.confirmField = true super options # User Add Widget View # -------------------------- # # View for a widget containing inputs and controls for creating a new # user and updating an existing one. ############################################################################## # User Add Widget ############################################################################## class UserAddWidgetView extends ResourceAddWidgetView resourceName: 'user' resourceModel: UserModel attribute2fieldView: name: TextareaFieldView255 page_content: ScriptFieldView markup_language: MarkupLanguageFieldView role: RoleFieldView username: UsernameFieldView password: PI:PASSWORD:<PASSWORD>END_PI password_confirm: UserPasswordConfirmFieldView primaryAttributes: [ 'first_name' 'last_name' 'email' 'role' 'username' 'password' 'password_confirm' ] editableSecondaryAttributes: [ 'affiliation' 'markup_language' 'page_content' ] getNewResourceData: -> console.log 'in getNewResourceData' super
[ { "context": " inputOptions :\n placeholder : 'pick a username'\n name : 'username'\n ", "end": 1001, "score": 0.6926931142807007, "start": 995, "tag": "USERNAME", "value": "pick a" }, { "context": " : 'pick a username'\n name : 'username'\n validate :\n rules ", "end": 1048, "score": 0.9887192249298096, "start": 1040, "tag": "USERNAME", "value": "username" }, { "context": "me : 'password'\n placeholder : 'set a password'\n validate :\n container : ", "end": 1914, "score": 0.6469966173171997, "start": 1900, "tag": "PASSWORD", "value": "set a password" }, { "context": " pistachio: ->\n\n \"\"\"\n {{> @email}}\n {{> @username}}\n {{> @password}}\n {{> @passwordStrength}}", "end": 3347, "score": 0.6125833988189697, "start": 3339, "tag": "USERNAME", "value": "username" } ]
client/landing/site.landing/coffee/team/forms/teamjoinbysignupform.coffee
ezgikaysi/koding
1
kd = require 'kd' utils = require './../../core/utils' TeamJoinTabForm = require './../forms/teamjointabform' LoginInputView = require './../../login/logininputview' module.exports = class TeamJoinBySignupForm extends TeamJoinTabForm constructor: (options = {}, data) -> teamData = utils.getTeamData() options.buttonTitle or= 'Sign up & join' options.email or= teamData.invitation?.email super options, data @email = new LoginInputView inputOptions : name : 'email' placeholder : 'your email address' defaultValue : @getOption 'email' validate : rules : { email: yes } messages : { email: 'Please type a valid email address.' } events : regExp : 'keyup' @email.inputReceivedKeyup() if @getOption 'email' @username = new LoginInputView inputOptions : placeholder : 'pick a username' name : 'username' validate : rules : required : yes rangeLength : [4, 25] regExp : /^[a-z\d]+([-][a-z\d]+)*$/i messages : required : 'Please enter a username.' regExp : 'For username only lowercase letters and numbers are allowed!' rangeLength : 'Username should be between 4 and 25 characters!' events : regExp : 'keyup' @passwordStrength = ps = new kd.CustomHTMLView tagName : 'figure' cssClass : 'PasswordStrength' partial : '<span></span>' # make this a reusable component - SY oldPass = null @password = new LoginInputView inputOptions : type : 'password' name : 'password' placeholder : 'set a password' validate : container : this rules : required : yes minLength : 8 messages : required : 'Please enter a password.' minLength : 'Passwords should be at least 8 characters.' keyup : (event) -> pass = @getValue() strength = ['bad', 'weak', 'moderate', 'good', 'excellent'] return if pass is oldPass if pass is '' ps.unsetClass strength.join ' ' oldPass = null return utils.checkPasswordStrength pass, (err, report) -> oldPass = pass return if pass isnt report.password # to avoid late responded ajax calls ps.unsetClass strength.join ' ' ps.setClass strength[report.score] @button = @getButton @getOption 'buttonTitle' @buttonLink = @getButtonLink "<a href='#'>Already have an account?</a>", (event) => kd.utils.stopDOMEvent event return unless event.target.tagName is 'A' @emit 'FormNeedsToBeChanged', yes, yes @on 'FormValidationFailed', @button.bound 'hideLoader' @on 'FormSubmitFailed', @button.bound 'hideLoader' submit: (formData) -> teamData = utils.getTeamData() teamData.signup ?= {} teamData.signup.alreadyMember = no super formData pistachio: -> """ {{> @email}} {{> @username}} {{> @password}} {{> @passwordStrength}} <div class='TeamsModal-button-separator'></div> {{> @button}} {{> @buttonLink}} """
30975
kd = require 'kd' utils = require './../../core/utils' TeamJoinTabForm = require './../forms/teamjointabform' LoginInputView = require './../../login/logininputview' module.exports = class TeamJoinBySignupForm extends TeamJoinTabForm constructor: (options = {}, data) -> teamData = utils.getTeamData() options.buttonTitle or= 'Sign up & join' options.email or= teamData.invitation?.email super options, data @email = new LoginInputView inputOptions : name : 'email' placeholder : 'your email address' defaultValue : @getOption 'email' validate : rules : { email: yes } messages : { email: 'Please type a valid email address.' } events : regExp : 'keyup' @email.inputReceivedKeyup() if @getOption 'email' @username = new LoginInputView inputOptions : placeholder : 'pick a username' name : 'username' validate : rules : required : yes rangeLength : [4, 25] regExp : /^[a-z\d]+([-][a-z\d]+)*$/i messages : required : 'Please enter a username.' regExp : 'For username only lowercase letters and numbers are allowed!' rangeLength : 'Username should be between 4 and 25 characters!' events : regExp : 'keyup' @passwordStrength = ps = new kd.CustomHTMLView tagName : 'figure' cssClass : 'PasswordStrength' partial : '<span></span>' # make this a reusable component - SY oldPass = null @password = new LoginInputView inputOptions : type : 'password' name : 'password' placeholder : '<PASSWORD>' validate : container : this rules : required : yes minLength : 8 messages : required : 'Please enter a password.' minLength : 'Passwords should be at least 8 characters.' keyup : (event) -> pass = @getValue() strength = ['bad', 'weak', 'moderate', 'good', 'excellent'] return if pass is oldPass if pass is '' ps.unsetClass strength.join ' ' oldPass = null return utils.checkPasswordStrength pass, (err, report) -> oldPass = pass return if pass isnt report.password # to avoid late responded ajax calls ps.unsetClass strength.join ' ' ps.setClass strength[report.score] @button = @getButton @getOption 'buttonTitle' @buttonLink = @getButtonLink "<a href='#'>Already have an account?</a>", (event) => kd.utils.stopDOMEvent event return unless event.target.tagName is 'A' @emit 'FormNeedsToBeChanged', yes, yes @on 'FormValidationFailed', @button.bound 'hideLoader' @on 'FormSubmitFailed', @button.bound 'hideLoader' submit: (formData) -> teamData = utils.getTeamData() teamData.signup ?= {} teamData.signup.alreadyMember = no super formData pistachio: -> """ {{> @email}} {{> @username}} {{> @password}} {{> @passwordStrength}} <div class='TeamsModal-button-separator'></div> {{> @button}} {{> @buttonLink}} """
true
kd = require 'kd' utils = require './../../core/utils' TeamJoinTabForm = require './../forms/teamjointabform' LoginInputView = require './../../login/logininputview' module.exports = class TeamJoinBySignupForm extends TeamJoinTabForm constructor: (options = {}, data) -> teamData = utils.getTeamData() options.buttonTitle or= 'Sign up & join' options.email or= teamData.invitation?.email super options, data @email = new LoginInputView inputOptions : name : 'email' placeholder : 'your email address' defaultValue : @getOption 'email' validate : rules : { email: yes } messages : { email: 'Please type a valid email address.' } events : regExp : 'keyup' @email.inputReceivedKeyup() if @getOption 'email' @username = new LoginInputView inputOptions : placeholder : 'pick a username' name : 'username' validate : rules : required : yes rangeLength : [4, 25] regExp : /^[a-z\d]+([-][a-z\d]+)*$/i messages : required : 'Please enter a username.' regExp : 'For username only lowercase letters and numbers are allowed!' rangeLength : 'Username should be between 4 and 25 characters!' events : regExp : 'keyup' @passwordStrength = ps = new kd.CustomHTMLView tagName : 'figure' cssClass : 'PasswordStrength' partial : '<span></span>' # make this a reusable component - SY oldPass = null @password = new LoginInputView inputOptions : type : 'password' name : 'password' placeholder : 'PI:PASSWORD:<PASSWORD>END_PI' validate : container : this rules : required : yes minLength : 8 messages : required : 'Please enter a password.' minLength : 'Passwords should be at least 8 characters.' keyup : (event) -> pass = @getValue() strength = ['bad', 'weak', 'moderate', 'good', 'excellent'] return if pass is oldPass if pass is '' ps.unsetClass strength.join ' ' oldPass = null return utils.checkPasswordStrength pass, (err, report) -> oldPass = pass return if pass isnt report.password # to avoid late responded ajax calls ps.unsetClass strength.join ' ' ps.setClass strength[report.score] @button = @getButton @getOption 'buttonTitle' @buttonLink = @getButtonLink "<a href='#'>Already have an account?</a>", (event) => kd.utils.stopDOMEvent event return unless event.target.tagName is 'A' @emit 'FormNeedsToBeChanged', yes, yes @on 'FormValidationFailed', @button.bound 'hideLoader' @on 'FormSubmitFailed', @button.bound 'hideLoader' submit: (formData) -> teamData = utils.getTeamData() teamData.signup ?= {} teamData.signup.alreadyMember = no super formData pistachio: -> """ {{> @email}} {{> @username}} {{> @password}} {{> @passwordStrength}} <div class='TeamsModal-button-separator'></div> {{> @button}} {{> @buttonLink}} """
[ { "context": "#\n# Author: Peter K. Lee (peter@corenova.com)\n#\n# All rights reserved. Thi", "end": 24, "score": 0.9998708963394165, "start": 12, "tag": "NAME", "value": "Peter K. Lee" }, { "context": "#\n# Author: Peter K. Lee (peter@corenova.com)\n#\n# All rights reserved. This program and the ac", "end": 44, "score": 0.9999251961708069, "start": 26, "tag": "EMAIL", "value": "peter@corenova.com" } ]
test/promise-intents.coffee
hashnfv/hashnfv-promise-backup
0
# # Author: Peter K. Lee (peter@corenova.com) # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # config = require 'config' assert = require 'assert' forge = require 'yangforge' app = forge.load '!yaml ../promise.yaml', async: false, pkgdir: __dirname # this is javascript promise framework and not related to opnfv-promise promise = require 'promise' if process.env.DEBUG debug = console.log else debug = -> # in the future with YF 0.12.x # app = forge.load('..').build('test') # app.set config # app.use 'proxy', target: x.x.x.x:5050, interface: 'restjson' describe "promise", -> before -> # ensure we have valid OpenStack environment to test against try config.get 'openstack.auth.endpoint' catch e throw new Error "missing OpenStack environmental variables" # below 'provider' is used across test suites provider = undefined # Test Scenario 00 (FUTURE) # describe "prepare OpenStack for testing", -> # before (done) -> # # ensure we have valid OpenStack environment to test against # try # config.get 'openstack.auth.url' # catch e # throw new Error "missing OpenStack environmental variables" # os = forge.load '!yaml ../openstack.yaml', async: false, pkgdir: __dirname # app.attach 'openstack', os.access 'openstack' # app.set config # describe "authenticate", -> # it "should retrieve available service catalog", (done) -> # app.access('openstack').invoke 'authenticate' # .then (res) -> # done() # .catch (err) -> done err # describe "create-tenant", -> # # create a new tenant for testing purposes # describe "upload-image", -> # # upload a new test image # Test Scenario 01 describe "register OpenStack into resource pool", -> pool = undefined # TC-01 describe "add-provider", -> it "should add a new OpenStack provider without error", (done) -> @timeout 5000 auth = config.get 'openstack.auth' auth['provider-type'] = 'openstack' app.access('opnfv-promise').invoke 'add-provider', auth .then (res) -> res.get('result').should.equal 'ok' provider = id: res.get('provider-id') # HACK - we delay by a second to allow time for discovering capacity and flavors setTimeout done, 1000 .catch (err) -> done err it "should update promise.providers with a new entry", -> app.get('opnfv-promise.promise.providers').should.have.length(1) it "should contain a new ResourceProvider record in the store", -> assert provider?.id?, "unable to check without ID" provider = app.access('opnfv-promise').find('ResourceProvider', provider.id) assert provider? # TC-02 describe "increase-capacity", -> it "should add more capacity to the reservation service without error", (done) -> app.access('opnfv-promise').invoke 'increase-capacity', source: provider capacity: cores: 20 ram: 51200 instances: 10 addresses: 10 .then (res) -> res.get('result').should.equal 'ok' pool = id: res.get('pool-id') done() .catch (err) -> done err it "should update promise.pools with a new entry", -> app.get('opnfv-promise.promise.pools').should.have.length(1) it "should contain a ResourcePool record in the store", -> assert pool?.id?, "unable to check without ID" pool = app.access('opnfv-promise').find('ResourcePool', pool.id) assert pool? # TC-03 describe "query-capacity", -> it "should report total collections and utilizations", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'total' .then (res) -> res.get('collections').should.be.Array res.get('collections').length.should.be.above(0) res.get('utilization').should.be.Array res.get('utilization').length.should.be.above(0) done() .catch (err) -> done err it "should contain newly added capacity pool", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'total' .then (res) -> res.get('collections').should.containEql "ResourcePool:#{pool.id}" done() .catch (err) -> done err # Test Scenario 02 describe "allocation without reservation", -> # TC-04 describe "create-instance", -> allocation = undefined instance_id = undefined before -> # XXX - need to determine image and flavor to use in the given provider for this test assert provider?, "unable to execute without registered 'provider'" it "should create a new server in target provider without error", (done) -> @timeout 10000 test = config.get 'openstack.test' app.access('opnfv-promise').invoke 'create-instance', 'provider-id': provider.id name: 'promise-test-no-reservation' image: test.image flavor: test.flavor networks: [ test.network ] .then (res) -> debug res.get() res.get('result').should.equal 'ok' instance_id = res.get('instance-id') done() .catch (err) -> done err it "should update promise.allocations with a new entry", -> app.get('opnfv-promise.promise.allocations').length.should.be.above(0) it "should contain a new ResourceAllocation record in the store", -> assert instance_id?, "unable to check without ID" allocation = app.access('opnfv-promise').find('ResourceAllocation', instance_id) assert allocation? it "should reference the created server ID from the provider", -> assert allocation?, "unable to check without record" allocation.get('instance-ref').should.have.property('provider') allocation.get('instance-ref').should.have.property('server') it "should have low priority state", -> assert allocation?, "unable to check without record" allocation.get('priority').should.equal 'low' # Test Scenario 03 describe "allocation using reservation for immediate use", -> reservation = undefined # TC-05 describe "create-reservation", -> it "should create reservation record (no start/end) without error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 25600 addresses: 3 instances: 3 .then (res) -> res.get('result').should.equal 'ok' reservation = id: res.get('reservation-id') done() .catch (err) -> done err it "should update promise.reservations with a new entry", -> app.get('opnfv-promise.promise.reservations').length.should.be.above(0) it "should contain a new ResourceReservation record in the store", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert reservation? # TC-06 describe "create-instance", -> allocation = undefined before -> assert provider?, "unable to execute without registered 'provider'" assert reservation?, "unable to execute without valid reservation record" it "should create a new server in target provider (with reservation) without error", (done) -> @timeout 10000 test = config.get 'openstack.test' app.access('opnfv-promise').invoke 'create-instance', 'provider-id': provider.id name: 'promise-test-reservation' image: test.image flavor: test.flavor networks: [ test.network ] 'reservation-id': reservation.id .then (res) -> debug res.get() res.get('result').should.equal 'ok' allocation = id: res.get('instance-id') done() .catch (err) -> done err it "should contain a new ResourceAllocation record in the store", -> assert allocation?.id?, "unable to check without ID" allocation = app.access('opnfv-promise').find('ResourceAllocation', allocation.id) assert allocation? it "should be referenced in the reservation record", -> assert reservation? and allocation?, "unable to check without records" reservation.get('allocations').should.containEql allocation.id it "should have high priority state", -> assert allocation?, "unable to check without record" allocation.get('priority').should.equal 'high' # Test Scenario 04 describe "reservation for future use", -> reservation = undefined start = new Date end = new Date # 7 days in the future start.setTime (start.getTime() + 7*60*60*1000) # 8 days in the future end.setTime (end.getTime() + 8*60*60*1000) # TC-07 describe "create-reservation", -> it "should create reservation record (for future) without error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', start: start.toJSON() end: end.toJSON() capacity: cores: 1 ram: 12800 addresses: 1 instances: 1 .then (res) -> res.get('result').should.equal 'ok' reservation = id: res.get('reservation-id') done() .catch (err) -> done err it "should update promise.reservations with a new entry", -> app.get('opnfv-promise.promise.reservations').length.should.be.above(0) it "should contain a new ResourceReservation record in the store", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert reservation? # TC-08 describe "query-reservation", -> it "should contain newly created future reservation", (done) -> app.access('opnfv-promise').invoke 'query-reservation', window: start: start.toJSON() end: end.toJSON() .then (res) -> res.get('reservations').should.containEql reservation.id done() .catch (err) -> done err # TC-09 describe "update-reservation", -> it "should modify existing reservation without error", (done) -> app.access('opnfv-promise').invoke 'update-reservation', 'reservation-id': reservation.id capacity: cores: 3 ram: 12800 addresses: 2 instances: 2 .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-10 describe "cancel-reservation", -> it "should modify existing reservation without error", (done) -> app.access('opnfv-promise').invoke 'cancel-reservation', 'reservation-id': reservation.id .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err it "should no longer contain record of the deleted reservation", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert not reservation? # Test Scenario 05 describe "capacity planning", -> # TC-11 describe "decrease-capacity", -> start = new Date end = new Date # 30 days in the future start.setTime (start.getTime() + 30*60*60*1000) # 45 days in the future end.setTime (end.getTime() + 45*60*60*1000) it "should decrease available capacity from a provider in the future", (done) -> app.access('opnfv-promise').invoke 'decrease-capacity', source: provider capacity: cores: 5 ram: 17920 instances: 5 start: start.toJSON() end: end.toJSON() .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-12 describe "increase-capacity", -> start = new Date end = new Date # 14 days in the future start.setTime (start.getTime() + 14*60*60*1000) # 21 days in the future end.setTime (end.getTime() + 21*60*60*1000) it "should increase available capacity from a provider in the future", (done) -> app.access('opnfv-promise').invoke 'decrease-capacity', source: provider capacity: cores: 1 ram: 3584 instances: 1 start: start.toJSON() end: end.toJSON() .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-13 (Should improve this TC) describe "query-capacity", -> it "should report available collections and utilizations", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'available' .then (res) -> res.get('collections').should.be.Array res.get('collections').length.should.be.above(0) res.get('utilization').should.be.Array res.get('utilization').length.should.be.above(0) done() .catch (err) -> done err # Test Scenario 06 describe "reservation with conflict", -> # TC-14 describe "create-reservation", -> it "should fail to create immediate reservation record with proper error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 17920 instances: 10 .then (res) -> res.get('result').should.equal 'conflict' done() .catch (err) -> done err it "should fail to create future reservation record with proper error", (done) -> start = new Date # 30 days in the future start.setTime (start.getTime() + 30*60*60*1000) app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 17920 instances: 10 start: start.toJSON() .then (res) -> res.get('result').should.equal 'conflict' done() .catch (err) -> done err # Test Scenario 07 describe "cleanup test allocations", -> allocations = undefined before -> allocations = app.get('opnfv-promise.promise.allocations') debug provider.get() debug allocations allocations.length.should.be.above(0) describe "destroy-instance", -> it "should successfully destroy all allocations", (done) -> @timeout 5000 promises = allocations.map (x) -> app.access('opnfv-promise').invoke 'destroy-instance', 'instance-id': x.id promise.all promises .then (res) -> res.forEach (x) -> debug x.get() x.get('result').should.equal 'ok' done() .catch (err) -> done err
199652
# # Author: <NAME> (<EMAIL>) # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # config = require 'config' assert = require 'assert' forge = require 'yangforge' app = forge.load '!yaml ../promise.yaml', async: false, pkgdir: __dirname # this is javascript promise framework and not related to opnfv-promise promise = require 'promise' if process.env.DEBUG debug = console.log else debug = -> # in the future with YF 0.12.x # app = forge.load('..').build('test') # app.set config # app.use 'proxy', target: x.x.x.x:5050, interface: 'restjson' describe "promise", -> before -> # ensure we have valid OpenStack environment to test against try config.get 'openstack.auth.endpoint' catch e throw new Error "missing OpenStack environmental variables" # below 'provider' is used across test suites provider = undefined # Test Scenario 00 (FUTURE) # describe "prepare OpenStack for testing", -> # before (done) -> # # ensure we have valid OpenStack environment to test against # try # config.get 'openstack.auth.url' # catch e # throw new Error "missing OpenStack environmental variables" # os = forge.load '!yaml ../openstack.yaml', async: false, pkgdir: __dirname # app.attach 'openstack', os.access 'openstack' # app.set config # describe "authenticate", -> # it "should retrieve available service catalog", (done) -> # app.access('openstack').invoke 'authenticate' # .then (res) -> # done() # .catch (err) -> done err # describe "create-tenant", -> # # create a new tenant for testing purposes # describe "upload-image", -> # # upload a new test image # Test Scenario 01 describe "register OpenStack into resource pool", -> pool = undefined # TC-01 describe "add-provider", -> it "should add a new OpenStack provider without error", (done) -> @timeout 5000 auth = config.get 'openstack.auth' auth['provider-type'] = 'openstack' app.access('opnfv-promise').invoke 'add-provider', auth .then (res) -> res.get('result').should.equal 'ok' provider = id: res.get('provider-id') # HACK - we delay by a second to allow time for discovering capacity and flavors setTimeout done, 1000 .catch (err) -> done err it "should update promise.providers with a new entry", -> app.get('opnfv-promise.promise.providers').should.have.length(1) it "should contain a new ResourceProvider record in the store", -> assert provider?.id?, "unable to check without ID" provider = app.access('opnfv-promise').find('ResourceProvider', provider.id) assert provider? # TC-02 describe "increase-capacity", -> it "should add more capacity to the reservation service without error", (done) -> app.access('opnfv-promise').invoke 'increase-capacity', source: provider capacity: cores: 20 ram: 51200 instances: 10 addresses: 10 .then (res) -> res.get('result').should.equal 'ok' pool = id: res.get('pool-id') done() .catch (err) -> done err it "should update promise.pools with a new entry", -> app.get('opnfv-promise.promise.pools').should.have.length(1) it "should contain a ResourcePool record in the store", -> assert pool?.id?, "unable to check without ID" pool = app.access('opnfv-promise').find('ResourcePool', pool.id) assert pool? # TC-03 describe "query-capacity", -> it "should report total collections and utilizations", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'total' .then (res) -> res.get('collections').should.be.Array res.get('collections').length.should.be.above(0) res.get('utilization').should.be.Array res.get('utilization').length.should.be.above(0) done() .catch (err) -> done err it "should contain newly added capacity pool", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'total' .then (res) -> res.get('collections').should.containEql "ResourcePool:#{pool.id}" done() .catch (err) -> done err # Test Scenario 02 describe "allocation without reservation", -> # TC-04 describe "create-instance", -> allocation = undefined instance_id = undefined before -> # XXX - need to determine image and flavor to use in the given provider for this test assert provider?, "unable to execute without registered 'provider'" it "should create a new server in target provider without error", (done) -> @timeout 10000 test = config.get 'openstack.test' app.access('opnfv-promise').invoke 'create-instance', 'provider-id': provider.id name: 'promise-test-no-reservation' image: test.image flavor: test.flavor networks: [ test.network ] .then (res) -> debug res.get() res.get('result').should.equal 'ok' instance_id = res.get('instance-id') done() .catch (err) -> done err it "should update promise.allocations with a new entry", -> app.get('opnfv-promise.promise.allocations').length.should.be.above(0) it "should contain a new ResourceAllocation record in the store", -> assert instance_id?, "unable to check without ID" allocation = app.access('opnfv-promise').find('ResourceAllocation', instance_id) assert allocation? it "should reference the created server ID from the provider", -> assert allocation?, "unable to check without record" allocation.get('instance-ref').should.have.property('provider') allocation.get('instance-ref').should.have.property('server') it "should have low priority state", -> assert allocation?, "unable to check without record" allocation.get('priority').should.equal 'low' # Test Scenario 03 describe "allocation using reservation for immediate use", -> reservation = undefined # TC-05 describe "create-reservation", -> it "should create reservation record (no start/end) without error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 25600 addresses: 3 instances: 3 .then (res) -> res.get('result').should.equal 'ok' reservation = id: res.get('reservation-id') done() .catch (err) -> done err it "should update promise.reservations with a new entry", -> app.get('opnfv-promise.promise.reservations').length.should.be.above(0) it "should contain a new ResourceReservation record in the store", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert reservation? # TC-06 describe "create-instance", -> allocation = undefined before -> assert provider?, "unable to execute without registered 'provider'" assert reservation?, "unable to execute without valid reservation record" it "should create a new server in target provider (with reservation) without error", (done) -> @timeout 10000 test = config.get 'openstack.test' app.access('opnfv-promise').invoke 'create-instance', 'provider-id': provider.id name: 'promise-test-reservation' image: test.image flavor: test.flavor networks: [ test.network ] 'reservation-id': reservation.id .then (res) -> debug res.get() res.get('result').should.equal 'ok' allocation = id: res.get('instance-id') done() .catch (err) -> done err it "should contain a new ResourceAllocation record in the store", -> assert allocation?.id?, "unable to check without ID" allocation = app.access('opnfv-promise').find('ResourceAllocation', allocation.id) assert allocation? it "should be referenced in the reservation record", -> assert reservation? and allocation?, "unable to check without records" reservation.get('allocations').should.containEql allocation.id it "should have high priority state", -> assert allocation?, "unable to check without record" allocation.get('priority').should.equal 'high' # Test Scenario 04 describe "reservation for future use", -> reservation = undefined start = new Date end = new Date # 7 days in the future start.setTime (start.getTime() + 7*60*60*1000) # 8 days in the future end.setTime (end.getTime() + 8*60*60*1000) # TC-07 describe "create-reservation", -> it "should create reservation record (for future) without error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', start: start.toJSON() end: end.toJSON() capacity: cores: 1 ram: 12800 addresses: 1 instances: 1 .then (res) -> res.get('result').should.equal 'ok' reservation = id: res.get('reservation-id') done() .catch (err) -> done err it "should update promise.reservations with a new entry", -> app.get('opnfv-promise.promise.reservations').length.should.be.above(0) it "should contain a new ResourceReservation record in the store", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert reservation? # TC-08 describe "query-reservation", -> it "should contain newly created future reservation", (done) -> app.access('opnfv-promise').invoke 'query-reservation', window: start: start.toJSON() end: end.toJSON() .then (res) -> res.get('reservations').should.containEql reservation.id done() .catch (err) -> done err # TC-09 describe "update-reservation", -> it "should modify existing reservation without error", (done) -> app.access('opnfv-promise').invoke 'update-reservation', 'reservation-id': reservation.id capacity: cores: 3 ram: 12800 addresses: 2 instances: 2 .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-10 describe "cancel-reservation", -> it "should modify existing reservation without error", (done) -> app.access('opnfv-promise').invoke 'cancel-reservation', 'reservation-id': reservation.id .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err it "should no longer contain record of the deleted reservation", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert not reservation? # Test Scenario 05 describe "capacity planning", -> # TC-11 describe "decrease-capacity", -> start = new Date end = new Date # 30 days in the future start.setTime (start.getTime() + 30*60*60*1000) # 45 days in the future end.setTime (end.getTime() + 45*60*60*1000) it "should decrease available capacity from a provider in the future", (done) -> app.access('opnfv-promise').invoke 'decrease-capacity', source: provider capacity: cores: 5 ram: 17920 instances: 5 start: start.toJSON() end: end.toJSON() .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-12 describe "increase-capacity", -> start = new Date end = new Date # 14 days in the future start.setTime (start.getTime() + 14*60*60*1000) # 21 days in the future end.setTime (end.getTime() + 21*60*60*1000) it "should increase available capacity from a provider in the future", (done) -> app.access('opnfv-promise').invoke 'decrease-capacity', source: provider capacity: cores: 1 ram: 3584 instances: 1 start: start.toJSON() end: end.toJSON() .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-13 (Should improve this TC) describe "query-capacity", -> it "should report available collections and utilizations", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'available' .then (res) -> res.get('collections').should.be.Array res.get('collections').length.should.be.above(0) res.get('utilization').should.be.Array res.get('utilization').length.should.be.above(0) done() .catch (err) -> done err # Test Scenario 06 describe "reservation with conflict", -> # TC-14 describe "create-reservation", -> it "should fail to create immediate reservation record with proper error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 17920 instances: 10 .then (res) -> res.get('result').should.equal 'conflict' done() .catch (err) -> done err it "should fail to create future reservation record with proper error", (done) -> start = new Date # 30 days in the future start.setTime (start.getTime() + 30*60*60*1000) app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 17920 instances: 10 start: start.toJSON() .then (res) -> res.get('result').should.equal 'conflict' done() .catch (err) -> done err # Test Scenario 07 describe "cleanup test allocations", -> allocations = undefined before -> allocations = app.get('opnfv-promise.promise.allocations') debug provider.get() debug allocations allocations.length.should.be.above(0) describe "destroy-instance", -> it "should successfully destroy all allocations", (done) -> @timeout 5000 promises = allocations.map (x) -> app.access('opnfv-promise').invoke 'destroy-instance', 'instance-id': x.id promise.all promises .then (res) -> res.forEach (x) -> debug x.get() x.get('result').should.equal 'ok' done() .catch (err) -> done err
true
# # Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # config = require 'config' assert = require 'assert' forge = require 'yangforge' app = forge.load '!yaml ../promise.yaml', async: false, pkgdir: __dirname # this is javascript promise framework and not related to opnfv-promise promise = require 'promise' if process.env.DEBUG debug = console.log else debug = -> # in the future with YF 0.12.x # app = forge.load('..').build('test') # app.set config # app.use 'proxy', target: x.x.x.x:5050, interface: 'restjson' describe "promise", -> before -> # ensure we have valid OpenStack environment to test against try config.get 'openstack.auth.endpoint' catch e throw new Error "missing OpenStack environmental variables" # below 'provider' is used across test suites provider = undefined # Test Scenario 00 (FUTURE) # describe "prepare OpenStack for testing", -> # before (done) -> # # ensure we have valid OpenStack environment to test against # try # config.get 'openstack.auth.url' # catch e # throw new Error "missing OpenStack environmental variables" # os = forge.load '!yaml ../openstack.yaml', async: false, pkgdir: __dirname # app.attach 'openstack', os.access 'openstack' # app.set config # describe "authenticate", -> # it "should retrieve available service catalog", (done) -> # app.access('openstack').invoke 'authenticate' # .then (res) -> # done() # .catch (err) -> done err # describe "create-tenant", -> # # create a new tenant for testing purposes # describe "upload-image", -> # # upload a new test image # Test Scenario 01 describe "register OpenStack into resource pool", -> pool = undefined # TC-01 describe "add-provider", -> it "should add a new OpenStack provider without error", (done) -> @timeout 5000 auth = config.get 'openstack.auth' auth['provider-type'] = 'openstack' app.access('opnfv-promise').invoke 'add-provider', auth .then (res) -> res.get('result').should.equal 'ok' provider = id: res.get('provider-id') # HACK - we delay by a second to allow time for discovering capacity and flavors setTimeout done, 1000 .catch (err) -> done err it "should update promise.providers with a new entry", -> app.get('opnfv-promise.promise.providers').should.have.length(1) it "should contain a new ResourceProvider record in the store", -> assert provider?.id?, "unable to check without ID" provider = app.access('opnfv-promise').find('ResourceProvider', provider.id) assert provider? # TC-02 describe "increase-capacity", -> it "should add more capacity to the reservation service without error", (done) -> app.access('opnfv-promise').invoke 'increase-capacity', source: provider capacity: cores: 20 ram: 51200 instances: 10 addresses: 10 .then (res) -> res.get('result').should.equal 'ok' pool = id: res.get('pool-id') done() .catch (err) -> done err it "should update promise.pools with a new entry", -> app.get('opnfv-promise.promise.pools').should.have.length(1) it "should contain a ResourcePool record in the store", -> assert pool?.id?, "unable to check without ID" pool = app.access('opnfv-promise').find('ResourcePool', pool.id) assert pool? # TC-03 describe "query-capacity", -> it "should report total collections and utilizations", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'total' .then (res) -> res.get('collections').should.be.Array res.get('collections').length.should.be.above(0) res.get('utilization').should.be.Array res.get('utilization').length.should.be.above(0) done() .catch (err) -> done err it "should contain newly added capacity pool", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'total' .then (res) -> res.get('collections').should.containEql "ResourcePool:#{pool.id}" done() .catch (err) -> done err # Test Scenario 02 describe "allocation without reservation", -> # TC-04 describe "create-instance", -> allocation = undefined instance_id = undefined before -> # XXX - need to determine image and flavor to use in the given provider for this test assert provider?, "unable to execute without registered 'provider'" it "should create a new server in target provider without error", (done) -> @timeout 10000 test = config.get 'openstack.test' app.access('opnfv-promise').invoke 'create-instance', 'provider-id': provider.id name: 'promise-test-no-reservation' image: test.image flavor: test.flavor networks: [ test.network ] .then (res) -> debug res.get() res.get('result').should.equal 'ok' instance_id = res.get('instance-id') done() .catch (err) -> done err it "should update promise.allocations with a new entry", -> app.get('opnfv-promise.promise.allocations').length.should.be.above(0) it "should contain a new ResourceAllocation record in the store", -> assert instance_id?, "unable to check without ID" allocation = app.access('opnfv-promise').find('ResourceAllocation', instance_id) assert allocation? it "should reference the created server ID from the provider", -> assert allocation?, "unable to check without record" allocation.get('instance-ref').should.have.property('provider') allocation.get('instance-ref').should.have.property('server') it "should have low priority state", -> assert allocation?, "unable to check without record" allocation.get('priority').should.equal 'low' # Test Scenario 03 describe "allocation using reservation for immediate use", -> reservation = undefined # TC-05 describe "create-reservation", -> it "should create reservation record (no start/end) without error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 25600 addresses: 3 instances: 3 .then (res) -> res.get('result').should.equal 'ok' reservation = id: res.get('reservation-id') done() .catch (err) -> done err it "should update promise.reservations with a new entry", -> app.get('opnfv-promise.promise.reservations').length.should.be.above(0) it "should contain a new ResourceReservation record in the store", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert reservation? # TC-06 describe "create-instance", -> allocation = undefined before -> assert provider?, "unable to execute without registered 'provider'" assert reservation?, "unable to execute without valid reservation record" it "should create a new server in target provider (with reservation) without error", (done) -> @timeout 10000 test = config.get 'openstack.test' app.access('opnfv-promise').invoke 'create-instance', 'provider-id': provider.id name: 'promise-test-reservation' image: test.image flavor: test.flavor networks: [ test.network ] 'reservation-id': reservation.id .then (res) -> debug res.get() res.get('result').should.equal 'ok' allocation = id: res.get('instance-id') done() .catch (err) -> done err it "should contain a new ResourceAllocation record in the store", -> assert allocation?.id?, "unable to check without ID" allocation = app.access('opnfv-promise').find('ResourceAllocation', allocation.id) assert allocation? it "should be referenced in the reservation record", -> assert reservation? and allocation?, "unable to check without records" reservation.get('allocations').should.containEql allocation.id it "should have high priority state", -> assert allocation?, "unable to check without record" allocation.get('priority').should.equal 'high' # Test Scenario 04 describe "reservation for future use", -> reservation = undefined start = new Date end = new Date # 7 days in the future start.setTime (start.getTime() + 7*60*60*1000) # 8 days in the future end.setTime (end.getTime() + 8*60*60*1000) # TC-07 describe "create-reservation", -> it "should create reservation record (for future) without error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', start: start.toJSON() end: end.toJSON() capacity: cores: 1 ram: 12800 addresses: 1 instances: 1 .then (res) -> res.get('result').should.equal 'ok' reservation = id: res.get('reservation-id') done() .catch (err) -> done err it "should update promise.reservations with a new entry", -> app.get('opnfv-promise.promise.reservations').length.should.be.above(0) it "should contain a new ResourceReservation record in the store", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert reservation? # TC-08 describe "query-reservation", -> it "should contain newly created future reservation", (done) -> app.access('opnfv-promise').invoke 'query-reservation', window: start: start.toJSON() end: end.toJSON() .then (res) -> res.get('reservations').should.containEql reservation.id done() .catch (err) -> done err # TC-09 describe "update-reservation", -> it "should modify existing reservation without error", (done) -> app.access('opnfv-promise').invoke 'update-reservation', 'reservation-id': reservation.id capacity: cores: 3 ram: 12800 addresses: 2 instances: 2 .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-10 describe "cancel-reservation", -> it "should modify existing reservation without error", (done) -> app.access('opnfv-promise').invoke 'cancel-reservation', 'reservation-id': reservation.id .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err it "should no longer contain record of the deleted reservation", -> assert reservation?.id?, "unable to check without ID" reservation = app.access('opnfv-promise').find('ResourceReservation', reservation.id) assert not reservation? # Test Scenario 05 describe "capacity planning", -> # TC-11 describe "decrease-capacity", -> start = new Date end = new Date # 30 days in the future start.setTime (start.getTime() + 30*60*60*1000) # 45 days in the future end.setTime (end.getTime() + 45*60*60*1000) it "should decrease available capacity from a provider in the future", (done) -> app.access('opnfv-promise').invoke 'decrease-capacity', source: provider capacity: cores: 5 ram: 17920 instances: 5 start: start.toJSON() end: end.toJSON() .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-12 describe "increase-capacity", -> start = new Date end = new Date # 14 days in the future start.setTime (start.getTime() + 14*60*60*1000) # 21 days in the future end.setTime (end.getTime() + 21*60*60*1000) it "should increase available capacity from a provider in the future", (done) -> app.access('opnfv-promise').invoke 'decrease-capacity', source: provider capacity: cores: 1 ram: 3584 instances: 1 start: start.toJSON() end: end.toJSON() .then (res) -> res.get('result').should.equal 'ok' done() .catch (err) -> done err # TC-13 (Should improve this TC) describe "query-capacity", -> it "should report available collections and utilizations", (done) -> app.access('opnfv-promise').invoke 'query-capacity', capacity: 'available' .then (res) -> res.get('collections').should.be.Array res.get('collections').length.should.be.above(0) res.get('utilization').should.be.Array res.get('utilization').length.should.be.above(0) done() .catch (err) -> done err # Test Scenario 06 describe "reservation with conflict", -> # TC-14 describe "create-reservation", -> it "should fail to create immediate reservation record with proper error", (done) -> app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 17920 instances: 10 .then (res) -> res.get('result').should.equal 'conflict' done() .catch (err) -> done err it "should fail to create future reservation record with proper error", (done) -> start = new Date # 30 days in the future start.setTime (start.getTime() + 30*60*60*1000) app.access('opnfv-promise').invoke 'create-reservation', capacity: cores: 5 ram: 17920 instances: 10 start: start.toJSON() .then (res) -> res.get('result').should.equal 'conflict' done() .catch (err) -> done err # Test Scenario 07 describe "cleanup test allocations", -> allocations = undefined before -> allocations = app.get('opnfv-promise.promise.allocations') debug provider.get() debug allocations allocations.length.should.be.above(0) describe "destroy-instance", -> it "should successfully destroy all allocations", (done) -> @timeout 5000 promises = allocations.map (x) -> app.access('opnfv-promise').invoke 'destroy-instance', 'instance-id': x.id promise.all promises .then (res) -> res.forEach (x) -> debug x.get() x.get('result').should.equal 'ok' done() .catch (err) -> done err
[ { "context": "\r\n <%= password_field_tag '${1:pin}' {2: , '1234', maxlength: 4, size: 6, class: \"pin_input\" } %>$", "end": 1074, "score": 0.9942630529403687, "start": 1070, "tag": "PASSWORD", "value": "1234" }, { "context": "\"\r\n <%= email_field_tag '${1:email}' ${2: , 'email@example.com', class: 'special_input', disabled: true } %>$0\r\n", "end": 9344, "score": 0.9999144673347473, "start": 9327, "tag": "EMAIL", "value": "email@example.com" } ]
snippets/dry-rails-views-html-form-tags.cson
dayogreats/dry
0
'.text.html.ruby,.text.html.erb': 'text_area_tag': 'prefix': 'text_area_tag' 'body': """ <%= text_area_tag(:${1:message}, "${1:Hi, nice site}", size: "24x6") %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'text_area_tag(name, content = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'text_field_tag': 'prefix': 'text_field_tag' 'body': """ <%= text_field_tag '${1:ip}', ${2:'0.0.0.0', maxlength: 15, size: 20, class: "ip-input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'text_area_tag(name, content = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'password_field_tag': 'prefix': 'password_field_tag' 'body': """ <%= password_field_tag '${1:pin}' {2: , '1234', maxlength: 4, size: 6, class: "pin_input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'password_field_tag(name = "password", value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'hidden_field_tag': 'prefix': 'hidden_field_tag' 'body': "<%= hidden_field_tag 'collected_input', '', onchange: \"alert('Input collected!')\" %>" 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'hidden_field_tag(name, value = nil, options = {})' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html' 'search_field_tag': 'prefix': 'search_field_tag' 'body': """ <%= search_field_tag '${1:search}' ${2:, 'Enter your search query here', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'search_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'select_tag': 'prefix': 'select_tag' 'body': """ <%= select_tag "${1:people}", options_from_collection_for_${2:select}(${3:@people, "id", "name"}), ${4:include_blank: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'select_tag(name, option_tags = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'image_submit_tag': 'prefix': 'image_submit_tag' 'body': """ <%= image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button") %>${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'image_submit_tag(source, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'submit_tag': 'prefix': 'submit_tag' 'body': """ <%= submit_tag(value = "${1:Save changes}", ${2: options = {confirm: " questions?", data: {disabled: true}})} %>${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'submit_tag(value = "Save changes", options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'label_tag': 'prefix': 'label_tag' 'body': """ <%= label_tag 'name', nil, class: 'small_label' %> ${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'label_tag(name = nil, content_or_options = nil, options = nil, &block) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'telephone_field_tag': 'prefix': 'telephone_field_tag' 'body': """ <%= telephone_field_tag '${1:tel}', ${2 '0123456789', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'telephone_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'phone_field_tag': 'prefix': 'phone_field_tag' 'body': """ <%= phone_field(:${1:user}, :${1:phone}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'phone_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'phone_field_tag': 'prefix': 'phone_field_tag' 'body': """ <%= phone_field(:${1:user}, :${1:phone}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'radio_button_tag(name, value, checked = false, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'date_field_tag': 'prefix': 'date_field_tag' 'body': """ <%= radio_button_tag '${1:color}' ${2:, "green", true, class: "color_input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'date_field_tag(name, value = nil, options = {}) />' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'datetime_field_tag': 'prefix': 'datetime_field_tag' 'body': """ <%= date_field_tag '${1:date}' ${2: , '01/01/2014', class: 'special_input', disabled: true } %>$ """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'datetime_field_tag(name, value = nil, options = {}) >' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'month_field_tag': 'prefix': 'month_field_tag' 'body': """ <%= month_field_tag(:${1:user}, ${1: min: 5, max: 8, step: 2}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'month_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'range_field_tag': 'prefix': 'range_field_tag' 'body': """ <%= range_field_tag(:${1:product}, :${2:discount}, in: 1..100) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': ' range_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'week_field_tag': 'prefix': 'week_field_tag' 'body': """ <%= week_field_tag(${1:name}, ${2: value = nil, options = {}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'week_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'number_field_tag': 'prefix': 'number_field_tag' 'body': """ <%= number_field_tag 'quantity' ${1: , '1', min: 3, max: 7, class: 'special_input', disabled: true} %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'number_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'color_field_tag': 'prefix': 'color_field_tag' 'body': """ <%= color_field_tag 'color', '${1:#DEF726}' ${2: , class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'color_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'url_field_tag': 'prefix': 'url_field_tag' 'body': """ <%= url_field_tag(${1:name}, ${2: value = nil, options = {}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'url_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'email_field_tag': 'prefix': 'email_field_tag' 'body': """ <%= email_field_tag '${1:email}' ${2: , 'email@example.com', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'email_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'time_field_tag': 'prefix': 'time_field_tag' 'body': """ <%= time_field_tag(${1:name}, ${2:value = nil, options = { min: 2, max: 5, step:3}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'time_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'file_field_tag': 'prefix': 'time_field_tag' 'body': """ <%= file_field_tag "${1:file}" %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'file_field_tag(name, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'button_field_tag': 'prefix': 'button_field_tag' 'body': """ <%= button_tag '${1:Reset}', ${2: type: 'reset', disabled: true, data: { confirm: "Are you sure?", disable_with: "Please wait..."} } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'button_tag(content_or_options = nil, options = nil, &block) ' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html' 'check_box_tag': 'prefix': 'check_box_tag' 'body': """ <% check_box_tag '${1:eula}', ${2:'accepted', false, disabled: true} %> """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'check_box_tag(name, value = "1", checked = false, options = {}) ' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html'
88235
'.text.html.ruby,.text.html.erb': 'text_area_tag': 'prefix': 'text_area_tag' 'body': """ <%= text_area_tag(:${1:message}, "${1:Hi, nice site}", size: "24x6") %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'text_area_tag(name, content = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'text_field_tag': 'prefix': 'text_field_tag' 'body': """ <%= text_field_tag '${1:ip}', ${2:'0.0.0.0', maxlength: 15, size: 20, class: "ip-input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'text_area_tag(name, content = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'password_field_tag': 'prefix': 'password_field_tag' 'body': """ <%= password_field_tag '${1:pin}' {2: , '<PASSWORD>', maxlength: 4, size: 6, class: "pin_input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'password_field_tag(name = "password", value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'hidden_field_tag': 'prefix': 'hidden_field_tag' 'body': "<%= hidden_field_tag 'collected_input', '', onchange: \"alert('Input collected!')\" %>" 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'hidden_field_tag(name, value = nil, options = {})' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html' 'search_field_tag': 'prefix': 'search_field_tag' 'body': """ <%= search_field_tag '${1:search}' ${2:, 'Enter your search query here', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'search_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'select_tag': 'prefix': 'select_tag' 'body': """ <%= select_tag "${1:people}", options_from_collection_for_${2:select}(${3:@people, "id", "name"}), ${4:include_blank: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'select_tag(name, option_tags = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'image_submit_tag': 'prefix': 'image_submit_tag' 'body': """ <%= image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button") %>${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'image_submit_tag(source, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'submit_tag': 'prefix': 'submit_tag' 'body': """ <%= submit_tag(value = "${1:Save changes}", ${2: options = {confirm: " questions?", data: {disabled: true}})} %>${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'submit_tag(value = "Save changes", options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'label_tag': 'prefix': 'label_tag' 'body': """ <%= label_tag 'name', nil, class: 'small_label' %> ${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'label_tag(name = nil, content_or_options = nil, options = nil, &block) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'telephone_field_tag': 'prefix': 'telephone_field_tag' 'body': """ <%= telephone_field_tag '${1:tel}', ${2 '0123456789', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'telephone_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'phone_field_tag': 'prefix': 'phone_field_tag' 'body': """ <%= phone_field(:${1:user}, :${1:phone}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'phone_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'phone_field_tag': 'prefix': 'phone_field_tag' 'body': """ <%= phone_field(:${1:user}, :${1:phone}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'radio_button_tag(name, value, checked = false, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'date_field_tag': 'prefix': 'date_field_tag' 'body': """ <%= radio_button_tag '${1:color}' ${2:, "green", true, class: "color_input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'date_field_tag(name, value = nil, options = {}) />' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'datetime_field_tag': 'prefix': 'datetime_field_tag' 'body': """ <%= date_field_tag '${1:date}' ${2: , '01/01/2014', class: 'special_input', disabled: true } %>$ """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'datetime_field_tag(name, value = nil, options = {}) >' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'month_field_tag': 'prefix': 'month_field_tag' 'body': """ <%= month_field_tag(:${1:user}, ${1: min: 5, max: 8, step: 2}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'month_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'range_field_tag': 'prefix': 'range_field_tag' 'body': """ <%= range_field_tag(:${1:product}, :${2:discount}, in: 1..100) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': ' range_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'week_field_tag': 'prefix': 'week_field_tag' 'body': """ <%= week_field_tag(${1:name}, ${2: value = nil, options = {}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'week_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'number_field_tag': 'prefix': 'number_field_tag' 'body': """ <%= number_field_tag 'quantity' ${1: , '1', min: 3, max: 7, class: 'special_input', disabled: true} %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'number_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'color_field_tag': 'prefix': 'color_field_tag' 'body': """ <%= color_field_tag 'color', '${1:#DEF726}' ${2: , class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'color_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'url_field_tag': 'prefix': 'url_field_tag' 'body': """ <%= url_field_tag(${1:name}, ${2: value = nil, options = {}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'url_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'email_field_tag': 'prefix': 'email_field_tag' 'body': """ <%= email_field_tag '${1:email}' ${2: , '<EMAIL>', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'email_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'time_field_tag': 'prefix': 'time_field_tag' 'body': """ <%= time_field_tag(${1:name}, ${2:value = nil, options = { min: 2, max: 5, step:3}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'time_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'file_field_tag': 'prefix': 'time_field_tag' 'body': """ <%= file_field_tag "${1:file}" %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'file_field_tag(name, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'button_field_tag': 'prefix': 'button_field_tag' 'body': """ <%= button_tag '${1:Reset}', ${2: type: 'reset', disabled: true, data: { confirm: "Are you sure?", disable_with: "Please wait..."} } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'button_tag(content_or_options = nil, options = nil, &block) ' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html' 'check_box_tag': 'prefix': 'check_box_tag' 'body': """ <% check_box_tag '${1:eula}', ${2:'accepted', false, disabled: true} %> """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'check_box_tag(name, value = "1", checked = false, options = {}) ' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html'
true
'.text.html.ruby,.text.html.erb': 'text_area_tag': 'prefix': 'text_area_tag' 'body': """ <%= text_area_tag(:${1:message}, "${1:Hi, nice site}", size: "24x6") %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'text_area_tag(name, content = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'text_field_tag': 'prefix': 'text_field_tag' 'body': """ <%= text_field_tag '${1:ip}', ${2:'0.0.0.0', maxlength: 15, size: 20, class: "ip-input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'text_area_tag(name, content = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'password_field_tag': 'prefix': 'password_field_tag' 'body': """ <%= password_field_tag '${1:pin}' {2: , 'PI:PASSWORD:<PASSWORD>END_PI', maxlength: 4, size: 6, class: "pin_input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'password_field_tag(name = "password", value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'hidden_field_tag': 'prefix': 'hidden_field_tag' 'body': "<%= hidden_field_tag 'collected_input', '', onchange: \"alert('Input collected!')\" %>" 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'hidden_field_tag(name, value = nil, options = {})' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html' 'search_field_tag': 'prefix': 'search_field_tag' 'body': """ <%= search_field_tag '${1:search}' ${2:, 'Enter your search query here', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'search_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'select_tag': 'prefix': 'select_tag' 'body': """ <%= select_tag "${1:people}", options_from_collection_for_${2:select}(${3:@people, "id", "name"}), ${4:include_blank: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'select_tag(name, option_tags = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'image_submit_tag': 'prefix': 'image_submit_tag' 'body': """ <%= image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button") %>${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'image_submit_tag(source, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'submit_tag': 'prefix': 'submit_tag' 'body': """ <%= submit_tag(value = "${1:Save changes}", ${2: options = {confirm: " questions?", data: {disabled: true}})} %>${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'submit_tag(value = "Save changes", options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'label_tag': 'prefix': 'label_tag' 'body': """ <%= label_tag 'name', nil, class: 'small_label' %> ${0} """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'label_tag(name = nil, content_or_options = nil, options = nil, &block) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'telephone_field_tag': 'prefix': 'telephone_field_tag' 'body': """ <%= telephone_field_tag '${1:tel}', ${2 '0123456789', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'telephone_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'phone_field_tag': 'prefix': 'phone_field_tag' 'body': """ <%= phone_field(:${1:user}, :${1:phone}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'phone_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'phone_field_tag': 'prefix': 'phone_field_tag' 'body': """ <%= phone_field(:${1:user}, :${1:phone}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'radio_button_tag(name, value, checked = false, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'date_field_tag': 'prefix': 'date_field_tag' 'body': """ <%= radio_button_tag '${1:color}' ${2:, "green", true, class: "color_input" } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'date_field_tag(name, value = nil, options = {}) />' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'datetime_field_tag': 'prefix': 'datetime_field_tag' 'body': """ <%= date_field_tag '${1:date}' ${2: , '01/01/2014', class: 'special_input', disabled: true } %>$ """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'datetime_field_tag(name, value = nil, options = {}) >' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'month_field_tag': 'prefix': 'month_field_tag' 'body': """ <%= month_field_tag(:${1:user}, ${1: min: 5, max: 8, step: 2}) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'month_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'range_field_tag': 'prefix': 'range_field_tag' 'body': """ <%= range_field_tag(:${1:product}, :${2:discount}, in: 1..100) %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': ' range_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'week_field_tag': 'prefix': 'week_field_tag' 'body': """ <%= week_field_tag(${1:name}, ${2: value = nil, options = {}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'week_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'number_field_tag': 'prefix': 'number_field_tag' 'body': """ <%= number_field_tag 'quantity' ${1: , '1', min: 3, max: 7, class: 'special_input', disabled: true} %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'number_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'color_field_tag': 'prefix': 'color_field_tag' 'body': """ <%= color_field_tag 'color', '${1:#DEF726}' ${2: , class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'color_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'url_field_tag': 'prefix': 'url_field_tag' 'body': """ <%= url_field_tag(${1:name}, ${2: value = nil, options = {}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'url_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'email_field_tag': 'prefix': 'email_field_tag' 'body': """ <%= email_field_tag '${1:email}' ${2: , 'PI:EMAIL:<EMAIL>END_PI', class: 'special_input', disabled: true } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'email_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'time_field_tag': 'prefix': 'time_field_tag' 'body': """ <%= time_field_tag(${1:name}, ${2:value = nil, options = { min: 2, max: 5, step:3}) } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'time_field_tag(name, value = nil, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'file_field_tag': 'prefix': 'time_field_tag' 'body': """ <%= file_field_tag "${1:file}" %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">Rails Form Tag</span>' 'description': 'file_field_tag(name, options = {}) ' 'descriptionMoreURL': 'http://guides.rubyonrails.org/form_helpers.html' 'button_field_tag': 'prefix': 'button_field_tag' 'body': """ <%= button_tag '${1:Reset}', ${2: type: 'reset', disabled: true, data: { confirm: "Are you sure?", disable_with: "Please wait..."} } %>$0 """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'button_tag(content_or_options = nil, options = nil, &block) ' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html' 'check_box_tag': 'prefix': 'check_box_tag' 'body': """ <% check_box_tag '${1:eula}', ${2:'accepted', false, disabled: true} %> """ 'leftLabelHTML': '<span style=\"color:#ed225d;display:inline-block;font-weight:400;font-size:1.25em\">rails</span>' 'description': 'check_box_tag(name, value = "1", checked = false, options = {}) ' 'descriptionMoreURL': 'http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html'
[ { "context": "{\n \"body\": {\n \"key\": {\n \"eldest_kid\": \"01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120b", "end": 118, "score": 0.9973297119140625, "start": 48, "tag": "KEY", "value": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a" }, { "context": "0b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a\",\n \"uid\": \"dbb165b7879fe7b1174df73bed0b9500\"", "end": 233, "score": 0.9953653216362, "start": 163, "tag": "KEY", "value": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a" }, { "context": "65b7879fe7b1174df73bed0b9500\",\n \"username\": \"max\"\n },\n \"team\" : {\n \"name\" : \"acme\",\n ", "end": 307, "score": 0.9995459318161011, "start": 304, "tag": "USERNAME", "value": "max" }, { "context": "ame\": \"max\"\n },\n \"team\" : {\n \"name\" : \"acme\",\n \"id\" : \"3399881122994004422\",\n \"memb", "end": 351, "score": 0.8262524008750916, "start": 347, "tag": "NAME", "value": "acme" }, { "context": "04422\",\n \"members\" : {\n \"owner\" : [ \"max\", \"chris\", \"cr#10\" ],\n \"admin\" : [ \"jack\"", "end": 435, "score": 0.7081623077392578, "start": 432, "tag": "USERNAME", "value": "max" }, { "context": "\n \"members\" : {\n \"owner\" : [ \"max\", \"chris\", \"cr#10\" ],\n \"admin\" : [ \"jack\" ],\n ", "end": 444, "score": 0.8100215196609497, "start": 439, "tag": "USERNAME", "value": "chris" }, { "context": "embers\" : {\n \"owner\" : [ \"max\", \"chris\", \"cr#10\" ],\n \"admin\" : [ \"jack\" ],\n \"write", "end": 453, "score": 0.9964731931686401, "start": 448, "tag": "USERNAME", "value": "cr#10" }, { "context": " \"max\", \"chris\", \"cr#10\" ],\n \"admin\" : [ \"jack\" ],\n \"writer\" : [ \"jinyang\" ],\n \"re", "end": 484, "score": 0.8105210661888123, "start": 480, "tag": "USERNAME", "value": "jack" }, { "context": " \"admin\" : [ \"jack\" ],\n \"writer\" : [ \"jinyang\" ],\n \"reader\" : [ \"robert#33\" ],\n },\n", "end": 518, "score": 0.998166024684906, "start": 511, "tag": "USERNAME", "value": "jinyang" }, { "context": " \"writer\" : [ \"jinyang\" ],\n \"reader\" : [ \"robert#33\" ],\n },\n \"shared_key\" : {\n # Epe", "end": 554, "score": 0.9980693459510803, "start": 545, "tag": "USERNAME", "value": "robert#33" }, { "context": "\n # Epemeral DH public key\n \"E\" : \"012030034004023059902834028430f\",\n \"gen\" : 1,\n \"boxes\" : {\n ", "end": 670, "score": 0.9807124733924866, "start": 640, "tag": "KEY", "value": "12030034004023059902834028430f" }, { "context": "n-link-of-shared-dh-key, box ]\n \"max\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"chris\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE", "end": 870, "score": 0.9996057152748108, "start": 796, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"," }, { "context": "RQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"chris\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"cr\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFG", "end": 961, "score": 0.9996302723884583, "start": 892, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPU" }, { "context": "Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"cr\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFG", "end": 1056, "score": 0.8403462767601013, "start": 985, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU" }, { "context": "aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNP", "end": 1090, "score": 0.7950505614280701, "start": 1080, "tag": "KEY", "value": "kwFkxDAqZQ" }, { "context": "wNPtxZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"\n },\n }\n },\n \"type\": \"team.roo", "end": 1151, "score": 0.8161052465438843, "start": 1093, "tag": "KEY", "value": "aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU" }, { "context": ",\n{\n \"body\": {\n \"key\": {\n \"eldest_kid\": \"01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a\",\n \"host\": \"keybase.io\",\n", "end": 1785, "score": 0.9726036787033081, "start": 1734, "tag": "KEY", "value": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b27" }, { "context": "65b7879fe7b1174df73bed0b9500\",\n \"username\": \"max\"\n },\n \"team\" : {\n \"name\" : \"acme.board", "end": 1993, "score": 0.9991828799247742, "start": 1990, "tag": "USERNAME", "value": "max" }, { "context": "f4422\",\n \"members\" : {\n \"admin\" : [ \"jack\" ],\n \"writer\" : [ \"jinyang\" ]\n }\n ", "end": 2127, "score": 0.9845226407051086, "start": 2123, "tag": "USERNAME", "value": "jack" }, { "context": " \"admin\" : [ \"jack\" ],\n \"writer\" : [ \"jinyang\" ]\n }\n },\n \"type\": \"team.new_subteam\",", "end": 2161, "score": 0.9989646077156067, "start": 2154, "tag": "USERNAME", "value": "jinyang" }, { "context": "567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb\",\n \"seqno\": 282,\n \"tag\": \"signature\"\n},\n{\n \"bo", "end": 2650, "score": 0.6028693914413452, "start": 2642, "tag": "KEY", "value": "22b928bb" }, { "context": ",\n{\n \"body\": {\n \"key\": {\n \"eldest_kid\": \"01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120b", "end": 2811, "score": 0.9757379293441772, "start": 2741, "tag": "KEY", "value": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a" }, { "context": "0b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a\",\n \"uid\": \"dbb165b7879fe7b1174df73bed0b9500\"", "end": 2926, "score": 0.9419119954109192, "start": 2856, "tag": "KEY", "value": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a" }, { "context": "65b7879fe7b1174df73bed0b9500\",\n \"username\": \"max\"\n },\n \"team\" : {\n \"id\" : \"3399881122ee", "end": 3000, "score": 0.9980597496032715, "start": 2997, "tag": "USERNAME", "value": "max" }, { "context": "eff4422\",\n \"members\" : {\n \"none\" : [ \"jinyang\" ]\n },\n \"shared_key\" : {\n # Epem", "end": 3106, "score": 0.9817185997962952, "start": 3099, "tag": "USERNAME", "value": "jinyang" }, { "context": "{\n # Epemeral DH public key\n \"E\" : \"012030034004023059902834028430f\",\n \"gen\" : 2,\n \"boxes\" : {\n ", "end": 3221, "score": 0.9908631443977356, "start": 3190, "tag": "KEY", "value": "012030034004023059902834028430f" }, { "context": "n-link-of-shared-dh-key, box ]\n \"max\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"chris\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE", "end": 3419, "score": 0.9997016191482544, "start": 3345, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"," }, { "context": "RQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"chris\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"cr\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95R", "end": 3515, "score": 0.9997028112411499, "start": 3441, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"," }, { "context": "Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"cr\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"", "end": 3570, "score": 0.970947265625, "start": 3534, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe" }, { "context": " \"cr\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"jack\" : \"", "end": 3579, "score": 0.6868906021118164, "start": 3572, "tag": "KEY", "value": "5B0d1Y+" }, { "context": " \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFG", "end": 3605, "score": 0.6245986223220825, "start": 3582, "tag": "KEY", "value": "VtbkVb96PwNPtxZp0GQPUFU" }, { "context": "aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNP", "end": 3639, "score": 0.6375340819358826, "start": 3629, "tag": "KEY", "value": "kwFkxDAqZQ" }, { "context": "xZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"\n },\n \"prev\" : \"kwFkxDAqZQTm+aLnRU", "end": 3700, "score": 0.6593871116638184, "start": 3645, "tag": "KEY", "value": "RUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU" }, { "context": "b96PwNPtxZp0GQPUFU=\"\n },\n \"prev\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96Pw", "end": 3740, "score": 0.5893357992172241, "start": 3732, "tag": "KEY", "value": "kwFkxDAq" }, { "context": "FU=\"\n },\n \"prev\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "end": 3754, "score": 0.6568397879600525, "start": 3748, "tag": "KEY", "value": "RUc7YD" }, { "context": " },\n \"prev\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"\n },\n \"", "end": 3768, "score": 0.633298397064209, "start": 3759, "tag": "KEY", "value": "E95Rj8fXe" }, { "context": " \"prev\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"\n },\n \"type\"", "end": 3773, "score": 0.5894920229911804, "start": 3769, "tag": "KEY", "value": "I5B0" }, { "context": "rev\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"\n },\n \"type\": \"team.ch", "end": 3783, "score": 0.6337424516677856, "start": 3774, "tag": "KEY", "value": "1Y+aRQVtb" }, { "context": "FkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"\n },\n \"type\": \"team.change_membership\",\n ", "end": 3803, "score": 0.6164228916168213, "start": 3784, "tag": "KEY", "value": "Vb96PwNPtxZp0GQPUFU" }, { "context": ",\n{\n \"body\": {\n \"key\": {\n \"eldest_kid\": \"01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120b", "end": 4450, "score": 0.986659049987793, "start": 4380, "tag": "KEY", "value": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a" }, { "context": "0b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a\",\n \"uid\": \"dbb165b7879fe7b1174df73bed0b9500\"", "end": 4565, "score": 0.976830005645752, "start": 4495, "tag": "KEY", "value": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a" }, { "context": "65b7879fe7b1174df73bed0b9500\",\n \"username\": \"max\"\n },\n \"team\" : {\n \"id\" : \"3399881122ee", "end": 4639, "score": 0.9966960549354553, "start": 4636, "tag": "USERNAME", "value": "max" }, { "context": "{\n # Epemeral DH public key\n \"E\" : \"012030034004023059902834028430f\",\n \"gen\" : 3,\n \"boxes\" : {\n ", "end": 4800, "score": 0.9994027614593506, "start": 4769, "tag": "KEY", "value": "012030034004023059902834028430f" }, { "context": "n-link-of-shared-dh-key, box ]\n \"max\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"chris\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE", "end": 4998, "score": 0.9997372627258301, "start": 4924, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"," }, { "context": "RQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"chris\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"cr\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95R", "end": 5094, "score": 0.9997390508651733, "start": 5020, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"," }, { "context": "Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"cr\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE9", "end": 5187, "score": 0.9997323751449585, "start": 5113, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"," }, { "context": "aRQVtbkVb96PwNPtxZp0GQPUFU=\",\n \"jack\" : \"kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"\n },\n \"prev\" : \"kwFkxDAqZQTm+aLnRUc7", "end": 5281, "score": 0.9997437000274658, "start": 5208, "tag": "KEY", "value": "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=\"" }, { "context": "ture\"\n},\n{\n \"body\": {\n \"key\": {\n \"eldest_kid\": \"01013ef90b4c4e62121d12a51d18569b57996002c8bdcc", "end": 5944, "score": 0.9931729435920715, "start": 5941, "tag": "KEY", "value": "kid" }, { "context": ",\n{\n \"body\": {\n \"key\": {\n \"eldest_kid\": \"01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120b", "end": 6018, "score": 0.999580979347229, "start": 5948, "tag": "KEY", "value": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a" }, { "context": "b40a\",\n \"host\": \"keybase.io\",\n \"kid\": \"0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a\",\n \"ui", "end": 6095, "score": 0.9430009126663208, "start": 6064, "tag": "KEY", "value": "120bd7350508b78d8be24a04789dc88" }, { "context": "65b7879fe7b1174df73bed0b9500\",\n \"username\": \"max\"\n },\n \"team\" : {\n \"id\" : \"3399881122ee", "end": 6207, "score": 0.9995459318161011, "start": 6204, "tag": "USERNAME", "value": "max" }, { "context": "7cbbd4914bd\",\n \"seqno\": 935116\n },\n \"prev\": \"f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb\",\n \"seqno\": 282,\n \"tag\": \"signature\"\n}\n\n", "end": 7061, "score": 0.8759753108024597, "start": 6997, "tag": "KEY", "value": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb" } ]
teams_sample.cson
Dexvirxx/proofs
118
{ "body": { "key": { "eldest_kid": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a", "host": "keybase.io", "kid": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "name" : "acme", "id" : "3399881122994004422", "members" : { "owner" : [ "max", "chris", "cr#10" ], "admin" : [ "jack" ], "writer" : [ "jinyang" ], "reader" : [ "robert#33" ], }, "shared_key" : { # Epemeral DH public key "E" : "012030034004023059902834028430f", "gen" : 1, "boxes" : { # pack [ version=1, chain-link-of-shared-dh-key, box ] "max" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "chris" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "cr" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "jack" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=" }, } }, "type": "team.root", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a", "host": "keybase.io", "kid": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "name" : "acme.board", "id" : "3399881122eeff4422", "members" : { "admin" : [ "jack" ], "writer" : [ "jinyang" ] } }, "type": "team.new_subteam", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a", "host": "keybase.io", "kid": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "members" : { "none" : [ "jinyang" ] }, "shared_key" : { # Epemeral DH public key "E" : "012030034004023059902834028430f", "gen" : 2, "boxes" : { # pack [ version, chain-link-of-shared-dh-key, box ] "max" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "chris" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "cr" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "jack" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=" }, "prev" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=" }, "type": "team.change_membership", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a", "host": "keybase.io", "kid": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "shared_key" : { # Epemeral DH public key "E" : "012030034004023059902834028430f", "gen" : 3, "boxes" : { # pack [ version, chain-link-of-shared-dh-key, box ] "max" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "chris" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "cr" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=", "jack" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=" }, "prev" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=" }, "type": "team.rotate", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "01013ef90b4c4e62121d12a51d18569b57996002c8bdccc9b2740935c9e4a07d20b40a", "host": "keybase.io", "kid": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "index" : { "root" : "44aabb343344555", "subteams" : { # Map of Team ID -> [ tail seqno, tail hash ] pairs "1123499eee334" : [ 10, "3349955000293945" ], "3344993440059" : [ 30, "3349950029945902" ], "4499928834552" : [ 40, "3399488592993949" ] } } }, "type": "team.index", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }
25142
{ "body": { "key": { "eldest_kid": "<KEY>", "host": "keybase.io", "kid": "<KEY>", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "name" : "<NAME>", "id" : "3399881122994004422", "members" : { "owner" : [ "max", "chris", "cr#10" ], "admin" : [ "jack" ], "writer" : [ "jinyang" ], "reader" : [ "robert#33" ], }, "shared_key" : { # Epemeral DH public key "E" : "0<KEY>", "gen" : 1, "boxes" : { # pack [ version=1, chain-link-of-shared-dh-key, box ] "max" : "<KEY> "chris" : "<KEY>FU=", "cr" : "<KEY>=", "jack" : "<KEY>Tm+<KEY>=" }, } }, "type": "team.root", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "<KEY>40935c9e4a07d20b40a", "host": "keybase.io", "kid": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "name" : "acme.board", "id" : "3399881122eeff4422", "members" : { "admin" : [ "jack" ], "writer" : [ "jinyang" ] } }, "type": "team.new_subteam", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f<KEY>", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "<KEY>", "host": "keybase.io", "kid": "<KEY>", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "members" : { "none" : [ "jinyang" ] }, "shared_key" : { # Epemeral DH public key "E" : "<KEY>", "gen" : 2, "boxes" : { # pack [ version, chain-link-of-shared-dh-key, box ] "max" : "<KEY> "chris" : "<KEY> "cr" : "<KEY>/I<KEY>aRQ<KEY>=", "jack" : "<KEY>Tm+aLn<KEY>=" }, "prev" : "<KEY>ZQTm+aLn<KEY>ZUFGd<KEY>/<KEY>d<KEY>k<KEY>=" }, "type": "team.change_membership", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "<KEY>", "host": "keybase.io", "kid": "<KEY>", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "shared_key" : { # Epemeral DH public key "E" : "<KEY>", "gen" : 3, "boxes" : { # pack [ version, chain-link-of-shared-dh-key, box ] "max" : "<KEY> "chris" : "<KEY> "cr" : "<KEY> "jack" : "<KEY> }, "prev" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=" }, "type": "team.rotate", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_<KEY>": "<KEY>", "host": "keybase.io", "kid": "0<KEY>f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "index" : { "root" : "44aabb343344555", "subteams" : { # Map of Team ID -> [ tail seqno, tail hash ] pairs "1123499eee334" : [ 10, "3349955000293945" ], "3344993440059" : [ 30, "3349950029945902" ], "4499928834552" : [ 40, "3399488592993949" ] } } }, "type": "team.index", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "<KEY>", "seqno": 282, "tag": "signature" }
true
{ "body": { "key": { "eldest_kid": "PI:KEY:<KEY>END_PI", "host": "keybase.io", "kid": "PI:KEY:<KEY>END_PI", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "name" : "PI:NAME:<NAME>END_PI", "id" : "3399881122994004422", "members" : { "owner" : [ "max", "chris", "cr#10" ], "admin" : [ "jack" ], "writer" : [ "jinyang" ], "reader" : [ "robert#33" ], }, "shared_key" : { # Epemeral DH public key "E" : "0PI:KEY:<KEY>END_PI", "gen" : 1, "boxes" : { # pack [ version=1, chain-link-of-shared-dh-key, box ] "max" : "PI:KEY:<KEY>END_PI "chris" : "PI:KEY:<KEY>END_PIFU=", "cr" : "PI:KEY:<KEY>END_PI=", "jack" : "PI:KEY:<KEY>END_PITm+PI:KEY:<KEY>END_PI=" }, } }, "type": "team.root", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "PI:KEY:<KEY>END_PI40935c9e4a07d20b40a", "host": "keybase.io", "kid": "0120bd7350508b78d8be24a04789dc88f409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "name" : "acme.board", "id" : "3399881122eeff4422", "members" : { "admin" : [ "jack" ], "writer" : [ "jinyang" ] } }, "type": "team.new_subteam", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17fPI:KEY:<KEY>END_PI", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "PI:KEY:<KEY>END_PI", "host": "keybase.io", "kid": "PI:KEY:<KEY>END_PI", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "members" : { "none" : [ "jinyang" ] }, "shared_key" : { # Epemeral DH public key "E" : "PI:KEY:<KEY>END_PI", "gen" : 2, "boxes" : { # pack [ version, chain-link-of-shared-dh-key, box ] "max" : "PI:KEY:<KEY>END_PI "chris" : "PI:KEY:<KEY>END_PI "cr" : "PI:KEY:<KEY>END_PI/IPI:KEY:<KEY>END_PIaRQPI:KEY:<KEY>END_PI=", "jack" : "PI:KEY:<KEY>END_PITm+aLnPI:KEY:<KEY>END_PI=" }, "prev" : "PI:KEY:<KEY>END_PIZQTm+aLnPI:KEY:<KEY>END_PIZUFGdPI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PIdPI:KEY:<KEY>END_PIkPI:KEY:<KEY>END_PI=" }, "type": "team.change_membership", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_kid": "PI:KEY:<KEY>END_PI", "host": "keybase.io", "kid": "PI:KEY:<KEY>END_PI", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "shared_key" : { # Epemeral DH public key "E" : "PI:KEY:<KEY>END_PI", "gen" : 3, "boxes" : { # pack [ version, chain-link-of-shared-dh-key, box ] "max" : "PI:KEY:<KEY>END_PI "chris" : "PI:KEY:<KEY>END_PI "cr" : "PI:KEY:<KEY>END_PI "jack" : "PI:KEY:<KEY>END_PI }, "prev" : "kwFkxDAqZQTm+aLnRUc7YDZUFGdE95Rj8fXe/I5B0d1Y+aRQVtbkVb96PwNPtxZp0GQPUFU=" }, "type": "team.rotate", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "f9562b567b87d1093431fa134bf1555106c5c32011480f06cf25e17f22b928bb", "seqno": 282, "tag": "signature" }, { "body": { "key": { "eldest_PI:KEY:<KEY>END_PI": "PI:KEY:<KEY>END_PI", "host": "keybase.io", "kid": "0PI:KEY:<KEY>END_PIf409c9fe607713dbc685215091b7a37aec130a", "uid": "dbb165b7879fe7b1174df73bed0b9500", "username": "max" }, "team" : { "id" : "3399881122eeff4422", "index" : { "root" : "44aabb343344555", "subteams" : { # Map of Team ID -> [ tail seqno, tail hash ] pairs "1123499eee334" : [ 10, "3349955000293945" ], "3344993440059" : [ 30, "3349950029945902" ], "4499928834552" : [ 40, "3399488592993949" ] } } }, "type": "team.index", "version": 1 }, "client": { "name": "keybase.io go client", "version": "1.0.18" }, "ctime": 1488484752, "expire_in": 504576000, "merkle_root": { "ctime": 1488484733, "hash": "cfd761cb7bd98478137e9a2e65a4b8e5e7c443348894d76a6f2a68f65c52c73cc69c8b633a4851ecd29671b3390e0a0b03af3d28adc3b18626b8d7cbbd4914bd", "seqno": 935116 }, "prev": "PI:KEY:<KEY>END_PI", "seqno": 282, "tag": "signature" }
[ { "context": "ign/factsMainViews/_view/EntityConceptName?key=[\\\"http://www.sec.gov/CIK/#{identifier}\\\",\\\"#{elementName}\\\"]&include_do", "end": 445, "score": 0.7091633081436157, "start": 426, "tag": "KEY", "value": "http://www.sec.gov/" }, { "context": "iew/EntityConceptName?key=[\\\"http://www.sec.gov/CIK/#{identifier}\\\",\\\"#{elementName}\\\"]&include_docs=tru", "end": 451, "score": 0.7736042141914368, "start": 447, "tag": "KEY", "value": "K/#{" }, { "context": "eptName?key=[\\\"http://www.sec.gov/CIK/#{identifier}\\\",\\\"#{elementName}\\\"]&include_docs=true&stale=upda", "end": 461, "score": 0.6647831201553345, "start": 461, "tag": "KEY", "value": "" } ]
routes/rawfacts.coffee
curtinmjc/XbrlServer
0
express = require('express') http = require('http') request = require('request') JSONStream = require('JSONStream') {tickerResolver} = require('./helpers') {getCloudantUrl} = require('./helpers') {ObjectStringTransformStream} = require('../streams/ObjectStringTransformStream') sendResponse = (identifier, elementName, res) -> request({url: "#{getCloudantUrl()}/facts/_design/factsMainViews/_view/EntityConceptName?key=[\"http://www.sec.gov/CIK/#{identifier}\",\"#{elementName}\"]&include_docs=true&stale=update_after&reduce=false"}) .pipe(JSONStream.parse('rows.*.doc')) .pipe(new ObjectStringTransformStream()) .pipe(res) router = express.Router() router.get(/\/rawfacts\/([a-zA-Z0-9]+)\/(.+)/, (req, res) -> cikOrTicker = req.params[0] elementName = req.params[1] cik = null if cikOrTicker.match(/[0-9]{10}/) sendResponse(cikOrTicker, elementName, res) else tickerResolver(cikOrTicker, (identifier) -> if not identifier? res.end('[]') else sendResponse(identifier.cik, elementName, res))) module.exports = router
81870
express = require('express') http = require('http') request = require('request') JSONStream = require('JSONStream') {tickerResolver} = require('./helpers') {getCloudantUrl} = require('./helpers') {ObjectStringTransformStream} = require('../streams/ObjectStringTransformStream') sendResponse = (identifier, elementName, res) -> request({url: "#{getCloudantUrl()}/facts/_design/factsMainViews/_view/EntityConceptName?key=[\"<KEY>CI<KEY>identifier<KEY>}\",\"#{elementName}\"]&include_docs=true&stale=update_after&reduce=false"}) .pipe(JSONStream.parse('rows.*.doc')) .pipe(new ObjectStringTransformStream()) .pipe(res) router = express.Router() router.get(/\/rawfacts\/([a-zA-Z0-9]+)\/(.+)/, (req, res) -> cikOrTicker = req.params[0] elementName = req.params[1] cik = null if cikOrTicker.match(/[0-9]{10}/) sendResponse(cikOrTicker, elementName, res) else tickerResolver(cikOrTicker, (identifier) -> if not identifier? res.end('[]') else sendResponse(identifier.cik, elementName, res))) module.exports = router
true
express = require('express') http = require('http') request = require('request') JSONStream = require('JSONStream') {tickerResolver} = require('./helpers') {getCloudantUrl} = require('./helpers') {ObjectStringTransformStream} = require('../streams/ObjectStringTransformStream') sendResponse = (identifier, elementName, res) -> request({url: "#{getCloudantUrl()}/facts/_design/factsMainViews/_view/EntityConceptName?key=[\"PI:KEY:<KEY>END_PICIPI:KEY:<KEY>END_PIidentifierPI:KEY:<KEY>END_PI}\",\"#{elementName}\"]&include_docs=true&stale=update_after&reduce=false"}) .pipe(JSONStream.parse('rows.*.doc')) .pipe(new ObjectStringTransformStream()) .pipe(res) router = express.Router() router.get(/\/rawfacts\/([a-zA-Z0-9]+)\/(.+)/, (req, res) -> cikOrTicker = req.params[0] elementName = req.params[1] cik = null if cikOrTicker.match(/[0-9]{10}/) sendResponse(cikOrTicker, elementName, res) else tickerResolver(cikOrTicker, (identifier) -> if not identifier? res.end('[]') else sendResponse(identifier.cik, elementName, res))) module.exports = router
[ { "context": " JSON scene\n# description compatible with hqz.\n#\n# Micah Elizabeth Scott <micah@scanlime.org>\n# This file is released into", "end": 145, "score": 0.999884843826294, "start": 124, "tag": "NAME", "value": "Micah Elizabeth Scott" }, { "context": "n compatible with hqz.\n#\n# Micah Elizabeth Scott <micah@scanlime.org>\n# This file is released into the public domain.\n", "end": 165, "score": 0.9999266862869263, "start": 147, "tag": "EMAIL", "value": "micah@scanlime.org" } ]
example /hqz/zen2json.coffee
amane312/photon_generator
0
#!/usr/bin/env coffee # # This script converts a zenphoton.com URL into a JSON scene # description compatible with hqz. # # Micah Elizabeth Scott <micah@scanlime.org> # This file is released into the public domain. # findOrAppend = (list, item) -> # Find an item in the list or append if it isn't already there. # Returns a zero-based index. Uses a loose equivalency test; # if two objects have the same JSON represenatation, they're equal to us. itemStr = JSON.stringify item for id in [0 .. list.length - 1] if itemStr == JSON.stringify list[id] return id id = list.length list.push item return id module.exports = parseZenBlob: (blob) -> # Parse a binary blob from zenphoton.com. # Switch to a decoder for this specific format version, encoded in # the first byte. try return switch blob.readUInt8 0 when 0x00 then @parseZenBlobV0 blob catch e # Bad format return null if e.name == 'AssertionError' throw e parseZenBlobV0: (blob) -> # Parse a binary blob for zenphoton.com format version 0 # Fixed header width = blob.readInt16BE 1 height = blob.readInt16BE 3 lightX = blob.readInt16BE 5 lightY = blob.readInt16BE 7 exposure = blob.readUInt8 9 numSegments = blob.readUInt16BE 10 # One light, monochromatic white light = [ 1, lightX, lightY, 0, 0, [0, 360], 0 ] # Fixed-size portions of the scene scene = resolution: [ width, height ] viewport: [ 0, 0, width, height ] exposure: exposure / 255.0 lights: [ light ] objects: [] materials: [] # Iterate over segments o = 12 for i in [0 .. numSegments-1] by 1 x0 = blob.readInt16BE o+0 y0 = blob.readInt16BE o+2 x1 = blob.readInt16BE o+4 y1 = blob.readInt16BE o+6 diffuse = blob.readUInt8 o+8 reflective = blob.readUInt8 o+9 transmissive = blob.readUInt8 o+10 o += 11 # Build a material mat = [] mat.push [ diffuse / 255.0, 'd' ] if diffuse > 0 mat.push [ reflective / 255.0, 'r' ] if reflective > 0 mat.push [ transmissive / 255.0, 't' ] if transmissive > 0 matID = findOrAppend scene.materials, mat # Build an object scene.objects.push [ matID, x0, y0, x1-x0, y1-y0 ] return scene parseURL: (url) -> # Parse an entire zenphoton.com URL. If other web sites were compatible # with this rendering system in the future, this would handle their URLs too. url = url.trim() zenPrefix = "http://zenphoton.com/#" if url.toLowerCase().slice(0, zenPrefix.length) == zenPrefix return @parseZenBlob new Buffer url.slice(zenPrefix.length), 'base64' main = (argv) -> if argv.length != 3 process.stderr.write "usage: zen2json http://zenphoton.com/#...\n" return 1 result = module.exports.parseURL argv[2] if not result process.stderr.write "Error parsing this URL. Are you sure it's complete?\n" return 1 process.stdout.write JSON.stringify result process.stdout.write "\n" # This file is usable as a command line tool or a node.js module process.exit main process.argv if require.main is module
38322
#!/usr/bin/env coffee # # This script converts a zenphoton.com URL into a JSON scene # description compatible with hqz. # # <NAME> <<EMAIL>> # This file is released into the public domain. # findOrAppend = (list, item) -> # Find an item in the list or append if it isn't already there. # Returns a zero-based index. Uses a loose equivalency test; # if two objects have the same JSON represenatation, they're equal to us. itemStr = JSON.stringify item for id in [0 .. list.length - 1] if itemStr == JSON.stringify list[id] return id id = list.length list.push item return id module.exports = parseZenBlob: (blob) -> # Parse a binary blob from zenphoton.com. # Switch to a decoder for this specific format version, encoded in # the first byte. try return switch blob.readUInt8 0 when 0x00 then @parseZenBlobV0 blob catch e # Bad format return null if e.name == 'AssertionError' throw e parseZenBlobV0: (blob) -> # Parse a binary blob for zenphoton.com format version 0 # Fixed header width = blob.readInt16BE 1 height = blob.readInt16BE 3 lightX = blob.readInt16BE 5 lightY = blob.readInt16BE 7 exposure = blob.readUInt8 9 numSegments = blob.readUInt16BE 10 # One light, monochromatic white light = [ 1, lightX, lightY, 0, 0, [0, 360], 0 ] # Fixed-size portions of the scene scene = resolution: [ width, height ] viewport: [ 0, 0, width, height ] exposure: exposure / 255.0 lights: [ light ] objects: [] materials: [] # Iterate over segments o = 12 for i in [0 .. numSegments-1] by 1 x0 = blob.readInt16BE o+0 y0 = blob.readInt16BE o+2 x1 = blob.readInt16BE o+4 y1 = blob.readInt16BE o+6 diffuse = blob.readUInt8 o+8 reflective = blob.readUInt8 o+9 transmissive = blob.readUInt8 o+10 o += 11 # Build a material mat = [] mat.push [ diffuse / 255.0, 'd' ] if diffuse > 0 mat.push [ reflective / 255.0, 'r' ] if reflective > 0 mat.push [ transmissive / 255.0, 't' ] if transmissive > 0 matID = findOrAppend scene.materials, mat # Build an object scene.objects.push [ matID, x0, y0, x1-x0, y1-y0 ] return scene parseURL: (url) -> # Parse an entire zenphoton.com URL. If other web sites were compatible # with this rendering system in the future, this would handle their URLs too. url = url.trim() zenPrefix = "http://zenphoton.com/#" if url.toLowerCase().slice(0, zenPrefix.length) == zenPrefix return @parseZenBlob new Buffer url.slice(zenPrefix.length), 'base64' main = (argv) -> if argv.length != 3 process.stderr.write "usage: zen2json http://zenphoton.com/#...\n" return 1 result = module.exports.parseURL argv[2] if not result process.stderr.write "Error parsing this URL. Are you sure it's complete?\n" return 1 process.stdout.write JSON.stringify result process.stdout.write "\n" # This file is usable as a command line tool or a node.js module process.exit main process.argv if require.main is module
true
#!/usr/bin/env coffee # # This script converts a zenphoton.com URL into a JSON scene # description compatible with hqz. # # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # This file is released into the public domain. # findOrAppend = (list, item) -> # Find an item in the list or append if it isn't already there. # Returns a zero-based index. Uses a loose equivalency test; # if two objects have the same JSON represenatation, they're equal to us. itemStr = JSON.stringify item for id in [0 .. list.length - 1] if itemStr == JSON.stringify list[id] return id id = list.length list.push item return id module.exports = parseZenBlob: (blob) -> # Parse a binary blob from zenphoton.com. # Switch to a decoder for this specific format version, encoded in # the first byte. try return switch blob.readUInt8 0 when 0x00 then @parseZenBlobV0 blob catch e # Bad format return null if e.name == 'AssertionError' throw e parseZenBlobV0: (blob) -> # Parse a binary blob for zenphoton.com format version 0 # Fixed header width = blob.readInt16BE 1 height = blob.readInt16BE 3 lightX = blob.readInt16BE 5 lightY = blob.readInt16BE 7 exposure = blob.readUInt8 9 numSegments = blob.readUInt16BE 10 # One light, monochromatic white light = [ 1, lightX, lightY, 0, 0, [0, 360], 0 ] # Fixed-size portions of the scene scene = resolution: [ width, height ] viewport: [ 0, 0, width, height ] exposure: exposure / 255.0 lights: [ light ] objects: [] materials: [] # Iterate over segments o = 12 for i in [0 .. numSegments-1] by 1 x0 = blob.readInt16BE o+0 y0 = blob.readInt16BE o+2 x1 = blob.readInt16BE o+4 y1 = blob.readInt16BE o+6 diffuse = blob.readUInt8 o+8 reflective = blob.readUInt8 o+9 transmissive = blob.readUInt8 o+10 o += 11 # Build a material mat = [] mat.push [ diffuse / 255.0, 'd' ] if diffuse > 0 mat.push [ reflective / 255.0, 'r' ] if reflective > 0 mat.push [ transmissive / 255.0, 't' ] if transmissive > 0 matID = findOrAppend scene.materials, mat # Build an object scene.objects.push [ matID, x0, y0, x1-x0, y1-y0 ] return scene parseURL: (url) -> # Parse an entire zenphoton.com URL. If other web sites were compatible # with this rendering system in the future, this would handle their URLs too. url = url.trim() zenPrefix = "http://zenphoton.com/#" if url.toLowerCase().slice(0, zenPrefix.length) == zenPrefix return @parseZenBlob new Buffer url.slice(zenPrefix.length), 'base64' main = (argv) -> if argv.length != 3 process.stderr.write "usage: zen2json http://zenphoton.com/#...\n" return 1 result = module.exports.parseURL argv[2] if not result process.stderr.write "Error parsing this URL. Are you sure it's complete?\n" return 1 process.stdout.write JSON.stringify result process.stdout.write "\n" # This file is usable as a command line tool or a node.js module process.exit main process.argv if require.main is module
[ { "context": "###\n\tfile: src/server/settings-srvr\n\n copyright mark hahn 2013\n MIT license\n https://github.com/mark-", "end": 60, "score": 0.9995383620262146, "start": 51, "tag": "NAME", "value": "mark hahn" }, { "context": " hahn 2013\n MIT license\n https://github.com/mark-hahn/bace/\n###\n\nfs = require 'fs'\nuser = require './us", "end": 114, "score": 0.9997274279594421, "start": 105, "tag": "USERNAME", "value": "mark-hahn" } ]
src/server/settings-srvr.coffee
mark-hahn/bace
1
### file: src/server/settings-srvr copyright mark hahn 2013 MIT license https://github.com/mark-hahn/bace/ ### fs = require 'fs' user = require './user-srvr' settings = exports avoidThemes = kr: yes themeList = [] console.log process.cwd() allFiles = fs.readdirSync 'ace/src-noconflict' for file in allFiles if (name = /^theme-(.+).js$/.exec file) and not avoidThemes[name[1]] themeList.push name[1] avoidLanguages = {} languageList = [] allFiles = fs.readdirSync 'ace/src-noconflict' for file in allFiles if (name = /^worker-(.+).js$/.exec file) and not avoidLanguages[name[1]] languageList.push name[1] settings.init = (client) -> client.on 'getThemeList', (data) -> if client.notSignedIn data.loginData then return client.emit 'themeList', themeList client.on 'setTheme', (data) -> if client.notSignedIn data.loginData then return user.saveUserSetting data.loginData.userId, 'theme', data.lbl client.on 'getLanguageList', (data) -> if client.notSignedIn data.loginData then return # console.log 'getLanguageList', languageList client.emit 'languageList', languageList
107423
### file: src/server/settings-srvr copyright <NAME> 2013 MIT license https://github.com/mark-hahn/bace/ ### fs = require 'fs' user = require './user-srvr' settings = exports avoidThemes = kr: yes themeList = [] console.log process.cwd() allFiles = fs.readdirSync 'ace/src-noconflict' for file in allFiles if (name = /^theme-(.+).js$/.exec file) and not avoidThemes[name[1]] themeList.push name[1] avoidLanguages = {} languageList = [] allFiles = fs.readdirSync 'ace/src-noconflict' for file in allFiles if (name = /^worker-(.+).js$/.exec file) and not avoidLanguages[name[1]] languageList.push name[1] settings.init = (client) -> client.on 'getThemeList', (data) -> if client.notSignedIn data.loginData then return client.emit 'themeList', themeList client.on 'setTheme', (data) -> if client.notSignedIn data.loginData then return user.saveUserSetting data.loginData.userId, 'theme', data.lbl client.on 'getLanguageList', (data) -> if client.notSignedIn data.loginData then return # console.log 'getLanguageList', languageList client.emit 'languageList', languageList
true
### file: src/server/settings-srvr copyright PI:NAME:<NAME>END_PI 2013 MIT license https://github.com/mark-hahn/bace/ ### fs = require 'fs' user = require './user-srvr' settings = exports avoidThemes = kr: yes themeList = [] console.log process.cwd() allFiles = fs.readdirSync 'ace/src-noconflict' for file in allFiles if (name = /^theme-(.+).js$/.exec file) and not avoidThemes[name[1]] themeList.push name[1] avoidLanguages = {} languageList = [] allFiles = fs.readdirSync 'ace/src-noconflict' for file in allFiles if (name = /^worker-(.+).js$/.exec file) and not avoidLanguages[name[1]] languageList.push name[1] settings.init = (client) -> client.on 'getThemeList', (data) -> if client.notSignedIn data.loginData then return client.emit 'themeList', themeList client.on 'setTheme', (data) -> if client.notSignedIn data.loginData then return user.saveUserSetting data.loginData.userId, 'theme', data.lbl client.on 'getLanguageList', (data) -> if client.notSignedIn data.loginData then return # console.log 'getLanguageList', languageList client.emit 'languageList', languageList
[ { "context": "e.openstreetmap.org/{z}/{x}/{y}.png',\n key: '1234'\n layerName: 'OpenStreetMap'\n styleId: ", "end": 594, "score": 0.9961836934089661, "start": 590, "tag": "KEY", "value": "1234" } ]
app/packages/grits-net-meteor/client/mapper/grits_map.coffee
billdmcconnell/fliightData
4
_imagePath = 'packages/bevanhunt_leaflet/images' # Creates an instance of a map # # @param [String] # @param [Object] options, Leaflet map options + height # @see http://leafletjs.com/reference.html#map-options class GritsMap extends L.Map constructor: (element, options) -> @_name = 'GritsMap' @_element = element or 'grits-map' @_gritsOverlayControl = null @_gritsOverlays = {} @_gritsTileLayers = {} @_gritsLayers = {} L.Icon.Default.imagePath = _imagePath OpenStreetMap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', key: '1234' layerName: 'OpenStreetMap' styleId: 22677) if typeof options == 'undefined' @_options = { center: [37.8, -92] zoomControl: false noWrap: true maxZoom: 18 minZoom: 0 layers: [OpenStreetMap] } else @_options = options if typeof @_options.layers == 'undefined' @_options.layers = [OpenStreetMap] for layer in @_options.layers @_gritsTileLayers[layer.options.layerName] = layer @_options.layers = [@_options.layers[0]] super(@_element, @_options) @_drawOverlayControls() @_createDefaultLayerGroups() return # creates the default layer groups required by the map _createDefaultLayerGroups: -> # Add analyze layers to a layer group then store to map analyzeLayers = {} analyzeLayers[GritsConstants.NODE_LAYER_ID] = new GritsNodeLayer(this, GritsConstants.NODE_LAYER_ID) analyzeLayers[GritsConstants.PATH_LAYER_ID] = new GritsPathLayer(this, GritsConstants.PATH_LAYER_ID) analyzeLayerGroup = new GritsLayerGroup(analyzeLayers, this, GritsConstants.ANALYZE_GROUP_LAYER_ID, 'Simulation Flight Routes') analyzeLayerGroup.add() this.addGritsLayerGroup(analyzeLayerGroup) # Add explore layers to a layer group then store to map exploreLayers = {} exploreLayers[GritsConstants.NODE_LAYER_ID] = new GritsNodeLayer(this, GritsConstants.NODE_LAYER_ID) exploreLayers[GritsConstants.PATH_LAYER_ID] = new GritsPathLayer(this, GritsConstants.PATH_LAYER_ID) exploreLayerGroup = new GritsLayerGroup(exploreLayers, this, GritsConstants.EXPLORE_GROUP_LAYER_ID, 'Direct Flight Routes') exploreLayerGroup.add() this.addGritsLayerGroup(exploreLayerGroup) # Add heatmap layer to a layer group then store to map heatmapLayers = {} heatmapLayers[GritsConstants.HEATMAP_LAYER_ID] = new GritsHeatmapLayer(this, GritsConstants.HEATMAP_LAYER_ID) heatmapLayerGroup = new GritsLayerGroup(heatmapLayers, this, GritsConstants.HEATMAP_GROUP_LAYER_ID, 'Heatmap') this.addGritsLayerGroup(heatmapLayerGroup) # Add all nodes layers to a layer group then add to map allNodesLayers = {} allNodesLayers[GritsConstants.NODE_LAYER_ID] = new GritsAllNodesLayer(this) allNodesLayerGroup = new GritsLayerGroup(allNodesLayers, this, GritsConstants.ALL_NODES_GROUP_LAYER_ID, 'All Nodes') this.addGritsLayerGroup(allNodesLayerGroup) # adds a layer reference to the map object # # @note This does not add the layer to the Leaflet map. Its just a container # @param [Object] layer, a GritsLayer instance addGritsLayerGroup: (layerGroup) -> if typeof layerGroup == 'undefined' throw new Error('A layer must be defined') return if !layerGroup instanceof GritsLayerGroup throw new Error('A map requires a valid GritsLayerGroup instance') return @_layers[layerGroup._id] = layerGroup return # gets a layer refreence from the map object # # @param [String] id, a string containing the name of the layer as shown # in the UI layer controls getGritsLayerGroup: (id) -> if typeof id == 'undefined' throw new Error('A GritsLayerGroup Id must be defined') return if @_layers.hasOwnProperty(id) == true return @_layers[id] return null # draws the overlay controls within the control box in the upper-right # corner of the map. It uses @_gritsOverlayControl to place the reference of # the overlay controls. _drawOverlayControls: () -> if @_gritsOverlayControl == null @_gritsOverlayControl = L.control.layers(@_gritsTileLayers, @_gritsOverlays).addTo this else @_gritsOverlayControl.removeFrom(this) @_gritsOverlayControl = L.control.layers(@_gritsTileLayers, @_gritsOverlays).addTo this return # adds a new overlay control to the map # # @param [String] layerName, string containing the name of the layer # @param [Object] layerGroup, the layerGroup object to add to the map controls addOverlayControl: (layerName, layerGroup) -> @_gritsOverlays[layerName] = layerGroup @_drawOverlayControls() window.dispatchEvent(new Event('mapper.addOverlayControl')) return # removes overlay control from the map # # @param [String] layerName, string containing the name of the layer removeOverlayControl: (layerName) -> if @_gritsOverlays.hasOwnProperty layerName delete @_gritsOverlays[layerName] @_drawOverlayControls() return
117049
_imagePath = 'packages/bevanhunt_leaflet/images' # Creates an instance of a map # # @param [String] # @param [Object] options, Leaflet map options + height # @see http://leafletjs.com/reference.html#map-options class GritsMap extends L.Map constructor: (element, options) -> @_name = 'GritsMap' @_element = element or 'grits-map' @_gritsOverlayControl = null @_gritsOverlays = {} @_gritsTileLayers = {} @_gritsLayers = {} L.Icon.Default.imagePath = _imagePath OpenStreetMap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', key: '<KEY>' layerName: 'OpenStreetMap' styleId: 22677) if typeof options == 'undefined' @_options = { center: [37.8, -92] zoomControl: false noWrap: true maxZoom: 18 minZoom: 0 layers: [OpenStreetMap] } else @_options = options if typeof @_options.layers == 'undefined' @_options.layers = [OpenStreetMap] for layer in @_options.layers @_gritsTileLayers[layer.options.layerName] = layer @_options.layers = [@_options.layers[0]] super(@_element, @_options) @_drawOverlayControls() @_createDefaultLayerGroups() return # creates the default layer groups required by the map _createDefaultLayerGroups: -> # Add analyze layers to a layer group then store to map analyzeLayers = {} analyzeLayers[GritsConstants.NODE_LAYER_ID] = new GritsNodeLayer(this, GritsConstants.NODE_LAYER_ID) analyzeLayers[GritsConstants.PATH_LAYER_ID] = new GritsPathLayer(this, GritsConstants.PATH_LAYER_ID) analyzeLayerGroup = new GritsLayerGroup(analyzeLayers, this, GritsConstants.ANALYZE_GROUP_LAYER_ID, 'Simulation Flight Routes') analyzeLayerGroup.add() this.addGritsLayerGroup(analyzeLayerGroup) # Add explore layers to a layer group then store to map exploreLayers = {} exploreLayers[GritsConstants.NODE_LAYER_ID] = new GritsNodeLayer(this, GritsConstants.NODE_LAYER_ID) exploreLayers[GritsConstants.PATH_LAYER_ID] = new GritsPathLayer(this, GritsConstants.PATH_LAYER_ID) exploreLayerGroup = new GritsLayerGroup(exploreLayers, this, GritsConstants.EXPLORE_GROUP_LAYER_ID, 'Direct Flight Routes') exploreLayerGroup.add() this.addGritsLayerGroup(exploreLayerGroup) # Add heatmap layer to a layer group then store to map heatmapLayers = {} heatmapLayers[GritsConstants.HEATMAP_LAYER_ID] = new GritsHeatmapLayer(this, GritsConstants.HEATMAP_LAYER_ID) heatmapLayerGroup = new GritsLayerGroup(heatmapLayers, this, GritsConstants.HEATMAP_GROUP_LAYER_ID, 'Heatmap') this.addGritsLayerGroup(heatmapLayerGroup) # Add all nodes layers to a layer group then add to map allNodesLayers = {} allNodesLayers[GritsConstants.NODE_LAYER_ID] = new GritsAllNodesLayer(this) allNodesLayerGroup = new GritsLayerGroup(allNodesLayers, this, GritsConstants.ALL_NODES_GROUP_LAYER_ID, 'All Nodes') this.addGritsLayerGroup(allNodesLayerGroup) # adds a layer reference to the map object # # @note This does not add the layer to the Leaflet map. Its just a container # @param [Object] layer, a GritsLayer instance addGritsLayerGroup: (layerGroup) -> if typeof layerGroup == 'undefined' throw new Error('A layer must be defined') return if !layerGroup instanceof GritsLayerGroup throw new Error('A map requires a valid GritsLayerGroup instance') return @_layers[layerGroup._id] = layerGroup return # gets a layer refreence from the map object # # @param [String] id, a string containing the name of the layer as shown # in the UI layer controls getGritsLayerGroup: (id) -> if typeof id == 'undefined' throw new Error('A GritsLayerGroup Id must be defined') return if @_layers.hasOwnProperty(id) == true return @_layers[id] return null # draws the overlay controls within the control box in the upper-right # corner of the map. It uses @_gritsOverlayControl to place the reference of # the overlay controls. _drawOverlayControls: () -> if @_gritsOverlayControl == null @_gritsOverlayControl = L.control.layers(@_gritsTileLayers, @_gritsOverlays).addTo this else @_gritsOverlayControl.removeFrom(this) @_gritsOverlayControl = L.control.layers(@_gritsTileLayers, @_gritsOverlays).addTo this return # adds a new overlay control to the map # # @param [String] layerName, string containing the name of the layer # @param [Object] layerGroup, the layerGroup object to add to the map controls addOverlayControl: (layerName, layerGroup) -> @_gritsOverlays[layerName] = layerGroup @_drawOverlayControls() window.dispatchEvent(new Event('mapper.addOverlayControl')) return # removes overlay control from the map # # @param [String] layerName, string containing the name of the layer removeOverlayControl: (layerName) -> if @_gritsOverlays.hasOwnProperty layerName delete @_gritsOverlays[layerName] @_drawOverlayControls() return
true
_imagePath = 'packages/bevanhunt_leaflet/images' # Creates an instance of a map # # @param [String] # @param [Object] options, Leaflet map options + height # @see http://leafletjs.com/reference.html#map-options class GritsMap extends L.Map constructor: (element, options) -> @_name = 'GritsMap' @_element = element or 'grits-map' @_gritsOverlayControl = null @_gritsOverlays = {} @_gritsTileLayers = {} @_gritsLayers = {} L.Icon.Default.imagePath = _imagePath OpenStreetMap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', key: 'PI:KEY:<KEY>END_PI' layerName: 'OpenStreetMap' styleId: 22677) if typeof options == 'undefined' @_options = { center: [37.8, -92] zoomControl: false noWrap: true maxZoom: 18 minZoom: 0 layers: [OpenStreetMap] } else @_options = options if typeof @_options.layers == 'undefined' @_options.layers = [OpenStreetMap] for layer in @_options.layers @_gritsTileLayers[layer.options.layerName] = layer @_options.layers = [@_options.layers[0]] super(@_element, @_options) @_drawOverlayControls() @_createDefaultLayerGroups() return # creates the default layer groups required by the map _createDefaultLayerGroups: -> # Add analyze layers to a layer group then store to map analyzeLayers = {} analyzeLayers[GritsConstants.NODE_LAYER_ID] = new GritsNodeLayer(this, GritsConstants.NODE_LAYER_ID) analyzeLayers[GritsConstants.PATH_LAYER_ID] = new GritsPathLayer(this, GritsConstants.PATH_LAYER_ID) analyzeLayerGroup = new GritsLayerGroup(analyzeLayers, this, GritsConstants.ANALYZE_GROUP_LAYER_ID, 'Simulation Flight Routes') analyzeLayerGroup.add() this.addGritsLayerGroup(analyzeLayerGroup) # Add explore layers to a layer group then store to map exploreLayers = {} exploreLayers[GritsConstants.NODE_LAYER_ID] = new GritsNodeLayer(this, GritsConstants.NODE_LAYER_ID) exploreLayers[GritsConstants.PATH_LAYER_ID] = new GritsPathLayer(this, GritsConstants.PATH_LAYER_ID) exploreLayerGroup = new GritsLayerGroup(exploreLayers, this, GritsConstants.EXPLORE_GROUP_LAYER_ID, 'Direct Flight Routes') exploreLayerGroup.add() this.addGritsLayerGroup(exploreLayerGroup) # Add heatmap layer to a layer group then store to map heatmapLayers = {} heatmapLayers[GritsConstants.HEATMAP_LAYER_ID] = new GritsHeatmapLayer(this, GritsConstants.HEATMAP_LAYER_ID) heatmapLayerGroup = new GritsLayerGroup(heatmapLayers, this, GritsConstants.HEATMAP_GROUP_LAYER_ID, 'Heatmap') this.addGritsLayerGroup(heatmapLayerGroup) # Add all nodes layers to a layer group then add to map allNodesLayers = {} allNodesLayers[GritsConstants.NODE_LAYER_ID] = new GritsAllNodesLayer(this) allNodesLayerGroup = new GritsLayerGroup(allNodesLayers, this, GritsConstants.ALL_NODES_GROUP_LAYER_ID, 'All Nodes') this.addGritsLayerGroup(allNodesLayerGroup) # adds a layer reference to the map object # # @note This does not add the layer to the Leaflet map. Its just a container # @param [Object] layer, a GritsLayer instance addGritsLayerGroup: (layerGroup) -> if typeof layerGroup == 'undefined' throw new Error('A layer must be defined') return if !layerGroup instanceof GritsLayerGroup throw new Error('A map requires a valid GritsLayerGroup instance') return @_layers[layerGroup._id] = layerGroup return # gets a layer refreence from the map object # # @param [String] id, a string containing the name of the layer as shown # in the UI layer controls getGritsLayerGroup: (id) -> if typeof id == 'undefined' throw new Error('A GritsLayerGroup Id must be defined') return if @_layers.hasOwnProperty(id) == true return @_layers[id] return null # draws the overlay controls within the control box in the upper-right # corner of the map. It uses @_gritsOverlayControl to place the reference of # the overlay controls. _drawOverlayControls: () -> if @_gritsOverlayControl == null @_gritsOverlayControl = L.control.layers(@_gritsTileLayers, @_gritsOverlays).addTo this else @_gritsOverlayControl.removeFrom(this) @_gritsOverlayControl = L.control.layers(@_gritsTileLayers, @_gritsOverlays).addTo this return # adds a new overlay control to the map # # @param [String] layerName, string containing the name of the layer # @param [Object] layerGroup, the layerGroup object to add to the map controls addOverlayControl: (layerName, layerGroup) -> @_gritsOverlays[layerName] = layerGroup @_drawOverlayControls() window.dispatchEvent(new Event('mapper.addOverlayControl')) return # removes overlay control from the map # # @param [String] layerName, string containing the name of the layer removeOverlayControl: (layerName) -> if @_gritsOverlays.hasOwnProperty layerName delete @_gritsOverlays[layerName] @_drawOverlayControls() return
[ { "context": "# Copyright (c) 2014. David M. Lee, II <leedm777@yahoo.com>\n'use strict'\n\nchai = req", "end": 34, "score": 0.9998681545257568, "start": 22, "tag": "NAME", "value": "David M. Lee" }, { "context": "# Copyright (c) 2014. David M. Lee, II <leedm777@yahoo.com>\n'use strict'\n\nchai = require 'chai'\nchaiAsPromis", "end": 58, "score": 0.9999305009841919, "start": 40, "tag": "EMAIL", "value": "leedm777@yahoo.com" } ]
test/bootstrap/index.coffee
building5/parfaitjs
1
# Copyright (c) 2014. David M. Lee, II <leedm777@yahoo.com> 'use strict' chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.config.includeStack = true chai.use chaiAsPromised if process.env.COVERAGE == 'true' console.log 'Enabling code coverage' require('blanket')()
126963
# Copyright (c) 2014. <NAME>, II <<EMAIL>> 'use strict' chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.config.includeStack = true chai.use chaiAsPromised if process.env.COVERAGE == 'true' console.log 'Enabling code coverage' require('blanket')()
true
# Copyright (c) 2014. PI:NAME:<NAME>END_PI, II <PI:EMAIL:<EMAIL>END_PI> 'use strict' chai = require 'chai' chaiAsPromised = require 'chai-as-promised' chai.config.includeStack = true chai.use chaiAsPromised if process.env.COVERAGE == 'true' console.log 'Enabling code coverage' require('blanket')()
[ { "context": "3-2014 TheGrid (Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed und", "end": 129, "score": 0.9998494982719421, "start": 116, "tag": "NAME", "value": "Henri Bergius" }, { "context": "(Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed under the M", "end": 137, "score": 0.9969424605369568, "start": 131, "tag": "NAME", "value": "Nemein" } ]
src/lib/Component.coffee
ensonic/noflo
1
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 Henri Bergius, Nemein # NoFlo may be freely distributed under the MIT license # # Baseclass for regular NoFlo components. {EventEmitter} = require 'events' ports = require './Ports' class Component extends EventEmitter description: '' icon: null started: false constructor: (options) -> options = {} unless options options.inPorts = {} unless options.inPorts if options.inPorts instanceof ports.InPorts @inPorts = options.inPorts else @inPorts = new ports.InPorts options.inPorts options.outPorts = {} unless options.outPorts if options.outPorts instanceof ports.OutPorts @outPorts = options.outPorts else @outPorts = new ports.OutPorts options.outPorts getDescription: -> @description isReady: -> true isSubgraph: -> false setIcon: (@icon) -> @emit 'icon', @icon getIcon: -> @icon error: (e, groups = [], errorPort = 'error') => if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired()) @outPorts[errorPort].beginGroup group for group in groups @outPorts[errorPort].send e @outPorts[errorPort].endGroup() for group in groups @outPorts[errorPort].disconnect() return throw e shutdown: -> @started = false # The startup function performs initialization for the component. start: -> @started = true @started isStarted: -> @started exports.Component = Component
71568
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 <NAME>, <NAME> # NoFlo may be freely distributed under the MIT license # # Baseclass for regular NoFlo components. {EventEmitter} = require 'events' ports = require './Ports' class Component extends EventEmitter description: '' icon: null started: false constructor: (options) -> options = {} unless options options.inPorts = {} unless options.inPorts if options.inPorts instanceof ports.InPorts @inPorts = options.inPorts else @inPorts = new ports.InPorts options.inPorts options.outPorts = {} unless options.outPorts if options.outPorts instanceof ports.OutPorts @outPorts = options.outPorts else @outPorts = new ports.OutPorts options.outPorts getDescription: -> @description isReady: -> true isSubgraph: -> false setIcon: (@icon) -> @emit 'icon', @icon getIcon: -> @icon error: (e, groups = [], errorPort = 'error') => if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired()) @outPorts[errorPort].beginGroup group for group in groups @outPorts[errorPort].send e @outPorts[errorPort].endGroup() for group in groups @outPorts[errorPort].disconnect() return throw e shutdown: -> @started = false # The startup function performs initialization for the component. start: -> @started = true @started isStarted: -> @started exports.Component = Component
true
# NoFlo - Flow-Based Programming for JavaScript # (c) 2013-2014 TheGrid (Rituwall Inc.) # (c) 2011-2012 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # NoFlo may be freely distributed under the MIT license # # Baseclass for regular NoFlo components. {EventEmitter} = require 'events' ports = require './Ports' class Component extends EventEmitter description: '' icon: null started: false constructor: (options) -> options = {} unless options options.inPorts = {} unless options.inPorts if options.inPorts instanceof ports.InPorts @inPorts = options.inPorts else @inPorts = new ports.InPorts options.inPorts options.outPorts = {} unless options.outPorts if options.outPorts instanceof ports.OutPorts @outPorts = options.outPorts else @outPorts = new ports.OutPorts options.outPorts getDescription: -> @description isReady: -> true isSubgraph: -> false setIcon: (@icon) -> @emit 'icon', @icon getIcon: -> @icon error: (e, groups = [], errorPort = 'error') => if @outPorts[errorPort] and (@outPorts[errorPort].isAttached() or not @outPorts[errorPort].isRequired()) @outPorts[errorPort].beginGroup group for group in groups @outPorts[errorPort].send e @outPorts[errorPort].endGroup() for group in groups @outPorts[errorPort].disconnect() return throw e shutdown: -> @started = false # The startup function performs initialization for the component. start: -> @started = true @started isStarted: -> @started exports.Component = Component
[ { "context": "tions.Patients [getJSONFixture('patients/CMSv5555/John_Smith.json')], parse: true\n patient = patients.model", "end": 2917, "score": 0.9569252729415894, "start": 2907, "tag": "NAME", "value": "John_Smith" }, { "context": " @patientBuilder.$(':input[name=last]').val(\"LAST NAME\")\n @patientBuilder.$(':input[name=first]').v", "end": 4930, "score": 0.8591437339782715, "start": 4921, "tag": "NAME", "value": "LAST NAME" }, { "context": "nt')\n expect(cqmPatient.familyName).toEqual 'LAST NAME'\n expect(cqmPatient.givenNames[0]).toEqual '", "end": 5978, "score": 0.980172872543335, "start": 5969, "tag": "NAME", "value": "LAST NAME" }, { "context": "'\n expect(cqmPatient.givenNames[0]).toEqual 'FIRST NAME'\n birthdateElement = (cqmPatient.qdmPatient.", "end": 6038, "score": 0.9908122420310974, "start": 6028, "tag": "NAME", "value": "FIRST NAME" } ]
spec/javascripts/patient_builder_tests/patient/patient_builder_spec.js.coffee
sb-benohe/bonnie
33
describe 'PatientBuilderView', -> beforeEach -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS134v6/CMS134v6.json', 'cqm_measure_data/CMS134v6/value_sets.json' @patients = new Thorax.Collections.Patients [getJSONFixture('patients/CMS134v6/Elements_Test.json'), getJSONFixture('patients/CMS134v6/Fail_Hospice_Not_Performed_Denex.json')], parse: true @patient = @patients.models[1] @bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add @measure @patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) @patientBuilder.render() spyOn(@patientBuilder.model, 'materialize') spyOn(@patientBuilder.originalModel, 'save').and.returnValue(true) @$el = @patientBuilder.$el afterEach -> bonnie.measures = @bonnie_measures_old it 'should not open patient builder for non existent measure', -> spyOn(bonnie,'showPageNotFound') bonnie.showPageNotFound.calls.reset() bonnie.renderPatientBuilder('non_existant_hqmf_set_id', @patient.id) expect(bonnie.showPageNotFound).toHaveBeenCalled() it 'should set the main view when calling showPageNotFound', -> spyOn(bonnie.mainView,'setView') bonnie.renderPatientBuilder('non_existant_hqmf_set_id', @patient.id) expect(bonnie.mainView.setView).toHaveBeenCalled() it 'renders the builder correctly', -> expect(@$el.find(":input[name='first']")).toHaveValue @patient.getFirstName() expect(@$el.find(":input[name='last']")).toHaveValue @patient.getLastName() expect(@$el.find(":input[name='birthdate']")).toHaveValue @patient.getBirthDate() expect(@$el.find(":input[name='birthtime']")).toHaveValue @patient.getBirthTime() expect(@$el.find(":input[name='notes']")).toHaveValue @patient.getNotes() expect(@patientBuilder.html()).not.toContainText "Warning: There are elements in the Patient History that do not use any codes from this measure's value sets:" it 'displays a warning if codes on dataElements do not exist on measure', -> @measure.attributes.cqmValueSets = [] patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) patientBuilder.render() expect(patientBuilder.html()).toContainText "Warning: There are elements in the Patient History that do not use any codes from this measure's value sets:" it 'does not display compare patient results button when there is no history', -> expect(@patientBuilder.$('button[data-call-method=showCompare]:first')).not.toExist() it "toggles patient expiration correctly", -> measure = loadMeasureWithValueSets 'cqm_measure_data/CMSv5555/CMSv5555.json', 'cqm_measure_data/CMSv5555/value_sets.json' patients = new Thorax.Collections.Patients [getJSONFixture('patients/CMSv5555/John_Smith.json')], parse: true patient = patients.models[0] bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add measure patientBuilder = new Thorax.Views.PatientBuilder(model: patient, measure: measure, patients: patients) patientBuilder.render() spyOn(patientBuilder.model, 'materialize') spyOn(patientBuilder.originalModel, 'save').and.returnValue(true) patientBuilder.appendTo 'body' # Press deceased check box and enter death date patientBuilder.$('input[type=checkbox][name=expired]:first').click() patientBuilder.$(':input[name=deathdate]').val('01/02/1994') patientBuilder.$(':input[name=deathtime]').val('1:15 PM') patientBuilder.$("button[data-call-method=save]").click() expect(patientBuilder.model.get('expired')).toEqual true expect(patientBuilder.model.get('deathdate')).toEqual '01/02/1994' expect(patientBuilder.model.get('deathtime')).toEqual "1:15 PM" expiredElement = (patientBuilder.model.get('cqmPatient').qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'expired')[0] expect(expiredElement.expiredDatetime.toString()).toEqual (new cqm.models.CQL.DateTime(1994,1,2,13,15,0,0,0).toString()) # Remove deathdate from patient patientBuilder.$("button[data-call-method=removeDeathDate]").click() patientBuilder.$("button[data-call-method=save]").click() expect(patientBuilder.model.get('expired')).toEqual false expect(patientBuilder.model.get('deathdate')).toEqual undefined expect(patientBuilder.model.get('deathtime')).toEqual undefined expiredElement = (patientBuilder.model.get('cqmPatient').qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'expired')[0] expect(expiredElement).not.toExist() patientBuilder.remove() describe "setting basic attributes and saving", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.$(':input[name=last]').val("LAST NAME") @patientBuilder.$(':input[name=first]').val("FIRST NAME") @patientBuilder.$('select[name=gender]').val('F') @patientBuilder.$(':input[name=birthdate]').val('01/02/1993') @patientBuilder.$(':input[name=birthtime]').val('1:15 PM') @patientBuilder.$('select[name=race]').val('2131-1') @patientBuilder.$('select[name=ethnicity]').val('2135-2') @patientBuilder.$(':input[name=notes]').val('EXAMPLE NOTES FOR TEST') @patientBuilder.$("button[data-call-method=save]").click() it "dynamically loads race, ethnicity, and gender codes from measure", -> expect(@patientBuilder.$('select[name=race]')[0].options.length).toEqual 6 expect(@patientBuilder.$('select[name=ethnicity]')[0].options.length).toEqual 2 expect(@patientBuilder.$('select[name=gender]')[0].options.length).toEqual 2 it "serializes the attributes correctly", -> thoraxPatient = @patientBuilder.model cqmPatient = thoraxPatient.get('cqmPatient') expect(cqmPatient.familyName).toEqual 'LAST NAME' expect(cqmPatient.givenNames[0]).toEqual 'FIRST NAME' birthdateElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'birthdate')[0] # If the measure doesn't have birthDate as a data criteria, the patient is forced to have one without a code expect(birthdateElement).not.toBeUndefined() expect(cqmPatient.qdmPatient.birthDatetime.toString()).toEqual (new cqm.models.CQL.DateTime(1993,1,2,13,15,0,0,0).toString()) expect(thoraxPatient.getBirthDate()).toEqual '01/02/1993' expect(thoraxPatient.getNotes()).toEqual 'EXAMPLE NOTES FOR TEST' expect(thoraxPatient.getGender().display).toEqual 'Female' genderElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'gender')[0] expect(genderElement.dataElementCodes[0].code).toEqual 'F' raceElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'race')[0] expect(raceElement.dataElementCodes[0].code).toEqual '2131-1' expect(raceElement.dataElementCodes[0].display).toEqual 'Other Race' expect(thoraxPatient.getRace().display).toEqual 'Other Race' ethnicityElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'ethnicity')[0] expect(ethnicityElement.dataElementCodes[0].code).toEqual '2135-2' expect(ethnicityElement.dataElementCodes[0].display).toEqual 'Hispanic or Latino' expect(thoraxPatient.getEthnicity().display).toEqual 'Hispanic or Latino' it "displayes correct values on the UI after saving", -> expect(@patientBuilder.$(':input[name=last]')[0].value).toEqual 'LAST NAME' expect(@patientBuilder.$(':input[name=first]')[0].value).toEqual 'FIRST NAME' expect(@patientBuilder.$(':input[name=birthdate]')[0].value).toEqual '01/02/1993' expect(@patientBuilder.$(':input[name=birthtime]')[0].value).toEqual '1:15 PM' expect(@patientBuilder.$(':input[name=notes]')[0].value).toEqual 'EXAMPLE NOTES FOR TEST' expect(@patientBuilder.$('select[name=race]')[0].value).toEqual '2131-1' expect(@patientBuilder.$('select[name=ethnicity]')[0].value).toEqual '2135-2' expect(@patientBuilder.$('select[name=gender]')[0].value).toEqual 'F' it "tries to save the patient correctly", -> expect(@patientBuilder.originalModel.save).toHaveBeenCalled() afterEach -> @patientBuilder.remove() describe "changing and blurring basic fields", -> beforeEach -> @patientBuilder.appendTo('body') @patientBuilder.$('select[name=gender]').val('M').change() @patientBuilder.$('input[name=birthdate]').blur() afterEach -> @patientBuilder.remove() xit "materializes the patient", -> # SKIP: The above change() and blur() commands do hit materialize when # executed in the browser console:w Not sure why the spy is not getting # hit here. expect(@patientBuilder.model.materialize).toHaveBeenCalled() expect(@patientBuilder.model.materialize.calls.count()).toEqual 2 describe "adding encounters to patient", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.render() # simulate dragging an encounter onto the patient @addEncounter = (position, targetSelector) -> $('.panel-title').click() # Expand the criteria to make draggables visible criteria = @$el.find(".draggable:eq(#{position})").draggable() target = @$el.find(targetSelector) targetView = target.view() # We used to simulate a drag, but that had issues with different viewport sizes, so instead we just # directly call the appropriate drop event handler if targetView.dropCriteria target.view().dropCriteria({ target: target }, { draggable: criteria }) else target.view().drop({ target: target }, { draggable: criteria }) it "adds data criteria to model when dragged", -> initialOriginalDataElementCount = @patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length # force materialize to get any patient characteristics that should exist added @patientBuilder.materialize(); initialSourceDataCriteriaCount = @patientBuilder.model.get('source_data_criteria').length initialDataElementCount = @patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length @addEncounter 1, '.criteria-container.droppable' expect(@patientBuilder.model.get('source_data_criteria').length).toEqual initialSourceDataCriteriaCount + 1 expect(@patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialDataElementCount + 1 # make sure the dataElements on the original model were not touched expect(@patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialOriginalDataElementCount it "can add multiples of the same criterion", -> initialOriginalDataElementCount = @patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length # force materialize to get any patient characteristics that should exist added @patientBuilder.materialize(); initialSourceDataCriteriaCount = @patientBuilder.model.get('source_data_criteria').length initialDataElementCount = @patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length @addEncounter 1, '.criteria-container.droppable' @addEncounter 1, '.criteria-container.droppable' # add the same one again expect(@patientBuilder.model.get('source_data_criteria').length).toEqual initialSourceDataCriteriaCount + 2 expect(@patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialDataElementCount + 2 # make sure the dataElements on the original model were not touched expect(@patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialOriginalDataElementCount it "has a default start and end date for the primary timing attributes when not dropped on an existing criteria", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-container.droppable' # get today in MP year and check the defaults are today 8:00-8:15 today = new Date() newStart = new cqm.models.CQL.DateTime(2012, today.getMonth() + 1, today.getDate(), 8, 0, 0, 0, 0) newEnd = new cqm.models.CQL.DateTime(2012, today.getMonth() + 1, today.getDate(), 8, 15, 0, 0, 0) newInterval = new cqm.models.CQL.Interval(newStart, newEnd) expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual newInterval # authorDatetime should be same as the start of the relevantPeriod expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual newStart it "acquires the interval of the drop target when dropping on an existing criteria", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.low).toEqual startDate expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.high).toEqual endDate it "acquires the authorDatetime of the drop target when dropping on an existing criteria", -> authorDatetime = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').authorDatetime # droppable 17 @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual authorDatetime it "acquires the interval of the drop target when dropping on an existing criteria even when low is null", -> @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low = null endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.low).toBe null expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.high).toEqual endDate it "acquires the start time and makes an end time of the drop target when dropping on an existing criteria with only authorDatetime ", -> startDate = @patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').authorDatetime # expecting end date to be 15 minutes later endDate = startDate.add(15, cqm.models.CQL.DateTime.Unit.MINUTE) # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:last' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual(new cqm.models.CQL.Interval(startDate, endDate)) it "acquires Interval[null,null] when dropping on an existing criteria with only authorDatetime that is null", -> @patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').authorDatetime = null # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:last' # interval should be [null,null] expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual(new cqm.models.CQL.Interval(null, null)) expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toBe(null) it "acquires the start of an interval as the authorDatetime when criteria with only authorDatetime is dropped on one with an Interval", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low # droppable 14 used. this is InterventionOrder that only has authorDatetime @addEncounter 14, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual(startDate) it "acquires null as the authorDatetime when criteria with only authorDatetime is dropped on one with an Interval that starts with null", -> # set the low of the drop target to be null @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low = null # droppable 14 used. this is InterventionOrder that only has authorDatetime @addEncounter 14, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toBe(null) it "materializes the patient", -> expect(@patientBuilder.model.materialize).not.toHaveBeenCalled() @addEncounter 1, '.criteria-container.droppable' expect(@patientBuilder.model.materialize).toHaveBeenCalled() afterEach -> @patientBuilder.remove() describe "editing basic attributes of a criteria", -> # SKIP: This should be re-enabled with patient builder timing work beforeEach -> @patientBuilder.appendTo 'body' # need to be specific with the query to select one of the data criteria with a period. # this is due to QDM 5.0 changes which make several data criteria only have an author time. $dataCriteria = @patientBuilder.$('div.patient-criteria:contains(Diagnosis: Diabetes):first') $dataCriteria.find('button[data-call-method=toggleDetails]:first').click() $dataCriteria.find(':input[name=start_date]:first').val('01/1/2012') $dataCriteria.find(':input[name=start_time]:first').val('3:33') # verify DOM as well expect($dataCriteria.find(':input[name=end_date]:first')).toBeDisabled() expect($dataCriteria.find(':input[name=end_time]:first')).toBeDisabled() @patientBuilder.$("button[data-call-method=save]").click() xit "serializes the attributes correctly", -> # SKIP: Re-endable with Patient Builder Timing Attributes dataCriteria = this.patient.get('cqmPatient').qdmPatient.conditions()[0] expect(dataCriteria.get('prevelancePeriod').low).toEqual moment.utc('01/1/2012 3:33', 'L LT').format('X') * 1000 expect(dataCriteria.get('prevelancePeriod').high).toBeUndefined() afterEach -> @patientBuilder.remove() describe "setting and unsetting a criteria as not performed", -> beforeEach -> @patientBuilder.appendTo 'body' it "does not serialize negationRationale for element that can't be negated", -> # 0th source_data_criteria is a diagnosis and therefore cannot have a negation and will not contain the negation expect(@patientBuilder.model.get('source_data_criteria').at(0).get('qdmDataElement').negationRationale).toEqual undefined it "serializes negationRationale to null for element that can be negated but isnt", -> # 1st source_data_criteria is an encounter that is not negated expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toEqual null it "serializes negationRationale for element that is negated", -> # The 2nd source_data_criteria is an intervention with negationRationale set to 'Emergency Department Visit' code: expect(@patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').negationRationale.code).toEqual '4525004' expect(@patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').negationRationale.system).toEqual '2.16.840.1.113883.6.96' it "toggles negations correctly", -> @patientBuilder.$('.criteria-data').children().toggleClass('hide') expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe false expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toBeNull() @patientBuilder.$('input[name=negation]:first').click() @patientBuilder.$('select[name="valueset"]').val('drc-99a051cdb6879ebe3d81f5c15cecbf4157040a6e1c12c711bacb61246e5a0d61').change() # No need to select code for test, one is selected by default expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe true expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toExist() @patientBuilder.$('input[name=negation]:first').click() expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe false expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toBeNull() afterEach -> @patientBuilder.remove() describe 'author date time', -> xit "removes author date time field value when not performed is checked", -> # SKIP: Re-enable with Patient Builder work authorDateTimePatient = @patients.models.filter((patient) -> patient.get('last') is 'AuthorDateTime')[0] patientBuilder = new Thorax.Views.PatientBuilder(model: authorDateTimePatient, measure: @measure, patients: @patients) patientBuilder.appendTo 'body' firstCriteria = patientBuilder.model.get('source_data_criteria').first() authorDateTime = patientBuilder.model.get('source_data_criteria').first().get('field_values').first().get('start_date') expect(authorDateTime).toEqual '04/24/2019' patientBuilder.$('input[name=negation]:first').click() expect(patientBuilder.model.get('source_data_criteria').first().get('field_values').length).toBe 0 startDate = new Date(patientBuilder.model.get('source_data_criteria').first().get('start_date')) expect(startDate.toString().includes("Tue Apr 17 2012")).toBe true patientBuilder.remove() describe "blurring basic fields of a criteria", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.$(':text[name=start_date]:first').blur() xit "materializes the patient", -> # SKIP: Re-enable with Patient Builder Work expect(@patientBuilder.model.materialize).toHaveBeenCalled() expect(@patientBuilder.model.materialize.calls.count()).toEqual 1 afterEach -> @patientBuilder.remove() describe "adding codes to an encounter", -> beforeEach -> @patientBuilder.appendTo 'body' @addCode = (codeSet, code, submit = true) -> @patientBuilder.$('.codeset-control:first').val(codeSet).change() $codelist = @patientBuilder.$('.codelist-control:first') expect($codelist.children("[value=#{code}]")).toExist() $codelist.val(code).change() # FIXME Our test JSON doesn't yet support value sets very well... write these tests when we have a source of value sets independent of the measures xit "adds a code", -> afterEach -> @patientBuilder.remove() describe "setting expected values", -> beforeEach -> @patientBuilder.appendTo 'body' @selectPopulationEV = (population, save=true) -> @patientBuilder.$("input[type=checkbox][name=#{population}]:first").click() @patientBuilder.$("button[data-call-method=save]").click() if save it "auto unselects DENOM and IPP when IPP is unselected", -> expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 0 @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto selects DENOM and IPP when NUMER is selected", -> @selectPopulationEV('NUMER', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 1 it "auto unselects DENOM when IPP is unselected", -> @selectPopulationEV('DENOM', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto unselects DENOM and NUMER when IPP is unselected", -> @selectPopulationEV('NUMER', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto selects DENOM and IPP when NUMER is selected", -> @selectPopulationEV('NUMER', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 1 it "auto unselects DENOM when IPP is unselected", -> @selectPopulationEV('DENOM', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto unselects DENOM and NUMER when IPP is unselected", -> @selectPopulationEV('NUMER', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it 'updates the values of the frontend mongoose model', -> expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) mongooseExpectecValue = (expectedValues.collection.parent.get('cqmPatient').expectedValues.filter (val) -> val.population_index is 0 && val.measure_id is '7B2A9277-43DA-4D99-9BEE-6AC271A07747')[0] expect(mongooseExpectecValue.IPP).toEqual 1 expect(mongooseExpectecValue.DENOM).toEqual 1 expect(mongooseExpectecValue.NUMER).toEqual 0 @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(mongooseExpectecValue.IPP).toEqual 0 expect(mongooseExpectecValue.DENOM).toEqual 0 expect(mongooseExpectecValue.NUMER).toEqual 0 @selectPopulationEV('NUMER', false) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(mongooseExpectecValue.IPP).toEqual 1 expect(mongooseExpectecValue.DENOM).toEqual 1 expect(mongooseExpectecValue.NUMER).toEqual 1 afterEach -> @patientBuilder.remove() describe "setting expected values for CV measure", -> beforeEach -> cqlMeasure = loadMeasureWithValueSets 'cqm_measure_data/CMS903v0/CMS903v0.json', 'cqm_measure_data/CMS903v0/value_sets.json' patientsJSON = [] patientsJSON.push(getJSONFixture('patients/CMS903v0/Visit_1 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits 1 Excl_2 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits 2 Excl_2 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits_2 ED.json')) patients = new Thorax.Collections.Patients patientsJSON, parse: true @patientBuilder = new Thorax.Views.PatientBuilder(model: patients.first(), measure: cqlMeasure) @patientBuilder.appendTo 'body' @setPopulationVal = (population, value=0, save=true) -> @patientBuilder.$("input[type=number][name=#{population}]:first").val(value).change() @patientBuilder.$("button[data-call-method=save]").click() if save it "IPP removal removes membership of all populations in CV measures", -> @setPopulationVal('IPP', 0, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('MSRPOPL')).toEqual 0 expect(expectedValues.get('MSRPOPLEX')).toEqual 0 expect(expectedValues.get('OBSERV')).toEqual undefined it "MSRPOPLEX addition adds membership to all populations in CV measures", -> # First set IPP to 0 to zero out all population membership @setPopulationVal('IPP', 0, true) @setPopulationVal('MSRPOPLEX', 4, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 4 expect(expectedValues.get('MSRPOPL')).toEqual 4 expect(expectedValues.get('MSRPOPLEX')).toEqual 4 # 4 MSRPOPLEX and 4 MSRPOPL means there should be no OBSERVs expect(expectedValues.get('OBSERV')).toEqual undefined it "MSRPOPLEX addition and removal adds and removes OBSERVs in CV measures", -> # First set IPP to 0 to zero out all population membership @setPopulationVal('IPP', 0, true) @setPopulationVal('MSRPOPLEX', 3, true) @setPopulationVal('MSRPOPL', 4, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 4 expect(expectedValues.get('MSRPOPL')).toEqual 4 expect(expectedValues.get('MSRPOPLEX')).toEqual 3 # 4 MSRPOPL and 3 MSRPOPLEX means there should be 1 OBSERVs expect(expectedValues.get('OBSERV').length).toEqual 1 @setPopulationVal('MSRPOPL', 6, true) expect(expectedValues.get('IPP')).toEqual 6 expect(expectedValues.get('MSRPOPL')).toEqual 6 expect(expectedValues.get('MSRPOPLEX')).toEqual 3 # 6 MSRPOPL and 3 MSRPOPLEX means there should be 3 OBSERVs expect(expectedValues.get('OBSERV').length).toEqual 3 # Should remove all observs @setPopulationVal('MSRPOPLEX', 6, true) expect(expectedValues.get('IPP')).toEqual 6 expect(expectedValues.get('MSRPOPL')).toEqual 6 expect(expectedValues.get('MSRPOPLEX')).toEqual 6 # 6 MSRPOPLEX and 6 MSRPOPL means there should be no OBSERVs expect(expectedValues.get('OBSERV')).toEqual undefined # set IPP to 0, should zero out all populations @setPopulationVal('IPP', 0, true) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('MSRPOPL')).toEqual 0 expect(expectedValues.get('MSRPOPLEX')).toEqual 0 expect(expectedValues.get('OBSERV')).toEqual undefined afterEach -> @patientBuilder.remove() describe 'CQL', -> beforeEach -> jasmine.getJSONFixtures().clearCache() @cqlMeasure = new Thorax.Models.Measure getJSONFixture('cqm_measure_data/deprecated_measures/CMS347/CMS347v3.json'), parse: true # preserve atomicity @bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add(@cqlMeasure, {parse: true}) afterEach -> bonnie.measures = @bonnie_measures_old xit "laboratory test performed should have custom view for components", -> # SKIP: Re-enable with Patient Builder Attributes # NOTE: these patients aren't in the DB so fixture will need to be swapped patients = new Thorax.Collections.Patients getJSONFixture('patients/CMS347/patients.json'), parse: true patientBuilder = new Thorax.Views.PatientBuilder(model: patients.first(), measure: @cqlMeasure) dataCriteria = patientBuilder.model.get('source_data_criteria').models laboratoryTestIndex = dataCriteria.findIndex((m) -> m.attributes.definition is 'laboratory_test') laboratoryTest = dataCriteria[laboratoryTestIndex] editCriteriaView = new Thorax.Views.EditCriteriaView(model: laboratoryTest) editFieldValueView = editCriteriaView.editFieldValueView editFieldValueView.render() editFieldValueView.$('select[name=key]').val('COMPONENT').change() expect(editFieldValueView.$('label[for=code]')).toExist() expect(editFieldValueView.$('label[for=code]')[0].innerHTML).toEqual('Code') expect(editFieldValueView.$('label[for=referenceRangeLow]')).toExist() expect(editFieldValueView.$('label[for=referenceRangeLow]')[0].innerHTML).toEqual('Reference Range - Low') expect(editFieldValueView.$('label[for=referenceRangeHigh]')).toExist() expect(editFieldValueView.$('label[for=referenceRangeHigh]')[0].innerHTML).toEqual('Reference Range - High') expect(editFieldValueView.$('select[name=code_list_id]')).toExist() editFieldValueView.$('select[name=key]').val('REASON').change() expect(editFieldValueView.$('label[for=code]').length).toEqual(0) expect(editFieldValueView.$('label[for=referenceRangeLow]').length).toEqual(0) expect(editFieldValueView.$('label[for=referenceRangeHigh]').length).toEqual(0) describe 'Composite Measure', -> beforeEach -> jasmine.getJSONFixtures().clearCache() # preserve atomicity @bonnie_measures_old = bonnie.measures valueSetsPath = 'cqm_measure_data/CMS890v0/value_sets.json' bonnie.measures = new Thorax.Collections.Measures() @compositeMeasure = loadMeasureWithValueSets 'cqm_measure_data/CMS890v0/CMS890v0.json', valueSetsPath bonnie.measures.push(@compositeMeasure) @components = getJSONFixture('cqm_measure_data/CMS890v0/components.json') @components = @components.map((component) -> new Thorax.Models.Measure component, parse: true) @components.forEach((component) -> bonnie.measures.push(component)) patientTest1 = getJSONFixture('patients/CMS890v0/Patient_Test 1.json') patientTest2 = getJSONFixture('patients/CMS890v0/Patient_Test 2.json') @compositePatients = new Thorax.Collections.Patients [patientTest1, patientTest2], parse: true @compositeMeasure.populateComponents() afterEach -> bonnie.measures = @bonnie_measures_old xit "should floor the observ value to at most 8 decimals", -> # SKIP: Re-enable with patient saving/expected value work patientBuilder = new Thorax.Views.PatientBuilder(model: @compositePatients.at(1), measure: @compositeMeasure) patientBuilder.render() expected_vals = patientBuilder.model.get('expected_values').findWhere({measure_id: "244B4F52-C9CA-45AA-8BDB-2F005DA05BFC"}) patientBuilder.$(':input[name=OBSERV]').val(0.123456781111111) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 0.12345678 patientBuilder.$(':input[name=OBSERV]').val(0.123456786666666) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 0.12345678 patientBuilder.$(':input[name=OBSERV]').val(1.5) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 1.5 it "should display a warning that the patient is shared", -> patientBuilder = new Thorax.Views.PatientBuilder(model: @compositePatients.first(), measure: @components[0]) patientBuilder.render() expect(patientBuilder.$("div.alert-warning")[0].innerHTML.substr(0,31).trim()).toEqual "Note: This patient is shared" it 'should have the breadcrumbs with composite and component measure', -> breadcrumb = new Thorax.Views.Breadcrumb() breadcrumb.addPatient(@components[0], @compositePatients.first()) breadcrumb.render() expect(breadcrumb.$("a")[1].childNodes[1].textContent).toEqual " CMS890v0 " # parent composite measure expect(breadcrumb.$("a")[2].childNodes[1].textContent).toEqual " CMS231v0 " # the component measure describe 'Direct Reference Code Usage', -> # Originally BONNIE-939 beforeEach -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS903v0/CMS903v0.json', 'cqm_measure_data/CMS903v0/value_sets.json' bonnie.measures.add(@measure, { parse: true }) @patient = new Thorax.Models.Patient getJSONFixture('patients/CMS903v0/Visits 2 Excl_2 ED.json'), parse: true xit 'Field Value Dropdown should contain direct reference code element', -> # SKIP: Re-enable with Patient Builder Code Work patientBuilder = new Thorax.Views.PatientBuilder(model: @patients.first(), measure: @measure) dataCriteria = patientBuilder.model.get('source_data_criteria').models edVisitIndex = dataCriteria.findIndex((m) -> m.attributes.description is 'Encounter, Performed: Emergency Department Visit') emergencyDepartmentVisit = dataCriteria[edVisitIndex] editCriteriaView = new Thorax.Views.EditCriteriaView(model: emergencyDepartmentVisit, measure: @measure) editFieldValueView = editCriteriaView.editFieldValueView expect(editFieldValueView.render()).toContain('drc-') it 'Adding direct reference code element should calculate correctly', -> population = @measure.get('populations').first() results = population.calculate(@patient) library = "LikeCMS32" statementResults = results.get("statement_results") titleOfClauseThatUsesDrc = statementResults[library]['Measure Population Exclusions'].raw[0].dischargeDisposition.display expect(titleOfClauseThatUsesDrc).toBe "Patient deceased during stay (discharge status = dead) (finding)" describe 'Allergy', -> # Originally BONNIE-785 beforeAll -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS12v0/CMS12v0.json', 'cqm_measure_data/CMS12v0/value_sets.json' bonnie.measures.add @measure medAllergy = getJSONFixture("patients/CMS12v0/MedAllergyEndIP_DENEXCEPPass.json") @patients = new Thorax.Collections.Patients [medAllergy], parse: true @patient = @patients.at(0) # MedAllergyEndIP_DENEXCEPPass @patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) sourceDataCriteria = @patientBuilder.model.get("source_data_criteria") @allergyIntolerance = sourceDataCriteria.findWhere({qdmCategory: "allergy"}) @patientBuilder.render() @patientBuilder.appendTo('body') afterEach -> @patientBuilder.remove() it 'is displayed on Patient Builder Page in Elements section', -> expect(@patientBuilder.$el.find("div#criteriaElements").html()).toContainText "allergy" it 'highlight is triggered by relevant cql clause', -> cqlLogicView = @patientBuilder.populationLogicView.getView().cqlLogicView sourceDataCriteria = cqlLogicView.latestResult.patient.get('source_data_criteria') patientDataCriteria = _.find(sourceDataCriteria.models, (sdc) -> sdc.get('qdmCategory') == 'allergy') dataCriteriaIds = [patientDataCriteria.get('_id').toString()] spyOn(patientDataCriteria, 'trigger') cqlLogicView.highlightPatientData(dataCriteriaIds) expect(patientDataCriteria.trigger).toHaveBeenCalled()
225389
describe 'PatientBuilderView', -> beforeEach -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS134v6/CMS134v6.json', 'cqm_measure_data/CMS134v6/value_sets.json' @patients = new Thorax.Collections.Patients [getJSONFixture('patients/CMS134v6/Elements_Test.json'), getJSONFixture('patients/CMS134v6/Fail_Hospice_Not_Performed_Denex.json')], parse: true @patient = @patients.models[1] @bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add @measure @patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) @patientBuilder.render() spyOn(@patientBuilder.model, 'materialize') spyOn(@patientBuilder.originalModel, 'save').and.returnValue(true) @$el = @patientBuilder.$el afterEach -> bonnie.measures = @bonnie_measures_old it 'should not open patient builder for non existent measure', -> spyOn(bonnie,'showPageNotFound') bonnie.showPageNotFound.calls.reset() bonnie.renderPatientBuilder('non_existant_hqmf_set_id', @patient.id) expect(bonnie.showPageNotFound).toHaveBeenCalled() it 'should set the main view when calling showPageNotFound', -> spyOn(bonnie.mainView,'setView') bonnie.renderPatientBuilder('non_existant_hqmf_set_id', @patient.id) expect(bonnie.mainView.setView).toHaveBeenCalled() it 'renders the builder correctly', -> expect(@$el.find(":input[name='first']")).toHaveValue @patient.getFirstName() expect(@$el.find(":input[name='last']")).toHaveValue @patient.getLastName() expect(@$el.find(":input[name='birthdate']")).toHaveValue @patient.getBirthDate() expect(@$el.find(":input[name='birthtime']")).toHaveValue @patient.getBirthTime() expect(@$el.find(":input[name='notes']")).toHaveValue @patient.getNotes() expect(@patientBuilder.html()).not.toContainText "Warning: There are elements in the Patient History that do not use any codes from this measure's value sets:" it 'displays a warning if codes on dataElements do not exist on measure', -> @measure.attributes.cqmValueSets = [] patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) patientBuilder.render() expect(patientBuilder.html()).toContainText "Warning: There are elements in the Patient History that do not use any codes from this measure's value sets:" it 'does not display compare patient results button when there is no history', -> expect(@patientBuilder.$('button[data-call-method=showCompare]:first')).not.toExist() it "toggles patient expiration correctly", -> measure = loadMeasureWithValueSets 'cqm_measure_data/CMSv5555/CMSv5555.json', 'cqm_measure_data/CMSv5555/value_sets.json' patients = new Thorax.Collections.Patients [getJSONFixture('patients/CMSv5555/<NAME>.json')], parse: true patient = patients.models[0] bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add measure patientBuilder = new Thorax.Views.PatientBuilder(model: patient, measure: measure, patients: patients) patientBuilder.render() spyOn(patientBuilder.model, 'materialize') spyOn(patientBuilder.originalModel, 'save').and.returnValue(true) patientBuilder.appendTo 'body' # Press deceased check box and enter death date patientBuilder.$('input[type=checkbox][name=expired]:first').click() patientBuilder.$(':input[name=deathdate]').val('01/02/1994') patientBuilder.$(':input[name=deathtime]').val('1:15 PM') patientBuilder.$("button[data-call-method=save]").click() expect(patientBuilder.model.get('expired')).toEqual true expect(patientBuilder.model.get('deathdate')).toEqual '01/02/1994' expect(patientBuilder.model.get('deathtime')).toEqual "1:15 PM" expiredElement = (patientBuilder.model.get('cqmPatient').qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'expired')[0] expect(expiredElement.expiredDatetime.toString()).toEqual (new cqm.models.CQL.DateTime(1994,1,2,13,15,0,0,0).toString()) # Remove deathdate from patient patientBuilder.$("button[data-call-method=removeDeathDate]").click() patientBuilder.$("button[data-call-method=save]").click() expect(patientBuilder.model.get('expired')).toEqual false expect(patientBuilder.model.get('deathdate')).toEqual undefined expect(patientBuilder.model.get('deathtime')).toEqual undefined expiredElement = (patientBuilder.model.get('cqmPatient').qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'expired')[0] expect(expiredElement).not.toExist() patientBuilder.remove() describe "setting basic attributes and saving", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.$(':input[name=last]').val("<NAME>") @patientBuilder.$(':input[name=first]').val("FIRST NAME") @patientBuilder.$('select[name=gender]').val('F') @patientBuilder.$(':input[name=birthdate]').val('01/02/1993') @patientBuilder.$(':input[name=birthtime]').val('1:15 PM') @patientBuilder.$('select[name=race]').val('2131-1') @patientBuilder.$('select[name=ethnicity]').val('2135-2') @patientBuilder.$(':input[name=notes]').val('EXAMPLE NOTES FOR TEST') @patientBuilder.$("button[data-call-method=save]").click() it "dynamically loads race, ethnicity, and gender codes from measure", -> expect(@patientBuilder.$('select[name=race]')[0].options.length).toEqual 6 expect(@patientBuilder.$('select[name=ethnicity]')[0].options.length).toEqual 2 expect(@patientBuilder.$('select[name=gender]')[0].options.length).toEqual 2 it "serializes the attributes correctly", -> thoraxPatient = @patientBuilder.model cqmPatient = thoraxPatient.get('cqmPatient') expect(cqmPatient.familyName).toEqual '<NAME>' expect(cqmPatient.givenNames[0]).toEqual '<NAME>' birthdateElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'birthdate')[0] # If the measure doesn't have birthDate as a data criteria, the patient is forced to have one without a code expect(birthdateElement).not.toBeUndefined() expect(cqmPatient.qdmPatient.birthDatetime.toString()).toEqual (new cqm.models.CQL.DateTime(1993,1,2,13,15,0,0,0).toString()) expect(thoraxPatient.getBirthDate()).toEqual '01/02/1993' expect(thoraxPatient.getNotes()).toEqual 'EXAMPLE NOTES FOR TEST' expect(thoraxPatient.getGender().display).toEqual 'Female' genderElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'gender')[0] expect(genderElement.dataElementCodes[0].code).toEqual 'F' raceElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'race')[0] expect(raceElement.dataElementCodes[0].code).toEqual '2131-1' expect(raceElement.dataElementCodes[0].display).toEqual 'Other Race' expect(thoraxPatient.getRace().display).toEqual 'Other Race' ethnicityElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'ethnicity')[0] expect(ethnicityElement.dataElementCodes[0].code).toEqual '2135-2' expect(ethnicityElement.dataElementCodes[0].display).toEqual 'Hispanic or Latino' expect(thoraxPatient.getEthnicity().display).toEqual 'Hispanic or Latino' it "displayes correct values on the UI after saving", -> expect(@patientBuilder.$(':input[name=last]')[0].value).toEqual 'LAST NAME' expect(@patientBuilder.$(':input[name=first]')[0].value).toEqual 'FIRST NAME' expect(@patientBuilder.$(':input[name=birthdate]')[0].value).toEqual '01/02/1993' expect(@patientBuilder.$(':input[name=birthtime]')[0].value).toEqual '1:15 PM' expect(@patientBuilder.$(':input[name=notes]')[0].value).toEqual 'EXAMPLE NOTES FOR TEST' expect(@patientBuilder.$('select[name=race]')[0].value).toEqual '2131-1' expect(@patientBuilder.$('select[name=ethnicity]')[0].value).toEqual '2135-2' expect(@patientBuilder.$('select[name=gender]')[0].value).toEqual 'F' it "tries to save the patient correctly", -> expect(@patientBuilder.originalModel.save).toHaveBeenCalled() afterEach -> @patientBuilder.remove() describe "changing and blurring basic fields", -> beforeEach -> @patientBuilder.appendTo('body') @patientBuilder.$('select[name=gender]').val('M').change() @patientBuilder.$('input[name=birthdate]').blur() afterEach -> @patientBuilder.remove() xit "materializes the patient", -> # SKIP: The above change() and blur() commands do hit materialize when # executed in the browser console:w Not sure why the spy is not getting # hit here. expect(@patientBuilder.model.materialize).toHaveBeenCalled() expect(@patientBuilder.model.materialize.calls.count()).toEqual 2 describe "adding encounters to patient", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.render() # simulate dragging an encounter onto the patient @addEncounter = (position, targetSelector) -> $('.panel-title').click() # Expand the criteria to make draggables visible criteria = @$el.find(".draggable:eq(#{position})").draggable() target = @$el.find(targetSelector) targetView = target.view() # We used to simulate a drag, but that had issues with different viewport sizes, so instead we just # directly call the appropriate drop event handler if targetView.dropCriteria target.view().dropCriteria({ target: target }, { draggable: criteria }) else target.view().drop({ target: target }, { draggable: criteria }) it "adds data criteria to model when dragged", -> initialOriginalDataElementCount = @patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length # force materialize to get any patient characteristics that should exist added @patientBuilder.materialize(); initialSourceDataCriteriaCount = @patientBuilder.model.get('source_data_criteria').length initialDataElementCount = @patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length @addEncounter 1, '.criteria-container.droppable' expect(@patientBuilder.model.get('source_data_criteria').length).toEqual initialSourceDataCriteriaCount + 1 expect(@patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialDataElementCount + 1 # make sure the dataElements on the original model were not touched expect(@patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialOriginalDataElementCount it "can add multiples of the same criterion", -> initialOriginalDataElementCount = @patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length # force materialize to get any patient characteristics that should exist added @patientBuilder.materialize(); initialSourceDataCriteriaCount = @patientBuilder.model.get('source_data_criteria').length initialDataElementCount = @patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length @addEncounter 1, '.criteria-container.droppable' @addEncounter 1, '.criteria-container.droppable' # add the same one again expect(@patientBuilder.model.get('source_data_criteria').length).toEqual initialSourceDataCriteriaCount + 2 expect(@patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialDataElementCount + 2 # make sure the dataElements on the original model were not touched expect(@patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialOriginalDataElementCount it "has a default start and end date for the primary timing attributes when not dropped on an existing criteria", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-container.droppable' # get today in MP year and check the defaults are today 8:00-8:15 today = new Date() newStart = new cqm.models.CQL.DateTime(2012, today.getMonth() + 1, today.getDate(), 8, 0, 0, 0, 0) newEnd = new cqm.models.CQL.DateTime(2012, today.getMonth() + 1, today.getDate(), 8, 15, 0, 0, 0) newInterval = new cqm.models.CQL.Interval(newStart, newEnd) expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual newInterval # authorDatetime should be same as the start of the relevantPeriod expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual newStart it "acquires the interval of the drop target when dropping on an existing criteria", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.low).toEqual startDate expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.high).toEqual endDate it "acquires the authorDatetime of the drop target when dropping on an existing criteria", -> authorDatetime = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').authorDatetime # droppable 17 @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual authorDatetime it "acquires the interval of the drop target when dropping on an existing criteria even when low is null", -> @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low = null endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.low).toBe null expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.high).toEqual endDate it "acquires the start time and makes an end time of the drop target when dropping on an existing criteria with only authorDatetime ", -> startDate = @patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').authorDatetime # expecting end date to be 15 minutes later endDate = startDate.add(15, cqm.models.CQL.DateTime.Unit.MINUTE) # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:last' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual(new cqm.models.CQL.Interval(startDate, endDate)) it "acquires Interval[null,null] when dropping on an existing criteria with only authorDatetime that is null", -> @patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').authorDatetime = null # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:last' # interval should be [null,null] expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual(new cqm.models.CQL.Interval(null, null)) expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toBe(null) it "acquires the start of an interval as the authorDatetime when criteria with only authorDatetime is dropped on one with an Interval", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low # droppable 14 used. this is InterventionOrder that only has authorDatetime @addEncounter 14, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual(startDate) it "acquires null as the authorDatetime when criteria with only authorDatetime is dropped on one with an Interval that starts with null", -> # set the low of the drop target to be null @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low = null # droppable 14 used. this is InterventionOrder that only has authorDatetime @addEncounter 14, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toBe(null) it "materializes the patient", -> expect(@patientBuilder.model.materialize).not.toHaveBeenCalled() @addEncounter 1, '.criteria-container.droppable' expect(@patientBuilder.model.materialize).toHaveBeenCalled() afterEach -> @patientBuilder.remove() describe "editing basic attributes of a criteria", -> # SKIP: This should be re-enabled with patient builder timing work beforeEach -> @patientBuilder.appendTo 'body' # need to be specific with the query to select one of the data criteria with a period. # this is due to QDM 5.0 changes which make several data criteria only have an author time. $dataCriteria = @patientBuilder.$('div.patient-criteria:contains(Diagnosis: Diabetes):first') $dataCriteria.find('button[data-call-method=toggleDetails]:first').click() $dataCriteria.find(':input[name=start_date]:first').val('01/1/2012') $dataCriteria.find(':input[name=start_time]:first').val('3:33') # verify DOM as well expect($dataCriteria.find(':input[name=end_date]:first')).toBeDisabled() expect($dataCriteria.find(':input[name=end_time]:first')).toBeDisabled() @patientBuilder.$("button[data-call-method=save]").click() xit "serializes the attributes correctly", -> # SKIP: Re-endable with Patient Builder Timing Attributes dataCriteria = this.patient.get('cqmPatient').qdmPatient.conditions()[0] expect(dataCriteria.get('prevelancePeriod').low).toEqual moment.utc('01/1/2012 3:33', 'L LT').format('X') * 1000 expect(dataCriteria.get('prevelancePeriod').high).toBeUndefined() afterEach -> @patientBuilder.remove() describe "setting and unsetting a criteria as not performed", -> beforeEach -> @patientBuilder.appendTo 'body' it "does not serialize negationRationale for element that can't be negated", -> # 0th source_data_criteria is a diagnosis and therefore cannot have a negation and will not contain the negation expect(@patientBuilder.model.get('source_data_criteria').at(0).get('qdmDataElement').negationRationale).toEqual undefined it "serializes negationRationale to null for element that can be negated but isnt", -> # 1st source_data_criteria is an encounter that is not negated expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toEqual null it "serializes negationRationale for element that is negated", -> # The 2nd source_data_criteria is an intervention with negationRationale set to 'Emergency Department Visit' code: expect(@patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').negationRationale.code).toEqual '4525004' expect(@patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').negationRationale.system).toEqual '2.16.840.1.113883.6.96' it "toggles negations correctly", -> @patientBuilder.$('.criteria-data').children().toggleClass('hide') expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe false expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toBeNull() @patientBuilder.$('input[name=negation]:first').click() @patientBuilder.$('select[name="valueset"]').val('drc-99a051cdb6879ebe3d81f5c15cecbf4157040a6e1c12c711bacb61246e5a0d61').change() # No need to select code for test, one is selected by default expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe true expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toExist() @patientBuilder.$('input[name=negation]:first').click() expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe false expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toBeNull() afterEach -> @patientBuilder.remove() describe 'author date time', -> xit "removes author date time field value when not performed is checked", -> # SKIP: Re-enable with Patient Builder work authorDateTimePatient = @patients.models.filter((patient) -> patient.get('last') is 'AuthorDateTime')[0] patientBuilder = new Thorax.Views.PatientBuilder(model: authorDateTimePatient, measure: @measure, patients: @patients) patientBuilder.appendTo 'body' firstCriteria = patientBuilder.model.get('source_data_criteria').first() authorDateTime = patientBuilder.model.get('source_data_criteria').first().get('field_values').first().get('start_date') expect(authorDateTime).toEqual '04/24/2019' patientBuilder.$('input[name=negation]:first').click() expect(patientBuilder.model.get('source_data_criteria').first().get('field_values').length).toBe 0 startDate = new Date(patientBuilder.model.get('source_data_criteria').first().get('start_date')) expect(startDate.toString().includes("Tue Apr 17 2012")).toBe true patientBuilder.remove() describe "blurring basic fields of a criteria", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.$(':text[name=start_date]:first').blur() xit "materializes the patient", -> # SKIP: Re-enable with Patient Builder Work expect(@patientBuilder.model.materialize).toHaveBeenCalled() expect(@patientBuilder.model.materialize.calls.count()).toEqual 1 afterEach -> @patientBuilder.remove() describe "adding codes to an encounter", -> beforeEach -> @patientBuilder.appendTo 'body' @addCode = (codeSet, code, submit = true) -> @patientBuilder.$('.codeset-control:first').val(codeSet).change() $codelist = @patientBuilder.$('.codelist-control:first') expect($codelist.children("[value=#{code}]")).toExist() $codelist.val(code).change() # FIXME Our test JSON doesn't yet support value sets very well... write these tests when we have a source of value sets independent of the measures xit "adds a code", -> afterEach -> @patientBuilder.remove() describe "setting expected values", -> beforeEach -> @patientBuilder.appendTo 'body' @selectPopulationEV = (population, save=true) -> @patientBuilder.$("input[type=checkbox][name=#{population}]:first").click() @patientBuilder.$("button[data-call-method=save]").click() if save it "auto unselects DENOM and IPP when IPP is unselected", -> expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 0 @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto selects DENOM and IPP when NUMER is selected", -> @selectPopulationEV('NUMER', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 1 it "auto unselects DENOM when IPP is unselected", -> @selectPopulationEV('DENOM', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto unselects DENOM and NUMER when IPP is unselected", -> @selectPopulationEV('NUMER', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto selects DENOM and IPP when NUMER is selected", -> @selectPopulationEV('NUMER', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 1 it "auto unselects DENOM when IPP is unselected", -> @selectPopulationEV('DENOM', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto unselects DENOM and NUMER when IPP is unselected", -> @selectPopulationEV('NUMER', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it 'updates the values of the frontend mongoose model', -> expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) mongooseExpectecValue = (expectedValues.collection.parent.get('cqmPatient').expectedValues.filter (val) -> val.population_index is 0 && val.measure_id is '7B2A9277-43DA-4D99-9BEE-6AC271A07747')[0] expect(mongooseExpectecValue.IPP).toEqual 1 expect(mongooseExpectecValue.DENOM).toEqual 1 expect(mongooseExpectecValue.NUMER).toEqual 0 @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(mongooseExpectecValue.IPP).toEqual 0 expect(mongooseExpectecValue.DENOM).toEqual 0 expect(mongooseExpectecValue.NUMER).toEqual 0 @selectPopulationEV('NUMER', false) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(mongooseExpectecValue.IPP).toEqual 1 expect(mongooseExpectecValue.DENOM).toEqual 1 expect(mongooseExpectecValue.NUMER).toEqual 1 afterEach -> @patientBuilder.remove() describe "setting expected values for CV measure", -> beforeEach -> cqlMeasure = loadMeasureWithValueSets 'cqm_measure_data/CMS903v0/CMS903v0.json', 'cqm_measure_data/CMS903v0/value_sets.json' patientsJSON = [] patientsJSON.push(getJSONFixture('patients/CMS903v0/Visit_1 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits 1 Excl_2 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits 2 Excl_2 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits_2 ED.json')) patients = new Thorax.Collections.Patients patientsJSON, parse: true @patientBuilder = new Thorax.Views.PatientBuilder(model: patients.first(), measure: cqlMeasure) @patientBuilder.appendTo 'body' @setPopulationVal = (population, value=0, save=true) -> @patientBuilder.$("input[type=number][name=#{population}]:first").val(value).change() @patientBuilder.$("button[data-call-method=save]").click() if save it "IPP removal removes membership of all populations in CV measures", -> @setPopulationVal('IPP', 0, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('MSRPOPL')).toEqual 0 expect(expectedValues.get('MSRPOPLEX')).toEqual 0 expect(expectedValues.get('OBSERV')).toEqual undefined it "MSRPOPLEX addition adds membership to all populations in CV measures", -> # First set IPP to 0 to zero out all population membership @setPopulationVal('IPP', 0, true) @setPopulationVal('MSRPOPLEX', 4, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 4 expect(expectedValues.get('MSRPOPL')).toEqual 4 expect(expectedValues.get('MSRPOPLEX')).toEqual 4 # 4 MSRPOPLEX and 4 MSRPOPL means there should be no OBSERVs expect(expectedValues.get('OBSERV')).toEqual undefined it "MSRPOPLEX addition and removal adds and removes OBSERVs in CV measures", -> # First set IPP to 0 to zero out all population membership @setPopulationVal('IPP', 0, true) @setPopulationVal('MSRPOPLEX', 3, true) @setPopulationVal('MSRPOPL', 4, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 4 expect(expectedValues.get('MSRPOPL')).toEqual 4 expect(expectedValues.get('MSRPOPLEX')).toEqual 3 # 4 MSRPOPL and 3 MSRPOPLEX means there should be 1 OBSERVs expect(expectedValues.get('OBSERV').length).toEqual 1 @setPopulationVal('MSRPOPL', 6, true) expect(expectedValues.get('IPP')).toEqual 6 expect(expectedValues.get('MSRPOPL')).toEqual 6 expect(expectedValues.get('MSRPOPLEX')).toEqual 3 # 6 MSRPOPL and 3 MSRPOPLEX means there should be 3 OBSERVs expect(expectedValues.get('OBSERV').length).toEqual 3 # Should remove all observs @setPopulationVal('MSRPOPLEX', 6, true) expect(expectedValues.get('IPP')).toEqual 6 expect(expectedValues.get('MSRPOPL')).toEqual 6 expect(expectedValues.get('MSRPOPLEX')).toEqual 6 # 6 MSRPOPLEX and 6 MSRPOPL means there should be no OBSERVs expect(expectedValues.get('OBSERV')).toEqual undefined # set IPP to 0, should zero out all populations @setPopulationVal('IPP', 0, true) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('MSRPOPL')).toEqual 0 expect(expectedValues.get('MSRPOPLEX')).toEqual 0 expect(expectedValues.get('OBSERV')).toEqual undefined afterEach -> @patientBuilder.remove() describe 'CQL', -> beforeEach -> jasmine.getJSONFixtures().clearCache() @cqlMeasure = new Thorax.Models.Measure getJSONFixture('cqm_measure_data/deprecated_measures/CMS347/CMS347v3.json'), parse: true # preserve atomicity @bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add(@cqlMeasure, {parse: true}) afterEach -> bonnie.measures = @bonnie_measures_old xit "laboratory test performed should have custom view for components", -> # SKIP: Re-enable with Patient Builder Attributes # NOTE: these patients aren't in the DB so fixture will need to be swapped patients = new Thorax.Collections.Patients getJSONFixture('patients/CMS347/patients.json'), parse: true patientBuilder = new Thorax.Views.PatientBuilder(model: patients.first(), measure: @cqlMeasure) dataCriteria = patientBuilder.model.get('source_data_criteria').models laboratoryTestIndex = dataCriteria.findIndex((m) -> m.attributes.definition is 'laboratory_test') laboratoryTest = dataCriteria[laboratoryTestIndex] editCriteriaView = new Thorax.Views.EditCriteriaView(model: laboratoryTest) editFieldValueView = editCriteriaView.editFieldValueView editFieldValueView.render() editFieldValueView.$('select[name=key]').val('COMPONENT').change() expect(editFieldValueView.$('label[for=code]')).toExist() expect(editFieldValueView.$('label[for=code]')[0].innerHTML).toEqual('Code') expect(editFieldValueView.$('label[for=referenceRangeLow]')).toExist() expect(editFieldValueView.$('label[for=referenceRangeLow]')[0].innerHTML).toEqual('Reference Range - Low') expect(editFieldValueView.$('label[for=referenceRangeHigh]')).toExist() expect(editFieldValueView.$('label[for=referenceRangeHigh]')[0].innerHTML).toEqual('Reference Range - High') expect(editFieldValueView.$('select[name=code_list_id]')).toExist() editFieldValueView.$('select[name=key]').val('REASON').change() expect(editFieldValueView.$('label[for=code]').length).toEqual(0) expect(editFieldValueView.$('label[for=referenceRangeLow]').length).toEqual(0) expect(editFieldValueView.$('label[for=referenceRangeHigh]').length).toEqual(0) describe 'Composite Measure', -> beforeEach -> jasmine.getJSONFixtures().clearCache() # preserve atomicity @bonnie_measures_old = bonnie.measures valueSetsPath = 'cqm_measure_data/CMS890v0/value_sets.json' bonnie.measures = new Thorax.Collections.Measures() @compositeMeasure = loadMeasureWithValueSets 'cqm_measure_data/CMS890v0/CMS890v0.json', valueSetsPath bonnie.measures.push(@compositeMeasure) @components = getJSONFixture('cqm_measure_data/CMS890v0/components.json') @components = @components.map((component) -> new Thorax.Models.Measure component, parse: true) @components.forEach((component) -> bonnie.measures.push(component)) patientTest1 = getJSONFixture('patients/CMS890v0/Patient_Test 1.json') patientTest2 = getJSONFixture('patients/CMS890v0/Patient_Test 2.json') @compositePatients = new Thorax.Collections.Patients [patientTest1, patientTest2], parse: true @compositeMeasure.populateComponents() afterEach -> bonnie.measures = @bonnie_measures_old xit "should floor the observ value to at most 8 decimals", -> # SKIP: Re-enable with patient saving/expected value work patientBuilder = new Thorax.Views.PatientBuilder(model: @compositePatients.at(1), measure: @compositeMeasure) patientBuilder.render() expected_vals = patientBuilder.model.get('expected_values').findWhere({measure_id: "244B4F52-C9CA-45AA-8BDB-2F005DA05BFC"}) patientBuilder.$(':input[name=OBSERV]').val(0.123456781111111) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 0.12345678 patientBuilder.$(':input[name=OBSERV]').val(0.123456786666666) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 0.12345678 patientBuilder.$(':input[name=OBSERV]').val(1.5) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 1.5 it "should display a warning that the patient is shared", -> patientBuilder = new Thorax.Views.PatientBuilder(model: @compositePatients.first(), measure: @components[0]) patientBuilder.render() expect(patientBuilder.$("div.alert-warning")[0].innerHTML.substr(0,31).trim()).toEqual "Note: This patient is shared" it 'should have the breadcrumbs with composite and component measure', -> breadcrumb = new Thorax.Views.Breadcrumb() breadcrumb.addPatient(@components[0], @compositePatients.first()) breadcrumb.render() expect(breadcrumb.$("a")[1].childNodes[1].textContent).toEqual " CMS890v0 " # parent composite measure expect(breadcrumb.$("a")[2].childNodes[1].textContent).toEqual " CMS231v0 " # the component measure describe 'Direct Reference Code Usage', -> # Originally BONNIE-939 beforeEach -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS903v0/CMS903v0.json', 'cqm_measure_data/CMS903v0/value_sets.json' bonnie.measures.add(@measure, { parse: true }) @patient = new Thorax.Models.Patient getJSONFixture('patients/CMS903v0/Visits 2 Excl_2 ED.json'), parse: true xit 'Field Value Dropdown should contain direct reference code element', -> # SKIP: Re-enable with Patient Builder Code Work patientBuilder = new Thorax.Views.PatientBuilder(model: @patients.first(), measure: @measure) dataCriteria = patientBuilder.model.get('source_data_criteria').models edVisitIndex = dataCriteria.findIndex((m) -> m.attributes.description is 'Encounter, Performed: Emergency Department Visit') emergencyDepartmentVisit = dataCriteria[edVisitIndex] editCriteriaView = new Thorax.Views.EditCriteriaView(model: emergencyDepartmentVisit, measure: @measure) editFieldValueView = editCriteriaView.editFieldValueView expect(editFieldValueView.render()).toContain('drc-') it 'Adding direct reference code element should calculate correctly', -> population = @measure.get('populations').first() results = population.calculate(@patient) library = "LikeCMS32" statementResults = results.get("statement_results") titleOfClauseThatUsesDrc = statementResults[library]['Measure Population Exclusions'].raw[0].dischargeDisposition.display expect(titleOfClauseThatUsesDrc).toBe "Patient deceased during stay (discharge status = dead) (finding)" describe 'Allergy', -> # Originally BONNIE-785 beforeAll -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS12v0/CMS12v0.json', 'cqm_measure_data/CMS12v0/value_sets.json' bonnie.measures.add @measure medAllergy = getJSONFixture("patients/CMS12v0/MedAllergyEndIP_DENEXCEPPass.json") @patients = new Thorax.Collections.Patients [medAllergy], parse: true @patient = @patients.at(0) # MedAllergyEndIP_DENEXCEPPass @patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) sourceDataCriteria = @patientBuilder.model.get("source_data_criteria") @allergyIntolerance = sourceDataCriteria.findWhere({qdmCategory: "allergy"}) @patientBuilder.render() @patientBuilder.appendTo('body') afterEach -> @patientBuilder.remove() it 'is displayed on Patient Builder Page in Elements section', -> expect(@patientBuilder.$el.find("div#criteriaElements").html()).toContainText "allergy" it 'highlight is triggered by relevant cql clause', -> cqlLogicView = @patientBuilder.populationLogicView.getView().cqlLogicView sourceDataCriteria = cqlLogicView.latestResult.patient.get('source_data_criteria') patientDataCriteria = _.find(sourceDataCriteria.models, (sdc) -> sdc.get('qdmCategory') == 'allergy') dataCriteriaIds = [patientDataCriteria.get('_id').toString()] spyOn(patientDataCriteria, 'trigger') cqlLogicView.highlightPatientData(dataCriteriaIds) expect(patientDataCriteria.trigger).toHaveBeenCalled()
true
describe 'PatientBuilderView', -> beforeEach -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS134v6/CMS134v6.json', 'cqm_measure_data/CMS134v6/value_sets.json' @patients = new Thorax.Collections.Patients [getJSONFixture('patients/CMS134v6/Elements_Test.json'), getJSONFixture('patients/CMS134v6/Fail_Hospice_Not_Performed_Denex.json')], parse: true @patient = @patients.models[1] @bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add @measure @patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) @patientBuilder.render() spyOn(@patientBuilder.model, 'materialize') spyOn(@patientBuilder.originalModel, 'save').and.returnValue(true) @$el = @patientBuilder.$el afterEach -> bonnie.measures = @bonnie_measures_old it 'should not open patient builder for non existent measure', -> spyOn(bonnie,'showPageNotFound') bonnie.showPageNotFound.calls.reset() bonnie.renderPatientBuilder('non_existant_hqmf_set_id', @patient.id) expect(bonnie.showPageNotFound).toHaveBeenCalled() it 'should set the main view when calling showPageNotFound', -> spyOn(bonnie.mainView,'setView') bonnie.renderPatientBuilder('non_existant_hqmf_set_id', @patient.id) expect(bonnie.mainView.setView).toHaveBeenCalled() it 'renders the builder correctly', -> expect(@$el.find(":input[name='first']")).toHaveValue @patient.getFirstName() expect(@$el.find(":input[name='last']")).toHaveValue @patient.getLastName() expect(@$el.find(":input[name='birthdate']")).toHaveValue @patient.getBirthDate() expect(@$el.find(":input[name='birthtime']")).toHaveValue @patient.getBirthTime() expect(@$el.find(":input[name='notes']")).toHaveValue @patient.getNotes() expect(@patientBuilder.html()).not.toContainText "Warning: There are elements in the Patient History that do not use any codes from this measure's value sets:" it 'displays a warning if codes on dataElements do not exist on measure', -> @measure.attributes.cqmValueSets = [] patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) patientBuilder.render() expect(patientBuilder.html()).toContainText "Warning: There are elements in the Patient History that do not use any codes from this measure's value sets:" it 'does not display compare patient results button when there is no history', -> expect(@patientBuilder.$('button[data-call-method=showCompare]:first')).not.toExist() it "toggles patient expiration correctly", -> measure = loadMeasureWithValueSets 'cqm_measure_data/CMSv5555/CMSv5555.json', 'cqm_measure_data/CMSv5555/value_sets.json' patients = new Thorax.Collections.Patients [getJSONFixture('patients/CMSv5555/PI:NAME:<NAME>END_PI.json')], parse: true patient = patients.models[0] bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add measure patientBuilder = new Thorax.Views.PatientBuilder(model: patient, measure: measure, patients: patients) patientBuilder.render() spyOn(patientBuilder.model, 'materialize') spyOn(patientBuilder.originalModel, 'save').and.returnValue(true) patientBuilder.appendTo 'body' # Press deceased check box and enter death date patientBuilder.$('input[type=checkbox][name=expired]:first').click() patientBuilder.$(':input[name=deathdate]').val('01/02/1994') patientBuilder.$(':input[name=deathtime]').val('1:15 PM') patientBuilder.$("button[data-call-method=save]").click() expect(patientBuilder.model.get('expired')).toEqual true expect(patientBuilder.model.get('deathdate')).toEqual '01/02/1994' expect(patientBuilder.model.get('deathtime')).toEqual "1:15 PM" expiredElement = (patientBuilder.model.get('cqmPatient').qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'expired')[0] expect(expiredElement.expiredDatetime.toString()).toEqual (new cqm.models.CQL.DateTime(1994,1,2,13,15,0,0,0).toString()) # Remove deathdate from patient patientBuilder.$("button[data-call-method=removeDeathDate]").click() patientBuilder.$("button[data-call-method=save]").click() expect(patientBuilder.model.get('expired')).toEqual false expect(patientBuilder.model.get('deathdate')).toEqual undefined expect(patientBuilder.model.get('deathtime')).toEqual undefined expiredElement = (patientBuilder.model.get('cqmPatient').qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'expired')[0] expect(expiredElement).not.toExist() patientBuilder.remove() describe "setting basic attributes and saving", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.$(':input[name=last]').val("PI:NAME:<NAME>END_PI") @patientBuilder.$(':input[name=first]').val("FIRST NAME") @patientBuilder.$('select[name=gender]').val('F') @patientBuilder.$(':input[name=birthdate]').val('01/02/1993') @patientBuilder.$(':input[name=birthtime]').val('1:15 PM') @patientBuilder.$('select[name=race]').val('2131-1') @patientBuilder.$('select[name=ethnicity]').val('2135-2') @patientBuilder.$(':input[name=notes]').val('EXAMPLE NOTES FOR TEST') @patientBuilder.$("button[data-call-method=save]").click() it "dynamically loads race, ethnicity, and gender codes from measure", -> expect(@patientBuilder.$('select[name=race]')[0].options.length).toEqual 6 expect(@patientBuilder.$('select[name=ethnicity]')[0].options.length).toEqual 2 expect(@patientBuilder.$('select[name=gender]')[0].options.length).toEqual 2 it "serializes the attributes correctly", -> thoraxPatient = @patientBuilder.model cqmPatient = thoraxPatient.get('cqmPatient') expect(cqmPatient.familyName).toEqual 'PI:NAME:<NAME>END_PI' expect(cqmPatient.givenNames[0]).toEqual 'PI:NAME:<NAME>END_PI' birthdateElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'birthdate')[0] # If the measure doesn't have birthDate as a data criteria, the patient is forced to have one without a code expect(birthdateElement).not.toBeUndefined() expect(cqmPatient.qdmPatient.birthDatetime.toString()).toEqual (new cqm.models.CQL.DateTime(1993,1,2,13,15,0,0,0).toString()) expect(thoraxPatient.getBirthDate()).toEqual '01/02/1993' expect(thoraxPatient.getNotes()).toEqual 'EXAMPLE NOTES FOR TEST' expect(thoraxPatient.getGender().display).toEqual 'Female' genderElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'gender')[0] expect(genderElement.dataElementCodes[0].code).toEqual 'F' raceElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'race')[0] expect(raceElement.dataElementCodes[0].code).toEqual '2131-1' expect(raceElement.dataElementCodes[0].display).toEqual 'Other Race' expect(thoraxPatient.getRace().display).toEqual 'Other Race' ethnicityElement = (cqmPatient.qdmPatient.patient_characteristics().filter (elem) -> elem.qdmStatus == 'ethnicity')[0] expect(ethnicityElement.dataElementCodes[0].code).toEqual '2135-2' expect(ethnicityElement.dataElementCodes[0].display).toEqual 'Hispanic or Latino' expect(thoraxPatient.getEthnicity().display).toEqual 'Hispanic or Latino' it "displayes correct values on the UI after saving", -> expect(@patientBuilder.$(':input[name=last]')[0].value).toEqual 'LAST NAME' expect(@patientBuilder.$(':input[name=first]')[0].value).toEqual 'FIRST NAME' expect(@patientBuilder.$(':input[name=birthdate]')[0].value).toEqual '01/02/1993' expect(@patientBuilder.$(':input[name=birthtime]')[0].value).toEqual '1:15 PM' expect(@patientBuilder.$(':input[name=notes]')[0].value).toEqual 'EXAMPLE NOTES FOR TEST' expect(@patientBuilder.$('select[name=race]')[0].value).toEqual '2131-1' expect(@patientBuilder.$('select[name=ethnicity]')[0].value).toEqual '2135-2' expect(@patientBuilder.$('select[name=gender]')[0].value).toEqual 'F' it "tries to save the patient correctly", -> expect(@patientBuilder.originalModel.save).toHaveBeenCalled() afterEach -> @patientBuilder.remove() describe "changing and blurring basic fields", -> beforeEach -> @patientBuilder.appendTo('body') @patientBuilder.$('select[name=gender]').val('M').change() @patientBuilder.$('input[name=birthdate]').blur() afterEach -> @patientBuilder.remove() xit "materializes the patient", -> # SKIP: The above change() and blur() commands do hit materialize when # executed in the browser console:w Not sure why the spy is not getting # hit here. expect(@patientBuilder.model.materialize).toHaveBeenCalled() expect(@patientBuilder.model.materialize.calls.count()).toEqual 2 describe "adding encounters to patient", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.render() # simulate dragging an encounter onto the patient @addEncounter = (position, targetSelector) -> $('.panel-title').click() # Expand the criteria to make draggables visible criteria = @$el.find(".draggable:eq(#{position})").draggable() target = @$el.find(targetSelector) targetView = target.view() # We used to simulate a drag, but that had issues with different viewport sizes, so instead we just # directly call the appropriate drop event handler if targetView.dropCriteria target.view().dropCriteria({ target: target }, { draggable: criteria }) else target.view().drop({ target: target }, { draggable: criteria }) it "adds data criteria to model when dragged", -> initialOriginalDataElementCount = @patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length # force materialize to get any patient characteristics that should exist added @patientBuilder.materialize(); initialSourceDataCriteriaCount = @patientBuilder.model.get('source_data_criteria').length initialDataElementCount = @patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length @addEncounter 1, '.criteria-container.droppable' expect(@patientBuilder.model.get('source_data_criteria').length).toEqual initialSourceDataCriteriaCount + 1 expect(@patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialDataElementCount + 1 # make sure the dataElements on the original model were not touched expect(@patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialOriginalDataElementCount it "can add multiples of the same criterion", -> initialOriginalDataElementCount = @patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length # force materialize to get any patient characteristics that should exist added @patientBuilder.materialize(); initialSourceDataCriteriaCount = @patientBuilder.model.get('source_data_criteria').length initialDataElementCount = @patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length @addEncounter 1, '.criteria-container.droppable' @addEncounter 1, '.criteria-container.droppable' # add the same one again expect(@patientBuilder.model.get('source_data_criteria').length).toEqual initialSourceDataCriteriaCount + 2 expect(@patientBuilder.model.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialDataElementCount + 2 # make sure the dataElements on the original model were not touched expect(@patientBuilder.originalModel.get('cqmPatient').qdmPatient.dataElements.length).toEqual initialOriginalDataElementCount it "has a default start and end date for the primary timing attributes when not dropped on an existing criteria", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-container.droppable' # get today in MP year and check the defaults are today 8:00-8:15 today = new Date() newStart = new cqm.models.CQL.DateTime(2012, today.getMonth() + 1, today.getDate(), 8, 0, 0, 0, 0) newEnd = new cqm.models.CQL.DateTime(2012, today.getMonth() + 1, today.getDate(), 8, 15, 0, 0, 0) newInterval = new cqm.models.CQL.Interval(newStart, newEnd) expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual newInterval # authorDatetime should be same as the start of the relevantPeriod expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual newStart it "acquires the interval of the drop target when dropping on an existing criteria", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.low).toEqual startDate expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.high).toEqual endDate it "acquires the authorDatetime of the drop target when dropping on an existing criteria", -> authorDatetime = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').authorDatetime # droppable 17 @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual authorDatetime it "acquires the interval of the drop target when dropping on an existing criteria even when low is null", -> @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low = null endDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.high # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.low).toBe null expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod.high).toEqual endDate it "acquires the start time and makes an end time of the drop target when dropping on an existing criteria with only authorDatetime ", -> startDate = @patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').authorDatetime # expecting end date to be 15 minutes later endDate = startDate.add(15, cqm.models.CQL.DateTime.Unit.MINUTE) # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:last' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual(new cqm.models.CQL.Interval(startDate, endDate)) it "acquires Interval[null,null] when dropping on an existing criteria with only authorDatetime that is null", -> @patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').authorDatetime = null # droppable 17 used because droppable 1 didn't have a start and end date @addEncounter 17, '.criteria-data.droppable:last' # interval should be [null,null] expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').relevantPeriod).toEqual(new cqm.models.CQL.Interval(null, null)) expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toBe(null) it "acquires the start of an interval as the authorDatetime when criteria with only authorDatetime is dropped on one with an Interval", -> startDate = @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low # droppable 14 used. this is InterventionOrder that only has authorDatetime @addEncounter 14, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toEqual(startDate) it "acquires null as the authorDatetime when criteria with only authorDatetime is dropped on one with an Interval that starts with null", -> # set the low of the drop target to be null @patientBuilder.model.get('source_data_criteria').first().get('qdmDataElement').prevalencePeriod.low = null # droppable 14 used. this is InterventionOrder that only has authorDatetime @addEncounter 14, '.criteria-data.droppable:first' expect(@patientBuilder.model.get('source_data_criteria').last().get('qdmDataElement').authorDatetime).toBe(null) it "materializes the patient", -> expect(@patientBuilder.model.materialize).not.toHaveBeenCalled() @addEncounter 1, '.criteria-container.droppable' expect(@patientBuilder.model.materialize).toHaveBeenCalled() afterEach -> @patientBuilder.remove() describe "editing basic attributes of a criteria", -> # SKIP: This should be re-enabled with patient builder timing work beforeEach -> @patientBuilder.appendTo 'body' # need to be specific with the query to select one of the data criteria with a period. # this is due to QDM 5.0 changes which make several data criteria only have an author time. $dataCriteria = @patientBuilder.$('div.patient-criteria:contains(Diagnosis: Diabetes):first') $dataCriteria.find('button[data-call-method=toggleDetails]:first').click() $dataCriteria.find(':input[name=start_date]:first').val('01/1/2012') $dataCriteria.find(':input[name=start_time]:first').val('3:33') # verify DOM as well expect($dataCriteria.find(':input[name=end_date]:first')).toBeDisabled() expect($dataCriteria.find(':input[name=end_time]:first')).toBeDisabled() @patientBuilder.$("button[data-call-method=save]").click() xit "serializes the attributes correctly", -> # SKIP: Re-endable with Patient Builder Timing Attributes dataCriteria = this.patient.get('cqmPatient').qdmPatient.conditions()[0] expect(dataCriteria.get('prevelancePeriod').low).toEqual moment.utc('01/1/2012 3:33', 'L LT').format('X') * 1000 expect(dataCriteria.get('prevelancePeriod').high).toBeUndefined() afterEach -> @patientBuilder.remove() describe "setting and unsetting a criteria as not performed", -> beforeEach -> @patientBuilder.appendTo 'body' it "does not serialize negationRationale for element that can't be negated", -> # 0th source_data_criteria is a diagnosis and therefore cannot have a negation and will not contain the negation expect(@patientBuilder.model.get('source_data_criteria').at(0).get('qdmDataElement').negationRationale).toEqual undefined it "serializes negationRationale to null for element that can be negated but isnt", -> # 1st source_data_criteria is an encounter that is not negated expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toEqual null it "serializes negationRationale for element that is negated", -> # The 2nd source_data_criteria is an intervention with negationRationale set to 'Emergency Department Visit' code: expect(@patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').negationRationale.code).toEqual '4525004' expect(@patientBuilder.model.get('source_data_criteria').at(2).get('qdmDataElement').negationRationale.system).toEqual '2.16.840.1.113883.6.96' it "toggles negations correctly", -> @patientBuilder.$('.criteria-data').children().toggleClass('hide') expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe false expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toBeNull() @patientBuilder.$('input[name=negation]:first').click() @patientBuilder.$('select[name="valueset"]').val('drc-99a051cdb6879ebe3d81f5c15cecbf4157040a6e1c12c711bacb61246e5a0d61').change() # No need to select code for test, one is selected by default expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe true expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toExist() @patientBuilder.$('input[name=negation]:first').click() expect(@patientBuilder.model.get('source_data_criteria').at(1).get('negation')).toBe false expect(@patientBuilder.model.get('source_data_criteria').at(1).get('qdmDataElement').negationRationale).toBeNull() afterEach -> @patientBuilder.remove() describe 'author date time', -> xit "removes author date time field value when not performed is checked", -> # SKIP: Re-enable with Patient Builder work authorDateTimePatient = @patients.models.filter((patient) -> patient.get('last') is 'AuthorDateTime')[0] patientBuilder = new Thorax.Views.PatientBuilder(model: authorDateTimePatient, measure: @measure, patients: @patients) patientBuilder.appendTo 'body' firstCriteria = patientBuilder.model.get('source_data_criteria').first() authorDateTime = patientBuilder.model.get('source_data_criteria').first().get('field_values').first().get('start_date') expect(authorDateTime).toEqual '04/24/2019' patientBuilder.$('input[name=negation]:first').click() expect(patientBuilder.model.get('source_data_criteria').first().get('field_values').length).toBe 0 startDate = new Date(patientBuilder.model.get('source_data_criteria').first().get('start_date')) expect(startDate.toString().includes("Tue Apr 17 2012")).toBe true patientBuilder.remove() describe "blurring basic fields of a criteria", -> beforeEach -> @patientBuilder.appendTo 'body' @patientBuilder.$(':text[name=start_date]:first').blur() xit "materializes the patient", -> # SKIP: Re-enable with Patient Builder Work expect(@patientBuilder.model.materialize).toHaveBeenCalled() expect(@patientBuilder.model.materialize.calls.count()).toEqual 1 afterEach -> @patientBuilder.remove() describe "adding codes to an encounter", -> beforeEach -> @patientBuilder.appendTo 'body' @addCode = (codeSet, code, submit = true) -> @patientBuilder.$('.codeset-control:first').val(codeSet).change() $codelist = @patientBuilder.$('.codelist-control:first') expect($codelist.children("[value=#{code}]")).toExist() $codelist.val(code).change() # FIXME Our test JSON doesn't yet support value sets very well... write these tests when we have a source of value sets independent of the measures xit "adds a code", -> afterEach -> @patientBuilder.remove() describe "setting expected values", -> beforeEach -> @patientBuilder.appendTo 'body' @selectPopulationEV = (population, save=true) -> @patientBuilder.$("input[type=checkbox][name=#{population}]:first").click() @patientBuilder.$("button[data-call-method=save]").click() if save it "auto unselects DENOM and IPP when IPP is unselected", -> expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 0 @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto selects DENOM and IPP when NUMER is selected", -> @selectPopulationEV('NUMER', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 1 it "auto unselects DENOM when IPP is unselected", -> @selectPopulationEV('DENOM', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto unselects DENOM and NUMER when IPP is unselected", -> @selectPopulationEV('NUMER', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto selects DENOM and IPP when NUMER is selected", -> @selectPopulationEV('NUMER', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 1 expect(expectedValues.get('DENOM')).toEqual 1 expect(expectedValues.get('NUMER')).toEqual 1 it "auto unselects DENOM when IPP is unselected", -> @selectPopulationEV('DENOM', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it "auto unselects DENOM and NUMER when IPP is unselected", -> @selectPopulationEV('NUMER', false) @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('DENOM')).toEqual 0 expect(expectedValues.get('NUMER')).toEqual 0 it 'updates the values of the frontend mongoose model', -> expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) mongooseExpectecValue = (expectedValues.collection.parent.get('cqmPatient').expectedValues.filter (val) -> val.population_index is 0 && val.measure_id is '7B2A9277-43DA-4D99-9BEE-6AC271A07747')[0] expect(mongooseExpectecValue.IPP).toEqual 1 expect(mongooseExpectecValue.DENOM).toEqual 1 expect(mongooseExpectecValue.NUMER).toEqual 0 @selectPopulationEV('IPP', true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(mongooseExpectecValue.IPP).toEqual 0 expect(mongooseExpectecValue.DENOM).toEqual 0 expect(mongooseExpectecValue.NUMER).toEqual 0 @selectPopulationEV('NUMER', false) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(mongooseExpectecValue.IPP).toEqual 1 expect(mongooseExpectecValue.DENOM).toEqual 1 expect(mongooseExpectecValue.NUMER).toEqual 1 afterEach -> @patientBuilder.remove() describe "setting expected values for CV measure", -> beforeEach -> cqlMeasure = loadMeasureWithValueSets 'cqm_measure_data/CMS903v0/CMS903v0.json', 'cqm_measure_data/CMS903v0/value_sets.json' patientsJSON = [] patientsJSON.push(getJSONFixture('patients/CMS903v0/Visit_1 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits 1 Excl_2 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits 2 Excl_2 ED.json')) patientsJSON.push(getJSONFixture('patients/CMS903v0/Visits_2 ED.json')) patients = new Thorax.Collections.Patients patientsJSON, parse: true @patientBuilder = new Thorax.Views.PatientBuilder(model: patients.first(), measure: cqlMeasure) @patientBuilder.appendTo 'body' @setPopulationVal = (population, value=0, save=true) -> @patientBuilder.$("input[type=number][name=#{population}]:first").val(value).change() @patientBuilder.$("button[data-call-method=save]").click() if save it "IPP removal removes membership of all populations in CV measures", -> @setPopulationVal('IPP', 0, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('MSRPOPL')).toEqual 0 expect(expectedValues.get('MSRPOPLEX')).toEqual 0 expect(expectedValues.get('OBSERV')).toEqual undefined it "MSRPOPLEX addition adds membership to all populations in CV measures", -> # First set IPP to 0 to zero out all population membership @setPopulationVal('IPP', 0, true) @setPopulationVal('MSRPOPLEX', 4, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 4 expect(expectedValues.get('MSRPOPL')).toEqual 4 expect(expectedValues.get('MSRPOPLEX')).toEqual 4 # 4 MSRPOPLEX and 4 MSRPOPL means there should be no OBSERVs expect(expectedValues.get('OBSERV')).toEqual undefined it "MSRPOPLEX addition and removal adds and removes OBSERVs in CV measures", -> # First set IPP to 0 to zero out all population membership @setPopulationVal('IPP', 0, true) @setPopulationVal('MSRPOPLEX', 3, true) @setPopulationVal('MSRPOPL', 4, true) expectedValues = @patientBuilder.model.get('expected_values').findWhere(population_index: 0) expect(expectedValues.get('IPP')).toEqual 4 expect(expectedValues.get('MSRPOPL')).toEqual 4 expect(expectedValues.get('MSRPOPLEX')).toEqual 3 # 4 MSRPOPL and 3 MSRPOPLEX means there should be 1 OBSERVs expect(expectedValues.get('OBSERV').length).toEqual 1 @setPopulationVal('MSRPOPL', 6, true) expect(expectedValues.get('IPP')).toEqual 6 expect(expectedValues.get('MSRPOPL')).toEqual 6 expect(expectedValues.get('MSRPOPLEX')).toEqual 3 # 6 MSRPOPL and 3 MSRPOPLEX means there should be 3 OBSERVs expect(expectedValues.get('OBSERV').length).toEqual 3 # Should remove all observs @setPopulationVal('MSRPOPLEX', 6, true) expect(expectedValues.get('IPP')).toEqual 6 expect(expectedValues.get('MSRPOPL')).toEqual 6 expect(expectedValues.get('MSRPOPLEX')).toEqual 6 # 6 MSRPOPLEX and 6 MSRPOPL means there should be no OBSERVs expect(expectedValues.get('OBSERV')).toEqual undefined # set IPP to 0, should zero out all populations @setPopulationVal('IPP', 0, true) expect(expectedValues.get('IPP')).toEqual 0 expect(expectedValues.get('MSRPOPL')).toEqual 0 expect(expectedValues.get('MSRPOPLEX')).toEqual 0 expect(expectedValues.get('OBSERV')).toEqual undefined afterEach -> @patientBuilder.remove() describe 'CQL', -> beforeEach -> jasmine.getJSONFixtures().clearCache() @cqlMeasure = new Thorax.Models.Measure getJSONFixture('cqm_measure_data/deprecated_measures/CMS347/CMS347v3.json'), parse: true # preserve atomicity @bonnie_measures_old = bonnie.measures bonnie.measures = new Thorax.Collections.Measures() bonnie.measures.add(@cqlMeasure, {parse: true}) afterEach -> bonnie.measures = @bonnie_measures_old xit "laboratory test performed should have custom view for components", -> # SKIP: Re-enable with Patient Builder Attributes # NOTE: these patients aren't in the DB so fixture will need to be swapped patients = new Thorax.Collections.Patients getJSONFixture('patients/CMS347/patients.json'), parse: true patientBuilder = new Thorax.Views.PatientBuilder(model: patients.first(), measure: @cqlMeasure) dataCriteria = patientBuilder.model.get('source_data_criteria').models laboratoryTestIndex = dataCriteria.findIndex((m) -> m.attributes.definition is 'laboratory_test') laboratoryTest = dataCriteria[laboratoryTestIndex] editCriteriaView = new Thorax.Views.EditCriteriaView(model: laboratoryTest) editFieldValueView = editCriteriaView.editFieldValueView editFieldValueView.render() editFieldValueView.$('select[name=key]').val('COMPONENT').change() expect(editFieldValueView.$('label[for=code]')).toExist() expect(editFieldValueView.$('label[for=code]')[0].innerHTML).toEqual('Code') expect(editFieldValueView.$('label[for=referenceRangeLow]')).toExist() expect(editFieldValueView.$('label[for=referenceRangeLow]')[0].innerHTML).toEqual('Reference Range - Low') expect(editFieldValueView.$('label[for=referenceRangeHigh]')).toExist() expect(editFieldValueView.$('label[for=referenceRangeHigh]')[0].innerHTML).toEqual('Reference Range - High') expect(editFieldValueView.$('select[name=code_list_id]')).toExist() editFieldValueView.$('select[name=key]').val('REASON').change() expect(editFieldValueView.$('label[for=code]').length).toEqual(0) expect(editFieldValueView.$('label[for=referenceRangeLow]').length).toEqual(0) expect(editFieldValueView.$('label[for=referenceRangeHigh]').length).toEqual(0) describe 'Composite Measure', -> beforeEach -> jasmine.getJSONFixtures().clearCache() # preserve atomicity @bonnie_measures_old = bonnie.measures valueSetsPath = 'cqm_measure_data/CMS890v0/value_sets.json' bonnie.measures = new Thorax.Collections.Measures() @compositeMeasure = loadMeasureWithValueSets 'cqm_measure_data/CMS890v0/CMS890v0.json', valueSetsPath bonnie.measures.push(@compositeMeasure) @components = getJSONFixture('cqm_measure_data/CMS890v0/components.json') @components = @components.map((component) -> new Thorax.Models.Measure component, parse: true) @components.forEach((component) -> bonnie.measures.push(component)) patientTest1 = getJSONFixture('patients/CMS890v0/Patient_Test 1.json') patientTest2 = getJSONFixture('patients/CMS890v0/Patient_Test 2.json') @compositePatients = new Thorax.Collections.Patients [patientTest1, patientTest2], parse: true @compositeMeasure.populateComponents() afterEach -> bonnie.measures = @bonnie_measures_old xit "should floor the observ value to at most 8 decimals", -> # SKIP: Re-enable with patient saving/expected value work patientBuilder = new Thorax.Views.PatientBuilder(model: @compositePatients.at(1), measure: @compositeMeasure) patientBuilder.render() expected_vals = patientBuilder.model.get('expected_values').findWhere({measure_id: "244B4F52-C9CA-45AA-8BDB-2F005DA05BFC"}) patientBuilder.$(':input[name=OBSERV]').val(0.123456781111111) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 0.12345678 patientBuilder.$(':input[name=OBSERV]').val(0.123456786666666) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 0.12345678 patientBuilder.$(':input[name=OBSERV]').val(1.5) patientBuilder.serializeWithChildren() expect(expected_vals.get("OBSERV")[0]).toEqual 1.5 it "should display a warning that the patient is shared", -> patientBuilder = new Thorax.Views.PatientBuilder(model: @compositePatients.first(), measure: @components[0]) patientBuilder.render() expect(patientBuilder.$("div.alert-warning")[0].innerHTML.substr(0,31).trim()).toEqual "Note: This patient is shared" it 'should have the breadcrumbs with composite and component measure', -> breadcrumb = new Thorax.Views.Breadcrumb() breadcrumb.addPatient(@components[0], @compositePatients.first()) breadcrumb.render() expect(breadcrumb.$("a")[1].childNodes[1].textContent).toEqual " CMS890v0 " # parent composite measure expect(breadcrumb.$("a")[2].childNodes[1].textContent).toEqual " CMS231v0 " # the component measure describe 'Direct Reference Code Usage', -> # Originally BONNIE-939 beforeEach -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS903v0/CMS903v0.json', 'cqm_measure_data/CMS903v0/value_sets.json' bonnie.measures.add(@measure, { parse: true }) @patient = new Thorax.Models.Patient getJSONFixture('patients/CMS903v0/Visits 2 Excl_2 ED.json'), parse: true xit 'Field Value Dropdown should contain direct reference code element', -> # SKIP: Re-enable with Patient Builder Code Work patientBuilder = new Thorax.Views.PatientBuilder(model: @patients.first(), measure: @measure) dataCriteria = patientBuilder.model.get('source_data_criteria').models edVisitIndex = dataCriteria.findIndex((m) -> m.attributes.description is 'Encounter, Performed: Emergency Department Visit') emergencyDepartmentVisit = dataCriteria[edVisitIndex] editCriteriaView = new Thorax.Views.EditCriteriaView(model: emergencyDepartmentVisit, measure: @measure) editFieldValueView = editCriteriaView.editFieldValueView expect(editFieldValueView.render()).toContain('drc-') it 'Adding direct reference code element should calculate correctly', -> population = @measure.get('populations').first() results = population.calculate(@patient) library = "LikeCMS32" statementResults = results.get("statement_results") titleOfClauseThatUsesDrc = statementResults[library]['Measure Population Exclusions'].raw[0].dischargeDisposition.display expect(titleOfClauseThatUsesDrc).toBe "Patient deceased during stay (discharge status = dead) (finding)" describe 'Allergy', -> # Originally BONNIE-785 beforeAll -> jasmine.getJSONFixtures().clearCache() @measure = loadMeasureWithValueSets 'cqm_measure_data/CMS12v0/CMS12v0.json', 'cqm_measure_data/CMS12v0/value_sets.json' bonnie.measures.add @measure medAllergy = getJSONFixture("patients/CMS12v0/MedAllergyEndIP_DENEXCEPPass.json") @patients = new Thorax.Collections.Patients [medAllergy], parse: true @patient = @patients.at(0) # MedAllergyEndIP_DENEXCEPPass @patientBuilder = new Thorax.Views.PatientBuilder(model: @patient, measure: @measure, patients: @patients) sourceDataCriteria = @patientBuilder.model.get("source_data_criteria") @allergyIntolerance = sourceDataCriteria.findWhere({qdmCategory: "allergy"}) @patientBuilder.render() @patientBuilder.appendTo('body') afterEach -> @patientBuilder.remove() it 'is displayed on Patient Builder Page in Elements section', -> expect(@patientBuilder.$el.find("div#criteriaElements").html()).toContainText "allergy" it 'highlight is triggered by relevant cql clause', -> cqlLogicView = @patientBuilder.populationLogicView.getView().cqlLogicView sourceDataCriteria = cqlLogicView.latestResult.patient.get('source_data_criteria') patientDataCriteria = _.find(sourceDataCriteria.models, (sdc) -> sdc.get('qdmCategory') == 'allergy') dataCriteriaIds = [patientDataCriteria.get('_id').toString()] spyOn(patientDataCriteria, 'trigger') cqlLogicView.highlightPatientData(dataCriteriaIds) expect(patientDataCriteria.trigger).toHaveBeenCalled()
[ { "context": " return\n\n invoSkills.push new Skill {\n name: 'invoke',\n key: 'r',\n secondsCd: 0,\n canBeChalle", "end": 3651, "score": 0.9656829237937927, "start": 3645, "tag": "NAME", "value": "invoke" }, { "context": "traSkills)\n }\n\n invoker = new Hero {\n name: 'invoker',\n skills: invoSkills,\n extraSkills: extraS", "end": 3845, "score": 0.9547193050384521, "start": 3838, "tag": "NAME", "value": "invoker" } ]
assets/js/src/HeroManager.coffee
juancjara/dota-game
0
HeroManager = () -> this.heros = {} return HeroManager::invoker = () -> extraSkills = [] extraSkills.push new Skill { canBeChallenge: true, srcImg: 'cold_snap', name: 'cold snap', clickNeeded: true, dependencies: 'qqq', effect: 'stun', key: 'y' } extraSkills.push new Skill { canBeChallenge: true, srcImg: 'sun_strike', name: 'sun strike', clickNeeded: true, secondsCd: 2, dependencies: 'eee', hitTime: 1.7, endDurationDmg: 475, key: 't' } extraSkills.push new Skill { canBeChallenge: true, name: 'ghost walk', srcImg: 'ghost_walk', clickNeeded: false, dependencies: 'qqw', key:'v' } extraSkills.push new Skill { canBeChallenge: true, name: 'ice wall', srcImg: 'ice_wall', clickNeeded: false, dependencies: 'qqe', effect: 'slow', key:'g' } extraSkills.push new Skill { canBeChallenge: true, name: 'emp', srcImg: 'emp', clickNeeded: true, dependencies: 'www', hitTime: 2.9, endDurationDmg: 275, key:'c' } extraSkills.push new Skill { canBeChallenge: true, name: 'tornado', srcImg: 'tornado', clickNeeded: true, dependencies: 'wwq', effect: 'invulnerable', duration: 2.5, endDurationDmg: 385, key:'x' } extraSkills.push new Skill { canBeChallenge: true, name: 'alacrity', srcImg: 'alacrity', clickNeeded: true, dependencies: 'wwe', key:'z' } extraSkills.push new Skill { canBeChallenge: true, name: 'forge spirit', srcImg: 'forge_spirit', clickNeeded: false, dependencies: 'eeq', key:'f' } extraSkills.push new Skill { canBeChallenge: true, name: 'deafening blast', srcImg: 'deafening_blast', clickNeeded: true, dependencies: 'qwe', key:'b' } extraSkills.push new Skill { canBeChallenge: true, name: 'chaos meteor', srcImg: 'chaos_meteor', clickNeeded: true, dependencies: 'wee', hitTime: 1.3, key:'d' } invoSkills = [] invoSkills.push new Skill { name: 'quas', key: 'q', secondsCd: 0, canBeChallenge: false, srcImg: 'quas', clickNeeded: false, customFun: () -> val = { key: 'q', srcImg: 'quas' } dispatcher.execute('addInvokerState', val) return } invoSkills.push new Skill { name: 'wex', key: 'w', secondsCd: 0, canBeChallenge: false, srcImg: 'wex', clickNeeded: false, customFun: () -> val = { key: 'w', srcImg: 'wex' } dispatcher.execute('addInvokerState', val) return } invoSkills.push new Skill { name: 'exort', key: 'e', secondsCd: 0, canBeChallenge: false, srcImg: 'exort', clickNeeded: false, customFun: () -> val = { key: 'e', srcImg: 'exort' } dispatcher.execute('addInvokerState', val) return } useSkill = (index) -> () -> dispatcher.execute 'useExtraSkill', index return invoSkills.push new Skill { customFun: useSkill(3), key: 'd' } invoSkills.push new Skill { customFun: useSkill(4), key: 'f' } skillInvoke = (extraSkills) -> () -> lastSkill = dispatcher.execute 'getLastSkill' i = 0 while i < extraSkills.length dep = extraSkills[i].dependencies nameSkill = extraSkills[i].name if lastSkill isnt nameSkill and dispatcher.execute 'isSameInvokerState' ,dep dispatcher.execute "changeSkill", i break i++ return invoSkills.push new Skill { name: 'invoke', key: 'r', secondsCd: 0, canBeChallenge: false, srcImg: 'invoke', clickNeeded: false, customFun: skillInvoke(extraSkills) } invoker = new Hero { name: 'invoker', skills: invoSkills, extraSkills: extraSkills, srcImg: 'invoker' } return invoker HeroManager::create = () -> #invoker this.heros['invoker'] = this.invoker() return this
224788
HeroManager = () -> this.heros = {} return HeroManager::invoker = () -> extraSkills = [] extraSkills.push new Skill { canBeChallenge: true, srcImg: 'cold_snap', name: 'cold snap', clickNeeded: true, dependencies: 'qqq', effect: 'stun', key: 'y' } extraSkills.push new Skill { canBeChallenge: true, srcImg: 'sun_strike', name: 'sun strike', clickNeeded: true, secondsCd: 2, dependencies: 'eee', hitTime: 1.7, endDurationDmg: 475, key: 't' } extraSkills.push new Skill { canBeChallenge: true, name: 'ghost walk', srcImg: 'ghost_walk', clickNeeded: false, dependencies: 'qqw', key:'v' } extraSkills.push new Skill { canBeChallenge: true, name: 'ice wall', srcImg: 'ice_wall', clickNeeded: false, dependencies: 'qqe', effect: 'slow', key:'g' } extraSkills.push new Skill { canBeChallenge: true, name: 'emp', srcImg: 'emp', clickNeeded: true, dependencies: 'www', hitTime: 2.9, endDurationDmg: 275, key:'c' } extraSkills.push new Skill { canBeChallenge: true, name: 'tornado', srcImg: 'tornado', clickNeeded: true, dependencies: 'wwq', effect: 'invulnerable', duration: 2.5, endDurationDmg: 385, key:'x' } extraSkills.push new Skill { canBeChallenge: true, name: 'alacrity', srcImg: 'alacrity', clickNeeded: true, dependencies: 'wwe', key:'z' } extraSkills.push new Skill { canBeChallenge: true, name: 'forge spirit', srcImg: 'forge_spirit', clickNeeded: false, dependencies: 'eeq', key:'f' } extraSkills.push new Skill { canBeChallenge: true, name: 'deafening blast', srcImg: 'deafening_blast', clickNeeded: true, dependencies: 'qwe', key:'b' } extraSkills.push new Skill { canBeChallenge: true, name: 'chaos meteor', srcImg: 'chaos_meteor', clickNeeded: true, dependencies: 'wee', hitTime: 1.3, key:'d' } invoSkills = [] invoSkills.push new Skill { name: 'quas', key: 'q', secondsCd: 0, canBeChallenge: false, srcImg: 'quas', clickNeeded: false, customFun: () -> val = { key: 'q', srcImg: 'quas' } dispatcher.execute('addInvokerState', val) return } invoSkills.push new Skill { name: 'wex', key: 'w', secondsCd: 0, canBeChallenge: false, srcImg: 'wex', clickNeeded: false, customFun: () -> val = { key: 'w', srcImg: 'wex' } dispatcher.execute('addInvokerState', val) return } invoSkills.push new Skill { name: 'exort', key: 'e', secondsCd: 0, canBeChallenge: false, srcImg: 'exort', clickNeeded: false, customFun: () -> val = { key: 'e', srcImg: 'exort' } dispatcher.execute('addInvokerState', val) return } useSkill = (index) -> () -> dispatcher.execute 'useExtraSkill', index return invoSkills.push new Skill { customFun: useSkill(3), key: 'd' } invoSkills.push new Skill { customFun: useSkill(4), key: 'f' } skillInvoke = (extraSkills) -> () -> lastSkill = dispatcher.execute 'getLastSkill' i = 0 while i < extraSkills.length dep = extraSkills[i].dependencies nameSkill = extraSkills[i].name if lastSkill isnt nameSkill and dispatcher.execute 'isSameInvokerState' ,dep dispatcher.execute "changeSkill", i break i++ return invoSkills.push new Skill { name: '<NAME>', key: 'r', secondsCd: 0, canBeChallenge: false, srcImg: 'invoke', clickNeeded: false, customFun: skillInvoke(extraSkills) } invoker = new Hero { name: '<NAME>', skills: invoSkills, extraSkills: extraSkills, srcImg: 'invoker' } return invoker HeroManager::create = () -> #invoker this.heros['invoker'] = this.invoker() return this
true
HeroManager = () -> this.heros = {} return HeroManager::invoker = () -> extraSkills = [] extraSkills.push new Skill { canBeChallenge: true, srcImg: 'cold_snap', name: 'cold snap', clickNeeded: true, dependencies: 'qqq', effect: 'stun', key: 'y' } extraSkills.push new Skill { canBeChallenge: true, srcImg: 'sun_strike', name: 'sun strike', clickNeeded: true, secondsCd: 2, dependencies: 'eee', hitTime: 1.7, endDurationDmg: 475, key: 't' } extraSkills.push new Skill { canBeChallenge: true, name: 'ghost walk', srcImg: 'ghost_walk', clickNeeded: false, dependencies: 'qqw', key:'v' } extraSkills.push new Skill { canBeChallenge: true, name: 'ice wall', srcImg: 'ice_wall', clickNeeded: false, dependencies: 'qqe', effect: 'slow', key:'g' } extraSkills.push new Skill { canBeChallenge: true, name: 'emp', srcImg: 'emp', clickNeeded: true, dependencies: 'www', hitTime: 2.9, endDurationDmg: 275, key:'c' } extraSkills.push new Skill { canBeChallenge: true, name: 'tornado', srcImg: 'tornado', clickNeeded: true, dependencies: 'wwq', effect: 'invulnerable', duration: 2.5, endDurationDmg: 385, key:'x' } extraSkills.push new Skill { canBeChallenge: true, name: 'alacrity', srcImg: 'alacrity', clickNeeded: true, dependencies: 'wwe', key:'z' } extraSkills.push new Skill { canBeChallenge: true, name: 'forge spirit', srcImg: 'forge_spirit', clickNeeded: false, dependencies: 'eeq', key:'f' } extraSkills.push new Skill { canBeChallenge: true, name: 'deafening blast', srcImg: 'deafening_blast', clickNeeded: true, dependencies: 'qwe', key:'b' } extraSkills.push new Skill { canBeChallenge: true, name: 'chaos meteor', srcImg: 'chaos_meteor', clickNeeded: true, dependencies: 'wee', hitTime: 1.3, key:'d' } invoSkills = [] invoSkills.push new Skill { name: 'quas', key: 'q', secondsCd: 0, canBeChallenge: false, srcImg: 'quas', clickNeeded: false, customFun: () -> val = { key: 'q', srcImg: 'quas' } dispatcher.execute('addInvokerState', val) return } invoSkills.push new Skill { name: 'wex', key: 'w', secondsCd: 0, canBeChallenge: false, srcImg: 'wex', clickNeeded: false, customFun: () -> val = { key: 'w', srcImg: 'wex' } dispatcher.execute('addInvokerState', val) return } invoSkills.push new Skill { name: 'exort', key: 'e', secondsCd: 0, canBeChallenge: false, srcImg: 'exort', clickNeeded: false, customFun: () -> val = { key: 'e', srcImg: 'exort' } dispatcher.execute('addInvokerState', val) return } useSkill = (index) -> () -> dispatcher.execute 'useExtraSkill', index return invoSkills.push new Skill { customFun: useSkill(3), key: 'd' } invoSkills.push new Skill { customFun: useSkill(4), key: 'f' } skillInvoke = (extraSkills) -> () -> lastSkill = dispatcher.execute 'getLastSkill' i = 0 while i < extraSkills.length dep = extraSkills[i].dependencies nameSkill = extraSkills[i].name if lastSkill isnt nameSkill and dispatcher.execute 'isSameInvokerState' ,dep dispatcher.execute "changeSkill", i break i++ return invoSkills.push new Skill { name: 'PI:NAME:<NAME>END_PI', key: 'r', secondsCd: 0, canBeChallenge: false, srcImg: 'invoke', clickNeeded: false, customFun: skillInvoke(extraSkills) } invoker = new Hero { name: 'PI:NAME:<NAME>END_PI', skills: invoSkills, extraSkills: extraSkills, srcImg: 'invoker' } return invoker HeroManager::create = () -> #invoker this.heros['invoker'] = this.invoker() return this
[ { "context": "onversationLink conversation={conversation} user={@props.user} key={conversation.id} />\n }\n ", "end": 3878, "score": 0.9876965880393982, "start": 3867, "tag": "USERNAME", "value": "@props.user" }, { "context": "conversation} user={@props.user} key={conversation.id} />\n }\n <Paginator\n ", "end": 3900, "score": 0.5373973846435547, "start": 3898, "tag": "KEY", "value": "id" }, { "context": ">Send a message</h1>\n <InboxForm user={@props.user} />\n </div>\n </div>\n }\n ", "end": 4226, "score": 0.9923514127731323, "start": 4215, "tag": "USERNAME", "value": "@props.user" } ]
app/talk/inbox.cjsx
ilacerna/Panoptes-Front-End
0
React = require 'react' PropTypes = require 'prop-types' createReactClass = require 'create-react-class' talkClient = require 'panoptes-client/lib/talk-client' apiClient = require 'panoptes-client/lib/api-client' {Link} = require 'react-router' { Helmet } = require 'react-helmet' counterpart = require 'counterpart' Paginator = require './lib/paginator' Loading = require('../components/loading-indicator').default InboxForm = require './inbox-form' talkConfig = require './config' {timeAgo} = require './lib/time' SignInPrompt = require '../partials/sign-in-prompt' alert = require('../lib/alert').default PAGE_SIZE = talkConfig.inboxPageSize promptToSignIn = -> alert (resolve) -> <SignInPrompt onChoose={resolve} /> counterpart.registerTranslations 'en', messagesPage: title: 'Inbox' ConversationLink = createReactClass displayName: 'ConversationLink' propTypes: user: PropTypes.object conversation: PropTypes.object getInitialState: -> users: [] messages: [] componentWillMount: -> apiClient .type 'users' .get @props.conversation.participant_ids.filter (userId) => userId isnt parseInt(@props.user.id) .then (users) => @setState {users} @props.conversation .get 'messages', {page_size: 1, sort: '-created_at'} .then (messages) => @setState {messages} render: -> unread = @props.conversation.is_unread <div className="conversation-link #{if unread then 'unread' else ''}"> <div> {@state.users.map (user, i) => <div key={user.id}> <strong><Link key={user.id} to="/users/#{user.login}">{user.display_name}</Link></strong> <div>{timeAgo(@state.messages[0]?.updated_at)}{', ' if i isnt (@state.users.length-1)}</div> </div>} </div> <Link to="/inbox/#{@props.conversation.id}"> {if unread <i className="fa fa-comments-o"/>} {@props.conversation.title} </Link> </div> module.exports = createReactClass displayName: 'TalkInbox' contextTypes: router: PropTypes.object.isRequired getDefaultProps: -> location: query: page: 1 getInitialState: -> conversations: [] componentWillMount: -> @setConversations @props.user, @props.location.query.page componentWillReceiveProps: (nextProps) -> unless nextProps.user is @props.user @setConversations(nextProps.user, @props.location.query.page) unless nextProps.location.query.page is @props.location.query.page @setConversations(nextProps.user, nextProps.location.query.page) setConversations: (user, page) -> return unless user? conversationsQuery = user_id: user.id page_size: PAGE_SIZE page: page sort: '-updated_at' include: 'users' talkClient .type 'conversations' .get conversationsQuery .then (conversations) => @setState {conversations} onPageChange: (page) -> @goToPage(page) goToPage: (n) -> @context.router.push "/inbox?page=#{n}" @setConversations(@props.user, n) message: (data, i) -> <p key={data.id} class>{data.body}</p> render: -> <div className="talk inbox content-container"> <Helmet title={counterpart 'messagesPage.title'} /> {unless @props.user? <p>Please <button className="link-style" type="button" onClick={promptToSignIn}>sign in</button> to view your inbox</p> else <div> <h1>Inbox</h1> {if @state.conversations.length is 0 <p>You have not started any private conversations yet. Send users private messages by visiting their profile page.</p> else conversationsMeta = @state.conversations[0].getMeta() <div> {@state.conversations.map (conversation) => <ConversationLink conversation={conversation} user={@props.user} key={conversation.id} /> } <Paginator page={+conversationsMeta.page} pageCount={+conversationsMeta.page_count} onPageChange={@onPageChange} /> </div>} <div> <h1>Send a message</h1> <InboxForm user={@props.user} /> </div> </div> } </div>
100361
React = require 'react' PropTypes = require 'prop-types' createReactClass = require 'create-react-class' talkClient = require 'panoptes-client/lib/talk-client' apiClient = require 'panoptes-client/lib/api-client' {Link} = require 'react-router' { Helmet } = require 'react-helmet' counterpart = require 'counterpart' Paginator = require './lib/paginator' Loading = require('../components/loading-indicator').default InboxForm = require './inbox-form' talkConfig = require './config' {timeAgo} = require './lib/time' SignInPrompt = require '../partials/sign-in-prompt' alert = require('../lib/alert').default PAGE_SIZE = talkConfig.inboxPageSize promptToSignIn = -> alert (resolve) -> <SignInPrompt onChoose={resolve} /> counterpart.registerTranslations 'en', messagesPage: title: 'Inbox' ConversationLink = createReactClass displayName: 'ConversationLink' propTypes: user: PropTypes.object conversation: PropTypes.object getInitialState: -> users: [] messages: [] componentWillMount: -> apiClient .type 'users' .get @props.conversation.participant_ids.filter (userId) => userId isnt parseInt(@props.user.id) .then (users) => @setState {users} @props.conversation .get 'messages', {page_size: 1, sort: '-created_at'} .then (messages) => @setState {messages} render: -> unread = @props.conversation.is_unread <div className="conversation-link #{if unread then 'unread' else ''}"> <div> {@state.users.map (user, i) => <div key={user.id}> <strong><Link key={user.id} to="/users/#{user.login}">{user.display_name}</Link></strong> <div>{timeAgo(@state.messages[0]?.updated_at)}{', ' if i isnt (@state.users.length-1)}</div> </div>} </div> <Link to="/inbox/#{@props.conversation.id}"> {if unread <i className="fa fa-comments-o"/>} {@props.conversation.title} </Link> </div> module.exports = createReactClass displayName: 'TalkInbox' contextTypes: router: PropTypes.object.isRequired getDefaultProps: -> location: query: page: 1 getInitialState: -> conversations: [] componentWillMount: -> @setConversations @props.user, @props.location.query.page componentWillReceiveProps: (nextProps) -> unless nextProps.user is @props.user @setConversations(nextProps.user, @props.location.query.page) unless nextProps.location.query.page is @props.location.query.page @setConversations(nextProps.user, nextProps.location.query.page) setConversations: (user, page) -> return unless user? conversationsQuery = user_id: user.id page_size: PAGE_SIZE page: page sort: '-updated_at' include: 'users' talkClient .type 'conversations' .get conversationsQuery .then (conversations) => @setState {conversations} onPageChange: (page) -> @goToPage(page) goToPage: (n) -> @context.router.push "/inbox?page=#{n}" @setConversations(@props.user, n) message: (data, i) -> <p key={data.id} class>{data.body}</p> render: -> <div className="talk inbox content-container"> <Helmet title={counterpart 'messagesPage.title'} /> {unless @props.user? <p>Please <button className="link-style" type="button" onClick={promptToSignIn}>sign in</button> to view your inbox</p> else <div> <h1>Inbox</h1> {if @state.conversations.length is 0 <p>You have not started any private conversations yet. Send users private messages by visiting their profile page.</p> else conversationsMeta = @state.conversations[0].getMeta() <div> {@state.conversations.map (conversation) => <ConversationLink conversation={conversation} user={@props.user} key={conversation.<KEY>} /> } <Paginator page={+conversationsMeta.page} pageCount={+conversationsMeta.page_count} onPageChange={@onPageChange} /> </div>} <div> <h1>Send a message</h1> <InboxForm user={@props.user} /> </div> </div> } </div>
true
React = require 'react' PropTypes = require 'prop-types' createReactClass = require 'create-react-class' talkClient = require 'panoptes-client/lib/talk-client' apiClient = require 'panoptes-client/lib/api-client' {Link} = require 'react-router' { Helmet } = require 'react-helmet' counterpart = require 'counterpart' Paginator = require './lib/paginator' Loading = require('../components/loading-indicator').default InboxForm = require './inbox-form' talkConfig = require './config' {timeAgo} = require './lib/time' SignInPrompt = require '../partials/sign-in-prompt' alert = require('../lib/alert').default PAGE_SIZE = talkConfig.inboxPageSize promptToSignIn = -> alert (resolve) -> <SignInPrompt onChoose={resolve} /> counterpart.registerTranslations 'en', messagesPage: title: 'Inbox' ConversationLink = createReactClass displayName: 'ConversationLink' propTypes: user: PropTypes.object conversation: PropTypes.object getInitialState: -> users: [] messages: [] componentWillMount: -> apiClient .type 'users' .get @props.conversation.participant_ids.filter (userId) => userId isnt parseInt(@props.user.id) .then (users) => @setState {users} @props.conversation .get 'messages', {page_size: 1, sort: '-created_at'} .then (messages) => @setState {messages} render: -> unread = @props.conversation.is_unread <div className="conversation-link #{if unread then 'unread' else ''}"> <div> {@state.users.map (user, i) => <div key={user.id}> <strong><Link key={user.id} to="/users/#{user.login}">{user.display_name}</Link></strong> <div>{timeAgo(@state.messages[0]?.updated_at)}{', ' if i isnt (@state.users.length-1)}</div> </div>} </div> <Link to="/inbox/#{@props.conversation.id}"> {if unread <i className="fa fa-comments-o"/>} {@props.conversation.title} </Link> </div> module.exports = createReactClass displayName: 'TalkInbox' contextTypes: router: PropTypes.object.isRequired getDefaultProps: -> location: query: page: 1 getInitialState: -> conversations: [] componentWillMount: -> @setConversations @props.user, @props.location.query.page componentWillReceiveProps: (nextProps) -> unless nextProps.user is @props.user @setConversations(nextProps.user, @props.location.query.page) unless nextProps.location.query.page is @props.location.query.page @setConversations(nextProps.user, nextProps.location.query.page) setConversations: (user, page) -> return unless user? conversationsQuery = user_id: user.id page_size: PAGE_SIZE page: page sort: '-updated_at' include: 'users' talkClient .type 'conversations' .get conversationsQuery .then (conversations) => @setState {conversations} onPageChange: (page) -> @goToPage(page) goToPage: (n) -> @context.router.push "/inbox?page=#{n}" @setConversations(@props.user, n) message: (data, i) -> <p key={data.id} class>{data.body}</p> render: -> <div className="talk inbox content-container"> <Helmet title={counterpart 'messagesPage.title'} /> {unless @props.user? <p>Please <button className="link-style" type="button" onClick={promptToSignIn}>sign in</button> to view your inbox</p> else <div> <h1>Inbox</h1> {if @state.conversations.length is 0 <p>You have not started any private conversations yet. Send users private messages by visiting their profile page.</p> else conversationsMeta = @state.conversations[0].getMeta() <div> {@state.conversations.map (conversation) => <ConversationLink conversation={conversation} user={@props.user} key={conversation.PI:KEY:<KEY>END_PI} /> } <Paginator page={+conversationsMeta.page} pageCount={+conversationsMeta.page_count} onPageChange={@onPageChange} /> </div>} <div> <h1>Send a message</h1> <InboxForm user={@props.user} /> </div> </div> } </div>
[ { "context": "###\n\tCopyright 2013 David Pearson.\n\tBSD License.\n###\n\n# Private: Switches two rows ", "end": 33, "score": 0.9998523592948914, "start": 20, "tag": "NAME", "value": "David Pearson" } ]
src/gelim.coffee
dpearson/linalgebra
1
### Copyright 2013 David Pearson. BSD License. ### # Private: Switches two rows in a matrix # # a - The matrix in which to switch rows # x - The first row's index (zero-offset) # y - The second row's index (zero-offset) # # Example: # swap [[1], [2], [3]], 0, 2 # => [[3], [2], [1]] # # Returns a modified version of a with the rows swapped swap=(a, x, y) -> tmp=a[y] a[y]=a[x] a[x]=tmp a # Performs Gaussian elimination on a matrix to place it # into Row Echelon Form # # a - The matrix to row reduce # # Example: # gelim [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]] # => [[1, 0.3333333333333333, -0.6666666666666666, # 3.6666666666666665], [0, 1, 0.4000000000000001, # 2.6], [0, 0, 1, -0.9999999999999999]] # # Returns a modified version of a in Row Echelon Form gelim=(a) -> x=0 while x<a.length max=x i=x while i<a.length if Math.abs(a[i][x])>Math.abs(a[max][x]) max=i i++ if a[max][x]==0 console.log "Not happening..." swap a, x, max i=x+1 while i<a.length j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ x++ aug=a[0].length-1 row=0 while row<a.length mult=1/a[row][row] col=row while col<=aug a[row][col]*=mult col++ row++ a # Performs Gauss-Jordan elimination on a matrix to place it # into Reduced Row Echelon Form # # a - The matrix to row reduce # # Example: # gjelim [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]] # => [[1, 0, 0, 2], [0, 1, 0, 3.0000000000000004], # [0, 0, 1, -0.9999999999999999]] # # Returns a modified version of a in Reduced Row Echelon Form gjelim=(a) -> x=0 while x<a.length max=x i=x while i<a.length if Math.abs(a[i][x])>Math.abs(a[max][x]) max=i i++ if a[max][x]==0 console.log "Not happening..." swap a, x, max i=0 while i<x j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ i=x+1 while i<a.length j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ x++ aug=a[0].length-1 row=0 while row<a.length mult=1/a[row][row] a[row][row]*=mult a[row][aug]*=mult row++ a exports.gelim=gelim exports.gjelim=gjelim
180955
### Copyright 2013 <NAME>. BSD License. ### # Private: Switches two rows in a matrix # # a - The matrix in which to switch rows # x - The first row's index (zero-offset) # y - The second row's index (zero-offset) # # Example: # swap [[1], [2], [3]], 0, 2 # => [[3], [2], [1]] # # Returns a modified version of a with the rows swapped swap=(a, x, y) -> tmp=a[y] a[y]=a[x] a[x]=tmp a # Performs Gaussian elimination on a matrix to place it # into Row Echelon Form # # a - The matrix to row reduce # # Example: # gelim [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]] # => [[1, 0.3333333333333333, -0.6666666666666666, # 3.6666666666666665], [0, 1, 0.4000000000000001, # 2.6], [0, 0, 1, -0.9999999999999999]] # # Returns a modified version of a in Row Echelon Form gelim=(a) -> x=0 while x<a.length max=x i=x while i<a.length if Math.abs(a[i][x])>Math.abs(a[max][x]) max=i i++ if a[max][x]==0 console.log "Not happening..." swap a, x, max i=x+1 while i<a.length j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ x++ aug=a[0].length-1 row=0 while row<a.length mult=1/a[row][row] col=row while col<=aug a[row][col]*=mult col++ row++ a # Performs Gauss-Jordan elimination on a matrix to place it # into Reduced Row Echelon Form # # a - The matrix to row reduce # # Example: # gjelim [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]] # => [[1, 0, 0, 2], [0, 1, 0, 3.0000000000000004], # [0, 0, 1, -0.9999999999999999]] # # Returns a modified version of a in Reduced Row Echelon Form gjelim=(a) -> x=0 while x<a.length max=x i=x while i<a.length if Math.abs(a[i][x])>Math.abs(a[max][x]) max=i i++ if a[max][x]==0 console.log "Not happening..." swap a, x, max i=0 while i<x j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ i=x+1 while i<a.length j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ x++ aug=a[0].length-1 row=0 while row<a.length mult=1/a[row][row] a[row][row]*=mult a[row][aug]*=mult row++ a exports.gelim=gelim exports.gjelim=gjelim
true
### Copyright 2013 PI:NAME:<NAME>END_PI. BSD License. ### # Private: Switches two rows in a matrix # # a - The matrix in which to switch rows # x - The first row's index (zero-offset) # y - The second row's index (zero-offset) # # Example: # swap [[1], [2], [3]], 0, 2 # => [[3], [2], [1]] # # Returns a modified version of a with the rows swapped swap=(a, x, y) -> tmp=a[y] a[y]=a[x] a[x]=tmp a # Performs Gaussian elimination on a matrix to place it # into Row Echelon Form # # a - The matrix to row reduce # # Example: # gelim [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]] # => [[1, 0.3333333333333333, -0.6666666666666666, # 3.6666666666666665], [0, 1, 0.4000000000000001, # 2.6], [0, 0, 1, -0.9999999999999999]] # # Returns a modified version of a in Row Echelon Form gelim=(a) -> x=0 while x<a.length max=x i=x while i<a.length if Math.abs(a[i][x])>Math.abs(a[max][x]) max=i i++ if a[max][x]==0 console.log "Not happening..." swap a, x, max i=x+1 while i<a.length j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ x++ aug=a[0].length-1 row=0 while row<a.length mult=1/a[row][row] col=row while col<=aug a[row][col]*=mult col++ row++ a # Performs Gauss-Jordan elimination on a matrix to place it # into Reduced Row Echelon Form # # a - The matrix to row reduce # # Example: # gjelim [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]] # => [[1, 0, 0, 2], [0, 1, 0, 3.0000000000000004], # [0, 0, 1, -0.9999999999999999]] # # Returns a modified version of a in Reduced Row Echelon Form gjelim=(a) -> x=0 while x<a.length max=x i=x while i<a.length if Math.abs(a[i][x])>Math.abs(a[max][x]) max=i i++ if a[max][x]==0 console.log "Not happening..." swap a, x, max i=0 while i<x j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ i=x+1 while i<a.length j=x+1 k=a[i][x]/a[x][x] while j<a[max].length a[i][j]-=a[x][j]*k j++ a[i][x]=0 i++ x++ aug=a[0].length-1 row=0 while row<a.length mult=1/a[row][row] a[row][row]*=mult a[row][aug]*=mult row++ a exports.gelim=gelim exports.gjelim=gjelim
[ { "context": " blog: \"Blog\"\n forum: \"Fórum\"\n account: \"Conta\"\n my_account: \"A Minha Conta\"\n profile: \"Pe", "end": 14821, "score": 0.9993863105773926, "start": 14816, "tag": "NAME", "value": "Conta" }, { "context": "um: \"Fórum\"\n account: \"Conta\"\n my_account: \"A Minha Conta\"\n profile: \"Perfil\"\n home: \"Início\"\n con", "end": 14853, "score": 0.9990798234939575, "start": 14840, "tag": "NAME", "value": "A Minha Conta" }, { "context": "ct\"\n contact: \"Contactar\"\n twitter_follow: \"Seguir\"\n my_classrooms: \"As Minhas Turmas\"\n my_cou", "end": 15073, "score": 0.9989967942237854, "start": 15067, "tag": "USERNAME", "value": "Seguir" }, { "context": "os\"\n# my_teachers: \"My Teachers\"\n careers: \"Carreiras\"\n facebook: \"Facebook\"\n twitter: \"Twitter\"\n", "end": 15201, "score": 0.999660074710846, "start": 15192, "tag": "NAME", "value": "Carreiras" }, { "context": "nta de professor gratuita\"\n play_as: \"Jogar Como\" # Ladder page\n# get_course_for_class: \"Assign", "end": 17856, "score": 0.9769256114959717, "start": 17855, "tag": "NAME", "value": "o" }, { "context": "adquirires este herói com gemas!\"\n anonymous: \"Jogador Anónimo\"\n level_difficulty: \"Dificuldade: \"\n awaiti", "end": 19383, "score": 0.9998528957366943, "start": 19368, "tag": "NAME", "value": "Jogador Anónimo" }, { "context": " sign_up: \"Criar Conta\"\n email_or_username: \"E-mail ou nome de utilizador\"\n log_in: \"Iniciar Sessão\"\n logging_in: \"A ", "end": 21819, "score": 0.7578554749488831, "start": 21793, "tag": "NAME", "value": "mail ou nome de utilizador" }, { "context": "Sessão\"\n log_out: \"Sair\"\n forgot_password: \"Esqueceste a tua palavra-passe?\"\n finishing: \"A Terminar\"\n sign_in_with_face", "end": 21957, "score": 0.9979825019836426, "start": 21927, "tag": "PASSWORD", "value": "Esqueceste a tua palavra-passe" }, { "context": "ount_title: \"Recuperar Conta\"\n send_password: \"Enviar Palavra-passe de Recuperação\"\n recovery_sent: \"E-mail de recuperação enviad", "end": 28006, "score": 0.9958989024162292, "start": 27971, "tag": "PASSWORD", "value": "Enviar Palavra-passe de Recuperação" }, { "context": "ect: \"Assunto\"\n email: \"E-mail\"\n password: \"Palavra-passe\"\n confirm_password: \"Confirmar Palavra-passe\"\n", "end": 30484, "score": 0.9989879131317139, "start": 30471, "tag": "PASSWORD", "value": "Palavra-passe" }, { "context": " password: \"Palavra-passe\"\n confirm_password: \"Confirmar Palavra-passe\"\n message: \"Mensagem\"\n code: \"Código\"\n l", "end": 30532, "score": 0.9988616108894348, "start": 30509, "tag": "PASSWORD", "value": "Confirmar Palavra-passe" }, { "context": " medium: \"Médio\"\n hard: \"Difícil\"\n player: \"Jogador\"\n player_level: \"Nível\" # Like player level 5,", "end": 30835, "score": 0.9544069170951843, "start": 30828, "tag": "NAME", "value": "Jogador" }, { "context": "queiro\"\n wizard: \"Feiticeiro\"\n first_name: \"Nome\"\n last_name: \"Apelido\"\n last_initial: \"Últi", "end": 31017, "score": 0.9993496537208557, "start": 31013, "tag": "NAME", "value": "Nome" }, { "context": "eiticeiro\"\n first_name: \"Nome\"\n last_name: \"Apelido\"\n last_initial: \"Última Inicial\"\n username:", "end": 31042, "score": 0.9981565475463867, "start": 31035, "tag": "NAME", "value": "Apelido" }, { "context": " last_initial: \"Última Inicial\"\n username: \"Nome de utilizador\"\n contact_us: \"Contacta-nos\"\n close_window:", "end": 31112, "score": 0.9988457560539246, "start": 31094, "tag": "USERNAME", "value": "Nome de utilizador" }, { "context": " entre a teoria e a prática. Mas na prática, há. - Yogi Berra\"\n tip_error_free: \"Há duas formas de escrever ", "end": 37635, "score": 0.9997079968452454, "start": 37625, "tag": "NAME", "value": "Yogi Berra" }, { "context": "programas sem erros; apenas a terceira funciona. - Alan Perlis\"\n tip_debugging_program: \"Se depurar é o proce", "end": 37747, "score": 0.9998435974121094, "start": 37736, "tag": "NAME", "value": "Alan Perlis" }, { "context": " programar deve ser o processo de os introduzir. - Edsger W. Dijkstra\"\n tip_forums: \"Vai aos fóruns e diz-nos o que ", "end": 37893, "score": 0.9995819330215454, "start": 37875, "tag": "NAME", "value": "Edsger W. Dijkstra" }, { "context": "ssible: \"Parece sempre impossível até ser feito. - Nelson Mandela\"\n tip_talk_is_cheap: \"Falar é fácil. Mostra-me", "end": 39032, "score": 0.9998860359191895, "start": 39018, "tag": "NAME", "value": "Nelson Mandela" }, { "context": "lk_is_cheap: \"Falar é fácil. Mostra-me o código. - Linus Torvalds\"\n tip_first_language: \"A coisa mais desastrosa", "end": 39109, "score": 0.9998644590377808, "start": 39095, "tag": "NAME", "value": "Linus Torvalds" }, { "context": "ender é a tua primeira linguagem de programação. - Alan Kay\"\n tip_hardware_problem: \"P: Quantos programado", "end": 39232, "score": 0.9998453855514526, "start": 39224, "tag": "NAME", "value": "Alan Kay" }, { "context": "roblema de 'hardware'.\"\n tip_hofstadters_law: \"Lei de Hofstadter: Tudo demora sempre mais do que pensas, mesmo qua", "end": 39411, "score": 0.8944858312606812, "start": 39394, "tag": "NAME", "value": "Lei de Hofstadter" }, { "context": "e mais do que pensas, mesmo quando tens em conta a Lei de Hofstadter.\"\n tip_premature_optimization: \"Uma otimização", "end": 39498, "score": 0.8647760152816772, "start": 39481, "tag": "NAME", "value": "Lei de Hofstadter" }, { "context": "Uma otimização permatura é a raíz de todo o mal. - Donald Knuth\"\n tip_brute_force: \"Quando em dúvida, usa a fo", "end": 39597, "score": 0.9997357130050659, "start": 39585, "tag": "NAME", "value": "Donald Knuth" }, { "context": "ute_force: \"Quando em dúvida, usa a força bruta. - Ken Thompson\"\n tip_extrapolation: \"Há apenas dois tipos de ", "end": 39672, "score": 0.9998611211776733, "start": 39660, "tag": "NAME", "value": "Ken Thompson" }, { "context": " o direito de controlares o teu próprio destino. - Linus Torvalds\"\n tip_no_code: \"Nenhum código é mais rápido qu", "end": 40011, "score": 0.9998151659965515, "start": 39997, "tag": "NAME", "value": "Linus Torvalds" }, { "context": "go nunca mente, mas os comentários às vezes sim. — Ron Jeffries\"\n tip_reusable_software: \"Antes de um software", "end": 40181, "score": 0.9998737573623657, "start": 40169, "tag": "NAME", "value": "Ron Jeffries" }, { "context": "o progresso da construção de um avião pelo peso. — Bill Gates\"\n tip_source_code: \"Quero mudar o mundo, mas n", "end": 40579, "score": 0.9998795390129089, "start": 40569, "tag": "NAME", "value": "Bill Gates" }, { "context": "ript_java: \"Java é para JavaScript o mesmo que Carro (Car) para Tapete (Carpet). - Chris Heilmann\"\n ", "end": 40738, "score": 0.9333216547966003, "start": 40736, "tag": "NAME", "value": "ro" }, { "context": "pt o mesmo que Carro (Car) para Tapete (Carpet). - Chris Heilmann\"\n tip_move_forward: \"Faças o que fizeres, segu", "end": 40783, "score": 0.9998603463172913, "start": 40769, "tag": "NAME", "value": "Chris Heilmann" }, { "context": "_forward: \"Faças o que fizeres, segue em frente. - Martin Luther King Jr\"\n tip_google: \"Tens um problema que não con", "end": 40866, "score": 0.9997867345809937, "start": 40848, "tag": "NAME", "value": "Martin Luther King" }, { "context": " O que elas odeiam mesmo são maus programadores. - Larry Niven\"\n tip_open_source_contribute: \"Podes ajudar a ", "end": 41150, "score": 0.9998816251754761, "start": 41139, "tag": "NAME", "value": "Larry Niven" }, { "context": "ip_recurse: \"Iterar é humano, recursar é divino. - L. Peter Deutsch\"\n tip_free_your_mind: \"Tens de libertar tudo, ", "end": 41296, "score": 0.9998598098754883, "start": 41280, "tag": "NAME", "value": "L. Peter Deutsch" }, { "context": "é o mais forte dos adversários tem uma fraqueza. - Itachi Uchiha\"\n tip_paper_and_pen: \"Antes de começares a pro", "end": 41503, "score": 0.999565064907074, "start": 41490, "tag": "NAME", "value": "Itachi Uchiha" }, { "context": "o, resolve o problema. Depois, escreve o código. - John Johnson\"\n tip_compiler_ignores_comments: \"Às vezes ach", "end": 41717, "score": 0.9998056292533875, "start": 41705, "tag": "NAME", "value": "John Johnson" }, { "context": "ere you come from. Your only limit is your soul. - Gusteau, Ratatouille\"\n# tip_nemo: \"When life gets you ", "end": 42357, "score": 0.7983076572418213, "start": 42350, "tag": "NAME", "value": "Gusteau" }, { "context": "e from. Your only limit is your soul. - Gusteau, Ratatouille\"\n# tip_nemo: \"When life gets you down, wan", "end": 42366, "score": 0.6169123649597168, "start": 42360, "tag": "NAME", "value": "atatou" }, { "context": "otta do? Just keep swimming, just keep swimming. - Dory, Finding Nemo\"\n# tip_internet_weather: \"Just move to the int", "end": 42508, "score": 0.9015687704086304, "start": 42490, "tag": "NAME", "value": "Dory, Finding Nemo" }, { "context": "live inside where the weather is always awesome. - John Green\"\n# tip_nerds: \"Nerds are allowed to love stuff", "end": 42653, "score": 0.9997345209121704, "start": 42643, "tag": "NAME", "value": "John Green" }, { "context": "own-in-the-chair-can't-control-yourself love it. - John Green\"\n# tip_self_taught: \"I taught myself 90% of wh", "end": 42784, "score": 0.9997862577438354, "start": 42774, "tag": "NAME", "value": "John Green" }, { "context": "elf 90% of what I've learned. And that's normal! - Hank Green\"\n# tip_luna_lovegood: \"Don't worry, you're jus", "end": 42882, "score": 0.9998382925987244, "start": 42872, "tag": "NAME", "value": "Hank Green" }, { "context": "good: \"Don't worry, you're just as sane as I am. - Luna Lovegood\"\n# tip_good_idea: \"The best way to have a good", "end": 42966, "score": 0.9995414018630981, "start": 42953, "tag": "NAME", "value": "Luna Lovegood" }, { "context": "y to have a good idea is to have a lot of ideas. - Linus Pauling\"\n# tip_programming_not_about_computers: \"Compu", "end": 43064, "score": 0.9997431039810181, "start": 43051, "tag": "NAME", "value": "Linus Pauling" }, { "context": "# tip_mulan: \"Believe you can, then you will. - Mulan\"\n project_complete: \"Projeto Completado!\"\n# ", "end": 43264, "score": 0.9967306852340698, "start": 43259, "tag": "NAME", "value": "Mulan" }, { "context": "PayPal? Envia um e-mail para\"\n support_part2: \"support@codecombat.com\"\n\n# announcement:\n# now_available: \"Now avail", "end": 51441, "score": 0.9999276399612427, "start": 51419, "tag": "EMAIL", "value": "support@codecombat.com" }, { "context": "Now available for subscribers!\"\n# subscriber: \"subscriber\"\n# cuddly_companions: \"Cuddly Companions!\" # P", "end": 51542, "score": 0.9954944252967834, "start": 51532, "tag": "USERNAME", "value": "subscriber" }, { "context": "e day. All the time, really.\"\n# griffin_name: \"Baby Griffin\"\n# griffin_description: \"Griffins are half eag", "end": 51815, "score": 0.999759316444397, "start": 51803, "tag": "NAME", "value": "Baby Griffin" }, { "context": "ottles full of health for you.\"\n# mimic_name: \"Mimic\"\n# mimic_description: \"Mimics can pick up coin", "end": 52041, "score": 0.684575080871582, "start": 52036, "tag": "NAME", "value": "Mimic" }, { "context": "to increase your gold supply.\"\n# cougar_name: \"Cougar\"\n# cougar_description: \"Cougars like to earn a", "end": 52184, "score": 0.8762907981872559, "start": 52178, "tag": "NAME", "value": "Cougar" }, { "context": "cougar_description: \"Cougars like to earn a PhD by Purring Happily Daily.\"\n# fox_name: \"Blue Fox\"\n# fox_description:", "end": 52263, "score": 0.9938793182373047, "start": 52242, "tag": "NAME", "value": "Purring Happily Daily" }, { "context": " creatures and can cast spells!\"\n# wolf_name: \"Wolf Pup\"\n# wolf_description: \"Wolf pups excel in hunti", "end": 52531, "score": 0.9766272902488708, "start": 52523, "tag": "NAME", "value": "Wolf Pup" }, { "context": " ritic_description: \"Ritic the Cold. Trapped in Kelvintaph Glacier for countless ages, finally free a", "end": 53219, "score": 0.5453343987464905, "start": 53216, "tag": "NAME", "value": "Kel" }, { "context": "rowth and learning in our team.\"\n nick_title: \"Co-fundador, CEO\"\n matt_title: \"Co-fundador, CTO\"\n cat_t", "end": 62046, "score": 0.7306390404701233, "start": 62035, "tag": "NAME", "value": "Co-fundador" }, { "context": "ning in our team.\"\n nick_title: \"Co-fundador, CEO\"\n matt_title: \"Co-fundador, CTO\"\n cat_title", "end": 62051, "score": 0.7043738961219788, "start": 62049, "tag": "NAME", "value": "EO" }, { "context": "e come a long way...\"\n# story_sketch_caption: \"Nick's very first sketch depicting a programming game ", "end": 65376, "score": 0.9605321884155273, "start": 65372, "tag": "NAME", "value": "Nick" }, { "context": ": \"Curriculum Specialist/Advisor\"\n principal: \"Diretor\"\n superintendent: \"Superintendente\"\n parent", "end": 70351, "score": 0.980375349521637, "start": 70344, "tag": "NAME", "value": "Diretor" }, { "context": " organization_label: \"Escola\"\n school_name: \"Nome da Escola\"\n city: \"Cidade\"\n state: \"Estado\" # ", "end": 70823, "score": 0.7404398918151855, "start": 70816, "tag": "NAME", "value": "Nome da" }, { "context": "ation_label: \"Escola\"\n school_name: \"Nome da Escola\"\n city: \"Cidade\"\n state: \"Estado\" # {change", "end": 70830, "score": 0.7734278440475464, "start": 70826, "tag": "NAME", "value": "cola" }, { "context": "u Nome de Utilizador Errado\"\n wrong_password: \"Palavra-passe Errada\"\n delete_this_account: \"Elimina esta conta per", "end": 74915, "score": 0.9988698959350586, "start": 74895, "tag": "PASSWORD", "value": "Palavra-passe Errada" }, { "context": "ara gerires a tua subscrição.\"\n new_password: \"Nova Palavra-passe\"\n new_password_verify: \"Verificar\"\n type_in", "end": 75290, "score": 0.9991940259933472, "start": 75272, "tag": "PASSWORD", "value": "Nova Palavra-passe" }, { "context": "d: \"Nova Palavra-passe\"\n new_password_verify: \"Verificar\"\n type_in_email: \"Escreve o teu e-mail ou nome", "end": 75327, "score": 0.9944503307342529, "start": 75318, "tag": "PASSWORD", "value": "Verificar" }, { "context": "minação do teu progresso.\"\n type_in_password: \"Escreve também a tua palavra-passe.\"\n email_subscripti", "end": 75562, "score": 0.6078996062278748, "start": 75555, "tag": "PASSWORD", "value": "Escreve" }, { "context": " type_in_password: \"Escreve também a tua palavra-passe.\"\n email_subscriptions: \"Subscrições de E-mail", "end": 75589, "score": 0.5260874032974243, "start": 75584, "tag": "PASSWORD", "value": "passe" }, { "context": "o no nosso fórum Discourse\"\n social_facebook: \"Gosta do CodeCombat no Facebook\"\n social_twitter: \"Segue o CodeCom", "end": 79198, "score": 0.99647057056427, "start": 79179, "tag": "USERNAME", "value": "Gosta do CodeCombat" }, { "context": "a do CodeCombat no Facebook\"\n social_twitter: \"Segue o CodeCombat no Twitter\"\n social_slack: \"Fala connosco no c", "end": 79251, "score": 0.9959759712219238, "start": 79233, "tag": "USERNAME", "value": "Segue o CodeCombat" }, { "context": "eus Clãs\"\n clan_name: \"Nome do Clã\"\n name: \"Nome\"\n chieftain: \"Líder\"\n edit_clan_name: \"Edit", "end": 80127, "score": 0.6138789057731628, "start": 80123, "tag": "NAME", "value": "Nome" }, { "context": "e: \"Nome do Clã\"\n name: \"Nome\"\n chieftain: \"Líder\"\n edit_clan_name: \"Editar Nome do Clã\"\n edi", "end": 80150, "score": 0.7470609545707703, "start": 80145, "tag": "NAME", "value": "Líder" }, { "context": "te Clã enviando-lhes esta ligação.\"\n members: \"Membros\"\n progress: \"Progresso\"\n not_started_1: \"nã", "end": 80670, "score": 0.9428303837776184, "start": 80663, "tag": "NAME", "value": "Membros" }, { "context": "xp_levels: \"Expandir os níveis\"\n rem_hero: \"Remover Herói\"\n status: \"Estado\"\n complete_2: \"Comp", "end": 80844, "score": 0.7135109305381775, "start": 80840, "tag": "NAME", "value": "over" }, { "context": "s: \"Expandir os níveis\"\n rem_hero: \"Remover Herói\"\n status: \"Estado\"\n complete_2: \"Completo\"\n", "end": 80850, "score": 0.8843636512756348, "start": 80848, "tag": "NAME", "value": "ói" }, { "context": "o_assign: \"to assign paid courses.\"\n student: \"Estudante\"\n teacher: \"Professor\"\n arena: \"Arena\"\n ", "end": 83903, "score": 0.9853746891021729, "start": 83894, "tag": "NAME", "value": "Estudante" }, { "context": " courses.\"\n student: \"Estudante\"\n teacher: \"Professor\"\n arena: \"Arena\"\n available_levels: \"Níveis", "end": 83928, "score": 0.9967365264892578, "start": 83919, "tag": "NAME", "value": "Professor" }, { "context": " \"Não és tu?\"\n continue_playing: \"Continuar a Jogar\"\n option1_header: \"Convidar Estudantes por E-m", "end": 85339, "score": 0.7581052780151367, "start": 85335, "tag": "NAME", "value": "ogar" }, { "context": "\n create_class: \"Criar Turma\"\n class_name: \"Nome da Turma\"\n# teacher_account_restricted: \"Your ", "end": 87700, "score": 0.6898153424263, "start": 87696, "tag": "NAME", "value": "Nome" }, { "context": ", we are offering free 1-week licenses!<br />Email Rob Arevalo (<a href=\\\"mailto:robarev@codecombat.com?subject=", "end": 95340, "score": 0.9998989701271057, "start": 95329, "tag": "NAME", "value": "Rob Arevalo" }, { "context": "icenses!<br />Email Rob Arevalo (<a href=\\\"mailto:robarev@codecombat.com?subject=Teacher Appreciation Week\\\">robarev@codec", "end": 95381, "score": 0.999907374382019, "start": 95359, "tag": "EMAIL", "value": "robarev@codecombat.com" }, { "context": "odecombat.com?subject=Teacher Appreciation Week\\\">robarev@codecombat.com</a>) with subject line \\\"<strong>Teacher Apprecia", "end": 95440, "score": 0.9998887181282043, "start": 95418, "tag": "EMAIL", "value": "robarev@codecombat.com" }, { "context": "nova palavra-passe abaixo:\"\n change_password: \"Alterar Palavra-passe\"\n changed: \"Alterada\"\n available_credits: \"", "end": 103034, "score": 0.9980951547622681, "start": 103013, "tag": "PASSWORD", "value": "Alterar Palavra-passe" }, { "context": "s: \"Detalhes do Estudante\"\n student_name: \"Nome do Estudante\"\n no_name: \"Nenhum nome fornecido.\"\n no_use", "end": 110964, "score": 0.6686754822731018, "start": 110952, "tag": "NAME", "value": "do Estudante" }, { "context": "Get in touch with our [school specialists](mailto:schools@codecombat.com) today!\"\n# teacher_quest_keep_going: \"Keep goi", "end": 117242, "score": 0.9991721510887146, "start": 117220, "tag": "EMAIL", "value": "schools@codecombat.com" }, { "context": "icenses: \"Partilhar Licenças\"\n shared_by: \"Partilhadas Por:\"\n# add_teacher_label: \"Enter exact teache", "end": 119332, "score": 0.8496994972229004, "start": 119325, "tag": "NAME", "value": "ilhadas" }, { "context": " para o teu professor\"\n\n game_dev:\n creator: \"Criador\"\n\n web_dev:\n image_gallery_title: \"Galeria de", "end": 121242, "score": 0.9809483885765076, "start": 121235, "tag": "USERNAME", "value": "Criador" }, { "context": " CodeCombat perante o mundo.\"\n teacher_title: \"Professor\"\n\n editor:\n main_title: \"Editores do CodeComb", "end": 123346, "score": 0.6215401291847229, "start": 123337, "tag": "NAME", "value": "Professor" }, { "context": "Bobby Duke Middle School\"\n# featured_teacher: \"Scott Baily\"\n# teacher_title: \"Technology Teacher Coachell", "end": 145570, "score": 0.9998730421066284, "start": 145559, "tag": "NAME", "value": "Scott Baily" }, { "context": "aching 21st century skills was the top priority of Bobby Duke Middle School Technology teacher, Scott Baily.\"\n#", "end": 146874, "score": 0.9979931712150574, "start": 146864, "tag": "NAME", "value": "Bobby Duke" }, { "context": "ty of Bobby Duke Middle School Technology teacher, Scott Baily.\"\n# paragraph3: \"Baily knew that teaching his ", "end": 146920, "score": 0.9998947978019714, "start": 146909, "tag": "NAME", "value": "Scott Baily" }, { "context": "chnology teacher, Scott Baily.\"\n# paragraph3: \"Baily knew that teaching his students coding was a key ", "end": 146946, "score": 0.9997856616973877, "start": 146941, "tag": "NAME", "value": "Baily" }, { "context": "They’re not even close.\"\n# quote_attribution: \"Scott Baily, Technology Teacher\"\n# read_full_story: \"Read ", "end": 147600, "score": 0.9998902678489685, "start": 147589, "tag": "NAME", "value": "Scott Baily" }, { "context": "acher & Student Spotlights\"\n# teacher_name_1: \"Amanda Henry\"\n# teacher_title_1: \"Rehabilitation Instructor", "end": 148186, "score": 0.9998909831047058, "start": 148174, "tag": "NAME", "value": "Amanda Henry" }, { "context": "n and drive to help those who need second chances, Amanda Henry helped change the lives of students who need posi", "end": 148387, "score": 0.9998752474784851, "start": 148375, "tag": "NAME", "value": "Amanda Henry" }, { "context": "els. With no previous computer science experience, Henry led her students to coding success in a regional ", "end": 148506, "score": 0.9997185468673706, "start": 148501, "tag": "NAME", "value": "Henry" }, { "context": "gional coding competition.\"\n# teacher_name_2: \"Kaila, Student\"\n# teacher_title_2: \"Maysville Community & Tec", "end": 148613, "score": 0.9997923970222473, "start": 148599, "tag": "NAME", "value": "Kaila, Student" }, { "context": "athway to a bright future.\"\n# teacher_name_3: \"Susan Jones-Szabo\"\n# teacher_title_3: \"Teacher Librarian\"\n# t", "end": 148924, "score": 0.9992426633834839, "start": 148907, "tag": "NAME", "value": "Susan Jones-Szabo" }, { "context": "cher_location_3: \"Alameda, CA\"\n# spotlight_3: \"Susan Jones-Szabo promotes an equitable atmosphere in her class whe", "end": 149092, "score": 0.9990320205688477, "start": 149075, "tag": "NAME", "value": "Susan Jones-Szabo" }, { "context": "o teu professor:\"\n teacher_email_placeholder: \"teacher.email@example.com\"\n student_name_placeholder: \"escreve o teu nom", "end": 156416, "score": 0.9999150633811951, "start": 156391, "tag": "EMAIL", "value": "teacher.email@example.com" }, { "context": "taken: \"E-mail já escolhido\"\n username_taken: \"Nome de utilizador já escolhido\"\n\n esper:\n line_no", "end": 164472, "score": 0.5521212220191956, "start": 164468, "tag": "USERNAME", "value": "Nome" }, { "context": "n: \"E-mail já escolhido\"\n username_taken: \"Nome de utilizador já escolhido\"\n\n esper:\n line_no: \"Linha $1: \"\n# uncaugh", "end": 164499, "score": 0.7281068563461304, "start": 164473, "tag": "NAME", "value": "de utilizador já escolhido" }, { "context": ":\n# refer_teacher: \"Refer Teacher\"\n# name: \"Your Name\"\n# parent_email: \"Your Email\"\n# teacher_ema", "end": 176304, "score": 0.997411847114563, "start": 176295, "tag": "NAME", "value": "Your Name" }, { "context": "get_cert_btn: \"Get Certificate\"\n# first_name: \"First Name\"\n# last_initial: \"Last Initial\"\n# teacher_e", "end": 178634, "score": 0.997549295425415, "start": 178624, "tag": "NAME", "value": "First Name" }, { "context": "? Contact your CodeCombat Account Manager or email support@codecombat.com. \"\n# license_stat_description: \"Licenses avail", "end": 179258, "score": 0.9999250173568726, "start": 179236, "tag": "EMAIL", "value": "support@codecombat.com" } ]
app/locale/pt-PT.coffee
desimil/codecombat
1
module.exports = nativeDescription: "Português (Portugal)", englishDescription: "Portuguese (Portugal)", translation: new_home: # title: "CodeCombat - Coding games to learn Python and JavaScript" # meta_keywords: "CodeCombat, python, javascript, Coding Games" # meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." # meta_og_url: "https://codecombat.com" # built_for_teachers_title: "A Coding Game Built with Teachers in Mind" # built_for_teachers_blurb: "Teaching kids to code can often feel overwhelming. CodeCombat helps all educators teach students how to code in either JavaScript or Python, two of the most popular programming languages. With a comprehensive curriculum that includes six computer science units and reinforces learning through project-based game development and web development units, kids will progress on a journey from basic syntax to recursion!" # built_for_teachers_subtitle1: "Computer Science" # built_for_teachers_subblurb1: "Starting with our free Introduction to Computer Science course, students master core coding concepts such as while/for loops, functions, and algorithms." # built_for_teachers_subtitle2: "Game Development" # built_for_teachers_subblurb2: "Learners construct mazes and use basic input handling to code their own games that can be shared with friends and family." # built_for_teachers_subtitle3: "Web Development" # built_for_teachers_subblurb3: "Using HTML, CSS, and jQuery, learners flex their creative muscles to program their own webpages with a custom URL to share with their classmates." # century_skills_title: "21st Century Skills" # century_skills_blurb1: "Students Don't Just Level Up Their Hero, They Level Up Themselves" # century_skills_quote1: "You mess up…so then you think about all of the possible ways to fix it, and then try again. I wouldn't be able to get here without trying hard." # century_skills_subtitle1: "Critical Thinking" # century_skills_subblurb1: "With coding puzzles that are naturally scaffolded into increasingly challenging levels, CodeCombat's programming game ensures kids are always practicing critical thinking." # century_skills_quote2: "Everyone else was making mazes, so I thought, ‘capture the flag’ and that’s what I did." # century_skills_subtitle2: "Creativity" # century_skills_subblurb2: "CodeCombat encourages students to showcase their creativity by building and sharing their own games and webpages." # century_skills_quote3: "If I got stuck on a level. I would work with people around me until we were all able to figure it out." # century_skills_subtitle3: "Collaboration" # century_skills_subblurb3: "Throughout the game, there are opportunities for students to collaborate when they get stuck and to work together using our pair programming guide." # century_skills_quote4: "I’ve always had aspirations of designing video games and learning how to code ... this is giving me a great starting point." # century_skills_subtitle4: "Communication" # century_skills_subblurb4: "Coding requires kids to practice new forms of communication, including communicating with the computer itself and conveying their ideas using the most efficient code." # classroom_in_box_title: "We Strive To:" # classroom_in_box_blurb1: "Engage every student so that they believe coding is for them." # classroom_in_box_blurb2: "Empower any educator to feel confident when teaching coding." # classroom_in_box_blurb3: "Inspire all school leaders to create a world-class computer science program." # creativity_rigor_title: "Where Creativity Meets Rigor" # creativity_rigor_subtitle1: "Make coding fun and teach real-world skills" # creativity_rigor_blurb1: "Students type real Python and JavaScript while playing games that encourage trial-and-error, critical thinking, and creativity. Students then apply the coding skills they’ve learned by developing their own games and websites in project-based courses." # creativity_rigor_subtitle2: "Reach students at their level" # creativity_rigor_blurb2: "Every CodeCombat level is scaffolded based on millions of data points and optimized to adapt to each learner. Practice levels and hints help students when they get stuck, and challenge levels assess students' learning throughout the game." # creativity_rigor_subtitle3: "Built for all teachers, regardless of experience" # creativity_rigor_blurb3: "CodeCombat’s self-paced, standards-aligned curriculum makes teaching computer science possible for everyone. CodeCombat equips teachers with the training, instructional resources, and dedicated support to feel confident and successful in the classroom." # featured_partners_title1: "Featured In" # featured_partners_title2: "Awards & Partners" # featured_partners_blurb1: "CollegeBoard Endorsed Provider" # featured_partners_blurb2: "Best Creativity Tool for Students" # featured_partners_blurb3: "Top Pick for Learning" # featured_partners_blurb4: "Code.org Official Partner" # featured_partners_blurb5: "CSforAll Official Member" # featured_partners_blurb6: "Hour of Code Activity Partner" # for_leaders_title: "For School Leaders" # for_leaders_blurb: "A Comprehensive, Standards-Aligned Computer Science Program" # for_leaders_subtitle1: "Easy Implementation" # for_leaders_subblurb1: "A web-based program that requires no IT support. Get started in under 5 minutes using Google or Clever Single Sign-On (SSO)." # for_leaders_subtitle2: "Full Coding Curriculum" # for_leaders_subblurb2: "A standards-aligned curriculum with instructional resources and professional development to enable any teacher to teach computer science." # for_leaders_subtitle3: "Flexible Use Cases" # for_leaders_subblurb3: "Whether you want to build a Middle School coding elective, a CTE pathway, or an AP Computer Science Principles class, CodeCombat is tailored to suit your needs." # for_leaders_subtitle4: "Real-World Skills" # for_leaders_subblurb4: "Students build grit and develop a growth mindset through coding challenges that prepare them for the 500K+ open computing jobs." # for_teachers_title: "For Teachers" # for_teachers_blurb: "Tools to Unlock Student Potential" # for_teachers_subtitle1: "Project-Based Learning" # for_teachers_subblurb1: "Promote creativity, problem-solving, and confidence in project-based courses where students develop their own games and webpages." # for_teachers_subtitle2: "Teacher Dashboard" # for_teachers_subblurb2: "View data on student progress, discover curriculum resources, and access real-time support to empower student learning." # for_teachers_subtitle3: "Built-in Assessments" # for_teachers_subblurb3: "Personalize instruction and ensure students understand core concepts with formative and summative assessments." # for_teachers_subtitle4: "Automatic Differentiation" # for_teachers_subblurb4: "Engage all learners in a diverse classroom with practice levels that adapt to each student's learning needs." # game_based_blurb: "CodeCombat is a game-based computer science program where students type real code and see their characters react in real time." # get_started: "Get started" # global_title: "Join Our Global Community of Learners and Educators" # global_subtitle1: "Learners" # global_subtitle2: "Lines of Code" # global_subtitle3: "Teachers" # global_subtitle4: "Countries" # go_to_my_classes: "Go to my classes" # go_to_my_courses: "Go to my courses" # quotes_quote1: "Name any program online, I’ve tried it. None of them match up to CodeCombat. Any teacher who wants their students to learn how to code... start here!" # quotes_quote2: " I was surprised about how easy and intuitive CodeCombat makes learning computer science. The scores on the AP exam were much higher than I expected and I believe CodeCombat is the reason why this was the case." # quotes_quote3: "CodeCombat has been the most beneficial for teaching my students real-life coding capabilities. My husband is a software engineer and he has tested out all of my programs. He put this as his top choice." # quotes_quote4: "The feedback … has been so positive that we are structuring a computer science class around CodeCombat. The program really engages the students with a gaming style platform that is entertaining and instructional at the same time. Keep up the good work, CodeCombat!" # see_example: "See example" slogan: "A forma mais cativante de aprender código real." # {change} # teach_cs1_free: "Teach CS1 Free" # teachers_love_codecombat_title: "Teachers Love CodeCombat" # teachers_love_codecombat_blurb1: "Report that their students enjoy using CodeCombat to learn how to code" # teachers_love_codecombat_blurb2: "Would recommend CodeCombat to other computer science teachers" # teachers_love_codecombat_blurb3: "Say that CodeCombat helps them support students’ problem solving abilities" # teachers_love_codecombat_subblurb: "In partnership with McREL International, a leader in research-based guidance and evaluations of educational technology." # try_the_game: "Try the game" classroom_edition: "Edição de Turma:" learn_to_code: "Aprender a programar:" play_now: "Jogar Agora" # im_an_educator: "I'm an Educator" im_a_teacher: "Sou um Professor" im_a_student: "Sou um Estudante" learn_more: "Saber mais" classroom_in_a_box: "Uma turma num pacote para ensinar ciências da computação." codecombat_is: "O CodeCombat é uma plataforma <strong>para estudantes</strong> para aprender ciências da computação enquanto se joga um jogo real." our_courses: "Os nossos cursos foram especificamente testados para <strong>terem sucesso na sala de aula</strong>, até para professores com pouca ou nenhuma experiência anterior de programação." watch_how: "Vê como o CodeCombat está a transformar o modo como as pessoas aprendem ciências da computação." top_screenshots_hint: "Os estudantes escrevem código e veem as alterações deles atualizarem em tempo real" designed_with: "Desenhado a pensar nos professores" real_code: "Código real e escrito" from_the_first_level: "desde o primeiro nível" getting_students: "Apresentar código escrito aos estudantes o mais rapidamete possível é crítico para aprenderem a sintaxe e a estrutura adequadas da programação." educator_resources: "Recursos para professores" course_guides: "e guias dos cursos" teaching_computer_science: "Ensinar ciências da computação não requer um curso caro, porque nós fornecemos ferramentas para ajudar todo o tipo de professores." accessible_to: "Acessível a" everyone: "todos" democratizing: "Democratizar o processo de aprender a programar está na base da nossa filosofia. Todos devem poder aprender a programar." forgot_learning: "Acho que eles se esqueceram que estavam a aprender alguma coisa." wanted_to_do: "Programar é algo que sempre quis fazer e nunca pensei que poderia aprender isso na escola." builds_concepts_up: "Gosto da forma como o CodeCombat desenvolve os conceitos. É muito fácil compreendê-los e é divertido descobri-los." why_games: "Porque é que aprender através de jogos é importante?" games_reward: "Os jogos recompensam o esforço produtivo." encourage: "Jogar é algo que encoraja a interação, a descoberta e a tentativa erro. Um bom jogo desafia o jogador a dominar habilidades com o tempo, que é o mesmo processo fundamental que os estudantes atravessam quando aprendem." excel: "Os jogos são excelentes a recompensar o" struggle: "esforço produtivo" kind_of_struggle: "o tipo de esforço que resulta numa aprendizagem que é cativante e" motivating: "motivadora" not_tedious: "não entediante." gaming_is_good: "Estudos sugerem que jogar é bom para o cérebro das crianças. (é verdade!)" # game_based: "When game-based learning systems are" # compared: "compared" # conventional: "against conventional assessment methods, the difference is clear: games are better at helping students retain knowledge, concentrate and" # perform_at_higher_level: "perform at a higher level of achievement" # feedback: "Games also provide real-time feedback that allows students to adjust their solution path and understand concepts more holistically, instead of being limited to just “correct” or “incorrect” answers." real_game: "Um jogo a sério, jogado com código a sério." # great_game: "A great game is more than just badges and achievements - it’s about a player’s journey, well-designed puzzles, and the ability to tackle challenges with agency and confidence." # agency: "CodeCombat is a game that gives players that agency and confidence with our robust typed code engine, which helps beginner and advanced students alike write proper, valid code." # request_demo_title: "Get your students started today!" # request_demo_subtitle: "Request a demo and get your students started in less than an hour." # get_started_title: "Set up your class today" # get_started_subtitle: "Set up a class, add your students, and monitor their progress as they learn computer science." request_demo: "Pedir uma Demonstração" # request_quote: "Request a Quote" setup_a_class: "Configurar uma Turma" have_an_account: "Tens uma conta?" logged_in_as: "Atualmente tens sessão iniciada como" # computer_science: "Our self-paced courses cover basic syntax to advanced concepts" ffa: "Grátis para todos os estudantes" coming_soon: "Mais, brevemente!" courses_available_in: "Os cursos estão disponíveis em JavaScript e Python. Os cursos de Desenvolvimento Web utilizam HTML, CSS e jQuery." # boast: "Boasts riddles that are complex enough to fascinate gamers and coders alike." # winning: "A winning combination of RPG gameplay and programming homework that pulls off making kid-friendly education legitimately enjoyable." run_class: "Tudo o que precisas para teres uma turma de ciências da computação na tua escola hoje, sem serem necessárias bases de CC." goto_classes: "Ir para As Minhas Turmas" view_profile: "Ver o Meu Perfil" view_progress: "Ver Progresso" go_to_courses: "Ir para Os Meus Cursos" want_coco: "Queres o CodeCombat na tua escola?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" map: "Mapa" play: "Níveis" # The top nav bar entry where players choose which levels to play community: "Comunidade" courses: "Cursos" blog: "Blog" forum: "Fórum" account: "Conta" my_account: "A Minha Conta" profile: "Perfil" home: "Início" contribute: "Contribuir" legal: "Legal" privacy: "Aviso de Privacidade" about: "Sobre" # impact: "Impact" contact: "Contactar" twitter_follow: "Seguir" my_classrooms: "As Minhas Turmas" my_courses: "Os Meus Cursos" # my_teachers: "My Teachers" careers: "Carreiras" facebook: "Facebook" twitter: "Twitter" create_a_class: "Criar uma Turma" other: "Outros" learn_to_code: "Aprende a Programar!" toggle_nav: "Alternar navegação" schools: "Escolas" get_involved: "Envolve-te" open_source: "Open source (GitHub)" support: "Suporte" faqs: "FAQs" copyright_prefix: "Direitos" copyright_suffix: "Todos os Direitos Reservados." help_pref: "Precisas de ajuda? Envia um e-mail para" help_suff: "e nós entraremos em contacto!" resource_hub: "Centro de Recursos" # apcsp: "AP CS Principles" parent: "Educadores" # browser_recommendation: "For the best experience we recommend using the latest version of Chrome. Download the browser here!" modal: close: "Fechar" okay: "Ok" # cancel: "Cancel" not_found: page_not_found: "Página não encontrada" diplomat_suggestion: title: "Ajuda a traduzir o CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Precisamos das tuas habilidades linguísticas." pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores de todo o mundo. Muitos deles querem jogar em Português, mas não falam Inglês, por isso, se sabes falar ambas, por favor considera registar-te como Diplomata para ajudares a traduzir o sítio do CodeCombat e todos os níveis para Português." missing_translations: "Até conseguirmos traduzir tudo para Português, irás ver em Inglês o que não estiver disponível em Português." learn_more: "Sabe mais sobre seres um Diplomata" subscribe_as_diplomat: "Subscreve-te como Diplomata" play: # title: "Play CodeCombat Levels - Learn Python, JavaScript, and HTML" # meta_description: "Learn programming with a coding game for beginners. Learn Python or JavaScript as you solve mazes, make your own games, and level up. Challenge your friends in multiplayer arena levels!" # level_title: "__level__ - Learn to Code in Python, JavaScript, HTML" # video_title: "__video__ | Video Level" # game_development_title: "__level__ | Game Development" # web_development_title: "__level__ | Web Development" anon_signup_title_1: "O CodeCombat tem uma" anon_signup_title_2: "Versão para Turmas!" anon_signup_enter_code: "Introduz um Código de Truma:" anon_signup_ask_teacher: "Não tens um? Pede ao teu professor!" anon_signup_create_class: "Queres criar uma turma?" anon_signup_setup_class: "Configura um turma, adiciona estudantes e monitoriza o progresso!" anon_signup_create_teacher: "Criar uma conta de professor gratuita" play_as: "Jogar Como" # Ladder page # get_course_for_class: "Assign Game Development and more to your classes!" # request_licenses: "Contact our school specialists for details." compete: "Competir!" # Course details page spectate: "Assistir" # Ladder page players: "jogadores" # Hover over a level on /play hours_played: "horas jogadas" # Hover over a level on /play items: "Itens" # Tooltip on item shop button from /play unlock: "Desbloquear" # For purchasing items and heroes confirm: "Confirmar" owned: "Obtido" # For items you own locked: "Bloqueado" available: "Disponível" skills_granted: "Habilidades Garantidas" # Property documentation details heroes: "Heróis" # Tooltip on hero shop button from /play achievements: "Conquistas" # Tooltip on achievement list button from /play settings: "Definições" # Tooltip on settings button from /play poll: "Votações" # Tooltip on poll button from /play next: "Próximo" # Go from choose hero to choose inventory before playing a level change_hero: "Alterar Herói" # Go back from choose inventory to choose hero change_hero_or_language: "Alterar Herói ou Linguagem" buy_gems: "Comprar Gemas" subscribers_only: "Apenas para Subscritores!" subscribe_unlock: "Subscreve-te para Desbloqueares!" subscriber_heroes: "Subscreve-te hoje para desbloqueares de imediato a Amara, a Hushbaum, e o Hattori!" subscriber_gems: "Subscreve-te hoje para adquirires este herói com gemas!" anonymous: "Jogador Anónimo" level_difficulty: "Dificuldade: " awaiting_levels_adventurer_prefix: "Lançamos novos níveis todas as semanas." awaiting_levels_adventurer: "Regista-te como Aventureiro" awaiting_levels_adventurer_suffix: "para seres o primeiro a jogar níveis novos." adjust_volume: "Ajustar volume" campaign_multiplayer: "Arenas Multijogador" campaign_multiplayer_description: "... nas quais programas contra outros jogadores." # brain_pop_done: "You’ve defeated the Ogres with code! You win!" # brain_pop_challenge: "Challenge yourself to play again using a different programming language!" # replay: "Replay" back_to_classroom: "Voltar à Turma" teacher_button: "Para Professores" # get_more_codecombat: "Get More CodeCombat" code: if: "se" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "senão" elif: "senão se" while: "enquanto" loop: "repetir" for: "para" break: "parar" continue: "continuar" pass: "passar" return: "devolver" then: "então" do: "fazer" end: "fim" function: "função" def: "definir" var: "variável" self: "próprio" hero: "herói" this: "isto" or: "ou" "||": "ou" and: "e" "&&": "e" not: "não" "!": "não" "=": "atribuir" "==": "é igual a" "===": "é estritamente igual a" "!=": "não é igual a" "!==": "não é estritamente igual a" ">": "é maior do que" ">=": "é maior do que ou igual a" "<": "é menor do que" "<=": "é menor do que ou igual a" "*": "multiplicado por" "/": "dividido por" "+": "mais" "-": "menos" "+=": "adicionar e atribuir" "-=": "subtrair e atribuir" True: "Verdadeiro" true: "verdadeiro" False: "Falso" false: "falso" undefined: "não definido" null: "nulo" nil: "nada" None: "Nenhum" share_progress_modal: blurb: "Estás a fazer grandes progressos! Conta ao teu educador o quanto aprendeste com o CodeCombat." email_invalid: "Endereço de e-mail inválido." form_blurb: "Introduz o e-mail do teu educador abaixo e nós vamos mostrar-lhe!" form_label: "Endereço de E-mail" placeholder: "endereço de e-mail" title: "Excelente Trabalho, Aprendiz" login: sign_up: "Criar Conta" email_or_username: "E-mail ou nome de utilizador" log_in: "Iniciar Sessão" logging_in: "A Iniciar Sessão" log_out: "Sair" forgot_password: "Esqueceste a tua palavra-passe?" finishing: "A Terminar" sign_in_with_facebook: "Iniciar sessão com o FB" sign_in_with_gplus: "Iniciar sessão com o Google" signup_switch: "Queres criar uma conta?" signup: # complete_subscription: "Complete Subscription" create_student_header: "Criar Conta de Estudante" create_teacher_header: "Criar Conta de Professor" create_individual_header: "Criar Conta Individual" email_announcements: "Receber anúncios sobre níveis e funcionalidades novos do CodeCombat!" sign_in_to_continue: "Inicia sessão ou cria uma conta para continuares" # teacher_email_announcements: "Keep me updated on new teacher resources, curriculum, and courses!" creating: "A Criar Conta..." sign_up: "Registar" log_in: "iniciar sessão com palavra-passe" # login: "Login" required: "Precisas de iniciar sessão antes de prosseguires." login_switch: "Já tens uma conta?" optional: "opcional" # connected_gplus_header: "You've successfully connected with Google+!" # connected_gplus_p: "Finish signing up so you can log in with your Google+ account." # connected_facebook_header: "You've successfully connected with Facebook!" # connected_facebook_p: "Finish signing up so you can log in with your Facebook account." hey_students: "Estudantes, introduzam o código de turma do vosso professor." birthday: "Aniversário" # parent_email_blurb: "We know you can't wait to learn programming &mdash; we're excited too! Your parents will receive an email with further instructions on how to create an account for you. Email {{email_link}} if you have any questions." # classroom_not_found: "No classes exist with this Class Code. Check your spelling or ask your teacher for help." checking: "A verificar..." account_exists: "Este e-mail já está a ser usado:" sign_in: "Iniciar sessão" email_good: "O e-mail parece bom!" name_taken: "Nome de utilizador já escolhido! Que tal {{suggestedName}}?" name_available: "Nome de utilizador disponível!" name_is_email: "O nome de utilizador não pode ser um e-mail" choose_type: "Escolhe o teu tipo de conta:" teacher_type_1: "Ensina programção usando o CodeCombat!" teacher_type_2: "Configura a tua turma" teacher_type_3: "Acede aos Guias dos Cursos" teacher_type_4: "Vê o progresso dos estudantes" signup_as_teacher: "Registar como Professor" student_type_1: "Aprende a programar enquanto jogas um jogo cativante!" student_type_2: "Joga com a tua turma" student_type_3: "Compete em arenas" student_type_4: "Escolhe o teu herói!" student_type_5: "Prepara o teu Código de Turma!" signup_as_student: "Registar como Estudante" individuals_or_parents: "Individuais e Educadores" individual_type: "Para jogadores a aprender a programar fora de uma turma. Os educadores devem registar-se aqui." signup_as_individual: "Registar como Individual" enter_class_code: "Introduz o teu Código de Turma" enter_birthdate: "Introduz a tua data de nascimento:" parent_use_birthdate: "Educadores, usem a vossa data de nascimento." ask_teacher_1: "Pergunta ao teu professor pelo teu Código de Turma." ask_teacher_2: "Não fazes parte de uma turma? Cria uma " ask_teacher_3: "Conta Individual" ask_teacher_4: " então." about_to_join: "Estás prestes a entrar em:" enter_parent_email: "Introduz o e-mail do teu educador:" # parent_email_error: "Something went wrong when trying to send the email. Check the email address and try again." # parent_email_sent: "We’ve sent an email with further instructions on how to create an account. Ask your parent to check their inbox." account_created: "Conta Criada!" confirm_student_blurb: "Aponta a tua informação para que não a esqueças. O teu professor também te pode ajudar a reiniciar a tua palavra-passe a qualquer altura." confirm_individual_blurb: "Aponta a tua informação de início de sessão caso precises dela mais tarde. Verifica o teu e-mail para que possas recuperar a tua conta se alguma vez esqueceres a tua palavra-passe - verifica a tua caixa de entrada!" write_this_down: "Aponta isto:" start_playing: "Começar a Jogar!" # sso_connected: "Successfully connected with:" select_your_starting_hero: "Escolhe o Teu Herói Inicial:" you_can_always_change_your_hero_later: "Podes sempre alterar o teu herói mais tarde." # finish: "Finish" # teacher_ready_to_create_class: "You're ready to create your first class!" # teacher_students_can_start_now: "Your students will be able to start playing the first course, Introduction to Computer Science, immediately." # teacher_list_create_class: "On the next screen you will be able to create a new class." # teacher_list_add_students: "Add students to the class by clicking the View Class link, then sending your students the Class Code or URL. You can also invite them via email if they have email addresses." # teacher_list_resource_hub_1: "Check out the" # teacher_list_resource_hub_2: "Course Guides" # teacher_list_resource_hub_3: "for solutions to every level, and the" # teacher_list_resource_hub_4: "Resource Hub" # teacher_list_resource_hub_5: "for curriculum guides, activities, and more!" # teacher_additional_questions: "That’s it! If you need additional help or have questions, reach out to __supportEmail__." # dont_use_our_email_silly: "Don't put our email here! Put your parent's email." # want_codecombat_in_school: "Want to play CodeCombat all the time?" # eu_confirmation: "I agree to allow CodeCombat to store my data on US servers." # eu_confirmation_place_of_processing: "Learn more about the possible risks" # eu_confirmation_student: "If you are not sure, ask your teacher." # eu_confirmation_individual: "If you do not want us to store your data on US servers, you can always keep playing anonymously without saving your code." recover: recover_account_title: "Recuperar Conta" send_password: "Enviar Palavra-passe de Recuperação" recovery_sent: "E-mail de recuperação enviado." items: primary: "Primários" secondary: "Secundários" armor: "Armadura" accessories: "Acessórios" misc: "Vários" books: "Livros" common: # default_title: "CodeCombat - Coding games to learn Python and JavaScript" # default_meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." back: "Voltar" # When used as an action verb, like "Navigate backward" coming_soon: "Brevemente!" continue: "Continuar" # When used as an action verb, like "Continue forward" next: "Próximo" default_code: "Código Original" loading: "A Carregar..." overview: "Visão Geral" processing: "A processar..." solution: "Solução" table_of_contents: "Tabela de Conteúdos" intro: "Introdução" saving: "A Guardar..." sending: "A Enviar..." send: "Enviar" sent: "Enviado" cancel: "Cancelar" save: "Guardar" publish: "Publicar" create: "Criar" fork: "Bifurcar" play: "Jogar" # When used as an action verb, like "Play next level" retry: "Tentar Novamente" actions: "Ações" info: "Informações" help: "Ajuda" watch: "Vigiar" unwatch: "Desvigiar" submit_patch: "Submeter Atualização" submit_changes: "Submeter Alterações" save_changes: "Guardar Alterações" required_field: "necessário" # submit: "Submit" # replay: "Replay" # complete: "Complete" general: and: "e" name: "Nome" date: "Data" body: "Corpo" version: "Versão" pending: "Pendentes" accepted: "Aceites" rejected: "Rejeitadas" withdrawn: "Canceladas" accept: "Aceitar" accept_and_save: "Aceitar&Guardar" reject: "Rejeitar" withdraw: "Cancelar" submitter: "Submissor" submitted: "Submeteu" commit_msg: "Mensagem da Submissão" version_history: "Histórico de Versões" version_history_for: "Histórico de Versões para: " select_changes: "Seleciona duas das alterações abaixo para veres a diferença." undo_prefix: "Desfazer" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Refazer" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Jogar pré-visualização do nível atual" result: "Resultado" results: "Resultados" description: "Descrição" or: "ou" subject: "Assunto" email: "E-mail" password: "Palavra-passe" confirm_password: "Confirmar Palavra-passe" message: "Mensagem" code: "Código" ladder: "Classificação" when: "Quando" opponent: "Adversário" rank: "Classificação" score: "Pontuação" win: "Vitória" loss: "Derrota" tie: "Empate" easy: "Fácil" medium: "Médio" hard: "Difícil" player: "Jogador" player_level: "Nível" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Guerreiro" ranger: "Arqueiro" wizard: "Feiticeiro" first_name: "Nome" last_name: "Apelido" last_initial: "Última Inicial" username: "Nome de utilizador" contact_us: "Contacta-nos" close_window: "Fechar Janela" learn_more: "Saber Mais" more: "Mais" fewer: "Menos" with: "com" units: second: "segundo" seconds: "segundos" sec: "seg" minute: "minuto" minutes: "minutos" hour: "hora" hours: "horas" day: "dia" days: "dias" week: "semana" weeks: "semanas" month: "mês" months: "meses" year: "ano" years: "anos" play_level: back_to_map: "Voltar ao Mapa" directions: "Direções" edit_level: "Editar Nível" keep_learning: "Continuar a Aprender" explore_codecombat: "Explorar o CodeCombat" finished_hoc: "Terminei a minha Hora do Código" get_certificate: "Obtém o teu certificado!" level_complete: "Nível Completo" completed_level: "Nível Completo:" course: "Curso:" done: "Concluir" next_level: "Próximo Nível" # combo_challenge: "Combo Challenge" # concept_challenge: "Concept Challenge" # challenge_unlocked: "Challenge Unlocked" # combo_challenge_unlocked: "Combo Challenge Unlocked" # concept_challenge_unlocked: "Concept Challenge Unlocked" # concept_challenge_complete: "Concept Challenge Complete!" # combo_challenge_complete: "Combo Challenge Complete!" # combo_challenge_complete_body: "Great job, it looks like you're well on your way to understanding __concept__!" # replay_level: "Replay Level" combo_concepts_used: "__complete__/__total__ Conceitos Usados" # combo_all_concepts_used: "You used all concepts possible to solve the challenge. Great job!" # combo_not_all_concepts_used: "You used __complete__ out of the __total__ concepts possible to solve the challenge. Try to get all __total__ concepts next time!" start_challenge: "Começar Desafio" next_game: "Próximo jogo" languages: "Linguagens" programming_language: "Linguagem de programação" show_menu: "Mostrar o menu do jogo" home: "Início" # Not used any more, will be removed soon. level: "Nível" # Like "Level: Dungeons of Kithgard" skip: "Saltar" game_menu: "Menu do Jogo" restart: "Reiniciar" goals: "Objetivos" goal: "Objetivo" # challenge_level_goals: "Challenge Level Goals" # challenge_level_goal: "Challenge Level Goal" # concept_challenge_goals: "Concept Challenge Goals" # combo_challenge_goals: "Challenge Level Goals" # concept_challenge_goal: "Concept Challenge Goal" # combo_challenge_goal: "Challenge Level Goal" running: "A Executar..." success: "Sucesso!" incomplete: "Incompletos" timed_out: "Ficaste sem tempo" failing: "A falhar" reload: "Recarregar" reload_title: "Recarregar o Código Todo?" reload_really: "Tens a certeza que queres recarregar este nível de volta ao início?" reload_confirm: "Recarregar Tudo" # restart_really: "Are you sure you want to restart the level? You'll loose all the code you've written." # restart_confirm: "Yes, Restart" test_level: "Testar Nível" victory: "Vitória" victory_title_prefix: "" victory_title_suffix: " Concluído" victory_sign_up: "Criar Conta para Guardar Progresso" victory_sign_up_poke: "Queres guardar o teu código? Cria uma conta grátis!" victory_rate_the_level: "Quão divertido foi este nível?" victory_return_to_ladder: "Voltar à Classificação" victory_saving_progress: "A Guardar Progresso" victory_go_home: "Ir para o Início" victory_review: "Conta-nos mais!" victory_review_placeholder: "Como foi o nível?" victory_hour_of_code_done: "Terminaste?" victory_hour_of_code_done_yes: "Sim, terminei a minha Hora do Código™!" victory_experience_gained: "XP Ganho" victory_gems_gained: "Gemas Ganhas" victory_new_item: "Novo Item" victory_new_hero: "Novo Herói" # victory_viking_code_school: "Holy smokes, that was a hard level you just beat! If you aren't already a software developer, you should be. You just got fast-tracked for acceptance with Viking Code School, where you can take your skills to the next level and become a professional web developer in 14 weeks." victory_become_a_viking: "Torna-te um Viking" victory_no_progress_for_teachers: "O progresso não é guardado para professores. Mas podes adicionar à tua turma uma conta de estudante para ti." tome_cast_button_run: "Executar" tome_cast_button_running: "A Executar" tome_cast_button_ran: "Executado" # tome_cast_button_update: "Update" tome_submit_button: "Submeter" tome_reload_method: "Recarregar o código original para recomeçar o nível" tome_available_spells: "Feitiços Disponíveis" tome_your_skills: "As Tuas Habilidades" hints: "Dicas" # videos: "Videos" hints_title: "Dica {{number}}" code_saved: "Código Guardado" skip_tutorial: "Saltar (esc)" keyboard_shortcuts: "Atalhos de Teclado" loading_start: "Iniciar Nível" # loading_start_combo: "Start Combo Challenge" # loading_start_concept: "Start Concept Challenge" problem_alert_title: "Corrige o Teu Código" time_current: "Agora:" time_total: "Máximo:" time_goto: "Ir para:" non_user_code_problem_title: "Impossível Carregar o Nível" infinite_loop_title: "'Loop' Infinito Detetado" infinite_loop_description: "O código inicial para construir o mundo nunca parou de ser executado. Provavelmente é muito lento ou contém um 'loop' infinito. Ou talvez haja um erro. Podes tentar executar este código novamente ou reiniciá-lo para o estado predefinido. Se isso não resultar, avisa-nos, por favor." check_dev_console: "Também podes abrir a consola para programadores para veres o que possa estar a correr mal." check_dev_console_link: "(instruções)" infinite_loop_try_again: "Tentar Novamente" infinite_loop_reset_level: "Reiniciar Nível" infinite_loop_comment_out: "Comentar o Meu Código" tip_toggle_play: "Alterna entre Jogar e Pausar com Ctrl+P." tip_scrub_shortcut: "Usa Ctrl+[ para rebobinar e Ctrl+] para avançar." tip_guide_exists: "Clica no guia, dentro do menu do jogo (no topo da página), para informações úteis." tip_open_source: "O CodeCombat faz parte da comunidade open source!" tip_tell_friends: "Estás a gostar do CodeCombat? Fala de nós aos teus amigos!" tip_beta_launch: "O CodeCombat lançou o seu beta em outubro de 2013." tip_think_solution: "Pensa na solução, não no problema." tip_theory_practice: "Teoricamente, não há diferença entre a teoria e a prática. Mas na prática, há. - Yogi Berra" tip_error_free: "Há duas formas de escrever programas sem erros; apenas a terceira funciona. - Alan Perlis" tip_debugging_program: "Se depurar é o processo de remover erros, então programar deve ser o processo de os introduzir. - Edsger W. Dijkstra" tip_forums: "Vai aos fóruns e diz-nos o que pensas!" tip_baby_coders: "No futuro, até os bebés serão Arcomagos." tip_morale_improves: "O carregamento vai continuar até que a moral melhore." tip_all_species: "Acreditamos em oportunidades iguais para todas as espécies, em relação a aprenderem a programar." tip_reticulating: "A reticular espinhas." tip_harry: "És um Feiticeiro, " tip_great_responsibility: "Com uma grande habilidade de programação vem uma grande responsabilidade de depuração." tip_munchkin: "Se não comeres os teus vegetais, um ogre virá atrás de ti enquanto estiveres a dormir." tip_binary: "Há apenas 10 tipos de pessoas no mundo: aquelas que percebem binário e aquelas que não." tip_commitment_yoda: "Um programador deve ter o compromisso mais profundo, a mente mais séria. ~ Yoda" tip_no_try: "Fazer. Ou não fazer. Não há nenhum tentar. - Yoda" tip_patience: "Paciência tu deves ter, jovem Padawan. - Yoda" tip_documented_bug: "Um erro documentado não é um erro; é uma funcionalidade." tip_impossible: "Parece sempre impossível até ser feito. - Nelson Mandela" tip_talk_is_cheap: "Falar é fácil. Mostra-me o código. - Linus Torvalds" tip_first_language: "A coisa mais desastrosa que podes aprender é a tua primeira linguagem de programação. - Alan Kay" tip_hardware_problem: "P: Quantos programadores são necessários para mudar uma lâmpada? R: Nenhum, é um problema de 'hardware'." tip_hofstadters_law: "Lei de Hofstadter: Tudo demora sempre mais do que pensas, mesmo quando tens em conta a Lei de Hofstadter." tip_premature_optimization: "Uma otimização permatura é a raíz de todo o mal. - Donald Knuth" tip_brute_force: "Quando em dúvida, usa a força bruta. - Ken Thompson" tip_extrapolation: "Há apenas dois tipos de pessoas: aquelas que conseguem tirar uma conclusão a partir de dados reduzidos..." tip_superpower: "A programação é a coisa mais próxima de um superpoder que temos." tip_control_destiny: "Em open source a sério, tens o direito de controlares o teu próprio destino. - Linus Torvalds" tip_no_code: "Nenhum código é mais rápido que código não existente." tip_code_never_lies: "O código nunca mente, mas os comentários às vezes sim. — Ron Jeffries" tip_reusable_software: "Antes de um software poder ser reutilizável, primeiro tem de ser utilizável." tip_optimization_operator: "Todas as linguagens têm um operador de otimização. Na maior parte delas esse operador é ‘//’." tip_lines_of_code: "Medir o progresso em programação pelo número de linhas de código é como medir o progresso da construção de um avião pelo peso. — Bill Gates" tip_source_code: "Quero mudar o mundo, mas não há maneira de me darem o código-fonte." tip_javascript_java: "Java é para JavaScript o mesmo que Carro (Car) para Tapete (Carpet). - Chris Heilmann" tip_move_forward: "Faças o que fizeres, segue em frente. - Martin Luther King Jr" tip_google: "Tens um problema que não consegues resolver? Vai ao Google!" tip_adding_evil: "A acrescentar uma pitada de mal." tip_hate_computers: "É o problema das pessoas que acham que odeiam coputadores. O que elas odeiam mesmo são maus programadores. - Larry Niven" tip_open_source_contribute: "Podes ajudar a melhorar o CodeCombat!" tip_recurse: "Iterar é humano, recursar é divino. - L. Peter Deutsch" tip_free_your_mind: "Tens de libertar tudo, Neo. Medo, dúvida e descrença. Liberta a tua mente. - Morpheus" tip_strong_opponents: "Até o mais forte dos adversários tem uma fraqueza. - Itachi Uchiha" tip_paper_and_pen: "Antes de começares a programar, podes sempre planear com uma folha de papel e uma caneta." tip_solve_then_write: "Primeiro, resolve o problema. Depois, escreve o código. - John Johnson" tip_compiler_ignores_comments: "Às vezes acho que o compilador ignora os meus comentários." tip_understand_recursion: "A única forma de entender recursão é entender recursão." # tip_life_and_polymorphism: "Open Source is like a totally polymorphic heterogeneous structure: All types are welcome." # tip_mistakes_proof_of_trying: "Mistakes in your code are just proof that you are trying." # tip_adding_orgres: "Rounding up ogres." # tip_sharpening_swords: "Sharpening the swords." # tip_ratatouille: "You must not let anyone define your limits because of where you come from. Your only limit is your soul. - Gusteau, Ratatouille" # tip_nemo: "When life gets you down, want to know what you've gotta do? Just keep swimming, just keep swimming. - Dory, Finding Nemo" # tip_internet_weather: "Just move to the internet, it's great here. We get to live inside where the weather is always awesome. - John Green" # tip_nerds: "Nerds are allowed to love stuff, like jump-up-and-down-in-the-chair-can't-control-yourself love it. - John Green" # tip_self_taught: "I taught myself 90% of what I've learned. And that's normal! - Hank Green" # tip_luna_lovegood: "Don't worry, you're just as sane as I am. - Luna Lovegood" # tip_good_idea: "The best way to have a good idea is to have a lot of ideas. - Linus Pauling" # tip_programming_not_about_computers: "Computer Science is no more about computers than astronomy is about telescopes. - Edsger Dijkstra" # tip_mulan: "Believe you can, then you will. - Mulan" project_complete: "Projeto Completado!" # share_this_project: "Share this project with friends or family:" ready_to_share: "Pronto para publicares o teu projeto?" # click_publish: "Click \"Publish\" to make it appear in the class gallery, then check out what your classmates built! You can come back and continue to work on this project. Any further changes will automatically be saved and shared with your classmates." # already_published_prefix: "Your changes have been published to the class gallery." # already_published_suffix: "Keep experimenting and making this project even better, or see what the rest of your class has built! Your changes will automatically be saved and shared with your classmates." view_gallery: "Ver Galeria" project_published_noty: "O teu nível foi publicado!" keep_editing: "Continuar a Editar" # learn_new_concepts: "Learn new concepts" # watch_a_video: "Watch a video on __concept_name__" # concept_unlocked: "Concept Unlocked" # use_at_least_one_concept: "Use at least one concept: " # command_bank: "Command Bank" # learning_goals: "Learning Goals" # start: "Start" # vega_character: "Vega Character" # click_to_continue: "Click to Continue" apis: methods: "Métodos" events: "Eventos" # handlers: "Handlers" properties: "Propriedades" # snippets: "Snippets" # spawnable: "Spawnable" html: "HTML" math: "Matemática" # array: "Array" object: "Objeto" # string: "String" function: "Função" vector: "Vetor" date: "Data" jquery: "jQuery" json: "JSON" number: "Número" webjavascript: "JavaScript" # amazon_hoc: # title: "Keep Learning with Amazon!" # congrats: "Congratulations on conquering that challenging Hour of Code!" # educate_1: "Now, keep learning about coding and cloud computing with AWS Educate, an exciting, free program from Amazon for both students and teachers. With AWS Educate, you can earn cool badges as you learn about the basics of the cloud and cutting-edge technologies such as gaming, virtual reality, and Alexa." # educate_2: "Learn more and sign up here" # future_eng_1: "You can also try to build your own school facts skill for Alexa" # future_eng_2: "here" # future_eng_3: "(device is not required). This Alexa activity is brought to you by the" # future_eng_4: "Amazon Future Engineer" # future_eng_5: "program which creates learning and work opportunities for all K-12 students in the United States who wish to pursue computer science." play_game_dev_level: created_by: "Criado por {{name}}" created_during_hoc: "Criado durante a Hora do Código" restart: "Recomeçar Nível" play: "Jogar Nível" play_more_codecombat: "Jogar Mais CodeCombat" default_student_instructions: "Clica para controlares o teu herói e ganhares o teu jogo!" goal_survive: "Sobrevive." goal_survive_time: "Sobrevive por __seconds__ segundos." goal_defeat: "Derrota todos os inimigos." goal_defeat_amount: "Derrota __amount__ inimigos." # goal_move: "Move to all the red X marks." # goal_collect: "Collect all the items." # goal_collect_amount: "Collect __amount__ items." game_menu: inventory_tab: "Inventário" save_load_tab: "Guardar/Carregar" options_tab: "Opções" guide_tab: "Guia" guide_video_tutorial: "Tutorial em Vídeo" guide_tips: "Dicas" multiplayer_tab: "Multijogador" auth_tab: "Regista-te" inventory_caption: "Equipa o teu herói" choose_hero_caption: "Escolhe o herói, a linguagem" options_caption: "Configura as definições" guide_caption: "Documentos e dicas" multiplayer_caption: "Joga com amigos!" auth_caption: "Guarda o teu progresso." leaderboard: view_other_solutions: "Ver Tabelas de Classificação" scores: "Pontuações" top_players: "Melhores Jogadores por" day: "Hoje" week: "Esta Semana" all: "Sempre" latest: "Mais Recentes" time: "Tempo de Vitória" damage_taken: "Dano Recebido" damage_dealt: "Dano Infligido" difficulty: "Dificuldade" gold_collected: "Ouro Recolhido" # survival_time: "Survived" defeated: "Inimigos Derrotados" code_length: "Linhas de Código" score_display: "__scoreType__: __score__" inventory: equipped_item: "Equipado" required_purchase_title: "Necessário" available_item: "Disponível" restricted_title: "Restrito" should_equip: "(clica duas vezes para equipares)" equipped: "(equipado)" locked: "(bloqueado)" restricted: "(restrito neste nível)" equip: "Equipar" unequip: "Desequipar" warrior_only: "Apenas Guerreiros" ranger_only: "Apenas Arqueiros" wizard_only: "Apenas Feiticeiros" buy_gems: few_gems: "Algumas gemas" pile_gems: "Pilha de gemas" chest_gems: "Arca de gemas" purchasing: "A Adquirir..." declined: "O teu cartão foi recusado." retrying: "Erro do servidor, a tentar novamente." prompt_title: "Sem Gemas Suficientes" prompt_body: "Queres obter mais?" prompt_button: "Entra na Loja" recovered: "A compra de gemas anterior foi recuperada. Por favor atualiza a página." price: "x{{gems}} / mês" buy_premium: "Comprar 'Premium'" purchase: "Adquirir" purchased: "Adquirido" subscribe_for_gems: prompt_title: "Gemas Insuficientes!" # prompt_body: "Subscribe to Premium to get gems and access to even more levels!" earn_gems: prompt_title: "Gemas Insuficientes" prompt_body: "Continua a jogar para receberes mais!" subscribe: # best_deal: "Best Deal!" # confirmation: "Congratulations! You now have a CodeCombat Premium Subscription!" # premium_already_subscribed: "You're already subscribed to Premium!" subscribe_modal_title: "CodeCombat 'Premium'" comparison_blurb: "Torna-te um Programador Mestre - subscreve-te ao <b>'Premium'</b> hoje!" must_be_logged: "Primeiro tens de ter sessão iniciada. Por favor, cria uma conta ou inicia sessão a partir do menu acima." subscribe_title: "Subscrever" # Actually used in subscribe buttons, too unsubscribe: "Cancelar Subscrição" confirm_unsubscribe: "Confirmar Cancelamento da Subscrição" never_mind: "Não Importa, Gostamos de Ti à Mesma" thank_you_months_prefix: "Obrigado por nos teres apoiado neste(s) último(s)" thank_you_months_suffix: "mês(meses)." thank_you: "Obrigado por apoiares o CodeCombat." sorry_to_see_you_go: "Lamentamos ver-te partir! Por favor, diz-nos o que podíamos ter feito melhor." unsubscribe_feedback_placeholder: "Oh, o que fomos fazer?" stripe_description: "Subscrição Mensal" buy_now: "Comprar Agora" subscription_required_to_play: "Precisas de uma subscrição para jogares este nível." unlock_help_videos: "Subscreve-te para desbloqueares todos os tutoriais em vídeo." personal_sub: "Subscrição Pessoal" # Accounts Subscription View below loading_info: "A carregar as informações da subscrição..." managed_by: "Gerida por" will_be_cancelled: "Será cancelada em" currently_free: "Atualmente tens uma subscrição gratuita" currently_free_until: "Atualmente tens uma subscrição até" free_subscription: "Subscrição gratuita" was_free_until: "Tinhas uma subscrição gratuita até" managed_subs: "Subscrições Geridas" subscribing: "A Subscrever..." current_recipients: "Beneficiários Atuais" unsubscribing: "A Cancelar a Subscrição" subscribe_prepaid: "Clica em Subscrever para usares um código pré-pago" using_prepaid: "A usar um código pré-pago para a subscrição mensal" feature_level_access: "Acede a 300+ níveis disponíveis" feature_heroes: "Desbloqueia heróis e animais exclusivos" feature_learn: "Aprende a criar jogos e websites" month_price: "$__price__" first_month_price: "Apenas $__price__ pelo teu primeiro mês!" lifetime: "Acesso Vitalício" lifetime_price: "$__price__" year_subscription: "Subscrição Anual" year_price: "$__price__/ano" support_part1: "Precisas de ajuda com o pagamento ou preferes PayPal? Envia um e-mail para" support_part2: "support@codecombat.com" # announcement: # now_available: "Now available for subscribers!" # subscriber: "subscriber" # cuddly_companions: "Cuddly Companions!" # Pet Announcement Modal # kindling_name: "Kindling Elemental" # kindling_description: "Kindling Elementals just want to keep you warm at night. And during the day. All the time, really." # griffin_name: "Baby Griffin" # griffin_description: "Griffins are half eagle, half lion, all adorable." # raven_name: "Raven" # raven_description: "Ravens are excellent at gathering shiny bottles full of health for you." # mimic_name: "Mimic" # mimic_description: "Mimics can pick up coins for you. Move them on top of coins to increase your gold supply." # cougar_name: "Cougar" # cougar_description: "Cougars like to earn a PhD by Purring Happily Daily." # fox_name: "Blue Fox" # fox_description: "Blue foxes are very clever and love digging in the dirt and snow!" # pugicorn_name: "Pugicorn" # pugicorn_description: "Pugicorns are some of the rarest creatures and can cast spells!" # wolf_name: "Wolf Pup" # wolf_description: "Wolf pups excel in hunting, gathering, and playing a mean game of hide-and-seek!" # ball_name: "Red Squeaky Ball" # ball_description: "ball.squeak()" # collect_pets: "Collect pets for your heroes!" # each_pet: "Each pet has a unique helper ability!" # upgrade_to_premium: "Become a {{subscriber}} to equip pets." # play_second_kithmaze: "Play {{the_second_kithmaze}} to unlock the Wolf Pup!" # the_second_kithmaze: "The Second Kithmaze" # keep_playing: "Keep playing to discover the first pet!" # coming_soon: "Coming soon" # ritic: "Ritic the Cold" # Ritic Announcement Modal # ritic_description: "Ritic the Cold. Trapped in Kelvintaph Glacier for countless ages, finally free and ready to tend to the ogres that imprisoned him." # ice_block: "A block of ice" # ice_description: "There appears to be something trapped inside..." # blink_name: "Blink" # blink_description: "Ritic disappears and reappears in a blink of an eye, leaving nothing but a shadow." # shadowStep_name: "Shadowstep" # shadowStep_description: "A master assassin knows how to walk between the shadows." # tornado_name: "Tornado" # tornado_description: "It is good to have a reset button when one's cover is blown." # wallOfDarkness_name: "Wall of Darkness" # wallOfDarkness_description: "Hide behind a wall of shadows to prevent the gaze of prying eyes." # avatar_selection: # pick_an_avatar: "Pick an avatar that will represent you as a player" # premium_features: # get_premium: "Get<br>CodeCombat<br>Premium" # Fit into the banner on the /features page # master_coder: "Become a Master Coder by subscribing today!" # paypal_redirect: "You will be redirected to PayPal to complete the subscription process." # subscribe_now: "Subscribe Now" # hero_blurb_1: "Get access to __premiumHeroesCount__ super-charged subscriber-only heroes! Harness the unstoppable power of Okar Stompfoot, the deadly precision of Naria of the Leaf, or summon \"adorable\" skeletons with Nalfar Cryptor." # hero_blurb_2: "Premium Warriors unlock stunning martial skills like Warcry, Stomp, and Hurl Enemy. Or, play as a Ranger, using stealth and bows, throwing knives, traps! Try your skill as a true coding Wizard, and unleash a powerful array of Primordial, Necromantic or Elemental magic!" # hero_caption: "Exciting new heroes!" # pet_blurb_1: "Pets aren't just adorable companions, they also provide unique functionality and methods. The Baby Griffin can carry units through the air, the Wolf Pup plays catch with enemy arrows, the Cougar is fond of chasing ogres around, and the Mimic attracts coins like a magnet!" # pet_blurb_2: "Collect all the pets to discover their unique abilities!" # pet_caption: "Adopt pets to accompany your hero!" # game_dev_blurb: "Learn game scripting and build new levels to share with your friends! Place the items you want, write code for unit logic and behavior, and see if your friends can beat the level!" # game_dev_caption: "Design your own games to challenge your friends!" # everything_in_premium: "Everything you get in CodeCombat Premium:" # list_gems: "Receive bonus gems to buy gear, pets, and heroes" # list_levels: "Gain access to __premiumLevelsCount__ more levels" # list_heroes: "Unlock exclusive heroes, include Ranger and Wizard classes" # list_game_dev: "Make and share games with friends" # list_web_dev: "Build websites and interactive apps" # list_items: "Equip Premium-only items like pets" # list_support: "Get Premium support to help you debug tricky code" # list_clans: "Create private clans to invite your friends and compete on a group leaderboard" choose_hero: choose_hero: "Escolhe o Teu Herói" programming_language: "Linguagem de Programação" programming_language_description: "Que linguagem de programação queres usar?" default: "Predefinida" experimental: "Experimental" python_blurb: "Simples mas poderoso; ótimo para iniciantes e peritos." javascript_blurb: "A linguagem da web. (Não é o mesmo que Java.)" coffeescript_blurb: "Javascript com sintaxe mais agradável." lua_blurb: "Linguagem para scripts de jogos." java_blurb: "(Apenas para Subscritores) Android e empresas." # cpp_blurb: "(Subscriber Only) Game development and high performance computing." status: "Estado" weapons: "Armas" weapons_warrior: "Espadas - Curto Alcance, Sem Magia" weapons_ranger: "Arcos, Armas - Longo Alcance, Sem Magia" weapons_wizard: "Varinhas, Bastões - Longo Alcance, Magia" attack: "Ataque" # Can also translate as "Attack" health: "Vida" speed: "Velocidade" regeneration: "Regeneração" range: "Alcance" # As in "attack or visual range" blocks: "Bloqueia" # As in "this shield blocks this much damage" backstab: "Colateral" # As in "this dagger does this much backstab damage" skills: "Habilidades" attack_1: "Dá" attack_2: "do dano da arma do" attack_3: "apresentado." health_1: "Ganha" health_2: "da vida da armadura do" health_3: "apresentado." speed_1: "Move a" speed_2: "metros por segundo." available_for_purchase: "Disponível para Aquisição" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nível para desbloquear:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Apenas certos heróis podem jogar este nível." # char_customization_modal: # heading: "Customize Your Hero" # body: "Body" # name_label: "Hero's Name" # hair_label: "Hair Color" # skin_label: "Skin Color" skill_docs: function: "função" # skill types method: "método" snippet: "fragmento" number: "número" array: "'array'" object: "objeto" string: "'string'" writable: "editável" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "apenas leitura" action: "Ação -" spell: "Feitiço -" action_name: "nome" action_cooldown: "Demora" action_specific_cooldown: "Tempo de Recarga" action_damage: "Dano" action_range: "Alcance" action_radius: "Raio" action_duration: "Duração" example: "Exemplo" ex: "ex" # Abbreviation of "example" current_value: "Valor Atual" default_value: "Valor Predefinido" parameters: "Parâmetros" required_parameters: "Parâmetros Necessários" optional_parameters: "Parâmetros Opcionais" returns: "Devolve" granted_by: "Garantido por" # still_undocumented: "Still undocumented, sorry." save_load: granularity_saved_games: "Guardados" granularity_change_history: "Histórico" options: general_options: "Opções Gerais" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volume" music_label: "Música" music_description: "Ativar ou desativar a música de fundo." editor_config_title: "Configurar Editor" editor_config_livecompletion_label: "Auto-completação em Tempo Real" editor_config_livecompletion_description: "Mostrar sugestões de auto-completação aquando da escrita." editor_config_invisibles_label: "Mostrar Invisíveis" editor_config_invisibles_description: "Mostrar invisíveis tais como espaços e tabulações." editor_config_indentguides_label: "Mostrar Guias de Indentação" editor_config_indentguides_description: "Mostrar linhas verticais para se ver melhor a indentação." editor_config_behaviors_label: "Comportamentos Inteligentes" editor_config_behaviors_description: "Auto-completar parênteses, chavetas e aspas." about: # title: "About CodeCombat - Engaging Students, Empowering Teachers, Inspiring Creation" # meta_description: "Our mission is to level computer science through game-based learning and make coding accessible to every learner. We believe programming is magic and want learners to be empowered to to create things from pure imagination." learn_more: "Saber Mais" main_title: "Se queres aprender a programar, precisas de escrever (muito) código." main_description: "No CodeCombat, o nosso trabalho é certificarmo-nos de que estás a fazer isso com um sorriso na cara." mission_link: "Missão" team_link: "Equipa" story_link: "História" press_link: "Imprensa" mission_title: "A nossa missão: tornar a programação acessível a todos os estudantes da Terra." mission_description_1: "<strong>A programação é mágica</strong>. É a capacidade de criar coisas a partir de imaginação pura. Começamos o CodeCombat para dar aos utilizadores a sensação de terem poderes mágicos nas pontas dos dedos ao usarem <strong>código escrito</strong>." # mission_description_2: "As it turns out, that enables them to learn faster too. WAY faster. It's like having a conversation instead of reading a manual. We want to bring that conversation to every school and to <strong>every student</strong>, because everyone should have the chance to learn the magic of programming." team_title: "Conhece a equipa do CodeCombat" # team_values: "We value open and respectful dialog, where the best idea wins. Our decisions are grounded in customer research and our process is focused on delivering tangible results for them. Everyone is hands-on, from our CEO to our GitHub contributors, because we value growth and learning in our team." nick_title: "Co-fundador, CEO" matt_title: "Co-fundador, CTO" cat_title: "Designer de Jogos" scott_title: "Co-fundador, Engenheiro de Software" maka_title: "Defensor dos Clientes" robin_title: "Gestora de Produto Sénior" nolan_title: "Gestor de Vendas" david_title: "Líder de Marketing" titles_csm: "Gerente de Sucesso do Cliente" titles_territory_manager: "Gestora de Território" # lawrence_title: "Customer Success Manager" # sean_title: "Senior Account Executive" # liz_title: "Senior Account Executive" # jane_title: "Account Executive" # shan_title: "Partnership Development Lead, China" # run_title: "Head of Operations, China" # lance_title: "Software Engineer Intern, China" # matias_title: "Senior Software Engineer" # ryan_title: "Customer Support Specialist" # maya_title: "Senior Curriculum Developer" # bill_title: "General Manager, China" # shasha_title: "Product and Visual Designer" # daniela_title: "Marketing Manager" # chelsea_title: "Operations Manager" # claire_title: "Executive Assistant" # bobby_title: "Game Designer" # brian_title: "Lead Game Designer" # andrew_title: "Software Engineer" # stephanie_title: "Customer Support Specialist" # rob_title: "Sales Development Representative" # shubhangi_title: "Senior Software Engineer" retrostyle_title: "Ilustração" retrostyle_blurb: "'RetroStyle Games'" # bryukh_title: "Gameplay Developer" bryukh_blurb: "Constrói puzzles" community_title: "...e a nossa comunidade open source" community_subtitle: "Mais de 500 contribuidores ajudaram a construir o CodeCombat, com mais a se juntarem todas as semanas!" community_description_3: "O CodeCombat é um" community_description_link_2: "projeto comunitário" # community_description_1: "with hundreds of players volunteering to create levels, contribute to our code to add features, fix bugs, playtest, and even translate the game into 50 languages so far. Employees, contributors and the site gain by sharing ideas and pooling effort, as does the open source community in general. The site is built on numerous open source projects, and we are open sourced to give back to the community and provide code-curious players a familiar project to explore and experiment with. Anyone can join the CodeCombat community! Check out our" community_description_link: "página de contribuição" community_description_2: "para mais informações." number_contributors: "Mais de 450 contribuidores deram o seu apoio e tempo a este projeto." story_title: "A nossa história até agora" story_subtitle: "Desde 2013, o CodeCombat cresceu de um mero conjunto de esboços para um jogo palpável e próspero." story_statistic_1a: "5,000,000+" story_statistic_1b: "jogadores no total" story_statistic_1c: "começaram a jornada de programação deles pelo CodeCombat" story_statistic_2a: "Fomos traduzidos para mais de 50 idiomas — os nossos jogadores saudam a partir de" story_statistic_2b: "190+ países" story_statistic_3a: "Juntos, eles escreveram" story_statistic_3b: "mil milhões de linhas de código (e continua a contar)" story_statistic_3c: "em muitas linguagens de programação diferentes" # story_long_way_1: "Though we've come a long way..." # story_sketch_caption: "Nick's very first sketch depicting a programming game in action." # story_long_way_2: "we still have much to do before we complete our quest, so..." # jobs_title: "Come work with us and help write CodeCombat history!" # jobs_subtitle: "Don't see a good fit but interested in keeping in touch? See our \"Create Your Own\" listing." jobs_benefits: "Benefícios de Empregado" jobs_benefit_4: "Férias ilimitadas" # jobs_benefit_5: "Professional development and continuing education support – free books and games!" # jobs_benefit_6: "Medical (gold), dental, vision, commuter, 401K" # jobs_benefit_7: "Sit-stand desks for all" # jobs_benefit_9: "10-year option exercise window" # jobs_benefit_10: "Maternity leave: 12 weeks paid, next 6 @ 55% salary" # jobs_benefit_11: "Paternity leave: 12 weeks paid" jobs_custom_title: "Cria o Teu Próprio" # jobs_custom_description: "Are you passionate about CodeCombat but don't see a job listed that matches your qualifications? Write us and show how you think you can contribute to our team. We'd love to hear from you!" # jobs_custom_contact_1: "Send us a note at" # jobs_custom_contact_2: "introducing yourself and we might get in touch in the future!" contact_title: "Imprensa e Contactos" contact_subtitle: "Precisas de mais informação? Entra em contacto connosco através de" # screenshots_title: "Game Screenshots" # screenshots_hint: "(click to view full size)" # downloads_title: "Download Assets & Information" about_codecombat: "Sobre o CodeCombat" logo: "Logótipo" # screenshots: "Screenshots" # character_art: "Character Art" # download_all: "Download All" previous: "Anterior" # location_title: "We're located in downtown SF:" teachers: licenses_needed: "Licenças necessárias" special_offer: special_offer: "Oferta Especial" # project_based_title: "Project-Based Courses" # project_based_description: "Web and Game Development courses feature shareable final projects." # great_for_clubs_title: "Great for clubs and electives" # great_for_clubs_description: "Teachers can purchase up to __maxQuantityStarterLicenses__ Starter Licenses." # low_price_title: "Just __starterLicensePrice__ per student" # low_price_description: "Starter Licenses are active for __starterLicenseLengthMonths__ months from purchase." # three_great_courses: "Three great courses included in the Starter License:" # license_limit_description: "Teachers can purchase up to __maxQuantityStarterLicenses__ Starter Licenses. You have already purchased __quantityAlreadyPurchased__. If you need more, contact __supportEmail__. Starter Licenses are valid for __starterLicenseLengthMonths__ months." # student_starter_license: "Student Starter License" # purchase_starter_licenses: "Purchase Starter Licenses" # purchase_starter_licenses_to_grant: "Purchase Starter Licenses to grant access to __starterLicenseCourseList__" # starter_licenses_can_be_used: "Starter Licenses can be used to assign additional courses immediately after purchase." # pay_now: "Pay Now" # we_accept_all_major_credit_cards: "We accept all major credit cards." # cs2_description: "builds on the foundation from Introduction to Computer Science, diving into if-statements, functions, events and more." # wd1_description: "introduces the basics of HTML and CSS while teaching skills needed for students to build their first webpage." # gd1_description: "uses syntax students are already familiar with to show them how to build and share their own playable game levels." # see_an_example_project: "see an example project" # get_started_today: "Get started today!" # want_all_the_courses: "Want all the courses? Request information on our Full Licenses." # compare_license_types: "Compare License Types:" # cs: "Computer Science" # wd: "Web Development" # wd1: "Web Development 1" # gd: "Game Development" # gd1: "Game Development 1" # maximum_students: "Maximum # of Students" # unlimited: "Unlimited" # priority_support: "Priority support" # yes: "Yes" # price_per_student: "__price__ per student" # pricing: "Pricing" # free: "Free" # purchase: "Purchase" # courses_prefix: "Courses" # courses_suffix: "" # course_prefix: "Course" # course_suffix: "" teachers_quote: # subtitle: "Learn more about CodeCombat with an interactive walk through of the product, pricing, and implementation!" # email_exists: "User exists with this email." phone_number: "Número de telemóvel" phone_number_help: "Qual é o melhor número para entrarmos em contacto contigo?" primary_role_label: "O Teu Cargo Principal" role_default: "Selecionar Cargo" # primary_role_default: "Select Primary Role" # purchaser_role_default: "Select Purchaser Role" tech_coordinator: "Coordenador de Tecnologia" # advisor: "Curriculum Specialist/Advisor" principal: "Diretor" superintendent: "Superintendente" parent: "Educador" # purchaser_role_label: "Your Purchaser Role" # influence_advocate: "Influence/Advocate" # evaluate_recommend: "Evaluate/Recommend" # approve_funds: "Approve Funds" # no_purchaser_role: "No role in purchase decisions" district_label: "Distrito" district_name: "Nome do Distrito" district_na: "Escreve N/A se não se aplicar" organization_label: "Escola" school_name: "Nome da Escola" city: "Cidade" state: "Estado" # {change} country: "País" num_students_help: "Quantos estudantes vão usar o CodeCombat?" num_students_default: "Selecionar Intervalo" education_level_label: "Nível de Educação dos Estudantes" education_level_help: "Escolhe todos os que se aplicarem." # elementary_school: "Elementary School" # high_school: "High School" please_explain: "(por favor, explica)" # middle_school: "Middle School" # college_plus: "College or higher" referrer: "Como ouviste falar de nós?" referrer_help: "Por exemplo: através de outro professor, de uma conferência, dos teus estudantes, do Code.org, etc." referrer_default: "Seleciona Um" # referrer_conference: "Conference (e.g. ISTE)" referrer_hoc: "Code.org/Hora do Código" referrer_teacher: "Um professor" referrer_admin: "Um administrador" referrer_student: "Um estudante" # referrer_pd: "Professional trainings/workshops" referrer_web: "Google" referrer_other: "Outro" # anything_else: "What kind of class do you anticipate using CodeCombat for?" # anything_else_helper: "" thanks_header: "Pedido Recebido!" # thanks_sub_header: "Thanks for expressing interest in CodeCombat for your school." # thanks_p: "We'll be in touch soon! If you need to get in contact, you can reach us at:" back_to_classes: "Voltar às Turmas" # finish_signup: "Finish creating your teacher account:" # finish_signup_p: "Create an account to set up a class, add your students, and monitor their progress as they learn computer science." # signup_with: "Sign up with:" connect_with: "Conectar com:" # conversion_warning: "WARNING: Your current account is a <em>Student Account</em>. Once you submit this form, your account will be updated to a Teacher Account." # learn_more_modal: "Teacher accounts on CodeCombat have the ability to monitor student progress, assign licenses and manage classrooms. Teacher accounts cannot be a part of a classroom - if you are currently enrolled in a class using this account, you will no longer be able to access it once you update to a Teacher Account." create_account: "Criar uma Conta de Professor" create_account_subtitle: "Obtém acesso a ferramentas reservadas a professores para usares o CodeCombat na sala de aula. <strong>Cria uma turma</strong>, adiciona os teus estudantes e <strong>monitoriza o progresso deles</strong>!" # convert_account_title: "Update to Teacher Account" # not: "Not" # full_name_required: "First and last name required" versions: save_version_title: "Guardar Nova Versão" new_major_version: "Nova Versão Principal" submitting_patch: "A Submeter Atualização..." cla_prefix: "Para guardares as alterações, precisas de concordar com o nosso" cla_url: "CLA" cla_suffix: "." cla_agree: "EU CONCORDO" owner_approve: "Um administrador terá de aprová-la antes de as tuas alterações ficarem visíveis." contact: contact_us: "Contacta o CodeCombat" welcome: "É bom ter notícias tuas! Usa este formulário para nos enviares um e-mail. " forum_prefix: "Para algo público, por favor usa o " forum_page: "nosso fórum" forum_suffix: " como alternativa." faq_prefix: "Há também uma" faq: "FAQ" subscribe_prefix: "Se precisas de ajuda a perceber um nível, por favor" subscribe: "compra uma subscrição do CodeCombat" subscribe_suffix: "e nós ficaremos felizes por ajudar-te com o teu código." subscriber_support: "Como és um subscritor do CodeCombat, os teus e-mails terão prioridade no nosso suporte." screenshot_included: "Captura de ecrã incluída." where_reply: "Para onde devemos enviar a resposta?" send: "Enviar Feedback" account_settings: title: "Definições da Conta" not_logged_in: "Inicia sessão ou cria uma conta para alterares as tuas definições." me_tab: "Eu" picture_tab: "Fotografia" delete_account_tab: "Elimina a Tua Conta" wrong_email: "E-mail ou Nome de Utilizador Errado" wrong_password: "Palavra-passe Errada" delete_this_account: "Elimina esta conta permanentemente" reset_progress_tab: "Reiniciar Todo o Progresso" reset_your_progress: "Limpar todo o teu progresso e começar de novo" god_mode: "Modo Deus" emails_tab: "E-mails" admin: "Administrador" manage_subscription: "Clica aqui para gerires a tua subscrição." new_password: "Nova Palavra-passe" new_password_verify: "Verificar" type_in_email: "Escreve o teu e-mail ou nome de utilizador para confirmares a eliminação da conta." type_in_email_progress: "Escreve o teu e-mail para confirmares a eliminação do teu progresso." type_in_password: "Escreve também a tua palavra-passe." email_subscriptions: "Subscrições de E-mail" email_subscriptions_none: "Sem Subscições de E-mail." email_announcements: "Anúncios" email_announcements_description: "Recebe e-mails sobre as últimas novidades e desenvolvimentos no CodeCombat." email_notifications: "Notificações" email_notifications_summary: "Controla, de uma forma personalizada e automática, os e-mails de notificações relacionados com a tua atividade no CodeCombat." email_any_notes: "Quaisquer Notificações" email_any_notes_description: "Desativa para parares de receber todos os e-mails de notificação de atividade." email_news: "Notícias" email_recruit_notes: "Oportunidades de Emprego" email_recruit_notes_description: "Se jogas muito bem, podemos contactar-te para te arranjar um (melhor) emprego." contributor_emails: "E-mail Para Contribuintes" contribute_prefix: "Estamos à procura de pessoas para se juntarem a nós! Visita a " contribute_page: "página de contribuição" contribute_suffix: " para mais informações." email_toggle: "Alternar Todos" error_saving: "Erro ao Guardar" saved: "Alterações Guardadas" password_mismatch: "As palavras-passe não coincidem." password_repeat: "Por favor repete a tua palavra-passe." keyboard_shortcuts: keyboard_shortcuts: "Atalhos de Teclado" space: "Espaço" enter: "Enter" press_enter: "pressiona enter" escape: "Esc" shift: "Shift" run_code: "Executar código atual." run_real_time: "Executar em tempo real." continue_script: "Saltar o script atual." skip_scripts: "Saltar todos os scripts saltáveis." toggle_playback: "Alternar entre Jogar e Pausar." scrub_playback: "Andar para a frente e para trás no tempo." single_scrub_playback: "Andar para a frente e para trás no tempo um único frame." scrub_execution: "Analisar a execução do feitiço atual." toggle_debug: "Ativar/desativar a janela de depuração." toggle_grid: "Ativar/desativar a sobreposição da grelha." toggle_pathfinding: "Ativar/desativar a sobreposição do encontrador de caminho." beautify: "Embelezar o código ao estandardizar a formatação." maximize_editor: "Maximizar/minimizar o editor de código." # cinematic: # click_anywhere_continue: "click anywhere to continue" community: main_title: "Comunidade do CodeCombat" introduction: "Confere abaixo as formas de te envolveres e escolhe a que te parece mais divertida. Estamos ansiosos por trabalhar contigo!" level_editor_prefix: "Usa o" level_editor_suffix: "do CodeCombat para criares e editares níveis. Os utilizadores já criaram níveis para aulas, amigos, maratonas hacker, estudantes e familiares. Se criar um nível novo parece intimidante, podes começar por bifurcar um dos nossos!" thang_editor_prefix: "Chamamos 'thangs' às unidades do jogo. Usa o" thang_editor_suffix: "para modificares a arte do CodeCombat. Faz as unidades lançarem projéteis, altera a direção de uma animação, altera os pontos de vida de uma unidade ou anexa as tuas próprias unidades." article_editor_prefix: "Vês um erro em alguns dos nossos documentos? Queres escrever algumas instruções para as tuas próprias criações? Confere o" article_editor_suffix: "e ajuda os jogadores do CodeCombat a obter o máximo do tempo de jogo deles." find_us: "Encontra-nos nestes sítios" social_github: "Confere todo o nosso código no GitHub" social_blog: "Lê o blog do CodeCombat no Sett" social_discource: "Junta-te à discussão no nosso fórum Discourse" social_facebook: "Gosta do CodeCombat no Facebook" social_twitter: "Segue o CodeCombat no Twitter" social_slack: "Fala connosco no canal público do CodeCombat no Slack" contribute_to_the_project: "Contribui para o projeto" clans: # title: "Join CodeCombat Clans - Learn to Code in Python, JavaScript, and HTML" # clan_title: "__clan__ - Join CodeCombat Clans and Learn to Code" # meta_description: "Join a Clan or build your own community of coders. Play multiplayer arena levels and level up your hero and your coding skills." clan: "Clã" clans: "Clãs" new_name: "Nome do novo clã" new_description: "Descrição do novo clã" make_private: "Tornar o clã privado" subs_only: "apenas para subscritores" create_clan: "Criar um Novo Clã" private_preview: "Pré-visualização" private_clans: "Clãs Privados" public_clans: "Clãs Públicos" my_clans: "Os Meus Clãs" clan_name: "Nome do Clã" name: "Nome" chieftain: "Líder" edit_clan_name: "Editar Nome do Clã" edit_clan_description: "Editar Descrição do Clã" edit_name: "editar nome" edit_description: "editar descrição" private: "(privado)" summary: "Resumo" average_level: "Nível em Média" average_achievements: "Conquistas em Média" delete_clan: "Eliminar o Clã" leave_clan: "Abandonar o Clã" join_clan: "Entrar no Clã" invite_1: "Convidar:" invite_2: "*Convida jogadores para este Clã enviando-lhes esta ligação." members: "Membros" progress: "Progresso" not_started_1: "não começado" started_1: "começado" complete_1: "completo" exp_levels: "Expandir os níveis" rem_hero: "Remover Herói" status: "Estado" complete_2: "Completo" started_2: "Começado" not_started_2: "Não Começado" view_solution: "Clica para veres a solução." view_attempt: "Clica para veres a tentativa." latest_achievement: "Última Conquista" playtime: "Tempo de jogo" last_played: "Última vez jogado" leagues_explanation: "Joga numa liga contra outros membros do clã nestas instâncias de arenas multijogador." track_concepts1: "Acompanhe os conceitos" track_concepts2a: "aprendidos por cada estudante" track_concepts2b: "aprendidos por cada membro" track_concepts3a: "Acompanhe os níveis completados por cada estudante" track_concepts3b: "Acompanhe os níveis completados por cada membro" track_concepts4a: "Veja, dos seus estudantes, as" track_concepts4b: "Veja, dos seus membros, as" track_concepts5: "soluções" track_concepts6a: "Ordene os estudantes por nome ou progresso" track_concepts6b: "Ordene os membros por nome ou progresso" track_concepts7: "É necessário um convite" track_concepts8: "para entrar" private_require_sub: "É necessária uma subscrição para criar ou entrar num clã privado." courses: create_new_class: "Criar Turma Nova" # hoc_blurb1: "Try the" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity! Construct four different minigames to learn the basics of game development, then make your own!" solutions_require_licenses: "As soluções dos níveis estão disponíveis para professores que tenham licenças." unnamed_class: "Turma Sem Nome" edit_settings1: "Editar Definições da Turma" add_students: "Adicionar Estudantes" stats: "Estatísticas" # student_email_invite_blurb: "Your students can also use class code <strong>__classCode__</strong> when creating a Student Account, no email required." total_students: "Estudantes no total:" average_time: "Média do tempo de jogo do nível:" total_time: "Tempo de jogo total:" average_levels: "Média de níveis completos:" total_levels: "Total de níveis completos:" students: "Estudantes" concepts: "Conceitos" play_time: "Tempo de jogo:" completed: "Completos:" enter_emails: "Separa cada endereço de e-mail com uma quebra de linha ou vírgulas" send_invites: "Convidar Estudantes" number_programming_students: "Número de Estudantes" number_total_students: "Total de Estudantes na Escola/Distrito" enroll: "Inscrever" enroll_paid: "Inscrever Estudantes em Cursos Pagos" get_enrollments: "Obter Mais Licenças" change_language: "Alterar Linguagem do Curso" keep_using: "Continuar a Usar" switch_to: "Mudar Para" greetings: "Saudações!" back_classrooms: "Voltar às minhas turmas" back_classroom: "Voltar à turma" back_courses: "Voltar aos meus cursos" edit_details: "Editar detalhes da turma" purchase_enrollments: "Adquirir Licenças de Estudante" remove_student: "remover estudante" # assign: "Assign" # to_assign: "to assign paid courses." student: "Estudante" teacher: "Professor" arena: "Arena" available_levels: "Níveis Disponíveis" started: "começado" complete: "completado" practice: "prática" required: "obrigatório" welcome_to_courses: "Aventureiros, sejam bem-vindos aos Cursos!" ready_to_play: "Pronto para jogar?" start_new_game: "Começar Novo Jogo" play_now_learn_header: "Joga agora para aprenderes" # play_now_learn_1: "basic syntax to control your character" # play_now_learn_2: "while loops to solve pesky puzzles" # play_now_learn_3: "strings & variables to customize actions" # play_now_learn_4: "how to defeat an ogre (important life skills!)" welcome_to_page: "O Meu Painel de Estudante" my_classes: "Turmas Atuais" class_added: "Turma adicionada com sucesso!" # view_map: "view map" # view_videos: "view videos" view_project_gallery: "ver os projetos dos meus colegas" join_class: "Entrar Numa Turma" join_class_2: "Entrar na turma" ask_teacher_for_code: "Pergunta ao teu professor se tens um código de turma do CodeCombat! Se tiveres, introdu-lo abaixo:" enter_c_code: "<Introduzir Código de Turma>" join: "Entrar" joining: "A entrar na turma" course_complete: "Curso Completo" play_arena: "Jogar na Arena" view_project: "Ver Projeto" start: "Começar" last_level: "Último nível jogado" not_you: "Não és tu?" continue_playing: "Continuar a Jogar" option1_header: "Convidar Estudantes por E-mail" remove_student1: "Remover Estudante" are_you_sure: "Tens a certeza de que queres remover este estudante desta turma?" # remove_description1: "Student will lose access to this classroom and assigned classes. Progress and gameplay is NOT lost, and the student can be added back to the classroom at any time." # remove_description2: "The activated paid license will not be returned." # license_will_revoke: "This student's paid license will be revoked and made available to assign to another student." keep_student: "Manter Estudante" removing_user: "A remover utilizador" subtitle: "Revê visões gerais de cursos e níveis" # Flat style redesign # changelog: "View latest changes to course levels." select_language: "Selecionar linguagem" select_level: "Selecionar nível" play_level: "Jogar Nível" concepts_covered: "Conceitos Abordados" view_guide_online: "Visões Gerais e Soluções do Nível" grants_lifetime_access: "Garante acesso a todos os Cursos." enrollment_credits_available: "Licenças Disponíveis:" language_select: "Seleciona uma linguagem" # ClassroomSettingsModal language_cannot_change: "A linguagem não pode ser alterada depois de estudantes entrarem numa turma." avg_student_exp_label: "Experiência Média de Programação dos Estudantes" avg_student_exp_desc: "Isto vai-nos ajudar a perceber qual o melhor andamento para os cursos." avg_student_exp_select: "Seleciona a melhor opção" avg_student_exp_none: "Nenhuma Experiência - pouca ou nenhuma experiência" avg_student_exp_beginner: "Iniciante - alguma exposição ou baseada em blocos" avg_student_exp_intermediate: "Intermédia - alguma experiência com código escrito" avg_student_exp_advanced: "Avançada - muita experiência com código escrito" avg_student_exp_varied: "Vários Níveis de Experiência" student_age_range_label: "Intervalo de Idades dos Estudantes" student_age_range_younger: "Menos de 6" student_age_range_older: "Mais de 18" student_age_range_to: "até" # estimated_class_dates_label: "Estimated Class Dates" # estimated_class_frequency_label: "Estimated Class Frequency" # classes_per_week: "classes per week" # minutes_per_class: "minutes per class" create_class: "Criar Turma" class_name: "Nome da Turma" # teacher_account_restricted: "Your account is a teacher account and cannot access student content." account_restricted: "É necessária uma conta de estudante para acederes a esta página." # update_account_login_title: "Log in to update your account" update_account_title: "A tua conta precisa de atenção!" # update_account_blurb: "Before you can access your classes, choose how you want to use this account." # update_account_current_type: "Current Account Type:" # update_account_account_email: "Account Email/Username:" update_account_am_teacher: "Sou um professor" # update_account_keep_access: "Keep access to classes I've created" # update_account_teachers_can: "Teacher accounts can:" # update_account_teachers_can1: "Create/manage/add classes" # update_account_teachers_can2: "Assign/enroll students in courses" # update_account_teachers_can3: "Unlock all course levels to try out" # update_account_teachers_can4: "Access new teacher-only features as we release them" # update_account_teachers_warning: "Warning: You will be removed from all classes that you have previously joined and will not be able to play as a student." # update_account_remain_teacher: "Remain a Teacher" # update_account_update_teacher: "Update to Teacher" update_account_am_student: "Sou um estudante" # update_account_remove_access: "Remove access to classes I have created" # update_account_students_can: "Student accounts can:" # update_account_students_can1: "Join classes" # update_account_students_can2: "Play through courses as a student and track your own progress" # update_account_students_can3: "Compete against classmates in arenas" # update_account_students_can4: "Access new student-only features as we release them" # update_account_students_warning: "Warning: You will not be able to manage any classes that you have previously created or create new classes." # unsubscribe_warning: "Warning: You will be unsubscribed from your monthly subscription." # update_account_remain_student: "Remain a Student" # update_account_update_student: "Update to Student" # need_a_class_code: "You'll need a Class Code for the class you're joining:" # update_account_not_sure: "Not sure which one to choose? Email" # update_account_confirm_update_student: "Are you sure you want to update your account to a Student experience?" # update_account_confirm_update_student2: "You will not be able to manage any classes that you have previously created or create new classes. Your previously created classes will be removed from CodeCombat and cannot be restored." # instructor: "Instructor: " # youve_been_invited_1: "You've been invited to join " # youve_been_invited_2: ", where you'll learn " # youve_been_invited_3: " with your classmates in CodeCombat." # by_joining_1: "By joining " # by_joining_2: "will be able to help reset your password if you forget or lose it. You can also verify your email address so that you can reset the password yourself!" # sent_verification: "We've sent a verification email to:" # you_can_edit: "You can edit your email address in " # account_settings: "Account Settings" select_your_hero: "Seleciona o Teu Herói" select_your_hero_description: "Podes sempre alterar o teu herói ao acederes à tua página de Cursos e clicares em \"Alterar Herói\"" select_this_hero: "Selecionar este herói" current_hero: "Herói Atual:" current_hero_female: "Heroína Atual:" # web_dev_language_transition: "All classes program in HTML / JavaScript for this course. Classes that have been using Python will start with extra JavaScript intro levels to ease the transition. Classes that are already using JavaScript will skip the intro levels." course_membership_required_to_play: "Precisas de te juntar a um curso para jogares este nível." # license_required_to_play: "Ask your teacher to assign a license to you so you can continue to play CodeCombat!" # update_old_classroom: "New school year, new levels!" # update_old_classroom_detail: "To make sure you're getting the most up-to-date levels, make sure you create a new class for this semester by clicking Create a New Class on your" # teacher_dashboard: "teacher dashboard" # update_old_classroom_detail_2: "and giving students the new Class Code that appears." # view_assessments: "View Assessments" # view_challenges: "view challenge levels" # view_ranking: "view ranking" # ranking_position: "Position" # ranking_players: "Players" # ranking_completed_leves: "Completed levels" # challenge: "Challenge:" # challenge_level: "Challenge Level:" status: "Estado:" # assessments: "Assessments" challenges: "Desafios" level_name: "Nome do Nível:" # keep_trying: "Keep Trying" start_challenge: "Começar Desafio" # locked: "Locked" concepts_used: "Conceitos Usados:" # show_change_log: "Show changes to this course's levels" # hide_change_log: "Hide changes to this course's levels" # concept_videos: "Concept Videos" # concept: "Concept:" # basic_syntax: "Basic Syntax" # while_loops: "While Loops" # variables: "Variables" # basic_syntax_desc: "Syntax is how we write code. Just as spelling and grammar are important in writing narratives and essays, syntax is important when writing code. Humans are good at figuring out what something means, even if it isn't exactly correct, but computers aren't that smart, and they need you to write very precisely." # while_loops_desc: "A loop is a way of repeating actions in a program. You can use them so you don't have to keep writing repetitive code, and when you don't know exactly how many times an action will need to occur to accomplish a task." # variables_desc: "Working with variables is like organizing things in shoeboxes. You give the shoebox a name, like \"School Supplies\", and then you put things inside. The exact contents of the box might change over time, but whatever's inside will always be called \"School Supplies\". In programming, variables are symbols used to store data that will change over the course of the program. Variables can hold a variety of data types, including numbers and strings." # locked_videos_desc: "Keep playing the game to unlock the __concept_name__ concept video." # unlocked_videos_desc: "Review the __concept_name__ concept video." # video_shown_before: "shown before __level__" # link_google_classroom: "Link Google Classroom" # select_your_classroom: "Select Your Classroom" # no_classrooms_found: "No classrooms found" # create_classroom_manually: "Create classroom manually" # classes: "Classes" # certificate_btn_print: "Print" # certificate_btn_toggle: "Toggle" # ask_next_course: "Want to play more? Ask your teacher for access to the next course." # set_start_locked_level: "Set start locked level" # no_level_limit: "No limit" project_gallery: no_projects_published: "Sê o primeiro a publicar um projeto neste curso!" view_project: "Ver Projeto" edit_project: "Editar Projeto" teacher: # assigning_course: "Assigning course" back_to_top: "Voltar ao Topo" # click_student_code: "Click on any level that the student has started or completed below to view the code they wrote." code: "Código de __name__" complete_solution: "Solução Completa" # course_not_started: "Student has not started this course yet." # appreciation_week_blurb1: "For <strong>Teacher Appreciation Week 2019</strong>, we are offering free 1-week licenses!<br />Email Rob Arevalo (<a href=\"mailto:robarev@codecombat.com?subject=Teacher Appreciation Week\">robarev@codecombat.com</a>) with subject line \"<strong>Teacher Appreciation Week</strong>\", and include:" # appreciation_week_blurb2: "the quantity of 1-week licenses you'd like (1 per student)" # appreciation_week_blurb3: "the email address of your CodeCombat teacher account" # appreciation_week_blurb4: "whether you'd like licenses for Week 1 (May 6-10) or Week 2 (May 13-17)" # hoc_happy_ed_week: "Happy Computer Science Education Week!" # hoc_blurb1: "Learn about the free" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity, download a new teacher lesson plan, and tell your students to log in to play!" # hoc_button_text: "View Activity" # no_code_yet: "Student has not written any code for this level yet." # open_ended_level: "Open-Ended Level" partial_solution: "Solução Parcial" # capstone_solution: "Capstone Solution" removing_course: "A remover o curso" # solution_arena_blurb: "Students are encouraged to solve arena levels creatively. The solution provided below meets the requirements of the arena level." # solution_challenge_blurb: "Students are encouraged to solve open-ended challenge levels creatively. One possible solution is displayed below." # solution_project_blurb: "Students are encouraged to build a creative project in this level. Please refer to curriculum guides in the Resource Hub for information on how to evaluate these projects." # students_code_blurb: "A correct solution to each level is provided where appropriate. In some cases, it’s possible for a student to solve a level using different code. Solutions are not shown for levels the student has not started." # course_solution: "Course Solution" # level_overview_solutions: "Level Overview and Solutions" # no_student_assigned: "No students have been assigned this course." # paren_new: "(new)" student_code: "Código de Estudante de __name__" teacher_dashboard: "Painel do Professor" # Navbar my_classes: "As Minhas Turmas" courses: "Guias dos Cursos" enrollments: "Licenças de Estudantes" resources: "Recursos" help: "Ajuda" language: "Linguagem" edit_class_settings: "editar definições da turma" access_restricted: "Atualização de Conta Necessária" teacher_account_required: "É necessária uma conta de professor para acederes a este conteúdo." create_teacher_account: "Criar Conta de Professor" what_is_a_teacher_account: "O que é uma Conta de Professor?" # teacher_account_explanation: "A CodeCombat Teacher account allows you to set up classrooms, monitor students’ progress as they work through courses, manage licenses and access resources to aid in your curriculum-building." current_classes: "Turmas Atuais" archived_classes: "Turmas Arquivadas" archived_classes_blurb: "As turmas podem ser arquivadas para referência futura. Desarquiva uma turma para a veres novamente na lista das Turmas Atuais." view_class: "ver turma" archive_class: "arquivar turma" unarchive_class: "desarquivar turma" unarchive_this_class: "Desarquivar esta turma" no_students_yet: "Esta turma ainda não tem estudantes." no_students_yet_view_class: "Ver turma para adicionar estudantes." try_refreshing: "(Podes precisar de atualizar a página)" create_new_class: "Criar uma Turma Nova" class_overview: "Visão Geral da Turma" # View Class page avg_playtime: "Tempo de jogo médio por nível" total_playtime: "Tempo de jogo total" avg_completed: "Média de níveis completos" total_completed: "Totalidade dos níveis completos" created: "Criada" concepts_covered: "Conceitos abordados" earliest_incomplete: "Nível mais básico incompleto" latest_complete: "Último nível completo" enroll_student: "Inscrever estudante" apply_license: "Aplicar Licença" revoke_license: "Revogar Licença" revoke_licenses: "Revogar Todas as Licenças" course_progress: "Progresso dos Cursos" not_applicable: "N/A" edit: "editar" edit_2: "Editar" remove: "remover" latest_completed: "Último completo:" sort_by: "Ordenar por" progress: "Progresso" concepts_used: "Conceitos usados pelo Estudante:" # concept_checked: "Concept checked:" completed: "Completaram" practice: "Prática" started: "Começaram" no_progress: "Nenhum progresso" # not_required: "Not required" # view_student_code: "Click to view student code" select_course: "Seleciona o curso para ser visto" progress_color_key: "Esquema de cores do progresso:" level_in_progress: "Nível em Progresso" level_not_started: "Nível Não Começado" project_or_arena: "Projeto ou Arena" # students_not_assigned: "Students who have not been assigned {{courseName}}" # course_overview: "Course Overview" copy_class_code: "Copiar Código de Turma" class_code_blurb: "Os estudantes podem entrar na tua turma ao usarem este Código de Turma. Não é necessário nenhum endereço de e-mail aquando da criação de uma conta de Estudante com este Código de Turma." copy_class_url: "Copiar URL da Turma" class_join_url_blurb: "Também podes publicar este URL único da turma numa página web partilhada." add_students_manually: "Convidar Estudantes por E-mail" bulk_assign: "Selecionar curso" # assigned_msg_1: "{{numberAssigned}} students were assigned {{courseName}}." assigned_msg_2: "{{numberEnrolled}} licenças foram aplicadas." # assigned_msg_3: "You now have {{remainingSpots}} available licenses remaining." assign_course: "Atribuir Curso" removed_course_msg: "{{numberRemoved}} estudantes foram removidos de {{courseName}}." remove_course: "Remover Curso" not_assigned_modal_title: "Os cursos não foram atribuídos" # not_assigned_modal_starter_body_1: "This course requires a Starter License. You do not have enough Starter Licenses available to assign this course to all __selected__ selected students." # not_assigned_modal_starter_body_2: "Purchase Starter Licenses to grant access to this course." # not_assigned_modal_full_body_1: "This course requires a Full License. You do not have enough Full Licenses available to assign this course to all __selected__ selected students." # not_assigned_modal_full_body_2: "You only have __numFullLicensesAvailable__ Full Licenses available (__numStudentsWithoutFullLicenses__ students do not currently have a Full License active)." # not_assigned_modal_full_body_3: "Please select fewer students, or reach out to __supportEmail__ for assistance." # assigned: "Assigned" enroll_selected_students: "Inscrever os Estudantes Selecionados" no_students_selected: "Nenhum estudante foi selecionado." # show_students_from: "Show students from" # Enroll students modal apply_licenses_to_the_following_students: "Aplicar Licenças aos Seguintes Estudantes" # students_have_licenses: "The following students already have licenses applied:" all_students: "Todos os Estudantes" apply_licenses: "Aplicar Licenças" not_enough_enrollments: "Não há licenças suficientes disponíveis." enrollments_blurb: "É necessário que os estudantes tenham uma licença para acederem a qualquer conteúdo depois do primeiro curso." how_to_apply_licenses: "Como Aplicar Licenças" export_student_progress: "Exportar Progresso dos Estudantes (CSV)" # send_email_to: "Send Recover Password Email to:" email_sent: "E-mail enviado" send_recovery_email: "Enviar e-mail de recuperação" enter_new_password_below: "Introduz a nova palavra-passe abaixo:" change_password: "Alterar Palavra-passe" changed: "Alterada" available_credits: "Licenças Disponíveis" pending_credits: "Licenças Pendentes" # empty_credits: "Exhausted Licenses" license_remaining: "licença restante" licenses_remaining: "licenças restantes" one_license_used: "1 de __totalLicenses__ licenças foi usada" num_licenses_used: "__numLicensesUsed__ de __totalLicenses__ licenças foram usadas" # starter_licenses: "starter licenses" # start_date: "start date:" # end_date: "end date:" get_enrollments_blurb: " Vamos ajudar-te a construir uma solução que satisfaça as necessidades da tua turma, escola ou distrito." # how_to_apply_licenses_blurb_1: "When a teacher assigns a course to a student for the first time, we’ll automatically apply a license. Use the bulk-assign dropdown in your classroom to assign a course to selected students:" # how_to_apply_licenses_blurb_2: "Can I still apply a license without assigning a course?" # how_to_apply_licenses_blurb_3: "Yes — go to the License Status tab in your classroom and click \"Apply License\" to any student who does not have an active license." request_sent: "Pedido Enviado!" # assessments: "Assessments" license_status: "Estado das Licenças" # status_expired: "Expired on {{date}}" status_not_enrolled: "Não Inscrito" # status_enrolled: "Expires on {{date}}" select_all: "Selecionar Todos" project: "Projeto" # project_gallery: "Project Gallery" view_project: "Ver Projeto" unpublished: "(não publicado)" # view_arena_ladder: "View Arena Ladder" resource_hub: "Centro de Recursos" # pacing_guides: "Classroom-in-a-Box Pacing Guides" # pacing_guides_desc: "Learn how to incorporate all of CodeCombat's resources to plan your school year!" # pacing_guides_elem: "Elementary School Pacing Guide" # pacing_guides_middle: "Middle School Pacing Guide" # pacing_guides_high: "High School Pacing Guide" # getting_started: "Getting Started" # educator_faq: "Educator FAQ" # educator_faq_desc: "Frequently asked questions about using CodeCombat in your classroom or school." # teacher_getting_started: "Teacher Getting Started Guide" # teacher_getting_started_desc: "New to CodeCombat? Download this Teacher Getting Started Guide to set up your account, create your first class, and invite students to the first course." # student_getting_started: "Student Quick Start Guide" # student_getting_started_desc: "You can distribute this guide to your students before starting CodeCombat so that they can familiarize themselves with the code editor. This guide can be used for both Python and JavaScript classrooms." # ap_cs_principles: "AP Computer Science Principles" # ap_cs_principles_desc: "AP Computer Science Principles gives students a broad introduction to the power, impact, and possibilities of Computer Science. The course emphasizes computational thinking and problem solving while also teaching the basics of programming." # cs1: "Introduction to Computer Science" # cs2: "Computer Science 2" # cs3: "Computer Science 3" # cs4: "Computer Science 4" # cs5: "Computer Science 5" # cs1_syntax_python: "Course 1 Python Syntax Guide" # cs1_syntax_python_desc: "Cheatsheet with references to common Python syntax that students will learn in Introduction to Computer Science." # cs1_syntax_javascript: "Course 1 JavaScript Syntax Guide" # cs1_syntax_javascript_desc: "Cheatsheet with references to common JavaScript syntax that students will learn in Introduction to Computer Science." coming_soon: "Guias adicionais em breve!" # engineering_cycle_worksheet: "Engineering Cycle Worksheet" # engineering_cycle_worksheet_desc: "Use this worksheet to teach students the basics of the engineering cycle: Assess, Design, Implement and Debug. Refer to the completed example worksheet as a guide." # engineering_cycle_worksheet_link: "View example" # progress_journal: "Progress Journal" # progress_journal_desc: "Encourage students to keep track of their progress via a progress journal." # cs1_curriculum: "Introduction to Computer Science - Curriculum Guide" # cs1_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 1." # arenas_curriculum: "Arena Levels - Teacher Guide" # arenas_curriculum_desc: "Instructions on how to run Wakka Maul, Cross Bones and Power Peak multiplayer arenas with your class." # assessments_curriculum: "Assessment Levels - Teacher Guide" # assessments_curriculum_desc: "Learn how to use Challenge Levels and Combo Challenge levels to assess students' learning outcomes." # cs2_curriculum: "Computer Science 2 - Curriculum Guide" # cs2_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 2." # cs3_curriculum: "Computer Science 3 - Curriculum Guide" # cs3_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 3." # cs4_curriculum: "Computer Science 4 - Curriculum Guide" # cs4_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 4." # cs5_curriculum_js: "Computer Science 5 - Curriculum Guide (JavaScript)" # cs5_curriculum_desc_js: "Scope and sequence, lesson plans, activities and more for Course 5 classes using JavaScript." # cs5_curriculum_py: "Computer Science 5 - Curriculum Guide (Python)" # cs5_curriculum_desc_py: "Scope and sequence, lesson plans, activities and more for Course 5 classes using Python." # cs1_pairprogramming: "Pair Programming Activity" # cs1_pairprogramming_desc: "Introduce students to a pair programming exercise that will help them become better listeners and communicators." # gd1: "Game Development 1" # gd1_guide: "Game Development 1 - Project Guide" # gd1_guide_desc: "Use this to guide your students as they create their first shareable game project in 5 days." # gd1_rubric: "Game Development 1 - Project Rubric" # gd1_rubric_desc: "Use this rubric to assess student projects at the end of Game Development 1." # gd2: "Game Development 2" # gd2_curriculum: "Game Development 2 - Curriculum Guide" # gd2_curriculum_desc: "Lesson plans for Game Development 2." # gd3: "Game Development 3" # gd3_curriculum: "Game Development 3 - Curriculum Guide" # gd3_curriculum_desc: "Lesson plans for Game Development 3." # wd1: "Web Development 1" # wd1_curriculum: "Web Development 1 - Curriculum Guide" # wd1_curriculum_desc: "Scope and sequence, lesson plans, activities, and more for Web Development 1." # wd1_headlines: "Headlines & Headers Activity" # wd1_headlines_example: "View sample solution" # wd1_headlines_desc: "Why are paragraph and header tags important? Use this activity to show how well-chosen headers make web pages easier to read. There are many correct solutions to this!" # wd1_html_syntax: "HTML Syntax Guide" # wd1_html_syntax_desc: "One-page reference for the HTML style students will learn in Web Development 1." # wd1_css_syntax: "CSS Syntax Guide" # wd1_css_syntax_desc: "One-page reference for the CSS and Style syntax students will learn in Web Development 1." # wd2: "Web Development 2" # wd2_jquery_syntax: "jQuery Functions Syntax Guide" # wd2_jquery_syntax_desc: "One-page reference for the jQuery functions students will learn in Web Development 2." # wd2_quizlet_worksheet: "Quizlet Planning Worksheet" # wd2_quizlet_worksheet_instructions: "View instructions & examples" # wd2_quizlet_worksheet_desc: "Before your students build their personality quiz project at the end of Web Development 2, they should plan out their quiz questions, outcomes and responses using this worksheet. Teachers can distribute the instructions and examples for students to refer to." student_overview: "Visão Geral" student_details: "Detalhes do Estudante" student_name: "Nome do Estudante" no_name: "Nenhum nome fornecido." no_username: "Nenhum nome de utilizador fornecido." no_email: "O estudante não tem nenhum endereço de e-mail definido." student_profile: "Perfil do Estudante" playtime_detail: "Detalhe do Tempo de Jogo" student_completed: "Completo pelo Estudante" student_in_progress: "Em progresso pelo Estudante" class_average: "Média da Turma" # not_assigned: "has not been assigned the following courses" playtime_axis: "Tempo de Jogo em Segundos" levels_axis: "Níveis em" student_state: "Como se está" student_state_2: "a sair?" # student_good: "is doing well in" # student_good_detail: "This student is keeping pace with the class." # student_warn: "might need some help in" # student_warn_detail: "This student might need some help with new concepts that have been introduced in this course." # student_great: "is doing great in" # student_great_detail: "This student might be a good candidate to help other students working through this course." # full_license: "Full License" # starter_license: "Starter License" # trial: "Trial" # hoc_welcome: "Happy Computer Science Education Week" # hoc_title: "Hour of Code Games - Free Activities to Learn Real Coding Languages" # hoc_meta_description: "Make your own game or code your way out of a dungeon! CodeCombat has four different Hour of Code activities and over 60 levels to learn code, play, and create." # hoc_intro: "There are three ways for your class to participate in Hour of Code with CodeCombat" # hoc_self_led: "Self-Led Gameplay" # hoc_self_led_desc: "Students can play through two Hour of Code CodeCombat tutorials on their own" # hoc_game_dev: "Game Development" # hoc_and: "and" # hoc_programming: "JavaScript/Python Programming" # hoc_teacher_led: "Teacher-Led Lessons" # hoc_teacher_led_desc1: "Download our" # hoc_teacher_led_link: "Introduction to Computer Science lesson plans" # hoc_teacher_led_desc2: "to introduce your students to programming concepts using offline activities" # hoc_group: "Group Gameplay" # hoc_group_desc_1: "Teachers can use the lessons in conjunction with our Introduction to Computer Science course to track student progress. See our" # hoc_group_link: "Getting Started Guide" # hoc_group_desc_2: "for more details" # hoc_additional_desc1: "For additional CodeCombat resources and activities, see our" # hoc_additional_desc2: "Questions" # hoc_additional_contact: "Get in touch" # revoke_confirm: "Are you sure you want to revoke a Full License from {{student_name}}? The license will become available to assign to another student." # revoke_all_confirm: "Are you sure you want to revoke Full Licenses from all students in this class?" revoking: "A revogar..." # unused_licenses: "You have unused Licenses that allow you to assign students paid courses when they're ready to learn more!" # remember_new_courses: "Remember to assign new courses!" more_info: "Mais Informação" # how_to_assign_courses: "How to Assign Courses" # select_students: "Select Students" # select_instructions: "Click the checkbox next to each student you want to assign courses to." # choose_course: "Choose Course" # choose_instructions: "Select the course from the dropdown menu you’d like to assign, then click “Assign to Selected Students.”" # push_projects: "We recommend assigning Web Development 1 or Game Development 1 after students have finished Introduction to Computer Science! See our {{resource_hub}} for more details on those courses." # teacher_quest: "Teacher's Quest for Success" # quests_complete: "Quests Complete" # teacher_quest_create_classroom: "Create Classroom" teacher_quest_add_students: "Adicionar Estudantes" # teacher_quest_teach_methods: "Help your students learn how to `call methods`." # teacher_quest_teach_methods_step1: "Get 75% of at least one class through the first level, __Dungeons of Kithgard__" # teacher_quest_teach_methods_step2: "Print out the [Student Quick Start Guide](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) in the Resource Hub." # teacher_quest_teach_strings: "Don't string your students along, teach them `strings`." # teacher_quest_teach_strings_step1: "Get 75% of at least one class through __True Names__" # teacher_quest_teach_strings_step2: "Use the Teacher Level Selector on [Course Guides](/teachers/courses) page to preview __True Names__." # teacher_quest_teach_loops: "Keep your students in the loop about `loops`." # teacher_quest_teach_loops_step1: "Get 75% of at least one class through __Fire Dancing__." # teacher_quest_teach_loops_step2: "Use the __Loops Activity__ in the [CS1 Curriculum guide](/teachers/resources/cs1) to reinforce this concept." # teacher_quest_teach_variables: "Vary it up with `variables`." # teacher_quest_teach_variables_step1: "Get 75% of at least one class through __Known Enemy__." # teacher_quest_teach_variables_step2: "Encourage collaboration by using the [Pair Programming Activity](/teachers/resources/pair-programming)." # teacher_quest_kithgard_gates_100: "Escape the Kithgard Gates with your class." # teacher_quest_kithgard_gates_100_step1: "Get 75% of at least one class through __Kithgard Gates__." # teacher_quest_kithgard_gates_100_step2: "Guide students to think through hard problems using the [Engineering Cycle Worksheet](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." # teacher_quest_wakka_maul_100: "Prepare to duel in Wakka Maul." # teacher_quest_wakka_maul_100_step1: "Get 75% of at least one class to __Wakka Maul__." # teacher_quest_wakka_maul_100_step2: "See the [Arena Guide](/teachers/resources/arenas) in the [Resource Hub](/teachers/resources) for tips on how to run a successful arena day." # teacher_quest_reach_gamedev: "Explore new worlds!" # teacher_quest_reach_gamedev_step1: "[Get licenses](/teachers/licenses) so that your students can explore new worlds, like Game Development and Web Development!" # teacher_quest_done: "Want your students to learn even more code? Get in touch with our [school specialists](mailto:schools@codecombat.com) today!" # teacher_quest_keep_going: "Keep going! Here's what you can do next:" # teacher_quest_more: "See all quests" # teacher_quest_less: "See fewer quests" # refresh_to_update: "(refresh the page to see updates)" # view_project_gallery: "View Project Gallery" # office_hours: "Teacher Webinars" # office_hours_detail: "Learn how to keep up with with your students as they create games and embark on their coding journey! Come and attend our" # office_hours_link: "teacher webinar" # office_hours_detail_2: "sessions." # success: "Success" # in_progress: "In Progress" # not_started: "Not Started" # mid_course: "Mid-Course" # end_course: "End of Course" # none: "None detected yet" # explain_open_ended: "Note: Students are encouraged to solve this level creatively — one possible solution is provided below." level_label: "Nível:" time_played_label: "Tempo Jogado:" # back_to_resource_hub: "Back to Resource Hub" # back_to_course_guides: "Back to Course Guides" print_guide: "Imprimir este guia" # combo: "Combo" # combo_explanation: "Students pass Combo challenge levels by using at least one listed concept. Review student code by clicking the progress dot." concept: "Conceito" # sync_google_classroom: "Sync Google Classroom" # try_ozaria_footer: "Try our new adventure game, Ozaria!" # teacher_ozaria_encouragement_modal: # title: "Build Computer Science Skills to Save Ozaria" # sub_title: "You are invited to try the new adventure game from CodeCombat" # cancel: "Back to CodeCombat" # accept: "Try First Unit Free" # bullet1: "Deepen student connection to learning through an epic story and immersive gameplay" # bullet2: "Teach CS fundamentals, Python or JavaScript and 21st century skills" # bullet3: "Unlock creativity through capstone projects" # bullet4: "Support instructions through dedicated curriculum resources" # you_can_return: "You can always return to CodeCombat" share_licenses: share_licenses: "Partilhar Licenças" shared_by: "Partilhadas Por:" # add_teacher_label: "Enter exact teacher email:" add_teacher_button: "Adicionar Professor" # subheader: "You can make your licenses available to other teachers in your organization. Each license can only be used for one student at a time." # teacher_not_found: "Teacher not found. Please make sure this teacher has already created a Teacher Account." # teacher_not_valid: "This is not a valid Teacher Account. Only teacher accounts can share licenses." # already_shared: "You've already shared these licenses with that teacher." # teachers_using_these: "Teachers who can access these licenses:" # footer: "When teachers revoke licenses from students, the licenses will be returned to the shared pool for other teachers in this group to use." you: "(tu)" one_license_used: "(1 licença usada)" licenses_used: "(__licensesUsed__ licenças usadas)" more_info: "Mais informação" sharing: game: "Jogo" webpage: "Página Web" # your_students_preview: "Your students will click here to see their finished projects! Unavailable in teacher preview." # unavailable: "Link sharing not available in teacher preview." share_game: "Partilhar Este Jogo" share_web: "Partilhar Esta Página Web" victory_share_prefix: "Partilha esta ligação para convidares os teus amigos e a tua família para" victory_share_prefix_short: "Convida pessoas para" victory_share_game: "jogarem o teu nível de jogo" victory_share_web: "verem a tua página web" victory_share_suffix: "." victory_course_share_prefix: "Esta ligação vai permitir que os teus amigos e a tua família" victory_course_share_game: "joguem o jogo" victory_course_share_web: "vejam a página web" victory_course_share_suffix: "que acabaste de criar." copy_url: "Copiar URL" share_with_teacher_email: "Envia para o teu professor" game_dev: creator: "Criador" web_dev: image_gallery_title: "Galeria de Imagens" select_an_image: "Seleciona uma imagem que queiras usar" scroll_down_for_more_images: "(Arrasta para baixo para mais imagens)" copy_the_url: "Copiar o URL abaixo" copy_the_url_description: "Útil se quiseres substituir uma imagem existente." copy_the_img_tag: "Copiar a etiqueta <img>" copy_the_img_tag_description: "Útil se quiseres inserir uma imagem nova." copy_url: "Copiar URL" copy_img: "Copiar <img>" how_to_copy_paste: "Como Copiar/Colar" copy: "Copiar" paste: "Colar" back_to_editing: "Voltar à Edição" classes: archmage_title: "Arcomago" archmage_title_description: "(Programador)" archmage_summary: "Se és um programador interessado em programar jogos educacionais, torna-te um Arcomago para nos ajudares a construir o CodeCombat!" artisan_title: "Artesão" artisan_title_description: "(Construtor de Níveis)" artisan_summary: "Constrói e partilha níveis para tu e os teus amigos jogarem. Torna-te um Artesão para aprenderes a arte de ensinar outros a programar." adventurer_title: "Aventureiro" adventurer_title_description: "(Testador de Níveis)" adventurer_summary: "Recebe os nossos novos níveis (até o conteúdo para subscritores) de graça, uma semana antes, e ajuda-nos a descobrir erros antes do lançamento para o público." scribe_title: "Escrivão" scribe_title_description: "(Editor de Artigos)" scribe_summary: "Bom código precisa de uma boa documentação. Escreve, edita e melhora os documentos lidos por milhões de jogadores pelo mundo." diplomat_title: "Diplomata" diplomat_title_description: "(Tradutor)" diplomat_summary: "O CodeCombat está traduzido em 45+ idiomas graças aos nossos Diplomatas. Ajuda-nos e contribui com traduções." ambassador_title: "Embaixador" ambassador_title_description: "(Suporte)" ambassador_summary: "Amansa os nossos utilizadores do fórum e direciona aqueles que têm questões. Os nossos Embaixadores representam o CodeCombat perante o mundo." teacher_title: "Professor" editor: main_title: "Editores do CodeCombat" article_title: "Editor de Artigos" thang_title: "Editor de Thangs" level_title: "Editor de Níveis" course_title: "Editor de Cursos" achievement_title: "Editor de Conquistas" poll_title: "Editor de Votações" back: "Voltar" revert: "Reverter" revert_models: "Reverter Modelos" pick_a_terrain: "Escolhe Um Terreno" dungeon: "Masmorra" indoor: "Interior" desert: "Deserto" grassy: "Relvado" mountain: "Montanha" glacier: "Glaciar" small: "Pequeno" large: "Grande" fork_title: "Bifurcar Nova Versão" fork_creating: "A Criar Bifurcação..." generate_terrain: "Gerar Terreno" more: "Mais" wiki: "Wiki" live_chat: "Chat ao Vivo" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Cores" level_some_options: "Algumas Opções?" level_tab_thangs: "Thangs" level_tab_scripts: "Scripts" level_tab_components: "Componentes" level_tab_systems: "Sistemas" level_tab_docs: "Documentação" level_tab_thangs_title: "Thangs Atuais" level_tab_thangs_all: "Todos" level_tab_thangs_conditions: "Condições Iniciais" level_tab_thangs_add: "Adicionar Thangs" level_tab_thangs_search: "Pesquisar thangs" add_components: "Adicionar Componentes" component_configs: "Configurações dos Componentes" config_thang: "Clica duas vezes para configurares uma thang" delete: "Eliminar" duplicate: "Duplicar" stop_duplicate: "Parar de Duplicar" rotate: "Rodar" level_component_tab_title: "Componentes Atuais" level_component_btn_new: "Criar Novo Componente" level_systems_tab_title: "Sistemas Atuais" level_systems_btn_new: "Cria Novo Sistema" level_systems_btn_add: "Adicionar Sistema" level_components_title: "Voltar para Todas as Thangs" level_components_type: "Tipo" level_component_edit_title: "Editar Componente" level_component_config_schema: "Configurar Esquema" level_system_edit_title: "Editar Sistema" create_system_title: "Criar Novo Sistema" new_component_title: "Criar Novo Componente" new_component_field_system: "Sistema" new_article_title: "Criar um Novo Artigo" new_thang_title: "Criar um Novo Tipo de Thang" new_level_title: "Criar um Novo Nível" new_article_title_login: "Inicia Sessão para Criares um Novo Artigo" new_thang_title_login: "Inicia Sessão para Criares um Novo Tipo de Thang" new_level_title_login: "Inicia Sessão para Criares um Novo Nível" new_achievement_title: "Criar uma Nova Conquista" new_achievement_title_login: "Inicia Sessão para Criares uma Nova Conquista" new_poll_title: "Criar uma Nova Votação" new_poll_title_login: "Iniciar Sessão para Criar uma Nova Votação" article_search_title: "Procurar Artigos Aqui" thang_search_title: "Procurar Thangs Aqui" level_search_title: "Procurar Níveis Aqui" achievement_search_title: "Procurar Conquistas" poll_search_title: "Procurar Votações" read_only_warning2: "Nota: não podes guardar nenhuma edição feita aqui, porque não tens sessão iniciada." no_achievements: "Ainda não foram adicionadas conquistas a este nível." achievement_query_misc: "Conquista-chave de uma lista de variados" achievement_query_goals: "Conquista-chave dos objetivos do nível" level_completion: "Completação do Nível" pop_i18n: "Propagar I18N" tasks: "Tarefas" clear_storage: "Limpa as tuas alterações locais" add_system_title: "Adicionar Sistemas ao Nível" done_adding: "Adição Concluída" article: edit_btn_preview: "Pré-visualizar" edit_article_title: "Editar Artigo" polls: priority: "Prioridade" contribute: page_title: "Contribuir" intro_blurb: "O CodeCombat faz parte da comunidade open source! Centenas de jogadores dedicados ajudaram-nos a transformar o jogo naquilo que ele é hoje. Junta-te a nós e escreve o próximo capítulo da aventura do CodeCombat para ensinar o mundo a programar!" alert_account_message_intro: "Hey, tu!" alert_account_message: "Para te subscreveres para receber e-mails de classes, necessitarás de iniciar sessão." archmage_introduction: "Uma das melhores partes da construção de jogos é que eles sintetizam muitas coisas diferentes. Gráficos, som, rede em tempo real, redes sociais, e, claro, muitos dos aspectos mais comuns da programação, desde a gestão de bases de dados de baixo nível, e administração do servidor até à construção do design e da interface do utilizador. Há muito a fazer, e se és um programador experiente com um verdadeiro desejo de mergulhar nas entranhas do CodeCombat, esta classe pode ser para ti. Gostaríamos muito de ter a tua ajuda para construir o melhor jogo de programação de sempre." class_attributes: "Atributos da Classe" archmage_attribute_1_pref: "Conhecimento em " archmage_attribute_1_suf: ", ou vontade de aprender. A maioria do nosso código está nesta linguagem. Se és um fã de Ruby ou Python, vais sentir-te em casa. É igual ao JavaScript, mas com uma sintaxe melhor." archmage_attribute_2: "Alguma experiência em programação e iniciativa pessoal. Nós ajudamos-te a orientares-te, mas não podemos gastar muito tempo a treinar-te." how_to_join: "Como Me Junto" join_desc_1: "Qualquer um pode ajudar! Só tens de conferir o nosso " join_desc_2: "para começares, e assinalar a caixa abaixo para te declarares um bravo Arcomago e receberes as últimas notícias por e-mail. Queres falar sobre o que fazer ou como te envolveres mais profundamente no projeto? " join_desc_3: " ou encontra-nos na nossa " join_desc_4: "e começamos a partir daí!" join_url_email: "Contacta-nos" join_url_slack: "canal público no Slack" archmage_subscribe_desc: "Receber e-mails relativos a novas oportunidades de programação e anúncios." artisan_introduction_pref: "Temos de construir mais níveis! As pessoas estão a pedir mais conteúdo, e nós mesmos só podemos construir estes tantos. Neste momento, a tua estação de trabalho é o nível um; o nosso editor de nível é pouco utilizável, até mesmo pelos seus criadores, por isso fica atento. Se tens visões de campanhas que abranjam 'for-loops' para o" artisan_introduction_suf: ", então esta classe pode ser para ti." # artisan_attribute_1: "Any experience in building content like this would be nice, such as using Blizzard's level editors. But not required!" # artisan_attribute_2: "A hankering to do a whole lot of testing and iteration. To make good levels, you need to take it to others and watch them play it, and be prepared to find a lot of things to fix." # artisan_attribute_3: "For the time being, endurance en par with an Adventurer. Our Level Editor is super preliminary and frustrating to use. You have been warned!" artisan_join_desc: "Usa o Editor de Níveis por esta ordem, pegar ou largar:" artisan_join_step1: "Lê a documentação." artisan_join_step2: "Cria um nível novo e explora níveis existentes." artisan_join_step3: "Encontra-nos na nossa sala Slack pública se necessitares de ajuda." artisan_join_step4: "Coloca os teus níveis no fórum para receberes feedback." artisan_subscribe_desc: "Receber e-mails relativos a novidades do editor de níveis e anúncios." # adventurer_introduction: "Let's be clear about your role: you are the tank. You're going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class might be for you." # adventurer_attribute_1: "A thirst for learning. You want to learn how to code and we want to teach you how to code. You'll probably be doing most of the teaching in this case, though." # adventurer_attribute_2: "Charismatic. Be gentle but articulate about what needs improving, and offer suggestions on how to improve." # adventurer_join_pref: "Either get together with (or recruit!) an Artisan and work with them, or check the box below to receive emails when there are new levels to test. We'll also be posting about levels to review on our networks like" # adventurer_forum_url: "our forum" # adventurer_join_suf: "so if you prefer to be notified those ways, sign up there!" adventurer_subscribe_desc: "Receber e-mails quando houver novos níveis para testar." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." scribe_attribute_1: "Habilidade com palavras é basicamente o que precisas. Não apenas gramática e ortografia, mas seres capaz de explicar ideias complicadas a outros." contact_us_url: "Contacta-nos" scribe_join_description: "fala-nos um bocado de ti, da tua experiência com a programação e do tipo de coisas sobre as quais gostarias de escrever. Começamos a partir daí!" scribe_subscribe_desc: "Receber e-mails sobre anúncios relativos à escrita de artigos." diplomat_introduction_pref: "Portanto, se há uma coisa que aprendemos com o nosso " diplomat_launch_url: "lançamento em Outubro" diplomat_introduction_suf: "é que há um interesse considerável no CodeCombat noutros países! Estamos a construir um exército de tradutores dispostos a transformar um conjunto de palavras num outro conjuto de palavras, para conseguir que o CodeCombat fique o mais acessível quanto posível em todo o mundo. Se gostas de dar espreitadelas a conteúdos futuros e disponibilizar os níveis para os teus colegas nacionais o mais depressa possível, então esta classe talvez seja para ti." diplomat_attribute_1: "Fluência em Inglês e no idioma para o qual gostarias de traduzir. Quando são tentadas passar ideias complicadas, é importante uma excelente compreensão das duas!" diplomat_i18n_page_prefix: "Podes começar a traduzir os nossos níveis se fores à nossa" diplomat_i18n_page: "página de traduções" diplomat_i18n_page_suffix: ", ou a nossa interface e website no GitHub." diplomat_join_pref_github: "Encontra o ficheiro 'locale' do teu idioma " diplomat_github_url: "no GitHub" diplomat_join_suf_github: ", edita-o online e submete um 'pull request'. Assinala ainda a caixa abaixo para ficares atualizado em relação a novos desenvolvimentos da internacionalização!" diplomat_subscribe_desc: "Receber e-mails sobre desenvolvimentos da i18n e níveis para traduzir." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got forums, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" ambassador_join_note_strong: "Nota" ambassador_join_note_desc: "Uma das nossas maiores prioridades é construir níveis multijogador onde os jogadores com dificuldade para passar níveis possam invocar feiticeiros mais experientes para os ajudarem. Esta será uma ótima forma de os embaixadores fazerem o que sabem. Vamos manter-te atualizado!" ambassador_subscribe_desc: "Receber e-mails relativos a novidades do suporte e desenvolvimentos do modo multijogador." teacher_subscribe_desc: "Receber e-mails sobre atualizações e anúncios para professores." changes_auto_save: "As alterações são guardadas automaticamente quando clicas nas caixas." diligent_scribes: "Os Nossos Dedicados Escrivões:" powerful_archmages: "Os Nossos Poderosos Arcomagos:" creative_artisans: "Os Nossos Creativos Artesãos:" brave_adventurers: "Os Nossos Bravos Aventureiros:" translating_diplomats: "Os Nossos Tradutores Diplomatas:" helpful_ambassadors: "Os Nossos Prestáveis Embaixadores:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Os Meus Jogos" simulate: "Simular" simulation_explanation: "Ao simulares jogos podes ter o teu jogo classificado mais rapidamente!" simulation_explanation_leagues: "Principalmente, vais ajudar a simular jogos para jogadores aliados nos teus clâs e cursos." simulate_games: "Simular Jogos!" games_simulated_by: "Jogos simulados por ti:" games_simulated_for: "Jogos simulados para ti:" games_in_queue: "Jogos na fila de espera atualmente:" games_simulated: "Jogos simulados" games_played: "Jogos jogados" ratio: "Rácio" leaderboard: "Tabela de Classificação" battle_as: "Lutar como " summary_your: "As Tuas " summary_matches: "Partidas - " summary_wins: " Vitórias, " summary_losses: " Derrotas" rank_no_code: "Sem Código Novo para Classificar" rank_my_game: "Classificar o Meu Jogo!" rank_submitting: "A submeter..." rank_submitted: "Submetido para Classificação" rank_failed: "A Classificação Falhou" rank_being_ranked: "Jogo a ser Classificado" rank_last_submitted: "submetido " help_simulate: "Ajudar a simular jogos?" code_being_simulated: "O teu novo código está a ser simulado por outros jogadores, para ser classificado. Isto será atualizado quando surgirem novas partidas." no_ranked_matches_pre: "Sem jogos classificados pela equipa " no_ranked_matches_post: "! Joga contra alguns adversários e volta aqui para veres o teu jogo classificado." choose_opponent: "Escolhe um Adversário" select_your_language: "Seleciona a tua linguagem!" tutorial_play: "Jogar Tutorial" tutorial_recommended: "Recomendado se nunca jogaste antes" tutorial_skip: "Saltar Tutorial" tutorial_not_sure: "Não tens a certeza do que se passa?" tutorial_play_first: "Joga o Tutorial primeiro." simple_ai: "CPU Simples" warmup: "Aquecimento" friends_playing: "Amigos a Jogar" log_in_for_friends: "Inicia sessão para jogares com os teus amigos!" social_connect_blurb: "Conecta-te e joga contra os teus amigos!" invite_friends_to_battle: "Convida os teus amigos para se juntarem a ti em batalha!" fight: "Lutar!" watch_victory: "Vê a tua vitória" defeat_the: "Derrota o" watch_battle: "Ver a batalha" tournament_started: ", começou" tournament_ends: "O Torneio acaba" tournament_ended: "O Torneio acabou" tournament_rules: "Regras do Torneio" tournament_blurb: "Escreve código, recolhe ouro, constrói exércitos, esmaga inimigos, ganha prémios e melhora a tua carreira no nosso torneio $40,000 Greed! Confere os detalhes" tournament_blurb_criss_cross: "Ganha ofertas, constrói caminhos, supera os adversários, apanha gemas e melhore a tua carreira no nosso torneio Criss-Cross! Confere os detalhes" tournament_blurb_zero_sum: "Liberta a tua criatividade de programação tanto na recolha de ouro como em táticas de combate nesta batalha-espelhada na montanha, entre o feiticeiro vermelho e o feiticeiro azul. O torneio começou na Sexta-feira, 27 de Março, e decorrerá até às 00:00 de Terça-feira, 7 de Abril. Compete por diversão e glória! Confere os detalhes" tournament_blurb_ace_of_coders: "Luta no glaciar congelado nesta partida espelhada do estilo domínio! O torneio começou Quarta-feira, 16 de Setembro, e decorrerá até Quarta-feira, 14 de Outubro às 23:00. Confere os detalhes" tournament_blurb_blog: "no nosso blog" rules: "Regras" winners: "Vencedores" league: "Liga" red_ai: "CPU Vermelho" # "Red AI Wins", at end of multiplayer match playback blue_ai: "CPU Azul" wins: "Vence" # At end of multiplayer match playback humans: "Vermelho" # Ladder page display team name ogres: "Azul" # live_tournament: "Live Tournament" # awaiting_tournament_title: "Tournament Inactive" # awaiting_tournament_blurb: "The tournament arena is not currently active." # tournament_end_desc: "The tournament is over, thanks for playing" user: # user_title: "__name__ - Learn to Code with CodeCombat" stats: "Estatísticas" singleplayer_title: "Níveis Um Jogador" multiplayer_title: "Níveis Multijogador" achievements_title: "Conquistas" last_played: "Última Vez Jogado" status: "Estado" status_completed: "Completo" status_unfinished: "Inacabado" no_singleplayer: "Sem jogos Um Jogador jogados." no_multiplayer: "Sem jogos Multijogador jogados." no_achievements: "Sem Conquistas ganhas." favorite_prefix: "A linguagem favorita é " favorite_postfix: "." not_member_of_clans: "Ainda não é membro de nenhum clã." # certificate_view: "view certificate" # certificate_click_to_view: "click to view certificate" # certificate_course_incomplete: "course incomplete" # certificate_of_completion: "Certificate of Completion" # certificate_endorsed_by: "Endorsed by" # certificate_stats: "Course Stats" # certificate_lines_of: "lines of" # certificate_levels_completed: "levels completed" # certificate_for: "For" # certificate_number: "No." achievements: last_earned: "Último Ganho" amount_achieved: "Quantidade" achievement: "Conquista" current_xp_prefix: "" current_xp_postfix: " no total" new_xp_prefix: "" new_xp_postfix: " ganho" left_xp_prefix: "" left_xp_infix: " até ao nível " left_xp_postfix: "" account: # title: "Account" # settings_title: "Account Settings" # unsubscribe_title: "Unsubscribe" # payments_title: "Payments" # subscription_title: "Subscription" # invoices_title: "Invoices" # prepaids_title: "Prepaids" payments: "Pagamentos" prepaid_codes: "Códigos Pré-pagos" purchased: "Adquirido" # subscribe_for_gems: "Subscribe for gems" subscription: "Subscrição" invoices: "Donativos" service_apple: "Apple" service_web: "Web" paid_on: "Pago Em" service: "Serviço" price: "Preço" gems: "Gemas" active: "Activa" subscribed: "Subscrito(a)" unsubscribed: "Não Subscrito(a)" active_until: "Ativa Até" cost: "Custo" next_payment: "Próximo Pagamento" card: "Cartão" status_unsubscribed_active: "Não estás subscrito e não te vamos cobrar, mas a tua conta ainda está ativa, por agora." status_unsubscribed: "Ganha acesso a novos níveis, heróis, itens e gemas de bónus com uma subscrição do CodeCombat!" not_yet_verified: "Ainda não foi verificado." resend_email: "Reenviar e-mail" email_sent: "E-mail enviado! Verifica a tua caixa de entrada." verifying_email: "A verificar o teu endereço de e-mail..." successfully_verified: "Verificaste o teu endereço de e-mail com sucesso!" verify_error: "Algo correu mal aquando da verificação do teu e-mail :(" # unsubscribe_from_marketing: "Unsubscribe __email__ from all CodeCombat marketing emails?" # unsubscribe_button: "Yes, unsubscribe" # unsubscribe_failed: "Failed" # unsubscribe_success: "Success" account_invoices: amount: "Quantidade em dólares americanos" declined: "O teu cartão foi recusado" invalid_amount: "Por favor introduz uma quantidade de dólares americanos." not_logged_in: "Inicia sessão ou cria uma conta para acederes aos donativos." pay: "Pagar Donativo" purchasing: "A adquirir..." retrying: "Erro do servidor, a tentar novamente." success: "Pago com sucesso. Obrigado!" account_prepaid: purchase_code: "Comprar um Código de Subscrição" # purchase_code1: "Subscription Codes can be redeemed to add premium subscription time to one or more accounts for the Home version of CodeCombat." # purchase_code2: "Each CodeCombat account can only redeem a particular Subscription Code once." # purchase_code3: "Subscription Code months will be added to the end of any existing subscription on the account." # purchase_code4: "Subscription Codes are for accounts playing the Home version of CodeCombat, they cannot be used in place of Student Licenses for the Classroom version." # purchase_code5: "For more information on Student Licenses, reach out to" users: "Utilizadores" months: "Meses" purchase_total: "Total" purchase_button: "Submeter Compra" your_codes: "Os Teus Códigos" redeem_codes: "Resgata um Código de Subscrição" prepaid_code: "Código Pré-pago" lookup_code: "Procurar código pré-pago" apply_account: "Aplicar à tua conta" copy_link: "Podes copiar a ligação do código e enviá-la a alguém." quantity: "Quantidade" redeemed: "Resgatado" no_codes: "Nenhum código ainda!" you_can1: "Podes" you_can2: "adquirir um código pré-pago" you_can3: "que pode ser aplicado à tua conta ou dado a outros." # ozaria_chrome: # sound_off: "Sound Off" # sound_on: "Sound On" # back_to_map: "Back to Map" # level_options: "Level Options" # restart_level: "Restart Level" # impact: # hero_heading: "Building A World-Class Computer Science Program" # hero_subheading: "We Help Empower Educators and Inspire Students Across the Country" # featured_partner_story: "Featured Partner Story" # partner_heading: "Successfully Teaching Coding at a Title I School" # partner_school: "Bobby Duke Middle School" # featured_teacher: "Scott Baily" # teacher_title: "Technology Teacher Coachella, CA" # implementation: "Implementation" # grades_taught: "Grades Taught" # length_use: "Length of Use" # length_use_time: "3 years" # students_enrolled: "Students Enrolled this Year" # students_enrolled_number: "130" # courses_covered: "Courses Covered" # course1: "CompSci 1" # course2: "CompSci 2" # course3: "CompSci 3" # course4: "CompSci 4" # course5: "GameDev 1" # fav_features: "Favorite Features" # responsive_support: "Responsive Support" # immediate_engagement: "Immediate Engagement" # paragraph1: "Bobby Duke Middle School sits nestled between the Southern California mountains of Coachella Valley to the west and east and the Salton Sea 33 miles south, and boasts a student population of 697 students within Coachella Valley Unified’s district-wide population of 18,861 students." # paragraph2: "The students of Bobby Duke Middle School reflect the socioeconomic challenges facing Coachella Valley’s residents and students within the district. With over 95% of the Bobby Duke Middle School student population qualifying for free and reduced-price meals and over 40% classified as English language learners, the importance of teaching 21st century skills was the top priority of Bobby Duke Middle School Technology teacher, Scott Baily." # paragraph3: "Baily knew that teaching his students coding was a key pathway to opportunity in a job landscape that increasingly prioritizes and necessitates computing skills. So, he decided to take on the exciting challenge of creating and teaching the only coding class in the school and finding a solution that was affordable, responsive to feedback, and engaging to students of all learning abilities and backgrounds." # teacher_quote: "When I got my hands on CodeCombat [and] started having my students use it, the light bulb went on. It was just night and day from every other program that we had used. They’re not even close." # quote_attribution: "Scott Baily, Technology Teacher" # read_full_story: "Read Full Story" # more_stories: "More Partner Stories" # partners_heading_1: "Supporting Multiple CS Pathways in One Class" # partners_school_1: "Preston High School" # partners_heading_2: "Excelling on the AP Exam" # partners_school_2: "River Ridge High School" # partners_heading_3: "Teaching Computer Science Without Prior Experience" # partners_school_3: "Riverdale High School" # download_study: "Download Research Study" # teacher_spotlight: "Teacher & Student Spotlights" # teacher_name_1: "Amanda Henry" # teacher_title_1: "Rehabilitation Instructor" # teacher_location_1: "Morehead, Kentucky" # spotlight_1: "Through her compassion and drive to help those who need second chances, Amanda Henry helped change the lives of students who need positive role models. With no previous computer science experience, Henry led her students to coding success in a regional coding competition." # teacher_name_2: "Kaila, Student" # teacher_title_2: "Maysville Community & Technical College" # teacher_location_2: "Lexington, Kentucky" # spotlight_2: "Kaila was a student who never thought she would be writing lines of code, let alone enrolled in college with a pathway to a bright future." # teacher_name_3: "Susan Jones-Szabo" # teacher_title_3: "Teacher Librarian" # teacher_school_3: "Ruby Bridges Elementary" # teacher_location_3: "Alameda, CA" # spotlight_3: "Susan Jones-Szabo promotes an equitable atmosphere in her class where everyone can find success in their own way. Mistakes and struggles are welcomed because everyone learns from a challenge, even the teacher." # continue_reading_blog: "Continue Reading on Blog..." loading_error: could_not_load: "Erro a carregar do servidor. Experimenta atualizar a página." connection_failure: "A Ligação Falhou" connection_failure_desc: "Não parece que estejas ligado à internet! Verifica a tua ligação de rede e depois recarrega esta página." login_required: "Sessão Iniciada Obrigatória" login_required_desc: "Precisas de ter sessão iniciada para acederes a esta página." unauthorized: "Precisas de ter sessão iniciada. Tens os cookies desativados?" forbidden: "Proibido" forbidden_desc: "Oh não, não há nada aqui que te possamos mostrar! Certifica-te de que tens sessão iniciada na conta correta ou visita uma das ligações abaixo para voltares para a programação!" # user_not_found: "User Not Found" not_found: "Não Encontrado" not_found_desc: "Hm, não há nada aqui. Visita uma das ligações seguintes para voltares para a programação!" not_allowed: "Método não permitido." timeout: "O Servidor Expirou" conflict: "Conflito de recursos." bad_input: "Má entrada." server_error: "Erro do servidor." unknown: "Erro Desconhecido" error: "ERRO" general_desc: "Algo correu mal, e, provavelmente, a culpa é nossa. Tenta esperar um pouco e depois recarregar a página, ou visita uma das ligações seguintes para voltares para a programação!" resources: level: "Nível" patch: "Atualização" patches: "Atualizações" system: "Sistema" systems: "Sistemas" component: "Componente" components: "Componentes" hero: "Herói" campaigns: "Campanhas" concepts: # advanced_css_rules: "Advanced CSS Rules" # advanced_css_selectors: "Advanced CSS Selectors" # advanced_html_attributes: "Advanced HTML Attributes" # advanced_html_tags: "Advanced HTML Tags" # algorithm_average: "Algorithm Average" # algorithm_find_minmax: "Algorithm Find Min/Max" # algorithm_search_binary: "Algorithm Search Binary" # algorithm_search_graph: "Algorithm Search Graph" # algorithm_sort: "Algorithm Sort" # algorithm_sum: "Algorithm Sum" arguments: "Argumentos" arithmetic: "Aritmética" # array_2d: "2D Array" # array_index: "Array Indexing" # array_iterating: "Iterating Over Arrays" # array_literals: "Array Literals" # array_searching: "Array Searching" # array_sorting: "Array Sorting" arrays: "'Arrays'" # basic_css_rules: "Basic CSS rules" # basic_css_selectors: "Basic CSS selectors" # basic_html_attributes: "Basic HTML Attributes" # basic_html_tags: "Basic HTML Tags" basic_syntax: "Sintaxe Básica" binary: "Binário" # boolean_and: "Boolean And" # boolean_inequality: "Boolean Inequality" # boolean_equality: "Boolean Equality" # boolean_greater_less: "Boolean Greater/Less" # boolean_logic_shortcircuit: "Boolean Logic Shortcircuiting" # boolean_not: "Boolean Not" # boolean_operator_precedence: "Boolean Operator Precedence" # boolean_or: "Boolean Or" # boolean_with_xycoordinates: "Coordinate Comparison" # bootstrap: "Bootstrap" break_statements: "Declarações 'Break'" classes: "Classes" continue_statements: "Declarações 'Continue'" # dom_events: "DOM Events" # dynamic_styling: "Dynamic Styling" events: "Eventos" # event_concurrency: "Event Concurrency" # event_data: "Event Data" # event_handlers: "Event Handlers" # event_spawn: "Spawn Event" for_loops: "'For Loops'" # for_loops_nested: "Nested For Loops" # for_loops_range: "For Loops Range" functions: "Funções" functions_parameters: "Parâmetros" functions_multiple_parameters: "Multiplos Parâmetros" # game_ai: "Game AI" # game_goals: "Game Goals" # game_spawn: "Game Spawn" graphics: "Gráficos" # graphs: "Graphs" # heaps: "Heaps" # if_condition: "Conditional If Statements" # if_else_if: "If/Else If Statements" # if_else_statements: "If/Else Statements" if_statements: "Declarações 'If'" # if_statements_nested: "Nested If Statements" # indexing: "Array Indexes" # input_handling_flags: "Input Handling - Flags" # input_handling_keyboard: "Input Handling - Keyboard" # input_handling_mouse: "Input Handling - Mouse" # intermediate_css_rules: "Intermediate CSS Rules" # intermediate_css_selectors: "Intermediate CSS Selectors" # intermediate_html_attributes: "Intermediate HTML Attributes" # intermediate_html_tags: "Intermediate HTML Tags" jquery: "jQuery" # jquery_animations: "jQuery Animations" # jquery_filtering: "jQuery Element Filtering" # jquery_selectors: "jQuery Selectors" # length: "Array Length" # math_coordinates: "Coordinate Math" math_geometry: "Geometria" math_operations: "Operações Matemáticas" # math_proportions: "Proportion Math" math_trigonometry: "Trigonometria" object_literals: "'Object Literals'" parameters: "Parâmetros" programs: "Programas" properties: "Propriedades" # property_access: "Accessing Properties" # property_assignment: "Assigning Properties" # property_coordinate: "Coordinate Property" # queues: "Data Structures - Queues" # reading_docs: "Reading the Docs" recursion: "Recursão" # return_statements: "Return Statements" # stacks: "Data Structures - Stacks" strings: "'Strings'" # strings_concatenation: "String Concatenation" # strings_substrings: "Substring" trees: "Estruturas de Dados - Árvores" variables: "Variáveis" vectors: "Vetores" # while_condition_loops: "While Loops with Conditionals" # while_loops_simple: "While Loops" # while_loops_nested: "Nested While Loops" xy_coordinates: "Pares de Coordenadas" advanced_strings: "'Strings' Avançadas" # Rest of concepts are deprecated algorithms: "Algoritmos" boolean_logic: "Lógica Booleana" basic_html: "HTML Básico" basic_css: "CSS Básico" # basic_web_scripting: "Basic Web Scripting" intermediate_html: "HTML Intermédio" intermediate_css: "CSS Intermédio" # intermediate_web_scripting: "Intermediate Web Scripting" advanced_html: "HTML Avançado" advanced_css: "CSS Avançado" # advanced_web_scripting: "Advanced Web Scripting" input_handling: "Manuseamento de 'Input'" while_loops: "'Loops While'" # place_game_objects: "Place game objects" construct_mazes: "Construir labirintos" # create_playable_game: "Create a playable, sharable game project" # alter_existing_web_pages: "Alter existing web pages" # create_sharable_web_page: "Create a sharable web page" # basic_input_handling: "Basic Input Handling" # basic_game_ai: "Basic Game AI" basic_javascript: "JavaScript Básico" # basic_event_handling: "Basic Event Handling" # create_sharable_interactive_web_page: "Create a sharable interactive web page" anonymous_teacher: # notify_teacher: "Notify Teacher" # create_teacher_account: "Create free teacher account" enter_student_name: "O teu nome:" enter_teacher_email: "O e-mail do teu professor:" teacher_email_placeholder: "teacher.email@example.com" student_name_placeholder: "escreve o teu nome aqui" teachers_section: "Professores:" students_section: "Estudantes:" # teacher_notified: "We've notified your teacher that you want to play more CodeCombat in your classroom!" delta: added: "Adicionado" modified: "Modificado" not_modified: "Não Modificado" deleted: "Eliminado" moved_index: "Índice Movido" text_diff: "Diferença de Texto" merge_conflict_with: "FUNDIR CONFLITO COM" no_changes: "Sem Alterações" legal: page_title: "Legal" opensource_introduction: "O CodeCombat faz parte da comunidade open source." opensource_description_prefix: "Confere " github_url: "o nosso GitHub" opensource_description_center: "e ajuda se quiseres! O CodeCombat é construído tendo por base dezenas de projetos open source, os quais nós amamos. Vê " archmage_wiki_url: "a nossa wiki dos Arcomagos" opensource_description_suffix: "para uma lista do software que faz com que este jogo seja possível." practices_title: "Melhores Práticas Respeitosas" practices_description: "Estas são as nossas promessas para contigo, o jogador, com um pouco menos de politiquices." privacy_title: "Privacidade" privacy_description: "Nós não vamos vender nenhuma das tuas informações pessoais." security_title: "Segurança" security_description: "Nós lutamos para manter as tuas informações pessoais seguras. Sendo um projeto open source, o nosso sítio tem o código disponível, pelo que qualquer pessoa pode rever e melhorar os nossos sistemas de segurança." email_title: "E-mail" email_description_prefix: "Nós não te inundaremos com spam. Através das" email_settings_url: "tuas definições de e-mail" email_description_suffix: "ou através de ligações presentes nos e-mails que enviamos, podes mudar as tuas preferências e parar a tua subscrição facilmente, em qualquer momento." cost_title: "Custo" cost_description: "O CodeCombat é gratuito para os níveis fundamentais, com uma subscrição de ${{price}} USD/mês para acederes a ramos de níveis extra e {{gems}} gemas de bónus por mês. Podes cancelar com um clique, e oferecemos uma garantia de 100% de devolução do dinheiro." copyrights_title: "Direitos Autorais e Licensas" contributor_title: "Contrato de Licença do Contribuinte (CLA)" contributor_description_prefix: "Todas as contribuições, tanto no sítio como no nosso repositório GitHub, estão sujeitas ao nosso" cla_url: "CLA" contributor_description_suffix: "com o qual deves concordar antes de contribuir." # code_title: "Client-Side Code - MIT" # client_code_description_prefix: "All client-side code for codecombat.com in the public GitHub repository and in the codecombat.com database, is licensed under the" mit_license_url: "Licença do MIT" code_description_suffix: "Isto inclui todo o código dentro dos Sistemas e dos Componentes, o qual é disponibilizado pelo CodeCombat para a criação de níveis." art_title: "Arte/Música - Creative Commons " art_description_prefix: "Todos os conteúdos comuns estão disponíveis à luz da" cc_license_url: "Licença 'Creative Commons Attribution 4.0 International'" art_description_suffix: "Conteúdo comum é, geralmente, qualquer coisa disponibilizada pelo CodeCombat com o propósito de criar Níveis. Isto inclui:" art_music: "Música" art_sound: "Som" art_artwork: "Arte" art_sprites: "Sprites" art_other: "Quaisquer e todos os trabalhos criativos não-código que são disponibilizados aquando da criação de Níveis." # art_access: "Currently there is no universal, easy system for fetching these assets. In general, fetch them from the URLs as used by the site, contact us for assistance, or help us in extending the site to make these assets more easily accessible." # art_paragraph_1: "For attribution, please name and link to codecombat.com near where the source is used or where appropriate for the medium. For example:" use_list_1: "Se usado num filme ou noutro jogo, inclui 'codecombat.com' nos créditos." # use_list_2: "If used on a website, include a link near the usage, for example underneath an image, or in a general attributions page where you might also mention other Creative Commons works and open source software being used on the site. Something that's already clearly referencing CodeCombat, such as a blog post mentioning CodeCombat, does not need some separate attribution." # art_paragraph_2: "If the content being used is created not by CodeCombat but instead by a user of codecombat.com, attribute them instead, and follow attribution directions provided in that resource's description if there are any." rights_title: "Direitos Reservados" rights_desc: "Todos os direitos estão reservados aos próprios Níveis. Isto inclui" rights_scripts: "Scripts" rights_unit: "Configurações das unidades" rights_writings: "Textos" rights_media: "Mídia (sons, música) e quaisquer outros conteúdos criativos feitos especificamente para esse Nível e que não foram disponibilizados para a criação de Níveis." # rights_clarification: "To clarify, anything that is made available in the Level Editor for the purpose of making levels is under CC, whereas the content created with the Level Editor or uploaded in the course of creation of Levels is not." nutshell_title: "Resumidamente" nutshell_description: "Qualquer um dos recursos que fornecemos no Editor de Níveis são de uso livre para criares Níveis. Mas reservamos o direito de distribuição restrita dos próprios Níveis (que são criados em codecombat.com) pelo que podemos cobrar por eles no futuro, se for isso que acabar por acontecer." # nutshell_see_also: "See also:" canonical: "A versão Inglesa deste documento é a versão definitiva e soberana. Se houver discrepâncias entre traduções, o documento Inglês prevalece." third_party_title: "Serviços de Terceiros" third_party_description: "O CodeCombat usa os seguintes serviços de terceiros (entre outros):" cookies_message: "O CodeCombat usa alguns cookies essenciais e não-essenciais." cookies_deny: "Recusar cookies não-essenciais" ladder_prizes: title: "Prémios do Torneio" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Estes prémios serão entregues de acordo com" blurb_2: "as regras do torneio" blurb_3: "aos melhores jogadores humanos e ogres." blurb_4: "Duas equipas significam o dobro dos prémios!" blurb_5: "(Haverá dois vencedores em primeiro lugar, dois em segundo, etc.)" rank: "Classificação" prizes: "Prémios" total_value: "Valor Total" in_cash: "em dinheiro" custom_wizard: "Um Feiticeiro do CodeCombat Personalizado" custom_avatar: "Um Avatar do CodeCombat Personalizado" heap: "para seis meses de acesso \"Startup\"" credits: "créditos" one_month_coupon: "cupão: escolhe Rails ou HTML" one_month_discount: "desconto de 30%: escolhe Rails ou HTML" license: "licença" oreilly: "ebook à tua escolha" calendar: year: "Ano" day: "Dia" month: "Mês" january: "janeiro" february: "fevereiro" march: "março" april: "abril" may: "maio" june: "junho" july: "julho" august: "agosto" september: "setembro" october: "outubro" november: "novembro" december: "dezembro" # code_play_create_account_modal: # title: "You did it!" # This section is only needed in US, UK, Mexico, India, and Germany # body: "You are now on your way to becoming a master coder. Sign up to receive an extra <strong>100 Gems</strong> & you will also be entered for a chance to <strong>win $2,500 & other Lenovo Prizes</strong>." # sign_up: "Sign up & keep coding ▶" # victory_sign_up_poke: "Create a free account to save your code & be entered for a chance to win prizes!" # victory_sign_up: "Sign up & be entered to <strong>win $2,500</strong>" server_error: email_taken: "E-mail já escolhido" username_taken: "Nome de utilizador já escolhido" esper: line_no: "Linha $1: " # uncaught: "Uncaught $1" # $1 will be an error type, eg "Uncaught SyntaxError" # reference_error: "ReferenceError: " # argument_error: "ArgumentError: " # type_error: "TypeError: " # syntax_error: "SyntaxError: " error: "Erro: " x_not_a_function: "$1 não é uma função" x_not_defined: "$1 não está definido" # spelling_issues: "Look out for spelling issues: did you mean `$1` instead of `$2`?" # capitalization_issues: "Look out for capitalization: `$1` should be `$2`." # py_empty_block: "Empty $1. Put 4 spaces in front of statements inside the $2 statement." # fx_missing_paren: "If you want to call `$1` as a function, you need `()`'s" # unmatched_token: "Unmatched `$1`. Every opening `$2` needs a closing `$3` to match it." # unterminated_string: "Unterminated string. Add a matching `\"` at the end of your string." # missing_semicolon: "Missing semicolon." # missing_quotes: "Missing quotes. Try `$1`" # argument_type: "`$1`'s argument `$2` should have type `$3`, but got `$4`: `$5`." # argument_type2: "`$1`'s argument `$2` should have type `$3`, but got `$4`." # target_a_unit: "Target a unit." # attack_capitalization: "Attack $1, not $2. (Capital letters are important.)" # empty_while: "Empty while statement. Put 4 spaces in front of statements inside the while statement." # line_of_site: "`$1`'s argument `$2` has a problem. Is there an enemy within your line-of-sight yet?" # need_a_after_while: "Need a `$1` after `$2`." # too_much_indentation: "Too much indentation at the beginning of this line." # missing_hero: "Missing `$1` keyword; should be `$2`." # takes_no_arguments: "`$1` takes no arguments." # no_one_named: "There's no one named \"$1\" to target." # separated_by_comma: "Function calls paramaters must be seperated by `,`s" # protected_property: "Can't read protected property: $1" # need_parens_to_call: "If you want to call `$1` as function, you need `()`'s" # expected_an_identifier: "Expected an identifier and instead saw '$1'." # unexpected_identifier: "Unexpected identifier" # unexpected_end_of: "Unexpected end of input" # unnecessary_semicolon: "Unnecessary semicolon." # unexpected_token_expected: "Unexpected token: expected $1 but found $2 while parsing $3" # unexpected_token: "Unexpected token $1" unexpected_token2: "Símbolo inesperado" unexpected_number: "Número inesperado" # unexpected: "Unexpected '$1'." # escape_pressed_code: "Escape pressed; code aborted." # target_an_enemy: "Target an enemy by name, like `$1`, not the string `$2`." # target_an_enemy_2: "Target an enemy by name, like $1." # cannot_read_property: "Cannot read property '$1' of undefined" # attempted_to_assign: "Attempted to assign to readonly property." # unexpected_early_end: "Unexpected early end of program." # you_need_a_string: "You need a string to build; one of $1" # unable_to_get_property: "Unable to get property '$1' of undefined or null reference" # TODO: Do we translate undefined/null? # code_never_finished_its: "Code never finished. It's either really slow or has an infinite loop." # unclosed_string: "Unclosed string." # unmatched: "Unmatched '$1'." # error_you_said_achoo: "You said: $1, but the password is: $2. (Capital letters are important.)" # indentation_error_unindent_does: "Indentation Error: unindent does not match any outer indentation level" # indentation_error: "Indentation error." # need_a_on_the: "Need a `:` on the end of the line following `$1`." # attempt_to_call_undefined: "attempt to call '$1' (a nil value)" # unterminated: "Unterminated `$1`" # target_an_enemy_variable: "Target an $1 variable, not the string $2. (Try using $3.)" # error_use_the_variable: "Use the variable name like `$1` instead of a string like `$2`" # indentation_unindent_does_not: "Indentation unindent does not match any outer indentation level" # unclosed_paren_in_function_arguments: "Unclosed $1 in function arguments." # unexpected_end_of_input: "Unexpected end of input" # there_is_no_enemy: "There is no `$1`. Use `$2` first." # Hints start here try_herofindnearestenemy: "Experimenta `$1`" there_is_no_function: "Não há nenhuma função `$1`, mas `$2` tem um método `$3`." # attacks_argument_enemy_has: "`$1`'s argument `$2` has a problem." # is_there_an_enemy: "Is there an enemy within your line-of-sight yet?" # target_is_null_is: "Target is $1. Is there always a target to attack? (Use $2?)" hero_has_no_method: "`$1` não tem nenhum método `$2`." there_is_a_problem: "Há um problema com o teu código." # did_you_mean: "Did you mean $1? You do not have an item equipped with that skill." # missing_a_quotation_mark: "Missing a quotation mark. " # missing_var_use_var: "Missing `$1`. Use `$2` to make a new variable." # you_do_not_have: "You do not have an item equipped with the $1 skill." # put_each_command_on: "Put each command on a separate line" # are_you_missing_a: "Are you missing a '$1' after '$2'? " # your_parentheses_must_match: "Your parentheses must match." # apcsp: # title: "AP Computer Science Principals | College Board Endorsed" # meta_description: "CodeCombat’s comprehensive curriculum and professional development program are all you need to offer College Board’s newest computer science course to your students." # syllabus: "AP CS Principles Syllabus" # syllabus_description: "Use this resource to plan CodeCombat curriculum for your AP Computer Science Principles class." # computational_thinking_practices: "Computational Thinking Practices" # learning_objectives: "Learning Objectives" # curricular_requirements: "Curricular Requirements" # unit_1: "Unit 1: Creative Technology" # unit_1_activity_1: "Unit 1 Activity: Technology Usability Review" # unit_2: "Unit 2: Computational Thinking" # unit_2_activity_1: "Unit 2 Activity: Binary Sequences" # unit_2_activity_2: "Unit 2 Activity: Computing Lesson Project" # unit_3: "Unit 3: Algorithms" # unit_3_activity_1: "Unit 3 Activity: Algorithms - Hitchhiker's Guide" # unit_3_activity_2: "Unit 3 Activity: Simulation - Predator & Prey" # unit_3_activity_3: "Unit 3 Activity: Algorithms - Pair Design and Programming" # unit_4: "Unit 4: Programming" # unit_4_activity_1: "Unit 4 Activity: Abstractions" # unit_4_activity_2: "Unit 4 Activity: Searching & Sorting" # unit_4_activity_3: "Unit 4 Activity: Refactoring" # unit_5: "Unit 5: The Internet" # unit_5_activity_1: "Unit 5 Activity: How the Internet Works" # unit_5_activity_2: "Unit 5 Activity: Internet Simulator" # unit_5_activity_3: "Unit 5 Activity: Chat Room Simulation" # unit_5_activity_4: "Unit 5 Activity: Cybersecurity" # unit_6: "Unit 6: Data" # unit_6_activity_1: "Unit 6 Activity: Introduction to Data" # unit_6_activity_2: "Unit 6 Activity: Big Data" # unit_6_activity_3: "Unit 6 Activity: Lossy & Lossless Compression" # unit_7: "Unit 7: Personal & Global Impact" # unit_7_activity_1: "Unit 7 Activity: Personal & Global Impact" # unit_7_activity_2: "Unit 7 Activity: Crowdsourcing" # unit_8: "Unit 8: Performance Tasks" # unit_8_description: "Prepare students for the Create Task by building their own games and practicing key concepts." # unit_8_activity_1: "Create Task Practice 1: Game Development 1" # unit_8_activity_2: "Create Task Practice 2: Game Development 2" # unit_8_activity_3: "Create Task Practice 3: Game Development 3" # unit_9: "Unit 9: AP Review" # unit_10: "Unit 10: Post-AP" # unit_10_activity_1: "Unit 10 Activity: Web Quiz" # parent_landing: # slogan_quote: "\"CodeCombat is really fun, and you learn a lot.\"" # quote_attr: "5th Grader, Oakland, CA" # refer_teacher: "Refer a Teacher" # focus_quote: "Unlock your child's future" # value_head1: "The most engaging way to learn typed code" # value_copy1: "CodeCombat is child’s personal tutor. Covering material aligned with national curriculum standards, your child will program algorithms, build websites and even design their own games." # value_head2: "Building critical skills for the 21st century" # value_copy2: "Your kids will learn how to navigate and become citizens in the digital world. CodeCombat is a solution that enhances your child’s critical thinking and resilience." # value_head3: "Heroes that your child will love" # value_copy3: "We know how important fun and engagement is for the developing brain, so we’ve packed in as much learning as we can while wrapping it up in a game they'll love." # dive_head1: "Not just for software engineers" # dive_intro: "Computer science skills have a wide range of applications. Take a look at a few examples below!" # medical_flag: "Medical Applications" # medical_flag_copy: "From mapping of the human genome to MRI machines, coding allows us to understand the body in ways we’ve never been able to before." # explore_flag: "Space Exploration" # explore_flag_copy: "Apollo got to the Moon thanks to hardworking human computers, and scientists use computer programs to analyze the gravity of planets and search for new stars." # filmaking_flag: "Filmmaking and Animation" # filmaking_flag_copy: "From the robotics of Jurassic Park to the incredible animation of Dreamworks and Pixar, films wouldn’t be the same without the digital creatives behind the scenes." # dive_head2: "Games are important for learning" # dive_par1: "Multiple studies have found that game-based learning promotes" # dive_link1: "cognitive development" # dive_par2: "in kids while also proving to be" # dive_link2: "more effective" # dive_par3: "in helping students" # dive_link3: "learn and retain knowledge" # dive_par4: "," # dive_link4: "concentrate" # dive_par5: ", and perform at a higher level of achievement." # dive_par6: "Game based learning is also good for developing" # dive_link5: "resilience" # dive_par7: ", cognitive reasoning, and" # dive_par8: ". Science is just telling us what learners already know. Children learn best by playing." # dive_link6: "executive functions" # dive_head3: "Team up with teachers" # dive_3_par1: "In the future, " # dive_3_link1: "coding is going to be as fundamental as learning to read and write" # dive_3_par2: ". We’ve worked closely with teachers to design and develop our content, and we can't wait to get your kids learning. Educational technology programs like CodeCombat work best when the teachers implement them consistently. Help us make that connection by introducing us to your child’s teachers!" # mission: "Our mission: to teach and engage" # mission1_heading: "Coding for today's generation" # mission2_heading: "Preparing for the future" # mission3_heading: "Supported by parents like you" # mission1_copy: "Our education specialists work closely with teachers to meet children where they are in the educational landscape. Kids learn skills that can be applied outside of the game because they learn how to solve problems, no matter what their learning style is." # mission2_copy: "A 2016 survey showed that 64% of girls in 3-5th grade want to learn how to code. There were 7 million job openings in 2015 required coding skills. We built CodeCombat because every child should be given a chance to create their best future." # mission3_copy: "At CodeCombat, we’re parents. We’re coders. We’re educators. But most of all, we’re people who believe in giving our kids the best opportunity for success in whatever it is they decide to do." # parent_modal: # refer_teacher: "Refer Teacher" # name: "Your Name" # parent_email: "Your Email" # teacher_email: "Teacher's Email" # message: "Message" # custom_message: "I just found CodeCombat and thought it'd be a great program for your classroom! It's a computer science learning platform with standards-aligned curriculum.\n\nComputer literacy is so important and I think this would be a great way to get students engaged in learning to code." # send: "Send Email" # hoc_2018: # banner: "Welcome to Hour of Code 2019!" # page_heading: "Your students will learn to code by building their own game!" # step_1: "Step 1: Watch Video Overview" # step_2: "Step 2: Try it Yourself" # step_3: "Step 3: Download Lesson Plan" # try_activity: "Try Activity" # download_pdf: "Download PDF" # teacher_signup_heading: "Turn Hour of Code into a Year of Code" # teacher_signup_blurb: "Everything you need to teach computer science, no prior experience needed." # teacher_signup_input_blurb: "Get first course free:" # teacher_signup_input_placeholder: "Teacher email address" # teacher_signup_input_button: "Get CS1 Free" # activities_header: "More Hour of Code Activities" # activity_label_1: "Escape the Dungeon!" # activity_label_2: " Beginner: Build a Game!" # activity_label_3: "Advanced: Build an Arcade Game!" # activity_button_1: "View Lesson" # about: "About CodeCombat" # about_copy: "A game-based, standards-aligned computer science program that teaches real, typed Python and JavaScript." # point1: "✓ Scaffolded" # point2: "✓ Differentiated" # point3: "✓ Assessments" # point4: "✓ Project-based courses" # point5: "✓ Student tracking" # point6: "✓ Full lesson plans" # title: "HOUR OF CODE 2019" # acronym: "HOC" # hoc_2018_interstitial: # welcome: "Welcome to CodeCombat's Hour of Code 2019!" # educator: "I'm an educator" # show_resources: "Show me teacher resources!" # student: "I'm a student" # ready_to_code: "I'm ready to code!" # hoc_2018_completion: # congratulations: "Congratulations on completing <b>Code, Play, Share!</b>" # send: "Send your Hour of Code game to friends and family!" # copy: "Copy URL" # get_certificate: "Get a certificate of completion to celebrate with your class!" # get_cert_btn: "Get Certificate" # first_name: "First Name" # last_initial: "Last Initial" # teacher_email: "Teacher's email address" # school_administrator: # title: "School Administrator Dashboard" # my_teachers: "My Teachers" # last_login: "Last Login" # licenses_used: "licenses used" # total_students: "total students" # active_students: "active students" # projects_created: "projects created" # other: "Other" # notice: "The following school administrators have view-only access to your classroom data:" # add_additional_teacher: "Need to add an additional teacher? Contact your CodeCombat Account Manager or email support@codecombat.com. " # license_stat_description: "Licenses available accounts for the total number of licenses available to the teacher, including Shared Licenses." # students_stat_description: "Total students accounts for all students across all classrooms, regardless of whether they have licenses applied." # active_students_stat_description: "Active students counts the number of students that have logged into CodeCombat in the last 60 days." # project_stat_description: "Projects created counts the total number of Game and Web development projects that have been created." # no_teachers: "You are not administrating any teachers." # interactives: # phenomenal_job: "Phenomenal Job!" # try_again: "Whoops, try again!" # select_statement_left: "Whoops, select a statement from the left before hitting \"Submit.\"" # fill_boxes: "Whoops, make sure to fill all boxes before hitting \"Submit.\"" # browser_recommendation: # title: "CodeCombat works best on Chrome!" # pitch_body: "For the best CodeCombat experience we recommend using the latest version of Chrome. Download the latest version of chrome by clicking the button below!" # download: "Download Chrome" # ignore: "Ignore"
117354
module.exports = nativeDescription: "Português (Portugal)", englishDescription: "Portuguese (Portugal)", translation: new_home: # title: "CodeCombat - Coding games to learn Python and JavaScript" # meta_keywords: "CodeCombat, python, javascript, Coding Games" # meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." # meta_og_url: "https://codecombat.com" # built_for_teachers_title: "A Coding Game Built with Teachers in Mind" # built_for_teachers_blurb: "Teaching kids to code can often feel overwhelming. CodeCombat helps all educators teach students how to code in either JavaScript or Python, two of the most popular programming languages. With a comprehensive curriculum that includes six computer science units and reinforces learning through project-based game development and web development units, kids will progress on a journey from basic syntax to recursion!" # built_for_teachers_subtitle1: "Computer Science" # built_for_teachers_subblurb1: "Starting with our free Introduction to Computer Science course, students master core coding concepts such as while/for loops, functions, and algorithms." # built_for_teachers_subtitle2: "Game Development" # built_for_teachers_subblurb2: "Learners construct mazes and use basic input handling to code their own games that can be shared with friends and family." # built_for_teachers_subtitle3: "Web Development" # built_for_teachers_subblurb3: "Using HTML, CSS, and jQuery, learners flex their creative muscles to program their own webpages with a custom URL to share with their classmates." # century_skills_title: "21st Century Skills" # century_skills_blurb1: "Students Don't Just Level Up Their Hero, They Level Up Themselves" # century_skills_quote1: "You mess up…so then you think about all of the possible ways to fix it, and then try again. I wouldn't be able to get here without trying hard." # century_skills_subtitle1: "Critical Thinking" # century_skills_subblurb1: "With coding puzzles that are naturally scaffolded into increasingly challenging levels, CodeCombat's programming game ensures kids are always practicing critical thinking." # century_skills_quote2: "Everyone else was making mazes, so I thought, ‘capture the flag’ and that’s what I did." # century_skills_subtitle2: "Creativity" # century_skills_subblurb2: "CodeCombat encourages students to showcase their creativity by building and sharing their own games and webpages." # century_skills_quote3: "If I got stuck on a level. I would work with people around me until we were all able to figure it out." # century_skills_subtitle3: "Collaboration" # century_skills_subblurb3: "Throughout the game, there are opportunities for students to collaborate when they get stuck and to work together using our pair programming guide." # century_skills_quote4: "I’ve always had aspirations of designing video games and learning how to code ... this is giving me a great starting point." # century_skills_subtitle4: "Communication" # century_skills_subblurb4: "Coding requires kids to practice new forms of communication, including communicating with the computer itself and conveying their ideas using the most efficient code." # classroom_in_box_title: "We Strive To:" # classroom_in_box_blurb1: "Engage every student so that they believe coding is for them." # classroom_in_box_blurb2: "Empower any educator to feel confident when teaching coding." # classroom_in_box_blurb3: "Inspire all school leaders to create a world-class computer science program." # creativity_rigor_title: "Where Creativity Meets Rigor" # creativity_rigor_subtitle1: "Make coding fun and teach real-world skills" # creativity_rigor_blurb1: "Students type real Python and JavaScript while playing games that encourage trial-and-error, critical thinking, and creativity. Students then apply the coding skills they’ve learned by developing their own games and websites in project-based courses." # creativity_rigor_subtitle2: "Reach students at their level" # creativity_rigor_blurb2: "Every CodeCombat level is scaffolded based on millions of data points and optimized to adapt to each learner. Practice levels and hints help students when they get stuck, and challenge levels assess students' learning throughout the game." # creativity_rigor_subtitle3: "Built for all teachers, regardless of experience" # creativity_rigor_blurb3: "CodeCombat’s self-paced, standards-aligned curriculum makes teaching computer science possible for everyone. CodeCombat equips teachers with the training, instructional resources, and dedicated support to feel confident and successful in the classroom." # featured_partners_title1: "Featured In" # featured_partners_title2: "Awards & Partners" # featured_partners_blurb1: "CollegeBoard Endorsed Provider" # featured_partners_blurb2: "Best Creativity Tool for Students" # featured_partners_blurb3: "Top Pick for Learning" # featured_partners_blurb4: "Code.org Official Partner" # featured_partners_blurb5: "CSforAll Official Member" # featured_partners_blurb6: "Hour of Code Activity Partner" # for_leaders_title: "For School Leaders" # for_leaders_blurb: "A Comprehensive, Standards-Aligned Computer Science Program" # for_leaders_subtitle1: "Easy Implementation" # for_leaders_subblurb1: "A web-based program that requires no IT support. Get started in under 5 minutes using Google or Clever Single Sign-On (SSO)." # for_leaders_subtitle2: "Full Coding Curriculum" # for_leaders_subblurb2: "A standards-aligned curriculum with instructional resources and professional development to enable any teacher to teach computer science." # for_leaders_subtitle3: "Flexible Use Cases" # for_leaders_subblurb3: "Whether you want to build a Middle School coding elective, a CTE pathway, or an AP Computer Science Principles class, CodeCombat is tailored to suit your needs." # for_leaders_subtitle4: "Real-World Skills" # for_leaders_subblurb4: "Students build grit and develop a growth mindset through coding challenges that prepare them for the 500K+ open computing jobs." # for_teachers_title: "For Teachers" # for_teachers_blurb: "Tools to Unlock Student Potential" # for_teachers_subtitle1: "Project-Based Learning" # for_teachers_subblurb1: "Promote creativity, problem-solving, and confidence in project-based courses where students develop their own games and webpages." # for_teachers_subtitle2: "Teacher Dashboard" # for_teachers_subblurb2: "View data on student progress, discover curriculum resources, and access real-time support to empower student learning." # for_teachers_subtitle3: "Built-in Assessments" # for_teachers_subblurb3: "Personalize instruction and ensure students understand core concepts with formative and summative assessments." # for_teachers_subtitle4: "Automatic Differentiation" # for_teachers_subblurb4: "Engage all learners in a diverse classroom with practice levels that adapt to each student's learning needs." # game_based_blurb: "CodeCombat is a game-based computer science program where students type real code and see their characters react in real time." # get_started: "Get started" # global_title: "Join Our Global Community of Learners and Educators" # global_subtitle1: "Learners" # global_subtitle2: "Lines of Code" # global_subtitle3: "Teachers" # global_subtitle4: "Countries" # go_to_my_classes: "Go to my classes" # go_to_my_courses: "Go to my courses" # quotes_quote1: "Name any program online, I’ve tried it. None of them match up to CodeCombat. Any teacher who wants their students to learn how to code... start here!" # quotes_quote2: " I was surprised about how easy and intuitive CodeCombat makes learning computer science. The scores on the AP exam were much higher than I expected and I believe CodeCombat is the reason why this was the case." # quotes_quote3: "CodeCombat has been the most beneficial for teaching my students real-life coding capabilities. My husband is a software engineer and he has tested out all of my programs. He put this as his top choice." # quotes_quote4: "The feedback … has been so positive that we are structuring a computer science class around CodeCombat. The program really engages the students with a gaming style platform that is entertaining and instructional at the same time. Keep up the good work, CodeCombat!" # see_example: "See example" slogan: "A forma mais cativante de aprender código real." # {change} # teach_cs1_free: "Teach CS1 Free" # teachers_love_codecombat_title: "Teachers Love CodeCombat" # teachers_love_codecombat_blurb1: "Report that their students enjoy using CodeCombat to learn how to code" # teachers_love_codecombat_blurb2: "Would recommend CodeCombat to other computer science teachers" # teachers_love_codecombat_blurb3: "Say that CodeCombat helps them support students’ problem solving abilities" # teachers_love_codecombat_subblurb: "In partnership with McREL International, a leader in research-based guidance and evaluations of educational technology." # try_the_game: "Try the game" classroom_edition: "Edição de Turma:" learn_to_code: "Aprender a programar:" play_now: "Jogar Agora" # im_an_educator: "I'm an Educator" im_a_teacher: "Sou um Professor" im_a_student: "Sou um Estudante" learn_more: "Saber mais" classroom_in_a_box: "Uma turma num pacote para ensinar ciências da computação." codecombat_is: "O CodeCombat é uma plataforma <strong>para estudantes</strong> para aprender ciências da computação enquanto se joga um jogo real." our_courses: "Os nossos cursos foram especificamente testados para <strong>terem sucesso na sala de aula</strong>, até para professores com pouca ou nenhuma experiência anterior de programação." watch_how: "Vê como o CodeCombat está a transformar o modo como as pessoas aprendem ciências da computação." top_screenshots_hint: "Os estudantes escrevem código e veem as alterações deles atualizarem em tempo real" designed_with: "Desenhado a pensar nos professores" real_code: "Código real e escrito" from_the_first_level: "desde o primeiro nível" getting_students: "Apresentar código escrito aos estudantes o mais rapidamete possível é crítico para aprenderem a sintaxe e a estrutura adequadas da programação." educator_resources: "Recursos para professores" course_guides: "e guias dos cursos" teaching_computer_science: "Ensinar ciências da computação não requer um curso caro, porque nós fornecemos ferramentas para ajudar todo o tipo de professores." accessible_to: "Acessível a" everyone: "todos" democratizing: "Democratizar o processo de aprender a programar está na base da nossa filosofia. Todos devem poder aprender a programar." forgot_learning: "Acho que eles se esqueceram que estavam a aprender alguma coisa." wanted_to_do: "Programar é algo que sempre quis fazer e nunca pensei que poderia aprender isso na escola." builds_concepts_up: "Gosto da forma como o CodeCombat desenvolve os conceitos. É muito fácil compreendê-los e é divertido descobri-los." why_games: "Porque é que aprender através de jogos é importante?" games_reward: "Os jogos recompensam o esforço produtivo." encourage: "Jogar é algo que encoraja a interação, a descoberta e a tentativa erro. Um bom jogo desafia o jogador a dominar habilidades com o tempo, que é o mesmo processo fundamental que os estudantes atravessam quando aprendem." excel: "Os jogos são excelentes a recompensar o" struggle: "esforço produtivo" kind_of_struggle: "o tipo de esforço que resulta numa aprendizagem que é cativante e" motivating: "motivadora" not_tedious: "não entediante." gaming_is_good: "Estudos sugerem que jogar é bom para o cérebro das crianças. (é verdade!)" # game_based: "When game-based learning systems are" # compared: "compared" # conventional: "against conventional assessment methods, the difference is clear: games are better at helping students retain knowledge, concentrate and" # perform_at_higher_level: "perform at a higher level of achievement" # feedback: "Games also provide real-time feedback that allows students to adjust their solution path and understand concepts more holistically, instead of being limited to just “correct” or “incorrect” answers." real_game: "Um jogo a sério, jogado com código a sério." # great_game: "A great game is more than just badges and achievements - it’s about a player’s journey, well-designed puzzles, and the ability to tackle challenges with agency and confidence." # agency: "CodeCombat is a game that gives players that agency and confidence with our robust typed code engine, which helps beginner and advanced students alike write proper, valid code." # request_demo_title: "Get your students started today!" # request_demo_subtitle: "Request a demo and get your students started in less than an hour." # get_started_title: "Set up your class today" # get_started_subtitle: "Set up a class, add your students, and monitor their progress as they learn computer science." request_demo: "Pedir uma Demonstração" # request_quote: "Request a Quote" setup_a_class: "Configurar uma Turma" have_an_account: "Tens uma conta?" logged_in_as: "Atualmente tens sessão iniciada como" # computer_science: "Our self-paced courses cover basic syntax to advanced concepts" ffa: "Grátis para todos os estudantes" coming_soon: "Mais, brevemente!" courses_available_in: "Os cursos estão disponíveis em JavaScript e Python. Os cursos de Desenvolvimento Web utilizam HTML, CSS e jQuery." # boast: "Boasts riddles that are complex enough to fascinate gamers and coders alike." # winning: "A winning combination of RPG gameplay and programming homework that pulls off making kid-friendly education legitimately enjoyable." run_class: "Tudo o que precisas para teres uma turma de ciências da computação na tua escola hoje, sem serem necessárias bases de CC." goto_classes: "Ir para As Minhas Turmas" view_profile: "Ver o Meu Perfil" view_progress: "Ver Progresso" go_to_courses: "Ir para Os Meus Cursos" want_coco: "Queres o CodeCombat na tua escola?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" map: "Mapa" play: "Níveis" # The top nav bar entry where players choose which levels to play community: "Comunidade" courses: "Cursos" blog: "Blog" forum: "Fórum" account: "<NAME>" my_account: "<NAME>" profile: "Perfil" home: "Início" contribute: "Contribuir" legal: "Legal" privacy: "Aviso de Privacidade" about: "Sobre" # impact: "Impact" contact: "Contactar" twitter_follow: "Seguir" my_classrooms: "As Minhas Turmas" my_courses: "Os Meus Cursos" # my_teachers: "My Teachers" careers: "<NAME>" facebook: "Facebook" twitter: "Twitter" create_a_class: "Criar uma Turma" other: "Outros" learn_to_code: "Aprende a Programar!" toggle_nav: "Alternar navegação" schools: "Escolas" get_involved: "Envolve-te" open_source: "Open source (GitHub)" support: "Suporte" faqs: "FAQs" copyright_prefix: "Direitos" copyright_suffix: "Todos os Direitos Reservados." help_pref: "Precisas de ajuda? Envia um e-mail para" help_suff: "e nós entraremos em contacto!" resource_hub: "Centro de Recursos" # apcsp: "AP CS Principles" parent: "Educadores" # browser_recommendation: "For the best experience we recommend using the latest version of Chrome. Download the browser here!" modal: close: "Fechar" okay: "Ok" # cancel: "Cancel" not_found: page_not_found: "Página não encontrada" diplomat_suggestion: title: "Ajuda a traduzir o CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Precisamos das tuas habilidades linguísticas." pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores de todo o mundo. Muitos deles querem jogar em Português, mas não falam Inglês, por isso, se sabes falar ambas, por favor considera registar-te como Diplomata para ajudares a traduzir o sítio do CodeCombat e todos os níveis para Português." missing_translations: "Até conseguirmos traduzir tudo para Português, irás ver em Inglês o que não estiver disponível em Português." learn_more: "Sabe mais sobre seres um Diplomata" subscribe_as_diplomat: "Subscreve-te como Diplomata" play: # title: "Play CodeCombat Levels - Learn Python, JavaScript, and HTML" # meta_description: "Learn programming with a coding game for beginners. Learn Python or JavaScript as you solve mazes, make your own games, and level up. Challenge your friends in multiplayer arena levels!" # level_title: "__level__ - Learn to Code in Python, JavaScript, HTML" # video_title: "__video__ | Video Level" # game_development_title: "__level__ | Game Development" # web_development_title: "__level__ | Web Development" anon_signup_title_1: "O CodeCombat tem uma" anon_signup_title_2: "Versão para Turmas!" anon_signup_enter_code: "Introduz um Código de Truma:" anon_signup_ask_teacher: "Não tens um? Pede ao teu professor!" anon_signup_create_class: "Queres criar uma turma?" anon_signup_setup_class: "Configura um turma, adiciona estudantes e monitoriza o progresso!" anon_signup_create_teacher: "Criar uma conta de professor gratuita" play_as: "Jogar Com<NAME>" # Ladder page # get_course_for_class: "Assign Game Development and more to your classes!" # request_licenses: "Contact our school specialists for details." compete: "Competir!" # Course details page spectate: "Assistir" # Ladder page players: "jogadores" # Hover over a level on /play hours_played: "horas jogadas" # Hover over a level on /play items: "Itens" # Tooltip on item shop button from /play unlock: "Desbloquear" # For purchasing items and heroes confirm: "Confirmar" owned: "Obtido" # For items you own locked: "Bloqueado" available: "Disponível" skills_granted: "Habilidades Garantidas" # Property documentation details heroes: "Heróis" # Tooltip on hero shop button from /play achievements: "Conquistas" # Tooltip on achievement list button from /play settings: "Definições" # Tooltip on settings button from /play poll: "Votações" # Tooltip on poll button from /play next: "Próximo" # Go from choose hero to choose inventory before playing a level change_hero: "Alterar Herói" # Go back from choose inventory to choose hero change_hero_or_language: "Alterar Herói ou Linguagem" buy_gems: "Comprar Gemas" subscribers_only: "Apenas para Subscritores!" subscribe_unlock: "Subscreve-te para Desbloqueares!" subscriber_heroes: "Subscreve-te hoje para desbloqueares de imediato a Amara, a Hushbaum, e o Hattori!" subscriber_gems: "Subscreve-te hoje para adquirires este herói com gemas!" anonymous: "<NAME>" level_difficulty: "Dificuldade: " awaiting_levels_adventurer_prefix: "Lançamos novos níveis todas as semanas." awaiting_levels_adventurer: "Regista-te como Aventureiro" awaiting_levels_adventurer_suffix: "para seres o primeiro a jogar níveis novos." adjust_volume: "Ajustar volume" campaign_multiplayer: "Arenas Multijogador" campaign_multiplayer_description: "... nas quais programas contra outros jogadores." # brain_pop_done: "You’ve defeated the Ogres with code! You win!" # brain_pop_challenge: "Challenge yourself to play again using a different programming language!" # replay: "Replay" back_to_classroom: "Voltar à Turma" teacher_button: "Para Professores" # get_more_codecombat: "Get More CodeCombat" code: if: "se" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "senão" elif: "senão se" while: "enquanto" loop: "repetir" for: "para" break: "parar" continue: "continuar" pass: "passar" return: "devolver" then: "então" do: "fazer" end: "fim" function: "função" def: "definir" var: "variável" self: "próprio" hero: "herói" this: "isto" or: "ou" "||": "ou" and: "e" "&&": "e" not: "não" "!": "não" "=": "atribuir" "==": "é igual a" "===": "é estritamente igual a" "!=": "não é igual a" "!==": "não é estritamente igual a" ">": "é maior do que" ">=": "é maior do que ou igual a" "<": "é menor do que" "<=": "é menor do que ou igual a" "*": "multiplicado por" "/": "dividido por" "+": "mais" "-": "menos" "+=": "adicionar e atribuir" "-=": "subtrair e atribuir" True: "Verdadeiro" true: "verdadeiro" False: "Falso" false: "falso" undefined: "não definido" null: "nulo" nil: "nada" None: "Nenhum" share_progress_modal: blurb: "Estás a fazer grandes progressos! Conta ao teu educador o quanto aprendeste com o CodeCombat." email_invalid: "Endereço de e-mail inválido." form_blurb: "Introduz o e-mail do teu educador abaixo e nós vamos mostrar-lhe!" form_label: "Endereço de E-mail" placeholder: "endereço de e-mail" title: "Excelente Trabalho, Aprendiz" login: sign_up: "Criar Conta" email_or_username: "E-<NAME>" log_in: "Iniciar Sessão" logging_in: "A Iniciar Sessão" log_out: "Sair" forgot_password: "<PASSWORD>?" finishing: "A Terminar" sign_in_with_facebook: "Iniciar sessão com o FB" sign_in_with_gplus: "Iniciar sessão com o Google" signup_switch: "Queres criar uma conta?" signup: # complete_subscription: "Complete Subscription" create_student_header: "Criar Conta de Estudante" create_teacher_header: "Criar Conta de Professor" create_individual_header: "Criar Conta Individual" email_announcements: "Receber anúncios sobre níveis e funcionalidades novos do CodeCombat!" sign_in_to_continue: "Inicia sessão ou cria uma conta para continuares" # teacher_email_announcements: "Keep me updated on new teacher resources, curriculum, and courses!" creating: "A Criar Conta..." sign_up: "Registar" log_in: "iniciar sessão com palavra-passe" # login: "Login" required: "Precisas de iniciar sessão antes de prosseguires." login_switch: "Já tens uma conta?" optional: "opcional" # connected_gplus_header: "You've successfully connected with Google+!" # connected_gplus_p: "Finish signing up so you can log in with your Google+ account." # connected_facebook_header: "You've successfully connected with Facebook!" # connected_facebook_p: "Finish signing up so you can log in with your Facebook account." hey_students: "Estudantes, introduzam o código de turma do vosso professor." birthday: "Aniversário" # parent_email_blurb: "We know you can't wait to learn programming &mdash; we're excited too! Your parents will receive an email with further instructions on how to create an account for you. Email {{email_link}} if you have any questions." # classroom_not_found: "No classes exist with this Class Code. Check your spelling or ask your teacher for help." checking: "A verificar..." account_exists: "Este e-mail já está a ser usado:" sign_in: "Iniciar sessão" email_good: "O e-mail parece bom!" name_taken: "Nome de utilizador já escolhido! Que tal {{suggestedName}}?" name_available: "Nome de utilizador disponível!" name_is_email: "O nome de utilizador não pode ser um e-mail" choose_type: "Escolhe o teu tipo de conta:" teacher_type_1: "Ensina programção usando o CodeCombat!" teacher_type_2: "Configura a tua turma" teacher_type_3: "Acede aos Guias dos Cursos" teacher_type_4: "Vê o progresso dos estudantes" signup_as_teacher: "Registar como Professor" student_type_1: "Aprende a programar enquanto jogas um jogo cativante!" student_type_2: "Joga com a tua turma" student_type_3: "Compete em arenas" student_type_4: "Escolhe o teu herói!" student_type_5: "Prepara o teu Código de Turma!" signup_as_student: "Registar como Estudante" individuals_or_parents: "Individuais e Educadores" individual_type: "Para jogadores a aprender a programar fora de uma turma. Os educadores devem registar-se aqui." signup_as_individual: "Registar como Individual" enter_class_code: "Introduz o teu Código de Turma" enter_birthdate: "Introduz a tua data de nascimento:" parent_use_birthdate: "Educadores, usem a vossa data de nascimento." ask_teacher_1: "Pergunta ao teu professor pelo teu Código de Turma." ask_teacher_2: "Não fazes parte de uma turma? Cria uma " ask_teacher_3: "Conta Individual" ask_teacher_4: " então." about_to_join: "Estás prestes a entrar em:" enter_parent_email: "Introduz o e-mail do teu educador:" # parent_email_error: "Something went wrong when trying to send the email. Check the email address and try again." # parent_email_sent: "We’ve sent an email with further instructions on how to create an account. Ask your parent to check their inbox." account_created: "Conta Criada!" confirm_student_blurb: "Aponta a tua informação para que não a esqueças. O teu professor também te pode ajudar a reiniciar a tua palavra-passe a qualquer altura." confirm_individual_blurb: "Aponta a tua informação de início de sessão caso precises dela mais tarde. Verifica o teu e-mail para que possas recuperar a tua conta se alguma vez esqueceres a tua palavra-passe - verifica a tua caixa de entrada!" write_this_down: "Aponta isto:" start_playing: "Começar a Jogar!" # sso_connected: "Successfully connected with:" select_your_starting_hero: "Escolhe o Teu Herói Inicial:" you_can_always_change_your_hero_later: "Podes sempre alterar o teu herói mais tarde." # finish: "Finish" # teacher_ready_to_create_class: "You're ready to create your first class!" # teacher_students_can_start_now: "Your students will be able to start playing the first course, Introduction to Computer Science, immediately." # teacher_list_create_class: "On the next screen you will be able to create a new class." # teacher_list_add_students: "Add students to the class by clicking the View Class link, then sending your students the Class Code or URL. You can also invite them via email if they have email addresses." # teacher_list_resource_hub_1: "Check out the" # teacher_list_resource_hub_2: "Course Guides" # teacher_list_resource_hub_3: "for solutions to every level, and the" # teacher_list_resource_hub_4: "Resource Hub" # teacher_list_resource_hub_5: "for curriculum guides, activities, and more!" # teacher_additional_questions: "That’s it! If you need additional help or have questions, reach out to __supportEmail__." # dont_use_our_email_silly: "Don't put our email here! Put your parent's email." # want_codecombat_in_school: "Want to play CodeCombat all the time?" # eu_confirmation: "I agree to allow CodeCombat to store my data on US servers." # eu_confirmation_place_of_processing: "Learn more about the possible risks" # eu_confirmation_student: "If you are not sure, ask your teacher." # eu_confirmation_individual: "If you do not want us to store your data on US servers, you can always keep playing anonymously without saving your code." recover: recover_account_title: "Recuperar Conta" send_password: "<PASSWORD>" recovery_sent: "E-mail de recuperação enviado." items: primary: "Primários" secondary: "Secundários" armor: "Armadura" accessories: "Acessórios" misc: "Vários" books: "Livros" common: # default_title: "CodeCombat - Coding games to learn Python and JavaScript" # default_meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." back: "Voltar" # When used as an action verb, like "Navigate backward" coming_soon: "Brevemente!" continue: "Continuar" # When used as an action verb, like "Continue forward" next: "Próximo" default_code: "Código Original" loading: "A Carregar..." overview: "Visão Geral" processing: "A processar..." solution: "Solução" table_of_contents: "Tabela de Conteúdos" intro: "Introdução" saving: "A Guardar..." sending: "A Enviar..." send: "Enviar" sent: "Enviado" cancel: "Cancelar" save: "Guardar" publish: "Publicar" create: "Criar" fork: "Bifurcar" play: "Jogar" # When used as an action verb, like "Play next level" retry: "Tentar Novamente" actions: "Ações" info: "Informações" help: "Ajuda" watch: "Vigiar" unwatch: "Desvigiar" submit_patch: "Submeter Atualização" submit_changes: "Submeter Alterações" save_changes: "Guardar Alterações" required_field: "necessário" # submit: "Submit" # replay: "Replay" # complete: "Complete" general: and: "e" name: "Nome" date: "Data" body: "Corpo" version: "Versão" pending: "Pendentes" accepted: "Aceites" rejected: "Rejeitadas" withdrawn: "Canceladas" accept: "Aceitar" accept_and_save: "Aceitar&Guardar" reject: "Rejeitar" withdraw: "Cancelar" submitter: "Submissor" submitted: "Submeteu" commit_msg: "Mensagem da Submissão" version_history: "Histórico de Versões" version_history_for: "Histórico de Versões para: " select_changes: "Seleciona duas das alterações abaixo para veres a diferença." undo_prefix: "Desfazer" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Refazer" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Jogar pré-visualização do nível atual" result: "Resultado" results: "Resultados" description: "Descrição" or: "ou" subject: "Assunto" email: "E-mail" password: "<PASSWORD>" confirm_password: "<PASSWORD>" message: "Mensagem" code: "Código" ladder: "Classificação" when: "Quando" opponent: "Adversário" rank: "Classificação" score: "Pontuação" win: "Vitória" loss: "Derrota" tie: "Empate" easy: "Fácil" medium: "Médio" hard: "Difícil" player: "<NAME>" player_level: "Nível" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Guerreiro" ranger: "Arqueiro" wizard: "Feiticeiro" first_name: "<NAME>" last_name: "<NAME>" last_initial: "Última Inicial" username: "Nome de utilizador" contact_us: "Contacta-nos" close_window: "Fechar Janela" learn_more: "Saber Mais" more: "Mais" fewer: "Menos" with: "com" units: second: "segundo" seconds: "segundos" sec: "seg" minute: "minuto" minutes: "minutos" hour: "hora" hours: "horas" day: "dia" days: "dias" week: "semana" weeks: "semanas" month: "mês" months: "meses" year: "ano" years: "anos" play_level: back_to_map: "Voltar ao Mapa" directions: "Direções" edit_level: "Editar Nível" keep_learning: "Continuar a Aprender" explore_codecombat: "Explorar o CodeCombat" finished_hoc: "Terminei a minha Hora do Código" get_certificate: "Obtém o teu certificado!" level_complete: "Nível Completo" completed_level: "Nível Completo:" course: "Curso:" done: "Concluir" next_level: "Próximo Nível" # combo_challenge: "Combo Challenge" # concept_challenge: "Concept Challenge" # challenge_unlocked: "Challenge Unlocked" # combo_challenge_unlocked: "Combo Challenge Unlocked" # concept_challenge_unlocked: "Concept Challenge Unlocked" # concept_challenge_complete: "Concept Challenge Complete!" # combo_challenge_complete: "Combo Challenge Complete!" # combo_challenge_complete_body: "Great job, it looks like you're well on your way to understanding __concept__!" # replay_level: "Replay Level" combo_concepts_used: "__complete__/__total__ Conceitos Usados" # combo_all_concepts_used: "You used all concepts possible to solve the challenge. Great job!" # combo_not_all_concepts_used: "You used __complete__ out of the __total__ concepts possible to solve the challenge. Try to get all __total__ concepts next time!" start_challenge: "Começar Desafio" next_game: "Próximo jogo" languages: "Linguagens" programming_language: "Linguagem de programação" show_menu: "Mostrar o menu do jogo" home: "Início" # Not used any more, will be removed soon. level: "Nível" # Like "Level: Dungeons of Kithgard" skip: "Saltar" game_menu: "Menu do Jogo" restart: "Reiniciar" goals: "Objetivos" goal: "Objetivo" # challenge_level_goals: "Challenge Level Goals" # challenge_level_goal: "Challenge Level Goal" # concept_challenge_goals: "Concept Challenge Goals" # combo_challenge_goals: "Challenge Level Goals" # concept_challenge_goal: "Concept Challenge Goal" # combo_challenge_goal: "Challenge Level Goal" running: "A Executar..." success: "Sucesso!" incomplete: "Incompletos" timed_out: "Ficaste sem tempo" failing: "A falhar" reload: "Recarregar" reload_title: "Recarregar o Código Todo?" reload_really: "Tens a certeza que queres recarregar este nível de volta ao início?" reload_confirm: "Recarregar Tudo" # restart_really: "Are you sure you want to restart the level? You'll loose all the code you've written." # restart_confirm: "Yes, Restart" test_level: "Testar Nível" victory: "Vitória" victory_title_prefix: "" victory_title_suffix: " Concluído" victory_sign_up: "Criar Conta para Guardar Progresso" victory_sign_up_poke: "Queres guardar o teu código? Cria uma conta grátis!" victory_rate_the_level: "Quão divertido foi este nível?" victory_return_to_ladder: "Voltar à Classificação" victory_saving_progress: "A Guardar Progresso" victory_go_home: "Ir para o Início" victory_review: "Conta-nos mais!" victory_review_placeholder: "Como foi o nível?" victory_hour_of_code_done: "Terminaste?" victory_hour_of_code_done_yes: "Sim, terminei a minha Hora do Código™!" victory_experience_gained: "XP Ganho" victory_gems_gained: "Gemas Ganhas" victory_new_item: "Novo Item" victory_new_hero: "Novo Herói" # victory_viking_code_school: "Holy smokes, that was a hard level you just beat! If you aren't already a software developer, you should be. You just got fast-tracked for acceptance with Viking Code School, where you can take your skills to the next level and become a professional web developer in 14 weeks." victory_become_a_viking: "Torna-te um Viking" victory_no_progress_for_teachers: "O progresso não é guardado para professores. Mas podes adicionar à tua turma uma conta de estudante para ti." tome_cast_button_run: "Executar" tome_cast_button_running: "A Executar" tome_cast_button_ran: "Executado" # tome_cast_button_update: "Update" tome_submit_button: "Submeter" tome_reload_method: "Recarregar o código original para recomeçar o nível" tome_available_spells: "Feitiços Disponíveis" tome_your_skills: "As Tuas Habilidades" hints: "Dicas" # videos: "Videos" hints_title: "Dica {{number}}" code_saved: "Código Guardado" skip_tutorial: "Saltar (esc)" keyboard_shortcuts: "Atalhos de Teclado" loading_start: "Iniciar Nível" # loading_start_combo: "Start Combo Challenge" # loading_start_concept: "Start Concept Challenge" problem_alert_title: "Corrige o Teu Código" time_current: "Agora:" time_total: "Máximo:" time_goto: "Ir para:" non_user_code_problem_title: "Impossível Carregar o Nível" infinite_loop_title: "'Loop' Infinito Detetado" infinite_loop_description: "O código inicial para construir o mundo nunca parou de ser executado. Provavelmente é muito lento ou contém um 'loop' infinito. Ou talvez haja um erro. Podes tentar executar este código novamente ou reiniciá-lo para o estado predefinido. Se isso não resultar, avisa-nos, por favor." check_dev_console: "Também podes abrir a consola para programadores para veres o que possa estar a correr mal." check_dev_console_link: "(instruções)" infinite_loop_try_again: "Tentar Novamente" infinite_loop_reset_level: "Reiniciar Nível" infinite_loop_comment_out: "Comentar o Meu Código" tip_toggle_play: "Alterna entre Jogar e Pausar com Ctrl+P." tip_scrub_shortcut: "Usa Ctrl+[ para rebobinar e Ctrl+] para avançar." tip_guide_exists: "Clica no guia, dentro do menu do jogo (no topo da página), para informações úteis." tip_open_source: "O CodeCombat faz parte da comunidade open source!" tip_tell_friends: "Estás a gostar do CodeCombat? Fala de nós aos teus amigos!" tip_beta_launch: "O CodeCombat lançou o seu beta em outubro de 2013." tip_think_solution: "Pensa na solução, não no problema." tip_theory_practice: "Teoricamente, não há diferença entre a teoria e a prática. Mas na prática, há. - <NAME>" tip_error_free: "Há duas formas de escrever programas sem erros; apenas a terceira funciona. - <NAME>" tip_debugging_program: "Se depurar é o processo de remover erros, então programar deve ser o processo de os introduzir. - <NAME>" tip_forums: "Vai aos fóruns e diz-nos o que pensas!" tip_baby_coders: "No futuro, até os bebés serão Arcomagos." tip_morale_improves: "O carregamento vai continuar até que a moral melhore." tip_all_species: "Acreditamos em oportunidades iguais para todas as espécies, em relação a aprenderem a programar." tip_reticulating: "A reticular espinhas." tip_harry: "És um Feiticeiro, " tip_great_responsibility: "Com uma grande habilidade de programação vem uma grande responsabilidade de depuração." tip_munchkin: "Se não comeres os teus vegetais, um ogre virá atrás de ti enquanto estiveres a dormir." tip_binary: "Há apenas 10 tipos de pessoas no mundo: aquelas que percebem binário e aquelas que não." tip_commitment_yoda: "Um programador deve ter o compromisso mais profundo, a mente mais séria. ~ Yoda" tip_no_try: "Fazer. Ou não fazer. Não há nenhum tentar. - Yoda" tip_patience: "Paciência tu deves ter, jovem Padawan. - Yoda" tip_documented_bug: "Um erro documentado não é um erro; é uma funcionalidade." tip_impossible: "Parece sempre impossível até ser feito. - <NAME>" tip_talk_is_cheap: "Falar é fácil. Mostra-me o código. - <NAME>" tip_first_language: "A coisa mais desastrosa que podes aprender é a tua primeira linguagem de programação. - <NAME>" tip_hardware_problem: "P: Quantos programadores são necessários para mudar uma lâmpada? R: Nenhum, é um problema de 'hardware'." tip_hofstadters_law: "<NAME>: Tudo demora sempre mais do que pensas, mesmo quando tens em conta a <NAME>." tip_premature_optimization: "Uma otimização permatura é a raíz de todo o mal. - <NAME>" tip_brute_force: "Quando em dúvida, usa a força bruta. - <NAME>" tip_extrapolation: "Há apenas dois tipos de pessoas: aquelas que conseguem tirar uma conclusão a partir de dados reduzidos..." tip_superpower: "A programação é a coisa mais próxima de um superpoder que temos." tip_control_destiny: "Em open source a sério, tens o direito de controlares o teu próprio destino. - <NAME>" tip_no_code: "Nenhum código é mais rápido que código não existente." tip_code_never_lies: "O código nunca mente, mas os comentários às vezes sim. — <NAME>" tip_reusable_software: "Antes de um software poder ser reutilizável, primeiro tem de ser utilizável." tip_optimization_operator: "Todas as linguagens têm um operador de otimização. Na maior parte delas esse operador é ‘//’." tip_lines_of_code: "Medir o progresso em programação pelo número de linhas de código é como medir o progresso da construção de um avião pelo peso. — <NAME>" tip_source_code: "Quero mudar o mundo, mas não há maneira de me darem o código-fonte." tip_javascript_java: "Java é para JavaScript o mesmo que Car<NAME> (Car) para Tapete (Carpet). - <NAME>" tip_move_forward: "Faças o que fizeres, segue em frente. - <NAME> Jr" tip_google: "Tens um problema que não consegues resolver? Vai ao Google!" tip_adding_evil: "A acrescentar uma pitada de mal." tip_hate_computers: "É o problema das pessoas que acham que odeiam coputadores. O que elas odeiam mesmo são maus programadores. - <NAME>" tip_open_source_contribute: "Podes ajudar a melhorar o CodeCombat!" tip_recurse: "Iterar é humano, recursar é divino. - <NAME>" tip_free_your_mind: "Tens de libertar tudo, Neo. Medo, dúvida e descrença. Liberta a tua mente. - Morpheus" tip_strong_opponents: "Até o mais forte dos adversários tem uma fraqueza. - <NAME>" tip_paper_and_pen: "Antes de começares a programar, podes sempre planear com uma folha de papel e uma caneta." tip_solve_then_write: "Primeiro, resolve o problema. Depois, escreve o código. - <NAME>" tip_compiler_ignores_comments: "Às vezes acho que o compilador ignora os meus comentários." tip_understand_recursion: "A única forma de entender recursão é entender recursão." # tip_life_and_polymorphism: "Open Source is like a totally polymorphic heterogeneous structure: All types are welcome." # tip_mistakes_proof_of_trying: "Mistakes in your code are just proof that you are trying." # tip_adding_orgres: "Rounding up ogres." # tip_sharpening_swords: "Sharpening the swords." # tip_ratatouille: "You must not let anyone define your limits because of where you come from. Your only limit is your soul. - <NAME>, R<NAME>ille" # tip_nemo: "When life gets you down, want to know what you've gotta do? Just keep swimming, just keep swimming. - <NAME>" # tip_internet_weather: "Just move to the internet, it's great here. We get to live inside where the weather is always awesome. - <NAME>" # tip_nerds: "Nerds are allowed to love stuff, like jump-up-and-down-in-the-chair-can't-control-yourself love it. - <NAME>" # tip_self_taught: "I taught myself 90% of what I've learned. And that's normal! - <NAME>" # tip_luna_lovegood: "Don't worry, you're just as sane as I am. - <NAME>" # tip_good_idea: "The best way to have a good idea is to have a lot of ideas. - <NAME>" # tip_programming_not_about_computers: "Computer Science is no more about computers than astronomy is about telescopes. - Edsger Dijkstra" # tip_mulan: "Believe you can, then you will. - <NAME>" project_complete: "Projeto Completado!" # share_this_project: "Share this project with friends or family:" ready_to_share: "Pronto para publicares o teu projeto?" # click_publish: "Click \"Publish\" to make it appear in the class gallery, then check out what your classmates built! You can come back and continue to work on this project. Any further changes will automatically be saved and shared with your classmates." # already_published_prefix: "Your changes have been published to the class gallery." # already_published_suffix: "Keep experimenting and making this project even better, or see what the rest of your class has built! Your changes will automatically be saved and shared with your classmates." view_gallery: "Ver Galeria" project_published_noty: "O teu nível foi publicado!" keep_editing: "Continuar a Editar" # learn_new_concepts: "Learn new concepts" # watch_a_video: "Watch a video on __concept_name__" # concept_unlocked: "Concept Unlocked" # use_at_least_one_concept: "Use at least one concept: " # command_bank: "Command Bank" # learning_goals: "Learning Goals" # start: "Start" # vega_character: "Vega Character" # click_to_continue: "Click to Continue" apis: methods: "Métodos" events: "Eventos" # handlers: "Handlers" properties: "Propriedades" # snippets: "Snippets" # spawnable: "Spawnable" html: "HTML" math: "Matemática" # array: "Array" object: "Objeto" # string: "String" function: "Função" vector: "Vetor" date: "Data" jquery: "jQuery" json: "JSON" number: "Número" webjavascript: "JavaScript" # amazon_hoc: # title: "Keep Learning with Amazon!" # congrats: "Congratulations on conquering that challenging Hour of Code!" # educate_1: "Now, keep learning about coding and cloud computing with AWS Educate, an exciting, free program from Amazon for both students and teachers. With AWS Educate, you can earn cool badges as you learn about the basics of the cloud and cutting-edge technologies such as gaming, virtual reality, and Alexa." # educate_2: "Learn more and sign up here" # future_eng_1: "You can also try to build your own school facts skill for Alexa" # future_eng_2: "here" # future_eng_3: "(device is not required). This Alexa activity is brought to you by the" # future_eng_4: "Amazon Future Engineer" # future_eng_5: "program which creates learning and work opportunities for all K-12 students in the United States who wish to pursue computer science." play_game_dev_level: created_by: "Criado por {{name}}" created_during_hoc: "Criado durante a Hora do Código" restart: "Recomeçar Nível" play: "Jogar Nível" play_more_codecombat: "Jogar Mais CodeCombat" default_student_instructions: "Clica para controlares o teu herói e ganhares o teu jogo!" goal_survive: "Sobrevive." goal_survive_time: "Sobrevive por __seconds__ segundos." goal_defeat: "Derrota todos os inimigos." goal_defeat_amount: "Derrota __amount__ inimigos." # goal_move: "Move to all the red X marks." # goal_collect: "Collect all the items." # goal_collect_amount: "Collect __amount__ items." game_menu: inventory_tab: "Inventário" save_load_tab: "Guardar/Carregar" options_tab: "Opções" guide_tab: "Guia" guide_video_tutorial: "Tutorial em Vídeo" guide_tips: "Dicas" multiplayer_tab: "Multijogador" auth_tab: "Regista-te" inventory_caption: "Equipa o teu herói" choose_hero_caption: "Escolhe o herói, a linguagem" options_caption: "Configura as definições" guide_caption: "Documentos e dicas" multiplayer_caption: "Joga com amigos!" auth_caption: "Guarda o teu progresso." leaderboard: view_other_solutions: "Ver Tabelas de Classificação" scores: "Pontuações" top_players: "Melhores Jogadores por" day: "Hoje" week: "Esta Semana" all: "Sempre" latest: "Mais Recentes" time: "Tempo de Vitória" damage_taken: "Dano Recebido" damage_dealt: "Dano Infligido" difficulty: "Dificuldade" gold_collected: "Ouro Recolhido" # survival_time: "Survived" defeated: "Inimigos Derrotados" code_length: "Linhas de Código" score_display: "__scoreType__: __score__" inventory: equipped_item: "Equipado" required_purchase_title: "Necessário" available_item: "Disponível" restricted_title: "Restrito" should_equip: "(clica duas vezes para equipares)" equipped: "(equipado)" locked: "(bloqueado)" restricted: "(restrito neste nível)" equip: "Equipar" unequip: "Desequipar" warrior_only: "Apenas Guerreiros" ranger_only: "Apenas Arqueiros" wizard_only: "Apenas Feiticeiros" buy_gems: few_gems: "Algumas gemas" pile_gems: "Pilha de gemas" chest_gems: "Arca de gemas" purchasing: "A Adquirir..." declined: "O teu cartão foi recusado." retrying: "Erro do servidor, a tentar novamente." prompt_title: "Sem Gemas Suficientes" prompt_body: "Queres obter mais?" prompt_button: "Entra na Loja" recovered: "A compra de gemas anterior foi recuperada. Por favor atualiza a página." price: "x{{gems}} / mês" buy_premium: "Comprar 'Premium'" purchase: "Adquirir" purchased: "Adquirido" subscribe_for_gems: prompt_title: "Gemas Insuficientes!" # prompt_body: "Subscribe to Premium to get gems and access to even more levels!" earn_gems: prompt_title: "Gemas Insuficientes" prompt_body: "Continua a jogar para receberes mais!" subscribe: # best_deal: "Best Deal!" # confirmation: "Congratulations! You now have a CodeCombat Premium Subscription!" # premium_already_subscribed: "You're already subscribed to Premium!" subscribe_modal_title: "CodeCombat 'Premium'" comparison_blurb: "Torna-te um Programador Mestre - subscreve-te ao <b>'Premium'</b> hoje!" must_be_logged: "Primeiro tens de ter sessão iniciada. Por favor, cria uma conta ou inicia sessão a partir do menu acima." subscribe_title: "Subscrever" # Actually used in subscribe buttons, too unsubscribe: "Cancelar Subscrição" confirm_unsubscribe: "Confirmar Cancelamento da Subscrição" never_mind: "Não Importa, Gostamos de Ti à Mesma" thank_you_months_prefix: "Obrigado por nos teres apoiado neste(s) último(s)" thank_you_months_suffix: "mês(meses)." thank_you: "Obrigado por apoiares o CodeCombat." sorry_to_see_you_go: "Lamentamos ver-te partir! Por favor, diz-nos o que podíamos ter feito melhor." unsubscribe_feedback_placeholder: "Oh, o que fomos fazer?" stripe_description: "Subscrição Mensal" buy_now: "Comprar Agora" subscription_required_to_play: "Precisas de uma subscrição para jogares este nível." unlock_help_videos: "Subscreve-te para desbloqueares todos os tutoriais em vídeo." personal_sub: "Subscrição Pessoal" # Accounts Subscription View below loading_info: "A carregar as informações da subscrição..." managed_by: "Gerida por" will_be_cancelled: "Será cancelada em" currently_free: "Atualmente tens uma subscrição gratuita" currently_free_until: "Atualmente tens uma subscrição até" free_subscription: "Subscrição gratuita" was_free_until: "Tinhas uma subscrição gratuita até" managed_subs: "Subscrições Geridas" subscribing: "A Subscrever..." current_recipients: "Beneficiários Atuais" unsubscribing: "A Cancelar a Subscrição" subscribe_prepaid: "Clica em Subscrever para usares um código pré-pago" using_prepaid: "A usar um código pré-pago para a subscrição mensal" feature_level_access: "Acede a 300+ níveis disponíveis" feature_heroes: "Desbloqueia heróis e animais exclusivos" feature_learn: "Aprende a criar jogos e websites" month_price: "$__price__" first_month_price: "Apenas $__price__ pelo teu primeiro mês!" lifetime: "Acesso Vitalício" lifetime_price: "$__price__" year_subscription: "Subscrição Anual" year_price: "$__price__/ano" support_part1: "Precisas de ajuda com o pagamento ou preferes PayPal? Envia um e-mail para" support_part2: "<EMAIL>" # announcement: # now_available: "Now available for subscribers!" # subscriber: "subscriber" # cuddly_companions: "Cuddly Companions!" # Pet Announcement Modal # kindling_name: "Kindling Elemental" # kindling_description: "Kindling Elementals just want to keep you warm at night. And during the day. All the time, really." # griffin_name: "<NAME>" # griffin_description: "Griffins are half eagle, half lion, all adorable." # raven_name: "Raven" # raven_description: "Ravens are excellent at gathering shiny bottles full of health for you." # mimic_name: "<NAME>" # mimic_description: "Mimics can pick up coins for you. Move them on top of coins to increase your gold supply." # cougar_name: "<NAME>" # cougar_description: "Cougars like to earn a PhD by <NAME>." # fox_name: "Blue Fox" # fox_description: "Blue foxes are very clever and love digging in the dirt and snow!" # pugicorn_name: "Pugicorn" # pugicorn_description: "Pugicorns are some of the rarest creatures and can cast spells!" # wolf_name: "<NAME>" # wolf_description: "Wolf pups excel in hunting, gathering, and playing a mean game of hide-and-seek!" # ball_name: "Red Squeaky Ball" # ball_description: "ball.squeak()" # collect_pets: "Collect pets for your heroes!" # each_pet: "Each pet has a unique helper ability!" # upgrade_to_premium: "Become a {{subscriber}} to equip pets." # play_second_kithmaze: "Play {{the_second_kithmaze}} to unlock the Wolf Pup!" # the_second_kithmaze: "The Second Kithmaze" # keep_playing: "Keep playing to discover the first pet!" # coming_soon: "Coming soon" # ritic: "Ritic the Cold" # Ritic Announcement Modal # ritic_description: "Ritic the Cold. Trapped in <NAME>vintaph Glacier for countless ages, finally free and ready to tend to the ogres that imprisoned him." # ice_block: "A block of ice" # ice_description: "There appears to be something trapped inside..." # blink_name: "Blink" # blink_description: "Ritic disappears and reappears in a blink of an eye, leaving nothing but a shadow." # shadowStep_name: "Shadowstep" # shadowStep_description: "A master assassin knows how to walk between the shadows." # tornado_name: "Tornado" # tornado_description: "It is good to have a reset button when one's cover is blown." # wallOfDarkness_name: "Wall of Darkness" # wallOfDarkness_description: "Hide behind a wall of shadows to prevent the gaze of prying eyes." # avatar_selection: # pick_an_avatar: "Pick an avatar that will represent you as a player" # premium_features: # get_premium: "Get<br>CodeCombat<br>Premium" # Fit into the banner on the /features page # master_coder: "Become a Master Coder by subscribing today!" # paypal_redirect: "You will be redirected to PayPal to complete the subscription process." # subscribe_now: "Subscribe Now" # hero_blurb_1: "Get access to __premiumHeroesCount__ super-charged subscriber-only heroes! Harness the unstoppable power of Okar Stompfoot, the deadly precision of Naria of the Leaf, or summon \"adorable\" skeletons with Nalfar Cryptor." # hero_blurb_2: "Premium Warriors unlock stunning martial skills like Warcry, Stomp, and Hurl Enemy. Or, play as a Ranger, using stealth and bows, throwing knives, traps! Try your skill as a true coding Wizard, and unleash a powerful array of Primordial, Necromantic or Elemental magic!" # hero_caption: "Exciting new heroes!" # pet_blurb_1: "Pets aren't just adorable companions, they also provide unique functionality and methods. The Baby Griffin can carry units through the air, the Wolf Pup plays catch with enemy arrows, the Cougar is fond of chasing ogres around, and the Mimic attracts coins like a magnet!" # pet_blurb_2: "Collect all the pets to discover their unique abilities!" # pet_caption: "Adopt pets to accompany your hero!" # game_dev_blurb: "Learn game scripting and build new levels to share with your friends! Place the items you want, write code for unit logic and behavior, and see if your friends can beat the level!" # game_dev_caption: "Design your own games to challenge your friends!" # everything_in_premium: "Everything you get in CodeCombat Premium:" # list_gems: "Receive bonus gems to buy gear, pets, and heroes" # list_levels: "Gain access to __premiumLevelsCount__ more levels" # list_heroes: "Unlock exclusive heroes, include Ranger and Wizard classes" # list_game_dev: "Make and share games with friends" # list_web_dev: "Build websites and interactive apps" # list_items: "Equip Premium-only items like pets" # list_support: "Get Premium support to help you debug tricky code" # list_clans: "Create private clans to invite your friends and compete on a group leaderboard" choose_hero: choose_hero: "Escolhe o Teu Herói" programming_language: "Linguagem de Programação" programming_language_description: "Que linguagem de programação queres usar?" default: "Predefinida" experimental: "Experimental" python_blurb: "Simples mas poderoso; ótimo para iniciantes e peritos." javascript_blurb: "A linguagem da web. (Não é o mesmo que Java.)" coffeescript_blurb: "Javascript com sintaxe mais agradável." lua_blurb: "Linguagem para scripts de jogos." java_blurb: "(Apenas para Subscritores) Android e empresas." # cpp_blurb: "(Subscriber Only) Game development and high performance computing." status: "Estado" weapons: "Armas" weapons_warrior: "Espadas - Curto Alcance, Sem Magia" weapons_ranger: "Arcos, Armas - Longo Alcance, Sem Magia" weapons_wizard: "Varinhas, Bastões - Longo Alcance, Magia" attack: "Ataque" # Can also translate as "Attack" health: "Vida" speed: "Velocidade" regeneration: "Regeneração" range: "Alcance" # As in "attack or visual range" blocks: "Bloqueia" # As in "this shield blocks this much damage" backstab: "Colateral" # As in "this dagger does this much backstab damage" skills: "Habilidades" attack_1: "Dá" attack_2: "do dano da arma do" attack_3: "apresentado." health_1: "Ganha" health_2: "da vida da armadura do" health_3: "apresentado." speed_1: "Move a" speed_2: "metros por segundo." available_for_purchase: "Disponível para Aquisição" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nível para desbloquear:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Apenas certos heróis podem jogar este nível." # char_customization_modal: # heading: "Customize Your Hero" # body: "Body" # name_label: "Hero's Name" # hair_label: "Hair Color" # skin_label: "Skin Color" skill_docs: function: "função" # skill types method: "método" snippet: "fragmento" number: "número" array: "'array'" object: "objeto" string: "'string'" writable: "editável" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "apenas leitura" action: "Ação -" spell: "Feitiço -" action_name: "nome" action_cooldown: "Demora" action_specific_cooldown: "Tempo de Recarga" action_damage: "Dano" action_range: "Alcance" action_radius: "Raio" action_duration: "Duração" example: "Exemplo" ex: "ex" # Abbreviation of "example" current_value: "Valor Atual" default_value: "Valor Predefinido" parameters: "Parâmetros" required_parameters: "Parâmetros Necessários" optional_parameters: "Parâmetros Opcionais" returns: "Devolve" granted_by: "Garantido por" # still_undocumented: "Still undocumented, sorry." save_load: granularity_saved_games: "Guardados" granularity_change_history: "Histórico" options: general_options: "Opções Gerais" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volume" music_label: "Música" music_description: "Ativar ou desativar a música de fundo." editor_config_title: "Configurar Editor" editor_config_livecompletion_label: "Auto-completação em Tempo Real" editor_config_livecompletion_description: "Mostrar sugestões de auto-completação aquando da escrita." editor_config_invisibles_label: "Mostrar Invisíveis" editor_config_invisibles_description: "Mostrar invisíveis tais como espaços e tabulações." editor_config_indentguides_label: "Mostrar Guias de Indentação" editor_config_indentguides_description: "Mostrar linhas verticais para se ver melhor a indentação." editor_config_behaviors_label: "Comportamentos Inteligentes" editor_config_behaviors_description: "Auto-completar parênteses, chavetas e aspas." about: # title: "About CodeCombat - Engaging Students, Empowering Teachers, Inspiring Creation" # meta_description: "Our mission is to level computer science through game-based learning and make coding accessible to every learner. We believe programming is magic and want learners to be empowered to to create things from pure imagination." learn_more: "Saber Mais" main_title: "Se queres aprender a programar, precisas de escrever (muito) código." main_description: "No CodeCombat, o nosso trabalho é certificarmo-nos de que estás a fazer isso com um sorriso na cara." mission_link: "Missão" team_link: "Equipa" story_link: "História" press_link: "Imprensa" mission_title: "A nossa missão: tornar a programação acessível a todos os estudantes da Terra." mission_description_1: "<strong>A programação é mágica</strong>. É a capacidade de criar coisas a partir de imaginação pura. Começamos o CodeCombat para dar aos utilizadores a sensação de terem poderes mágicos nas pontas dos dedos ao usarem <strong>código escrito</strong>." # mission_description_2: "As it turns out, that enables them to learn faster too. WAY faster. It's like having a conversation instead of reading a manual. We want to bring that conversation to every school and to <strong>every student</strong>, because everyone should have the chance to learn the magic of programming." team_title: "Conhece a equipa do CodeCombat" # team_values: "We value open and respectful dialog, where the best idea wins. Our decisions are grounded in customer research and our process is focused on delivering tangible results for them. Everyone is hands-on, from our CEO to our GitHub contributors, because we value growth and learning in our team." nick_title: "<NAME>, C<NAME>" matt_title: "Co-fundador, CTO" cat_title: "Designer de Jogos" scott_title: "Co-fundador, Engenheiro de Software" maka_title: "Defensor dos Clientes" robin_title: "Gestora de Produto Sénior" nolan_title: "Gestor de Vendas" david_title: "Líder de Marketing" titles_csm: "Gerente de Sucesso do Cliente" titles_territory_manager: "Gestora de Território" # lawrence_title: "Customer Success Manager" # sean_title: "Senior Account Executive" # liz_title: "Senior Account Executive" # jane_title: "Account Executive" # shan_title: "Partnership Development Lead, China" # run_title: "Head of Operations, China" # lance_title: "Software Engineer Intern, China" # matias_title: "Senior Software Engineer" # ryan_title: "Customer Support Specialist" # maya_title: "Senior Curriculum Developer" # bill_title: "General Manager, China" # shasha_title: "Product and Visual Designer" # daniela_title: "Marketing Manager" # chelsea_title: "Operations Manager" # claire_title: "Executive Assistant" # bobby_title: "Game Designer" # brian_title: "Lead Game Designer" # andrew_title: "Software Engineer" # stephanie_title: "Customer Support Specialist" # rob_title: "Sales Development Representative" # shubhangi_title: "Senior Software Engineer" retrostyle_title: "Ilustração" retrostyle_blurb: "'RetroStyle Games'" # bryukh_title: "Gameplay Developer" bryukh_blurb: "Constrói puzzles" community_title: "...e a nossa comunidade open source" community_subtitle: "Mais de 500 contribuidores ajudaram a construir o CodeCombat, com mais a se juntarem todas as semanas!" community_description_3: "O CodeCombat é um" community_description_link_2: "projeto comunitário" # community_description_1: "with hundreds of players volunteering to create levels, contribute to our code to add features, fix bugs, playtest, and even translate the game into 50 languages so far. Employees, contributors and the site gain by sharing ideas and pooling effort, as does the open source community in general. The site is built on numerous open source projects, and we are open sourced to give back to the community and provide code-curious players a familiar project to explore and experiment with. Anyone can join the CodeCombat community! Check out our" community_description_link: "página de contribuição" community_description_2: "para mais informações." number_contributors: "Mais de 450 contribuidores deram o seu apoio e tempo a este projeto." story_title: "A nossa história até agora" story_subtitle: "Desde 2013, o CodeCombat cresceu de um mero conjunto de esboços para um jogo palpável e próspero." story_statistic_1a: "5,000,000+" story_statistic_1b: "jogadores no total" story_statistic_1c: "começaram a jornada de programação deles pelo CodeCombat" story_statistic_2a: "Fomos traduzidos para mais de 50 idiomas — os nossos jogadores saudam a partir de" story_statistic_2b: "190+ países" story_statistic_3a: "Juntos, eles escreveram" story_statistic_3b: "mil milhões de linhas de código (e continua a contar)" story_statistic_3c: "em muitas linguagens de programação diferentes" # story_long_way_1: "Though we've come a long way..." # story_sketch_caption: "<NAME>'s very first sketch depicting a programming game in action." # story_long_way_2: "we still have much to do before we complete our quest, so..." # jobs_title: "Come work with us and help write CodeCombat history!" # jobs_subtitle: "Don't see a good fit but interested in keeping in touch? See our \"Create Your Own\" listing." jobs_benefits: "Benefícios de Empregado" jobs_benefit_4: "Férias ilimitadas" # jobs_benefit_5: "Professional development and continuing education support – free books and games!" # jobs_benefit_6: "Medical (gold), dental, vision, commuter, 401K" # jobs_benefit_7: "Sit-stand desks for all" # jobs_benefit_9: "10-year option exercise window" # jobs_benefit_10: "Maternity leave: 12 weeks paid, next 6 @ 55% salary" # jobs_benefit_11: "Paternity leave: 12 weeks paid" jobs_custom_title: "Cria o Teu Próprio" # jobs_custom_description: "Are you passionate about CodeCombat but don't see a job listed that matches your qualifications? Write us and show how you think you can contribute to our team. We'd love to hear from you!" # jobs_custom_contact_1: "Send us a note at" # jobs_custom_contact_2: "introducing yourself and we might get in touch in the future!" contact_title: "Imprensa e Contactos" contact_subtitle: "Precisas de mais informação? Entra em contacto connosco através de" # screenshots_title: "Game Screenshots" # screenshots_hint: "(click to view full size)" # downloads_title: "Download Assets & Information" about_codecombat: "Sobre o CodeCombat" logo: "Logótipo" # screenshots: "Screenshots" # character_art: "Character Art" # download_all: "Download All" previous: "Anterior" # location_title: "We're located in downtown SF:" teachers: licenses_needed: "Licenças necessárias" special_offer: special_offer: "Oferta Especial" # project_based_title: "Project-Based Courses" # project_based_description: "Web and Game Development courses feature shareable final projects." # great_for_clubs_title: "Great for clubs and electives" # great_for_clubs_description: "Teachers can purchase up to __maxQuantityStarterLicenses__ Starter Licenses." # low_price_title: "Just __starterLicensePrice__ per student" # low_price_description: "Starter Licenses are active for __starterLicenseLengthMonths__ months from purchase." # three_great_courses: "Three great courses included in the Starter License:" # license_limit_description: "Teachers can purchase up to __maxQuantityStarterLicenses__ Starter Licenses. You have already purchased __quantityAlreadyPurchased__. If you need more, contact __supportEmail__. Starter Licenses are valid for __starterLicenseLengthMonths__ months." # student_starter_license: "Student Starter License" # purchase_starter_licenses: "Purchase Starter Licenses" # purchase_starter_licenses_to_grant: "Purchase Starter Licenses to grant access to __starterLicenseCourseList__" # starter_licenses_can_be_used: "Starter Licenses can be used to assign additional courses immediately after purchase." # pay_now: "Pay Now" # we_accept_all_major_credit_cards: "We accept all major credit cards." # cs2_description: "builds on the foundation from Introduction to Computer Science, diving into if-statements, functions, events and more." # wd1_description: "introduces the basics of HTML and CSS while teaching skills needed for students to build their first webpage." # gd1_description: "uses syntax students are already familiar with to show them how to build and share their own playable game levels." # see_an_example_project: "see an example project" # get_started_today: "Get started today!" # want_all_the_courses: "Want all the courses? Request information on our Full Licenses." # compare_license_types: "Compare License Types:" # cs: "Computer Science" # wd: "Web Development" # wd1: "Web Development 1" # gd: "Game Development" # gd1: "Game Development 1" # maximum_students: "Maximum # of Students" # unlimited: "Unlimited" # priority_support: "Priority support" # yes: "Yes" # price_per_student: "__price__ per student" # pricing: "Pricing" # free: "Free" # purchase: "Purchase" # courses_prefix: "Courses" # courses_suffix: "" # course_prefix: "Course" # course_suffix: "" teachers_quote: # subtitle: "Learn more about CodeCombat with an interactive walk through of the product, pricing, and implementation!" # email_exists: "User exists with this email." phone_number: "Número de telemóvel" phone_number_help: "Qual é o melhor número para entrarmos em contacto contigo?" primary_role_label: "O Teu Cargo Principal" role_default: "Selecionar Cargo" # primary_role_default: "Select Primary Role" # purchaser_role_default: "Select Purchaser Role" tech_coordinator: "Coordenador de Tecnologia" # advisor: "Curriculum Specialist/Advisor" principal: "<NAME>" superintendent: "Superintendente" parent: "Educador" # purchaser_role_label: "Your Purchaser Role" # influence_advocate: "Influence/Advocate" # evaluate_recommend: "Evaluate/Recommend" # approve_funds: "Approve Funds" # no_purchaser_role: "No role in purchase decisions" district_label: "Distrito" district_name: "Nome do Distrito" district_na: "Escreve N/A se não se aplicar" organization_label: "Escola" school_name: "<NAME> Es<NAME>" city: "Cidade" state: "Estado" # {change} country: "País" num_students_help: "Quantos estudantes vão usar o CodeCombat?" num_students_default: "Selecionar Intervalo" education_level_label: "Nível de Educação dos Estudantes" education_level_help: "Escolhe todos os que se aplicarem." # elementary_school: "Elementary School" # high_school: "High School" please_explain: "(por favor, explica)" # middle_school: "Middle School" # college_plus: "College or higher" referrer: "Como ouviste falar de nós?" referrer_help: "Por exemplo: através de outro professor, de uma conferência, dos teus estudantes, do Code.org, etc." referrer_default: "Seleciona Um" # referrer_conference: "Conference (e.g. ISTE)" referrer_hoc: "Code.org/Hora do Código" referrer_teacher: "Um professor" referrer_admin: "Um administrador" referrer_student: "Um estudante" # referrer_pd: "Professional trainings/workshops" referrer_web: "Google" referrer_other: "Outro" # anything_else: "What kind of class do you anticipate using CodeCombat for?" # anything_else_helper: "" thanks_header: "Pedido Recebido!" # thanks_sub_header: "Thanks for expressing interest in CodeCombat for your school." # thanks_p: "We'll be in touch soon! If you need to get in contact, you can reach us at:" back_to_classes: "Voltar às Turmas" # finish_signup: "Finish creating your teacher account:" # finish_signup_p: "Create an account to set up a class, add your students, and monitor their progress as they learn computer science." # signup_with: "Sign up with:" connect_with: "Conectar com:" # conversion_warning: "WARNING: Your current account is a <em>Student Account</em>. Once you submit this form, your account will be updated to a Teacher Account." # learn_more_modal: "Teacher accounts on CodeCombat have the ability to monitor student progress, assign licenses and manage classrooms. Teacher accounts cannot be a part of a classroom - if you are currently enrolled in a class using this account, you will no longer be able to access it once you update to a Teacher Account." create_account: "Criar uma Conta de Professor" create_account_subtitle: "Obtém acesso a ferramentas reservadas a professores para usares o CodeCombat na sala de aula. <strong>Cria uma turma</strong>, adiciona os teus estudantes e <strong>monitoriza o progresso deles</strong>!" # convert_account_title: "Update to Teacher Account" # not: "Not" # full_name_required: "First and last name required" versions: save_version_title: "Guardar Nova Versão" new_major_version: "Nova Versão Principal" submitting_patch: "A Submeter Atualização..." cla_prefix: "Para guardares as alterações, precisas de concordar com o nosso" cla_url: "CLA" cla_suffix: "." cla_agree: "EU CONCORDO" owner_approve: "Um administrador terá de aprová-la antes de as tuas alterações ficarem visíveis." contact: contact_us: "Contacta o CodeCombat" welcome: "É bom ter notícias tuas! Usa este formulário para nos enviares um e-mail. " forum_prefix: "Para algo público, por favor usa o " forum_page: "nosso fórum" forum_suffix: " como alternativa." faq_prefix: "Há também uma" faq: "FAQ" subscribe_prefix: "Se precisas de ajuda a perceber um nível, por favor" subscribe: "compra uma subscrição do CodeCombat" subscribe_suffix: "e nós ficaremos felizes por ajudar-te com o teu código." subscriber_support: "Como és um subscritor do CodeCombat, os teus e-mails terão prioridade no nosso suporte." screenshot_included: "Captura de ecrã incluída." where_reply: "Para onde devemos enviar a resposta?" send: "Enviar Feedback" account_settings: title: "Definições da Conta" not_logged_in: "Inicia sessão ou cria uma conta para alterares as tuas definições." me_tab: "Eu" picture_tab: "Fotografia" delete_account_tab: "Elimina a Tua Conta" wrong_email: "E-mail ou Nome de Utilizador Errado" wrong_password: "<PASSWORD>" delete_this_account: "Elimina esta conta permanentemente" reset_progress_tab: "Reiniciar Todo o Progresso" reset_your_progress: "Limpar todo o teu progresso e começar de novo" god_mode: "Modo Deus" emails_tab: "E-mails" admin: "Administrador" manage_subscription: "Clica aqui para gerires a tua subscrição." new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" type_in_email: "Escreve o teu e-mail ou nome de utilizador para confirmares a eliminação da conta." type_in_email_progress: "Escreve o teu e-mail para confirmares a eliminação do teu progresso." type_in_password: "<PASSWORD> também a tua palavra-<PASSWORD>." email_subscriptions: "Subscrições de E-mail" email_subscriptions_none: "Sem Subscições de E-mail." email_announcements: "Anúncios" email_announcements_description: "Recebe e-mails sobre as últimas novidades e desenvolvimentos no CodeCombat." email_notifications: "Notificações" email_notifications_summary: "Controla, de uma forma personalizada e automática, os e-mails de notificações relacionados com a tua atividade no CodeCombat." email_any_notes: "Quaisquer Notificações" email_any_notes_description: "Desativa para parares de receber todos os e-mails de notificação de atividade." email_news: "Notícias" email_recruit_notes: "Oportunidades de Emprego" email_recruit_notes_description: "Se jogas muito bem, podemos contactar-te para te arranjar um (melhor) emprego." contributor_emails: "E-mail Para Contribuintes" contribute_prefix: "Estamos à procura de pessoas para se juntarem a nós! Visita a " contribute_page: "página de contribuição" contribute_suffix: " para mais informações." email_toggle: "Alternar Todos" error_saving: "Erro ao Guardar" saved: "Alterações Guardadas" password_mismatch: "As palavras-passe não coincidem." password_repeat: "Por favor repete a tua palavra-passe." keyboard_shortcuts: keyboard_shortcuts: "Atalhos de Teclado" space: "Espaço" enter: "Enter" press_enter: "pressiona enter" escape: "Esc" shift: "Shift" run_code: "Executar código atual." run_real_time: "Executar em tempo real." continue_script: "Saltar o script atual." skip_scripts: "Saltar todos os scripts saltáveis." toggle_playback: "Alternar entre Jogar e Pausar." scrub_playback: "Andar para a frente e para trás no tempo." single_scrub_playback: "Andar para a frente e para trás no tempo um único frame." scrub_execution: "Analisar a execução do feitiço atual." toggle_debug: "Ativar/desativar a janela de depuração." toggle_grid: "Ativar/desativar a sobreposição da grelha." toggle_pathfinding: "Ativar/desativar a sobreposição do encontrador de caminho." beautify: "Embelezar o código ao estandardizar a formatação." maximize_editor: "Maximizar/minimizar o editor de código." # cinematic: # click_anywhere_continue: "click anywhere to continue" community: main_title: "Comunidade do CodeCombat" introduction: "Confere abaixo as formas de te envolveres e escolhe a que te parece mais divertida. Estamos ansiosos por trabalhar contigo!" level_editor_prefix: "Usa o" level_editor_suffix: "do CodeCombat para criares e editares níveis. Os utilizadores já criaram níveis para aulas, amigos, maratonas hacker, estudantes e familiares. Se criar um nível novo parece intimidante, podes começar por bifurcar um dos nossos!" thang_editor_prefix: "Chamamos 'thangs' às unidades do jogo. Usa o" thang_editor_suffix: "para modificares a arte do CodeCombat. Faz as unidades lançarem projéteis, altera a direção de uma animação, altera os pontos de vida de uma unidade ou anexa as tuas próprias unidades." article_editor_prefix: "Vês um erro em alguns dos nossos documentos? Queres escrever algumas instruções para as tuas próprias criações? Confere o" article_editor_suffix: "e ajuda os jogadores do CodeCombat a obter o máximo do tempo de jogo deles." find_us: "Encontra-nos nestes sítios" social_github: "Confere todo o nosso código no GitHub" social_blog: "Lê o blog do CodeCombat no Sett" social_discource: "Junta-te à discussão no nosso fórum Discourse" social_facebook: "Gosta do CodeCombat no Facebook" social_twitter: "Segue o CodeCombat no Twitter" social_slack: "Fala connosco no canal público do CodeCombat no Slack" contribute_to_the_project: "Contribui para o projeto" clans: # title: "Join CodeCombat Clans - Learn to Code in Python, JavaScript, and HTML" # clan_title: "__clan__ - Join CodeCombat Clans and Learn to Code" # meta_description: "Join a Clan or build your own community of coders. Play multiplayer arena levels and level up your hero and your coding skills." clan: "Clã" clans: "Clãs" new_name: "Nome do novo clã" new_description: "Descrição do novo clã" make_private: "Tornar o clã privado" subs_only: "apenas para subscritores" create_clan: "Criar um Novo Clã" private_preview: "Pré-visualização" private_clans: "Clãs Privados" public_clans: "Clãs Públicos" my_clans: "Os Meus Clãs" clan_name: "Nome do Clã" name: "<NAME>" chieftain: "<NAME>" edit_clan_name: "Editar Nome do Clã" edit_clan_description: "Editar Descrição do Clã" edit_name: "editar nome" edit_description: "editar descrição" private: "(privado)" summary: "Resumo" average_level: "Nível em Média" average_achievements: "Conquistas em Média" delete_clan: "Eliminar o Clã" leave_clan: "Abandonar o Clã" join_clan: "Entrar no Clã" invite_1: "Convidar:" invite_2: "*Convida jogadores para este Clã enviando-lhes esta ligação." members: "<NAME>" progress: "Progresso" not_started_1: "não começado" started_1: "começado" complete_1: "completo" exp_levels: "Expandir os níveis" rem_hero: "Rem<NAME> Her<NAME>" status: "Estado" complete_2: "Completo" started_2: "Começado" not_started_2: "Não Começado" view_solution: "Clica para veres a solução." view_attempt: "Clica para veres a tentativa." latest_achievement: "Última Conquista" playtime: "Tempo de jogo" last_played: "Última vez jogado" leagues_explanation: "Joga numa liga contra outros membros do clã nestas instâncias de arenas multijogador." track_concepts1: "Acompanhe os conceitos" track_concepts2a: "aprendidos por cada estudante" track_concepts2b: "aprendidos por cada membro" track_concepts3a: "Acompanhe os níveis completados por cada estudante" track_concepts3b: "Acompanhe os níveis completados por cada membro" track_concepts4a: "Veja, dos seus estudantes, as" track_concepts4b: "Veja, dos seus membros, as" track_concepts5: "soluções" track_concepts6a: "Ordene os estudantes por nome ou progresso" track_concepts6b: "Ordene os membros por nome ou progresso" track_concepts7: "É necessário um convite" track_concepts8: "para entrar" private_require_sub: "É necessária uma subscrição para criar ou entrar num clã privado." courses: create_new_class: "Criar Turma Nova" # hoc_blurb1: "Try the" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity! Construct four different minigames to learn the basics of game development, then make your own!" solutions_require_licenses: "As soluções dos níveis estão disponíveis para professores que tenham licenças." unnamed_class: "Turma Sem Nome" edit_settings1: "Editar Definições da Turma" add_students: "Adicionar Estudantes" stats: "Estatísticas" # student_email_invite_blurb: "Your students can also use class code <strong>__classCode__</strong> when creating a Student Account, no email required." total_students: "Estudantes no total:" average_time: "Média do tempo de jogo do nível:" total_time: "Tempo de jogo total:" average_levels: "Média de níveis completos:" total_levels: "Total de níveis completos:" students: "Estudantes" concepts: "Conceitos" play_time: "Tempo de jogo:" completed: "Completos:" enter_emails: "Separa cada endereço de e-mail com uma quebra de linha ou vírgulas" send_invites: "Convidar Estudantes" number_programming_students: "Número de Estudantes" number_total_students: "Total de Estudantes na Escola/Distrito" enroll: "Inscrever" enroll_paid: "Inscrever Estudantes em Cursos Pagos" get_enrollments: "Obter Mais Licenças" change_language: "Alterar Linguagem do Curso" keep_using: "Continuar a Usar" switch_to: "Mudar Para" greetings: "Saudações!" back_classrooms: "Voltar às minhas turmas" back_classroom: "Voltar à turma" back_courses: "Voltar aos meus cursos" edit_details: "Editar detalhes da turma" purchase_enrollments: "Adquirir Licenças de Estudante" remove_student: "remover estudante" # assign: "Assign" # to_assign: "to assign paid courses." student: "<NAME>" teacher: "<NAME>" arena: "Arena" available_levels: "Níveis Disponíveis" started: "começado" complete: "completado" practice: "prática" required: "obrigatório" welcome_to_courses: "Aventureiros, sejam bem-vindos aos Cursos!" ready_to_play: "Pronto para jogar?" start_new_game: "Começar Novo Jogo" play_now_learn_header: "Joga agora para aprenderes" # play_now_learn_1: "basic syntax to control your character" # play_now_learn_2: "while loops to solve pesky puzzles" # play_now_learn_3: "strings & variables to customize actions" # play_now_learn_4: "how to defeat an ogre (important life skills!)" welcome_to_page: "O Meu Painel de Estudante" my_classes: "Turmas Atuais" class_added: "Turma adicionada com sucesso!" # view_map: "view map" # view_videos: "view videos" view_project_gallery: "ver os projetos dos meus colegas" join_class: "Entrar Numa Turma" join_class_2: "Entrar na turma" ask_teacher_for_code: "Pergunta ao teu professor se tens um código de turma do CodeCombat! Se tiveres, introdu-lo abaixo:" enter_c_code: "<Introduzir Código de Turma>" join: "Entrar" joining: "A entrar na turma" course_complete: "Curso Completo" play_arena: "Jogar na Arena" view_project: "Ver Projeto" start: "Começar" last_level: "Último nível jogado" not_you: "Não és tu?" continue_playing: "Continuar a J<NAME>" option1_header: "Convidar Estudantes por E-mail" remove_student1: "Remover Estudante" are_you_sure: "Tens a certeza de que queres remover este estudante desta turma?" # remove_description1: "Student will lose access to this classroom and assigned classes. Progress and gameplay is NOT lost, and the student can be added back to the classroom at any time." # remove_description2: "The activated paid license will not be returned." # license_will_revoke: "This student's paid license will be revoked and made available to assign to another student." keep_student: "Manter Estudante" removing_user: "A remover utilizador" subtitle: "Revê visões gerais de cursos e níveis" # Flat style redesign # changelog: "View latest changes to course levels." select_language: "Selecionar linguagem" select_level: "Selecionar nível" play_level: "Jogar Nível" concepts_covered: "Conceitos Abordados" view_guide_online: "Visões Gerais e Soluções do Nível" grants_lifetime_access: "Garante acesso a todos os Cursos." enrollment_credits_available: "Licenças Disponíveis:" language_select: "Seleciona uma linguagem" # ClassroomSettingsModal language_cannot_change: "A linguagem não pode ser alterada depois de estudantes entrarem numa turma." avg_student_exp_label: "Experiência Média de Programação dos Estudantes" avg_student_exp_desc: "Isto vai-nos ajudar a perceber qual o melhor andamento para os cursos." avg_student_exp_select: "Seleciona a melhor opção" avg_student_exp_none: "Nenhuma Experiência - pouca ou nenhuma experiência" avg_student_exp_beginner: "Iniciante - alguma exposição ou baseada em blocos" avg_student_exp_intermediate: "Intermédia - alguma experiência com código escrito" avg_student_exp_advanced: "Avançada - muita experiência com código escrito" avg_student_exp_varied: "Vários Níveis de Experiência" student_age_range_label: "Intervalo de Idades dos Estudantes" student_age_range_younger: "Menos de 6" student_age_range_older: "Mais de 18" student_age_range_to: "até" # estimated_class_dates_label: "Estimated Class Dates" # estimated_class_frequency_label: "Estimated Class Frequency" # classes_per_week: "classes per week" # minutes_per_class: "minutes per class" create_class: "Criar Turma" class_name: "<NAME> da Turma" # teacher_account_restricted: "Your account is a teacher account and cannot access student content." account_restricted: "É necessária uma conta de estudante para acederes a esta página." # update_account_login_title: "Log in to update your account" update_account_title: "A tua conta precisa de atenção!" # update_account_blurb: "Before you can access your classes, choose how you want to use this account." # update_account_current_type: "Current Account Type:" # update_account_account_email: "Account Email/Username:" update_account_am_teacher: "Sou um professor" # update_account_keep_access: "Keep access to classes I've created" # update_account_teachers_can: "Teacher accounts can:" # update_account_teachers_can1: "Create/manage/add classes" # update_account_teachers_can2: "Assign/enroll students in courses" # update_account_teachers_can3: "Unlock all course levels to try out" # update_account_teachers_can4: "Access new teacher-only features as we release them" # update_account_teachers_warning: "Warning: You will be removed from all classes that you have previously joined and will not be able to play as a student." # update_account_remain_teacher: "Remain a Teacher" # update_account_update_teacher: "Update to Teacher" update_account_am_student: "Sou um estudante" # update_account_remove_access: "Remove access to classes I have created" # update_account_students_can: "Student accounts can:" # update_account_students_can1: "Join classes" # update_account_students_can2: "Play through courses as a student and track your own progress" # update_account_students_can3: "Compete against classmates in arenas" # update_account_students_can4: "Access new student-only features as we release them" # update_account_students_warning: "Warning: You will not be able to manage any classes that you have previously created or create new classes." # unsubscribe_warning: "Warning: You will be unsubscribed from your monthly subscription." # update_account_remain_student: "Remain a Student" # update_account_update_student: "Update to Student" # need_a_class_code: "You'll need a Class Code for the class you're joining:" # update_account_not_sure: "Not sure which one to choose? Email" # update_account_confirm_update_student: "Are you sure you want to update your account to a Student experience?" # update_account_confirm_update_student2: "You will not be able to manage any classes that you have previously created or create new classes. Your previously created classes will be removed from CodeCombat and cannot be restored." # instructor: "Instructor: " # youve_been_invited_1: "You've been invited to join " # youve_been_invited_2: ", where you'll learn " # youve_been_invited_3: " with your classmates in CodeCombat." # by_joining_1: "By joining " # by_joining_2: "will be able to help reset your password if you forget or lose it. You can also verify your email address so that you can reset the password yourself!" # sent_verification: "We've sent a verification email to:" # you_can_edit: "You can edit your email address in " # account_settings: "Account Settings" select_your_hero: "Seleciona o Teu Herói" select_your_hero_description: "Podes sempre alterar o teu herói ao acederes à tua página de Cursos e clicares em \"Alterar Herói\"" select_this_hero: "Selecionar este herói" current_hero: "Herói Atual:" current_hero_female: "Heroína Atual:" # web_dev_language_transition: "All classes program in HTML / JavaScript for this course. Classes that have been using Python will start with extra JavaScript intro levels to ease the transition. Classes that are already using JavaScript will skip the intro levels." course_membership_required_to_play: "Precisas de te juntar a um curso para jogares este nível." # license_required_to_play: "Ask your teacher to assign a license to you so you can continue to play CodeCombat!" # update_old_classroom: "New school year, new levels!" # update_old_classroom_detail: "To make sure you're getting the most up-to-date levels, make sure you create a new class for this semester by clicking Create a New Class on your" # teacher_dashboard: "teacher dashboard" # update_old_classroom_detail_2: "and giving students the new Class Code that appears." # view_assessments: "View Assessments" # view_challenges: "view challenge levels" # view_ranking: "view ranking" # ranking_position: "Position" # ranking_players: "Players" # ranking_completed_leves: "Completed levels" # challenge: "Challenge:" # challenge_level: "Challenge Level:" status: "Estado:" # assessments: "Assessments" challenges: "Desafios" level_name: "Nome do Nível:" # keep_trying: "Keep Trying" start_challenge: "Começar Desafio" # locked: "Locked" concepts_used: "Conceitos Usados:" # show_change_log: "Show changes to this course's levels" # hide_change_log: "Hide changes to this course's levels" # concept_videos: "Concept Videos" # concept: "Concept:" # basic_syntax: "Basic Syntax" # while_loops: "While Loops" # variables: "Variables" # basic_syntax_desc: "Syntax is how we write code. Just as spelling and grammar are important in writing narratives and essays, syntax is important when writing code. Humans are good at figuring out what something means, even if it isn't exactly correct, but computers aren't that smart, and they need you to write very precisely." # while_loops_desc: "A loop is a way of repeating actions in a program. You can use them so you don't have to keep writing repetitive code, and when you don't know exactly how many times an action will need to occur to accomplish a task." # variables_desc: "Working with variables is like organizing things in shoeboxes. You give the shoebox a name, like \"School Supplies\", and then you put things inside. The exact contents of the box might change over time, but whatever's inside will always be called \"School Supplies\". In programming, variables are symbols used to store data that will change over the course of the program. Variables can hold a variety of data types, including numbers and strings." # locked_videos_desc: "Keep playing the game to unlock the __concept_name__ concept video." # unlocked_videos_desc: "Review the __concept_name__ concept video." # video_shown_before: "shown before __level__" # link_google_classroom: "Link Google Classroom" # select_your_classroom: "Select Your Classroom" # no_classrooms_found: "No classrooms found" # create_classroom_manually: "Create classroom manually" # classes: "Classes" # certificate_btn_print: "Print" # certificate_btn_toggle: "Toggle" # ask_next_course: "Want to play more? Ask your teacher for access to the next course." # set_start_locked_level: "Set start locked level" # no_level_limit: "No limit" project_gallery: no_projects_published: "Sê o primeiro a publicar um projeto neste curso!" view_project: "Ver Projeto" edit_project: "Editar Projeto" teacher: # assigning_course: "Assigning course" back_to_top: "Voltar ao Topo" # click_student_code: "Click on any level that the student has started or completed below to view the code they wrote." code: "Código de __name__" complete_solution: "Solução Completa" # course_not_started: "Student has not started this course yet." # appreciation_week_blurb1: "For <strong>Teacher Appreciation Week 2019</strong>, we are offering free 1-week licenses!<br />Email <NAME> (<a href=\"mailto:<EMAIL>?subject=Teacher Appreciation Week\"><EMAIL></a>) with subject line \"<strong>Teacher Appreciation Week</strong>\", and include:" # appreciation_week_blurb2: "the quantity of 1-week licenses you'd like (1 per student)" # appreciation_week_blurb3: "the email address of your CodeCombat teacher account" # appreciation_week_blurb4: "whether you'd like licenses for Week 1 (May 6-10) or Week 2 (May 13-17)" # hoc_happy_ed_week: "Happy Computer Science Education Week!" # hoc_blurb1: "Learn about the free" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity, download a new teacher lesson plan, and tell your students to log in to play!" # hoc_button_text: "View Activity" # no_code_yet: "Student has not written any code for this level yet." # open_ended_level: "Open-Ended Level" partial_solution: "Solução Parcial" # capstone_solution: "Capstone Solution" removing_course: "A remover o curso" # solution_arena_blurb: "Students are encouraged to solve arena levels creatively. The solution provided below meets the requirements of the arena level." # solution_challenge_blurb: "Students are encouraged to solve open-ended challenge levels creatively. One possible solution is displayed below." # solution_project_blurb: "Students are encouraged to build a creative project in this level. Please refer to curriculum guides in the Resource Hub for information on how to evaluate these projects." # students_code_blurb: "A correct solution to each level is provided where appropriate. In some cases, it’s possible for a student to solve a level using different code. Solutions are not shown for levels the student has not started." # course_solution: "Course Solution" # level_overview_solutions: "Level Overview and Solutions" # no_student_assigned: "No students have been assigned this course." # paren_new: "(new)" student_code: "Código de Estudante de __name__" teacher_dashboard: "Painel do Professor" # Navbar my_classes: "As Minhas Turmas" courses: "Guias dos Cursos" enrollments: "Licenças de Estudantes" resources: "Recursos" help: "Ajuda" language: "Linguagem" edit_class_settings: "editar definições da turma" access_restricted: "Atualização de Conta Necessária" teacher_account_required: "É necessária uma conta de professor para acederes a este conteúdo." create_teacher_account: "Criar Conta de Professor" what_is_a_teacher_account: "O que é uma Conta de Professor?" # teacher_account_explanation: "A CodeCombat Teacher account allows you to set up classrooms, monitor students’ progress as they work through courses, manage licenses and access resources to aid in your curriculum-building." current_classes: "Turmas Atuais" archived_classes: "Turmas Arquivadas" archived_classes_blurb: "As turmas podem ser arquivadas para referência futura. Desarquiva uma turma para a veres novamente na lista das Turmas Atuais." view_class: "ver turma" archive_class: "arquivar turma" unarchive_class: "desarquivar turma" unarchive_this_class: "Desarquivar esta turma" no_students_yet: "Esta turma ainda não tem estudantes." no_students_yet_view_class: "Ver turma para adicionar estudantes." try_refreshing: "(Podes precisar de atualizar a página)" create_new_class: "Criar uma Turma Nova" class_overview: "Visão Geral da Turma" # View Class page avg_playtime: "Tempo de jogo médio por nível" total_playtime: "Tempo de jogo total" avg_completed: "Média de níveis completos" total_completed: "Totalidade dos níveis completos" created: "Criada" concepts_covered: "Conceitos abordados" earliest_incomplete: "Nível mais básico incompleto" latest_complete: "Último nível completo" enroll_student: "Inscrever estudante" apply_license: "Aplicar Licença" revoke_license: "Revogar Licença" revoke_licenses: "Revogar Todas as Licenças" course_progress: "Progresso dos Cursos" not_applicable: "N/A" edit: "editar" edit_2: "Editar" remove: "remover" latest_completed: "Último completo:" sort_by: "Ordenar por" progress: "Progresso" concepts_used: "Conceitos usados pelo Estudante:" # concept_checked: "Concept checked:" completed: "Completaram" practice: "Prática" started: "Começaram" no_progress: "Nenhum progresso" # not_required: "Not required" # view_student_code: "Click to view student code" select_course: "Seleciona o curso para ser visto" progress_color_key: "Esquema de cores do progresso:" level_in_progress: "Nível em Progresso" level_not_started: "Nível Não Começado" project_or_arena: "Projeto ou Arena" # students_not_assigned: "Students who have not been assigned {{courseName}}" # course_overview: "Course Overview" copy_class_code: "Copiar Código de Turma" class_code_blurb: "Os estudantes podem entrar na tua turma ao usarem este Código de Turma. Não é necessário nenhum endereço de e-mail aquando da criação de uma conta de Estudante com este Código de Turma." copy_class_url: "Copiar URL da Turma" class_join_url_blurb: "Também podes publicar este URL único da turma numa página web partilhada." add_students_manually: "Convidar Estudantes por E-mail" bulk_assign: "Selecionar curso" # assigned_msg_1: "{{numberAssigned}} students were assigned {{courseName}}." assigned_msg_2: "{{numberEnrolled}} licenças foram aplicadas." # assigned_msg_3: "You now have {{remainingSpots}} available licenses remaining." assign_course: "Atribuir Curso" removed_course_msg: "{{numberRemoved}} estudantes foram removidos de {{courseName}}." remove_course: "Remover Curso" not_assigned_modal_title: "Os cursos não foram atribuídos" # not_assigned_modal_starter_body_1: "This course requires a Starter License. You do not have enough Starter Licenses available to assign this course to all __selected__ selected students." # not_assigned_modal_starter_body_2: "Purchase Starter Licenses to grant access to this course." # not_assigned_modal_full_body_1: "This course requires a Full License. You do not have enough Full Licenses available to assign this course to all __selected__ selected students." # not_assigned_modal_full_body_2: "You only have __numFullLicensesAvailable__ Full Licenses available (__numStudentsWithoutFullLicenses__ students do not currently have a Full License active)." # not_assigned_modal_full_body_3: "Please select fewer students, or reach out to __supportEmail__ for assistance." # assigned: "Assigned" enroll_selected_students: "Inscrever os Estudantes Selecionados" no_students_selected: "Nenhum estudante foi selecionado." # show_students_from: "Show students from" # Enroll students modal apply_licenses_to_the_following_students: "Aplicar Licenças aos Seguintes Estudantes" # students_have_licenses: "The following students already have licenses applied:" all_students: "Todos os Estudantes" apply_licenses: "Aplicar Licenças" not_enough_enrollments: "Não há licenças suficientes disponíveis." enrollments_blurb: "É necessário que os estudantes tenham uma licença para acederem a qualquer conteúdo depois do primeiro curso." how_to_apply_licenses: "Como Aplicar Licenças" export_student_progress: "Exportar Progresso dos Estudantes (CSV)" # send_email_to: "Send Recover Password Email to:" email_sent: "E-mail enviado" send_recovery_email: "Enviar e-mail de recuperação" enter_new_password_below: "Introduz a nova palavra-passe abaixo:" change_password: "<PASSWORD>" changed: "Alterada" available_credits: "Licenças Disponíveis" pending_credits: "Licenças Pendentes" # empty_credits: "Exhausted Licenses" license_remaining: "licença restante" licenses_remaining: "licenças restantes" one_license_used: "1 de __totalLicenses__ licenças foi usada" num_licenses_used: "__numLicensesUsed__ de __totalLicenses__ licenças foram usadas" # starter_licenses: "starter licenses" # start_date: "start date:" # end_date: "end date:" get_enrollments_blurb: " Vamos ajudar-te a construir uma solução que satisfaça as necessidades da tua turma, escola ou distrito." # how_to_apply_licenses_blurb_1: "When a teacher assigns a course to a student for the first time, we’ll automatically apply a license. Use the bulk-assign dropdown in your classroom to assign a course to selected students:" # how_to_apply_licenses_blurb_2: "Can I still apply a license without assigning a course?" # how_to_apply_licenses_blurb_3: "Yes — go to the License Status tab in your classroom and click \"Apply License\" to any student who does not have an active license." request_sent: "Pedido Enviado!" # assessments: "Assessments" license_status: "Estado das Licenças" # status_expired: "Expired on {{date}}" status_not_enrolled: "Não Inscrito" # status_enrolled: "Expires on {{date}}" select_all: "Selecionar Todos" project: "Projeto" # project_gallery: "Project Gallery" view_project: "Ver Projeto" unpublished: "(não publicado)" # view_arena_ladder: "View Arena Ladder" resource_hub: "Centro de Recursos" # pacing_guides: "Classroom-in-a-Box Pacing Guides" # pacing_guides_desc: "Learn how to incorporate all of CodeCombat's resources to plan your school year!" # pacing_guides_elem: "Elementary School Pacing Guide" # pacing_guides_middle: "Middle School Pacing Guide" # pacing_guides_high: "High School Pacing Guide" # getting_started: "Getting Started" # educator_faq: "Educator FAQ" # educator_faq_desc: "Frequently asked questions about using CodeCombat in your classroom or school." # teacher_getting_started: "Teacher Getting Started Guide" # teacher_getting_started_desc: "New to CodeCombat? Download this Teacher Getting Started Guide to set up your account, create your first class, and invite students to the first course." # student_getting_started: "Student Quick Start Guide" # student_getting_started_desc: "You can distribute this guide to your students before starting CodeCombat so that they can familiarize themselves with the code editor. This guide can be used for both Python and JavaScript classrooms." # ap_cs_principles: "AP Computer Science Principles" # ap_cs_principles_desc: "AP Computer Science Principles gives students a broad introduction to the power, impact, and possibilities of Computer Science. The course emphasizes computational thinking and problem solving while also teaching the basics of programming." # cs1: "Introduction to Computer Science" # cs2: "Computer Science 2" # cs3: "Computer Science 3" # cs4: "Computer Science 4" # cs5: "Computer Science 5" # cs1_syntax_python: "Course 1 Python Syntax Guide" # cs1_syntax_python_desc: "Cheatsheet with references to common Python syntax that students will learn in Introduction to Computer Science." # cs1_syntax_javascript: "Course 1 JavaScript Syntax Guide" # cs1_syntax_javascript_desc: "Cheatsheet with references to common JavaScript syntax that students will learn in Introduction to Computer Science." coming_soon: "Guias adicionais em breve!" # engineering_cycle_worksheet: "Engineering Cycle Worksheet" # engineering_cycle_worksheet_desc: "Use this worksheet to teach students the basics of the engineering cycle: Assess, Design, Implement and Debug. Refer to the completed example worksheet as a guide." # engineering_cycle_worksheet_link: "View example" # progress_journal: "Progress Journal" # progress_journal_desc: "Encourage students to keep track of their progress via a progress journal." # cs1_curriculum: "Introduction to Computer Science - Curriculum Guide" # cs1_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 1." # arenas_curriculum: "Arena Levels - Teacher Guide" # arenas_curriculum_desc: "Instructions on how to run Wakka Maul, Cross Bones and Power Peak multiplayer arenas with your class." # assessments_curriculum: "Assessment Levels - Teacher Guide" # assessments_curriculum_desc: "Learn how to use Challenge Levels and Combo Challenge levels to assess students' learning outcomes." # cs2_curriculum: "Computer Science 2 - Curriculum Guide" # cs2_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 2." # cs3_curriculum: "Computer Science 3 - Curriculum Guide" # cs3_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 3." # cs4_curriculum: "Computer Science 4 - Curriculum Guide" # cs4_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 4." # cs5_curriculum_js: "Computer Science 5 - Curriculum Guide (JavaScript)" # cs5_curriculum_desc_js: "Scope and sequence, lesson plans, activities and more for Course 5 classes using JavaScript." # cs5_curriculum_py: "Computer Science 5 - Curriculum Guide (Python)" # cs5_curriculum_desc_py: "Scope and sequence, lesson plans, activities and more for Course 5 classes using Python." # cs1_pairprogramming: "Pair Programming Activity" # cs1_pairprogramming_desc: "Introduce students to a pair programming exercise that will help them become better listeners and communicators." # gd1: "Game Development 1" # gd1_guide: "Game Development 1 - Project Guide" # gd1_guide_desc: "Use this to guide your students as they create their first shareable game project in 5 days." # gd1_rubric: "Game Development 1 - Project Rubric" # gd1_rubric_desc: "Use this rubric to assess student projects at the end of Game Development 1." # gd2: "Game Development 2" # gd2_curriculum: "Game Development 2 - Curriculum Guide" # gd2_curriculum_desc: "Lesson plans for Game Development 2." # gd3: "Game Development 3" # gd3_curriculum: "Game Development 3 - Curriculum Guide" # gd3_curriculum_desc: "Lesson plans for Game Development 3." # wd1: "Web Development 1" # wd1_curriculum: "Web Development 1 - Curriculum Guide" # wd1_curriculum_desc: "Scope and sequence, lesson plans, activities, and more for Web Development 1." # wd1_headlines: "Headlines & Headers Activity" # wd1_headlines_example: "View sample solution" # wd1_headlines_desc: "Why are paragraph and header tags important? Use this activity to show how well-chosen headers make web pages easier to read. There are many correct solutions to this!" # wd1_html_syntax: "HTML Syntax Guide" # wd1_html_syntax_desc: "One-page reference for the HTML style students will learn in Web Development 1." # wd1_css_syntax: "CSS Syntax Guide" # wd1_css_syntax_desc: "One-page reference for the CSS and Style syntax students will learn in Web Development 1." # wd2: "Web Development 2" # wd2_jquery_syntax: "jQuery Functions Syntax Guide" # wd2_jquery_syntax_desc: "One-page reference for the jQuery functions students will learn in Web Development 2." # wd2_quizlet_worksheet: "Quizlet Planning Worksheet" # wd2_quizlet_worksheet_instructions: "View instructions & examples" # wd2_quizlet_worksheet_desc: "Before your students build their personality quiz project at the end of Web Development 2, they should plan out their quiz questions, outcomes and responses using this worksheet. Teachers can distribute the instructions and examples for students to refer to." student_overview: "Visão Geral" student_details: "Detalhes do Estudante" student_name: "Nome <NAME>" no_name: "Nenhum nome fornecido." no_username: "Nenhum nome de utilizador fornecido." no_email: "O estudante não tem nenhum endereço de e-mail definido." student_profile: "Perfil do Estudante" playtime_detail: "Detalhe do Tempo de Jogo" student_completed: "Completo pelo Estudante" student_in_progress: "Em progresso pelo Estudante" class_average: "Média da Turma" # not_assigned: "has not been assigned the following courses" playtime_axis: "Tempo de Jogo em Segundos" levels_axis: "Níveis em" student_state: "Como se está" student_state_2: "a sair?" # student_good: "is doing well in" # student_good_detail: "This student is keeping pace with the class." # student_warn: "might need some help in" # student_warn_detail: "This student might need some help with new concepts that have been introduced in this course." # student_great: "is doing great in" # student_great_detail: "This student might be a good candidate to help other students working through this course." # full_license: "Full License" # starter_license: "Starter License" # trial: "Trial" # hoc_welcome: "Happy Computer Science Education Week" # hoc_title: "Hour of Code Games - Free Activities to Learn Real Coding Languages" # hoc_meta_description: "Make your own game or code your way out of a dungeon! CodeCombat has four different Hour of Code activities and over 60 levels to learn code, play, and create." # hoc_intro: "There are three ways for your class to participate in Hour of Code with CodeCombat" # hoc_self_led: "Self-Led Gameplay" # hoc_self_led_desc: "Students can play through two Hour of Code CodeCombat tutorials on their own" # hoc_game_dev: "Game Development" # hoc_and: "and" # hoc_programming: "JavaScript/Python Programming" # hoc_teacher_led: "Teacher-Led Lessons" # hoc_teacher_led_desc1: "Download our" # hoc_teacher_led_link: "Introduction to Computer Science lesson plans" # hoc_teacher_led_desc2: "to introduce your students to programming concepts using offline activities" # hoc_group: "Group Gameplay" # hoc_group_desc_1: "Teachers can use the lessons in conjunction with our Introduction to Computer Science course to track student progress. See our" # hoc_group_link: "Getting Started Guide" # hoc_group_desc_2: "for more details" # hoc_additional_desc1: "For additional CodeCombat resources and activities, see our" # hoc_additional_desc2: "Questions" # hoc_additional_contact: "Get in touch" # revoke_confirm: "Are you sure you want to revoke a Full License from {{student_name}}? The license will become available to assign to another student." # revoke_all_confirm: "Are you sure you want to revoke Full Licenses from all students in this class?" revoking: "A revogar..." # unused_licenses: "You have unused Licenses that allow you to assign students paid courses when they're ready to learn more!" # remember_new_courses: "Remember to assign new courses!" more_info: "Mais Informação" # how_to_assign_courses: "How to Assign Courses" # select_students: "Select Students" # select_instructions: "Click the checkbox next to each student you want to assign courses to." # choose_course: "Choose Course" # choose_instructions: "Select the course from the dropdown menu you’d like to assign, then click “Assign to Selected Students.”" # push_projects: "We recommend assigning Web Development 1 or Game Development 1 after students have finished Introduction to Computer Science! See our {{resource_hub}} for more details on those courses." # teacher_quest: "Teacher's Quest for Success" # quests_complete: "Quests Complete" # teacher_quest_create_classroom: "Create Classroom" teacher_quest_add_students: "Adicionar Estudantes" # teacher_quest_teach_methods: "Help your students learn how to `call methods`." # teacher_quest_teach_methods_step1: "Get 75% of at least one class through the first level, __Dungeons of Kithgard__" # teacher_quest_teach_methods_step2: "Print out the [Student Quick Start Guide](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) in the Resource Hub." # teacher_quest_teach_strings: "Don't string your students along, teach them `strings`." # teacher_quest_teach_strings_step1: "Get 75% of at least one class through __True Names__" # teacher_quest_teach_strings_step2: "Use the Teacher Level Selector on [Course Guides](/teachers/courses) page to preview __True Names__." # teacher_quest_teach_loops: "Keep your students in the loop about `loops`." # teacher_quest_teach_loops_step1: "Get 75% of at least one class through __Fire Dancing__." # teacher_quest_teach_loops_step2: "Use the __Loops Activity__ in the [CS1 Curriculum guide](/teachers/resources/cs1) to reinforce this concept." # teacher_quest_teach_variables: "Vary it up with `variables`." # teacher_quest_teach_variables_step1: "Get 75% of at least one class through __Known Enemy__." # teacher_quest_teach_variables_step2: "Encourage collaboration by using the [Pair Programming Activity](/teachers/resources/pair-programming)." # teacher_quest_kithgard_gates_100: "Escape the Kithgard Gates with your class." # teacher_quest_kithgard_gates_100_step1: "Get 75% of at least one class through __Kithgard Gates__." # teacher_quest_kithgard_gates_100_step2: "Guide students to think through hard problems using the [Engineering Cycle Worksheet](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." # teacher_quest_wakka_maul_100: "Prepare to duel in Wakka Maul." # teacher_quest_wakka_maul_100_step1: "Get 75% of at least one class to __Wakka Maul__." # teacher_quest_wakka_maul_100_step2: "See the [Arena Guide](/teachers/resources/arenas) in the [Resource Hub](/teachers/resources) for tips on how to run a successful arena day." # teacher_quest_reach_gamedev: "Explore new worlds!" # teacher_quest_reach_gamedev_step1: "[Get licenses](/teachers/licenses) so that your students can explore new worlds, like Game Development and Web Development!" # teacher_quest_done: "Want your students to learn even more code? Get in touch with our [school specialists](mailto:<EMAIL>) today!" # teacher_quest_keep_going: "Keep going! Here's what you can do next:" # teacher_quest_more: "See all quests" # teacher_quest_less: "See fewer quests" # refresh_to_update: "(refresh the page to see updates)" # view_project_gallery: "View Project Gallery" # office_hours: "Teacher Webinars" # office_hours_detail: "Learn how to keep up with with your students as they create games and embark on their coding journey! Come and attend our" # office_hours_link: "teacher webinar" # office_hours_detail_2: "sessions." # success: "Success" # in_progress: "In Progress" # not_started: "Not Started" # mid_course: "Mid-Course" # end_course: "End of Course" # none: "None detected yet" # explain_open_ended: "Note: Students are encouraged to solve this level creatively — one possible solution is provided below." level_label: "Nível:" time_played_label: "Tempo Jogado:" # back_to_resource_hub: "Back to Resource Hub" # back_to_course_guides: "Back to Course Guides" print_guide: "Imprimir este guia" # combo: "Combo" # combo_explanation: "Students pass Combo challenge levels by using at least one listed concept. Review student code by clicking the progress dot." concept: "Conceito" # sync_google_classroom: "Sync Google Classroom" # try_ozaria_footer: "Try our new adventure game, Ozaria!" # teacher_ozaria_encouragement_modal: # title: "Build Computer Science Skills to Save Ozaria" # sub_title: "You are invited to try the new adventure game from CodeCombat" # cancel: "Back to CodeCombat" # accept: "Try First Unit Free" # bullet1: "Deepen student connection to learning through an epic story and immersive gameplay" # bullet2: "Teach CS fundamentals, Python or JavaScript and 21st century skills" # bullet3: "Unlock creativity through capstone projects" # bullet4: "Support instructions through dedicated curriculum resources" # you_can_return: "You can always return to CodeCombat" share_licenses: share_licenses: "Partilhar Licenças" shared_by: "Part<NAME> Por:" # add_teacher_label: "Enter exact teacher email:" add_teacher_button: "Adicionar Professor" # subheader: "You can make your licenses available to other teachers in your organization. Each license can only be used for one student at a time." # teacher_not_found: "Teacher not found. Please make sure this teacher has already created a Teacher Account." # teacher_not_valid: "This is not a valid Teacher Account. Only teacher accounts can share licenses." # already_shared: "You've already shared these licenses with that teacher." # teachers_using_these: "Teachers who can access these licenses:" # footer: "When teachers revoke licenses from students, the licenses will be returned to the shared pool for other teachers in this group to use." you: "(tu)" one_license_used: "(1 licença usada)" licenses_used: "(__licensesUsed__ licenças usadas)" more_info: "Mais informação" sharing: game: "Jogo" webpage: "Página Web" # your_students_preview: "Your students will click here to see their finished projects! Unavailable in teacher preview." # unavailable: "Link sharing not available in teacher preview." share_game: "Partilhar Este Jogo" share_web: "Partilhar Esta Página Web" victory_share_prefix: "Partilha esta ligação para convidares os teus amigos e a tua família para" victory_share_prefix_short: "Convida pessoas para" victory_share_game: "jogarem o teu nível de jogo" victory_share_web: "verem a tua página web" victory_share_suffix: "." victory_course_share_prefix: "Esta ligação vai permitir que os teus amigos e a tua família" victory_course_share_game: "joguem o jogo" victory_course_share_web: "vejam a página web" victory_course_share_suffix: "que acabaste de criar." copy_url: "Copiar URL" share_with_teacher_email: "Envia para o teu professor" game_dev: creator: "Criador" web_dev: image_gallery_title: "Galeria de Imagens" select_an_image: "Seleciona uma imagem que queiras usar" scroll_down_for_more_images: "(Arrasta para baixo para mais imagens)" copy_the_url: "Copiar o URL abaixo" copy_the_url_description: "Útil se quiseres substituir uma imagem existente." copy_the_img_tag: "Copiar a etiqueta <img>" copy_the_img_tag_description: "Útil se quiseres inserir uma imagem nova." copy_url: "Copiar URL" copy_img: "Copiar <img>" how_to_copy_paste: "Como Copiar/Colar" copy: "Copiar" paste: "Colar" back_to_editing: "Voltar à Edição" classes: archmage_title: "Arcomago" archmage_title_description: "(Programador)" archmage_summary: "Se és um programador interessado em programar jogos educacionais, torna-te um Arcomago para nos ajudares a construir o CodeCombat!" artisan_title: "Artesão" artisan_title_description: "(Construtor de Níveis)" artisan_summary: "Constrói e partilha níveis para tu e os teus amigos jogarem. Torna-te um Artesão para aprenderes a arte de ensinar outros a programar." adventurer_title: "Aventureiro" adventurer_title_description: "(Testador de Níveis)" adventurer_summary: "Recebe os nossos novos níveis (até o conteúdo para subscritores) de graça, uma semana antes, e ajuda-nos a descobrir erros antes do lançamento para o público." scribe_title: "Escrivão" scribe_title_description: "(Editor de Artigos)" scribe_summary: "Bom código precisa de uma boa documentação. Escreve, edita e melhora os documentos lidos por milhões de jogadores pelo mundo." diplomat_title: "Diplomata" diplomat_title_description: "(Tradutor)" diplomat_summary: "O CodeCombat está traduzido em 45+ idiomas graças aos nossos Diplomatas. Ajuda-nos e contribui com traduções." ambassador_title: "Embaixador" ambassador_title_description: "(Suporte)" ambassador_summary: "Amansa os nossos utilizadores do fórum e direciona aqueles que têm questões. Os nossos Embaixadores representam o CodeCombat perante o mundo." teacher_title: "<NAME>" editor: main_title: "Editores do CodeCombat" article_title: "Editor de Artigos" thang_title: "Editor de Thangs" level_title: "Editor de Níveis" course_title: "Editor de Cursos" achievement_title: "Editor de Conquistas" poll_title: "Editor de Votações" back: "Voltar" revert: "Reverter" revert_models: "Reverter Modelos" pick_a_terrain: "Escolhe Um Terreno" dungeon: "Masmorra" indoor: "Interior" desert: "Deserto" grassy: "Relvado" mountain: "Montanha" glacier: "Glaciar" small: "Pequeno" large: "Grande" fork_title: "Bifurcar Nova Versão" fork_creating: "A Criar Bifurcação..." generate_terrain: "Gerar Terreno" more: "Mais" wiki: "Wiki" live_chat: "Chat ao Vivo" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Cores" level_some_options: "Algumas Opções?" level_tab_thangs: "Thangs" level_tab_scripts: "Scripts" level_tab_components: "Componentes" level_tab_systems: "Sistemas" level_tab_docs: "Documentação" level_tab_thangs_title: "Thangs Atuais" level_tab_thangs_all: "Todos" level_tab_thangs_conditions: "Condições Iniciais" level_tab_thangs_add: "Adicionar Thangs" level_tab_thangs_search: "Pesquisar thangs" add_components: "Adicionar Componentes" component_configs: "Configurações dos Componentes" config_thang: "Clica duas vezes para configurares uma thang" delete: "Eliminar" duplicate: "Duplicar" stop_duplicate: "Parar de Duplicar" rotate: "Rodar" level_component_tab_title: "Componentes Atuais" level_component_btn_new: "Criar Novo Componente" level_systems_tab_title: "Sistemas Atuais" level_systems_btn_new: "Cria Novo Sistema" level_systems_btn_add: "Adicionar Sistema" level_components_title: "Voltar para Todas as Thangs" level_components_type: "Tipo" level_component_edit_title: "Editar Componente" level_component_config_schema: "Configurar Esquema" level_system_edit_title: "Editar Sistema" create_system_title: "Criar Novo Sistema" new_component_title: "Criar Novo Componente" new_component_field_system: "Sistema" new_article_title: "Criar um Novo Artigo" new_thang_title: "Criar um Novo Tipo de Thang" new_level_title: "Criar um Novo Nível" new_article_title_login: "Inicia Sessão para Criares um Novo Artigo" new_thang_title_login: "Inicia Sessão para Criares um Novo Tipo de Thang" new_level_title_login: "Inicia Sessão para Criares um Novo Nível" new_achievement_title: "Criar uma Nova Conquista" new_achievement_title_login: "Inicia Sessão para Criares uma Nova Conquista" new_poll_title: "Criar uma Nova Votação" new_poll_title_login: "Iniciar Sessão para Criar uma Nova Votação" article_search_title: "Procurar Artigos Aqui" thang_search_title: "Procurar Thangs Aqui" level_search_title: "Procurar Níveis Aqui" achievement_search_title: "Procurar Conquistas" poll_search_title: "Procurar Votações" read_only_warning2: "Nota: não podes guardar nenhuma edição feita aqui, porque não tens sessão iniciada." no_achievements: "Ainda não foram adicionadas conquistas a este nível." achievement_query_misc: "Conquista-chave de uma lista de variados" achievement_query_goals: "Conquista-chave dos objetivos do nível" level_completion: "Completação do Nível" pop_i18n: "Propagar I18N" tasks: "Tarefas" clear_storage: "Limpa as tuas alterações locais" add_system_title: "Adicionar Sistemas ao Nível" done_adding: "Adição Concluída" article: edit_btn_preview: "Pré-visualizar" edit_article_title: "Editar Artigo" polls: priority: "Prioridade" contribute: page_title: "Contribuir" intro_blurb: "O CodeCombat faz parte da comunidade open source! Centenas de jogadores dedicados ajudaram-nos a transformar o jogo naquilo que ele é hoje. Junta-te a nós e escreve o próximo capítulo da aventura do CodeCombat para ensinar o mundo a programar!" alert_account_message_intro: "Hey, tu!" alert_account_message: "Para te subscreveres para receber e-mails de classes, necessitarás de iniciar sessão." archmage_introduction: "Uma das melhores partes da construção de jogos é que eles sintetizam muitas coisas diferentes. Gráficos, som, rede em tempo real, redes sociais, e, claro, muitos dos aspectos mais comuns da programação, desde a gestão de bases de dados de baixo nível, e administração do servidor até à construção do design e da interface do utilizador. Há muito a fazer, e se és um programador experiente com um verdadeiro desejo de mergulhar nas entranhas do CodeCombat, esta classe pode ser para ti. Gostaríamos muito de ter a tua ajuda para construir o melhor jogo de programação de sempre." class_attributes: "Atributos da Classe" archmage_attribute_1_pref: "Conhecimento em " archmage_attribute_1_suf: ", ou vontade de aprender. A maioria do nosso código está nesta linguagem. Se és um fã de Ruby ou Python, vais sentir-te em casa. É igual ao JavaScript, mas com uma sintaxe melhor." archmage_attribute_2: "Alguma experiência em programação e iniciativa pessoal. Nós ajudamos-te a orientares-te, mas não podemos gastar muito tempo a treinar-te." how_to_join: "Como Me Junto" join_desc_1: "Qualquer um pode ajudar! Só tens de conferir o nosso " join_desc_2: "para começares, e assinalar a caixa abaixo para te declarares um bravo Arcomago e receberes as últimas notícias por e-mail. Queres falar sobre o que fazer ou como te envolveres mais profundamente no projeto? " join_desc_3: " ou encontra-nos na nossa " join_desc_4: "e começamos a partir daí!" join_url_email: "Contacta-nos" join_url_slack: "canal público no Slack" archmage_subscribe_desc: "Receber e-mails relativos a novas oportunidades de programação e anúncios." artisan_introduction_pref: "Temos de construir mais níveis! As pessoas estão a pedir mais conteúdo, e nós mesmos só podemos construir estes tantos. Neste momento, a tua estação de trabalho é o nível um; o nosso editor de nível é pouco utilizável, até mesmo pelos seus criadores, por isso fica atento. Se tens visões de campanhas que abranjam 'for-loops' para o" artisan_introduction_suf: ", então esta classe pode ser para ti." # artisan_attribute_1: "Any experience in building content like this would be nice, such as using Blizzard's level editors. But not required!" # artisan_attribute_2: "A hankering to do a whole lot of testing and iteration. To make good levels, you need to take it to others and watch them play it, and be prepared to find a lot of things to fix." # artisan_attribute_3: "For the time being, endurance en par with an Adventurer. Our Level Editor is super preliminary and frustrating to use. You have been warned!" artisan_join_desc: "Usa o Editor de Níveis por esta ordem, pegar ou largar:" artisan_join_step1: "Lê a documentação." artisan_join_step2: "Cria um nível novo e explora níveis existentes." artisan_join_step3: "Encontra-nos na nossa sala Slack pública se necessitares de ajuda." artisan_join_step4: "Coloca os teus níveis no fórum para receberes feedback." artisan_subscribe_desc: "Receber e-mails relativos a novidades do editor de níveis e anúncios." # adventurer_introduction: "Let's be clear about your role: you are the tank. You're going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class might be for you." # adventurer_attribute_1: "A thirst for learning. You want to learn how to code and we want to teach you how to code. You'll probably be doing most of the teaching in this case, though." # adventurer_attribute_2: "Charismatic. Be gentle but articulate about what needs improving, and offer suggestions on how to improve." # adventurer_join_pref: "Either get together with (or recruit!) an Artisan and work with them, or check the box below to receive emails when there are new levels to test. We'll also be posting about levels to review on our networks like" # adventurer_forum_url: "our forum" # adventurer_join_suf: "so if you prefer to be notified those ways, sign up there!" adventurer_subscribe_desc: "Receber e-mails quando houver novos níveis para testar." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." scribe_attribute_1: "Habilidade com palavras é basicamente o que precisas. Não apenas gramática e ortografia, mas seres capaz de explicar ideias complicadas a outros." contact_us_url: "Contacta-nos" scribe_join_description: "fala-nos um bocado de ti, da tua experiência com a programação e do tipo de coisas sobre as quais gostarias de escrever. Começamos a partir daí!" scribe_subscribe_desc: "Receber e-mails sobre anúncios relativos à escrita de artigos." diplomat_introduction_pref: "Portanto, se há uma coisa que aprendemos com o nosso " diplomat_launch_url: "lançamento em Outubro" diplomat_introduction_suf: "é que há um interesse considerável no CodeCombat noutros países! Estamos a construir um exército de tradutores dispostos a transformar um conjunto de palavras num outro conjuto de palavras, para conseguir que o CodeCombat fique o mais acessível quanto posível em todo o mundo. Se gostas de dar espreitadelas a conteúdos futuros e disponibilizar os níveis para os teus colegas nacionais o mais depressa possível, então esta classe talvez seja para ti." diplomat_attribute_1: "Fluência em Inglês e no idioma para o qual gostarias de traduzir. Quando são tentadas passar ideias complicadas, é importante uma excelente compreensão das duas!" diplomat_i18n_page_prefix: "Podes começar a traduzir os nossos níveis se fores à nossa" diplomat_i18n_page: "página de traduções" diplomat_i18n_page_suffix: ", ou a nossa interface e website no GitHub." diplomat_join_pref_github: "Encontra o ficheiro 'locale' do teu idioma " diplomat_github_url: "no GitHub" diplomat_join_suf_github: ", edita-o online e submete um 'pull request'. Assinala ainda a caixa abaixo para ficares atualizado em relação a novos desenvolvimentos da internacionalização!" diplomat_subscribe_desc: "Receber e-mails sobre desenvolvimentos da i18n e níveis para traduzir." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got forums, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" ambassador_join_note_strong: "Nota" ambassador_join_note_desc: "Uma das nossas maiores prioridades é construir níveis multijogador onde os jogadores com dificuldade para passar níveis possam invocar feiticeiros mais experientes para os ajudarem. Esta será uma ótima forma de os embaixadores fazerem o que sabem. Vamos manter-te atualizado!" ambassador_subscribe_desc: "Receber e-mails relativos a novidades do suporte e desenvolvimentos do modo multijogador." teacher_subscribe_desc: "Receber e-mails sobre atualizações e anúncios para professores." changes_auto_save: "As alterações são guardadas automaticamente quando clicas nas caixas." diligent_scribes: "Os Nossos Dedicados Escrivões:" powerful_archmages: "Os Nossos Poderosos Arcomagos:" creative_artisans: "Os Nossos Creativos Artesãos:" brave_adventurers: "Os Nossos Bravos Aventureiros:" translating_diplomats: "Os Nossos Tradutores Diplomatas:" helpful_ambassadors: "Os Nossos Prestáveis Embaixadores:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Os Meus Jogos" simulate: "Simular" simulation_explanation: "Ao simulares jogos podes ter o teu jogo classificado mais rapidamente!" simulation_explanation_leagues: "Principalmente, vais ajudar a simular jogos para jogadores aliados nos teus clâs e cursos." simulate_games: "Simular Jogos!" games_simulated_by: "Jogos simulados por ti:" games_simulated_for: "Jogos simulados para ti:" games_in_queue: "Jogos na fila de espera atualmente:" games_simulated: "Jogos simulados" games_played: "Jogos jogados" ratio: "Rácio" leaderboard: "Tabela de Classificação" battle_as: "Lutar como " summary_your: "As Tuas " summary_matches: "Partidas - " summary_wins: " Vitórias, " summary_losses: " Derrotas" rank_no_code: "Sem Código Novo para Classificar" rank_my_game: "Classificar o Meu Jogo!" rank_submitting: "A submeter..." rank_submitted: "Submetido para Classificação" rank_failed: "A Classificação Falhou" rank_being_ranked: "Jogo a ser Classificado" rank_last_submitted: "submetido " help_simulate: "Ajudar a simular jogos?" code_being_simulated: "O teu novo código está a ser simulado por outros jogadores, para ser classificado. Isto será atualizado quando surgirem novas partidas." no_ranked_matches_pre: "Sem jogos classificados pela equipa " no_ranked_matches_post: "! Joga contra alguns adversários e volta aqui para veres o teu jogo classificado." choose_opponent: "Escolhe um Adversário" select_your_language: "Seleciona a tua linguagem!" tutorial_play: "Jogar Tutorial" tutorial_recommended: "Recomendado se nunca jogaste antes" tutorial_skip: "Saltar Tutorial" tutorial_not_sure: "Não tens a certeza do que se passa?" tutorial_play_first: "Joga o Tutorial primeiro." simple_ai: "CPU Simples" warmup: "Aquecimento" friends_playing: "Amigos a Jogar" log_in_for_friends: "Inicia sessão para jogares com os teus amigos!" social_connect_blurb: "Conecta-te e joga contra os teus amigos!" invite_friends_to_battle: "Convida os teus amigos para se juntarem a ti em batalha!" fight: "Lutar!" watch_victory: "Vê a tua vitória" defeat_the: "Derrota o" watch_battle: "Ver a batalha" tournament_started: ", começou" tournament_ends: "O Torneio acaba" tournament_ended: "O Torneio acabou" tournament_rules: "Regras do Torneio" tournament_blurb: "Escreve código, recolhe ouro, constrói exércitos, esmaga inimigos, ganha prémios e melhora a tua carreira no nosso torneio $40,000 Greed! Confere os detalhes" tournament_blurb_criss_cross: "Ganha ofertas, constrói caminhos, supera os adversários, apanha gemas e melhore a tua carreira no nosso torneio Criss-Cross! Confere os detalhes" tournament_blurb_zero_sum: "Liberta a tua criatividade de programação tanto na recolha de ouro como em táticas de combate nesta batalha-espelhada na montanha, entre o feiticeiro vermelho e o feiticeiro azul. O torneio começou na Sexta-feira, 27 de Março, e decorrerá até às 00:00 de Terça-feira, 7 de Abril. Compete por diversão e glória! Confere os detalhes" tournament_blurb_ace_of_coders: "Luta no glaciar congelado nesta partida espelhada do estilo domínio! O torneio começou Quarta-feira, 16 de Setembro, e decorrerá até Quarta-feira, 14 de Outubro às 23:00. Confere os detalhes" tournament_blurb_blog: "no nosso blog" rules: "Regras" winners: "Vencedores" league: "Liga" red_ai: "CPU Vermelho" # "Red AI Wins", at end of multiplayer match playback blue_ai: "CPU Azul" wins: "Vence" # At end of multiplayer match playback humans: "Vermelho" # Ladder page display team name ogres: "Azul" # live_tournament: "Live Tournament" # awaiting_tournament_title: "Tournament Inactive" # awaiting_tournament_blurb: "The tournament arena is not currently active." # tournament_end_desc: "The tournament is over, thanks for playing" user: # user_title: "__name__ - Learn to Code with CodeCombat" stats: "Estatísticas" singleplayer_title: "Níveis Um Jogador" multiplayer_title: "Níveis Multijogador" achievements_title: "Conquistas" last_played: "Última Vez Jogado" status: "Estado" status_completed: "Completo" status_unfinished: "Inacabado" no_singleplayer: "Sem jogos Um Jogador jogados." no_multiplayer: "Sem jogos Multijogador jogados." no_achievements: "Sem Conquistas ganhas." favorite_prefix: "A linguagem favorita é " favorite_postfix: "." not_member_of_clans: "Ainda não é membro de nenhum clã." # certificate_view: "view certificate" # certificate_click_to_view: "click to view certificate" # certificate_course_incomplete: "course incomplete" # certificate_of_completion: "Certificate of Completion" # certificate_endorsed_by: "Endorsed by" # certificate_stats: "Course Stats" # certificate_lines_of: "lines of" # certificate_levels_completed: "levels completed" # certificate_for: "For" # certificate_number: "No." achievements: last_earned: "Último Ganho" amount_achieved: "Quantidade" achievement: "Conquista" current_xp_prefix: "" current_xp_postfix: " no total" new_xp_prefix: "" new_xp_postfix: " ganho" left_xp_prefix: "" left_xp_infix: " até ao nível " left_xp_postfix: "" account: # title: "Account" # settings_title: "Account Settings" # unsubscribe_title: "Unsubscribe" # payments_title: "Payments" # subscription_title: "Subscription" # invoices_title: "Invoices" # prepaids_title: "Prepaids" payments: "Pagamentos" prepaid_codes: "Códigos Pré-pagos" purchased: "Adquirido" # subscribe_for_gems: "Subscribe for gems" subscription: "Subscrição" invoices: "Donativos" service_apple: "Apple" service_web: "Web" paid_on: "Pago Em" service: "Serviço" price: "Preço" gems: "Gemas" active: "Activa" subscribed: "Subscrito(a)" unsubscribed: "Não Subscrito(a)" active_until: "Ativa Até" cost: "Custo" next_payment: "Próximo Pagamento" card: "Cartão" status_unsubscribed_active: "Não estás subscrito e não te vamos cobrar, mas a tua conta ainda está ativa, por agora." status_unsubscribed: "Ganha acesso a novos níveis, heróis, itens e gemas de bónus com uma subscrição do CodeCombat!" not_yet_verified: "Ainda não foi verificado." resend_email: "Reenviar e-mail" email_sent: "E-mail enviado! Verifica a tua caixa de entrada." verifying_email: "A verificar o teu endereço de e-mail..." successfully_verified: "Verificaste o teu endereço de e-mail com sucesso!" verify_error: "Algo correu mal aquando da verificação do teu e-mail :(" # unsubscribe_from_marketing: "Unsubscribe __email__ from all CodeCombat marketing emails?" # unsubscribe_button: "Yes, unsubscribe" # unsubscribe_failed: "Failed" # unsubscribe_success: "Success" account_invoices: amount: "Quantidade em dólares americanos" declined: "O teu cartão foi recusado" invalid_amount: "Por favor introduz uma quantidade de dólares americanos." not_logged_in: "Inicia sessão ou cria uma conta para acederes aos donativos." pay: "Pagar Donativo" purchasing: "A adquirir..." retrying: "Erro do servidor, a tentar novamente." success: "Pago com sucesso. Obrigado!" account_prepaid: purchase_code: "Comprar um Código de Subscrição" # purchase_code1: "Subscription Codes can be redeemed to add premium subscription time to one or more accounts for the Home version of CodeCombat." # purchase_code2: "Each CodeCombat account can only redeem a particular Subscription Code once." # purchase_code3: "Subscription Code months will be added to the end of any existing subscription on the account." # purchase_code4: "Subscription Codes are for accounts playing the Home version of CodeCombat, they cannot be used in place of Student Licenses for the Classroom version." # purchase_code5: "For more information on Student Licenses, reach out to" users: "Utilizadores" months: "Meses" purchase_total: "Total" purchase_button: "Submeter Compra" your_codes: "Os Teus Códigos" redeem_codes: "Resgata um Código de Subscrição" prepaid_code: "Código Pré-pago" lookup_code: "Procurar código pré-pago" apply_account: "Aplicar à tua conta" copy_link: "Podes copiar a ligação do código e enviá-la a alguém." quantity: "Quantidade" redeemed: "Resgatado" no_codes: "Nenhum código ainda!" you_can1: "Podes" you_can2: "adquirir um código pré-pago" you_can3: "que pode ser aplicado à tua conta ou dado a outros." # ozaria_chrome: # sound_off: "Sound Off" # sound_on: "Sound On" # back_to_map: "Back to Map" # level_options: "Level Options" # restart_level: "Restart Level" # impact: # hero_heading: "Building A World-Class Computer Science Program" # hero_subheading: "We Help Empower Educators and Inspire Students Across the Country" # featured_partner_story: "Featured Partner Story" # partner_heading: "Successfully Teaching Coding at a Title I School" # partner_school: "Bobby Duke Middle School" # featured_teacher: "<NAME>" # teacher_title: "Technology Teacher Coachella, CA" # implementation: "Implementation" # grades_taught: "Grades Taught" # length_use: "Length of Use" # length_use_time: "3 years" # students_enrolled: "Students Enrolled this Year" # students_enrolled_number: "130" # courses_covered: "Courses Covered" # course1: "CompSci 1" # course2: "CompSci 2" # course3: "CompSci 3" # course4: "CompSci 4" # course5: "GameDev 1" # fav_features: "Favorite Features" # responsive_support: "Responsive Support" # immediate_engagement: "Immediate Engagement" # paragraph1: "Bobby Duke Middle School sits nestled between the Southern California mountains of Coachella Valley to the west and east and the Salton Sea 33 miles south, and boasts a student population of 697 students within Coachella Valley Unified’s district-wide population of 18,861 students." # paragraph2: "The students of Bobby Duke Middle School reflect the socioeconomic challenges facing Coachella Valley’s residents and students within the district. With over 95% of the Bobby Duke Middle School student population qualifying for free and reduced-price meals and over 40% classified as English language learners, the importance of teaching 21st century skills was the top priority of <NAME> Middle School Technology teacher, <NAME>." # paragraph3: "<NAME> knew that teaching his students coding was a key pathway to opportunity in a job landscape that increasingly prioritizes and necessitates computing skills. So, he decided to take on the exciting challenge of creating and teaching the only coding class in the school and finding a solution that was affordable, responsive to feedback, and engaging to students of all learning abilities and backgrounds." # teacher_quote: "When I got my hands on CodeCombat [and] started having my students use it, the light bulb went on. It was just night and day from every other program that we had used. They’re not even close." # quote_attribution: "<NAME>, Technology Teacher" # read_full_story: "Read Full Story" # more_stories: "More Partner Stories" # partners_heading_1: "Supporting Multiple CS Pathways in One Class" # partners_school_1: "Preston High School" # partners_heading_2: "Excelling on the AP Exam" # partners_school_2: "River Ridge High School" # partners_heading_3: "Teaching Computer Science Without Prior Experience" # partners_school_3: "Riverdale High School" # download_study: "Download Research Study" # teacher_spotlight: "Teacher & Student Spotlights" # teacher_name_1: "<NAME>" # teacher_title_1: "Rehabilitation Instructor" # teacher_location_1: "Morehead, Kentucky" # spotlight_1: "Through her compassion and drive to help those who need second chances, <NAME> helped change the lives of students who need positive role models. With no previous computer science experience, <NAME> led her students to coding success in a regional coding competition." # teacher_name_2: "<NAME>" # teacher_title_2: "Maysville Community & Technical College" # teacher_location_2: "Lexington, Kentucky" # spotlight_2: "Kaila was a student who never thought she would be writing lines of code, let alone enrolled in college with a pathway to a bright future." # teacher_name_3: "<NAME>" # teacher_title_3: "Teacher Librarian" # teacher_school_3: "Ruby Bridges Elementary" # teacher_location_3: "Alameda, CA" # spotlight_3: "<NAME> promotes an equitable atmosphere in her class where everyone can find success in their own way. Mistakes and struggles are welcomed because everyone learns from a challenge, even the teacher." # continue_reading_blog: "Continue Reading on Blog..." loading_error: could_not_load: "Erro a carregar do servidor. Experimenta atualizar a página." connection_failure: "A Ligação Falhou" connection_failure_desc: "Não parece que estejas ligado à internet! Verifica a tua ligação de rede e depois recarrega esta página." login_required: "Sessão Iniciada Obrigatória" login_required_desc: "Precisas de ter sessão iniciada para acederes a esta página." unauthorized: "Precisas de ter sessão iniciada. Tens os cookies desativados?" forbidden: "Proibido" forbidden_desc: "Oh não, não há nada aqui que te possamos mostrar! Certifica-te de que tens sessão iniciada na conta correta ou visita uma das ligações abaixo para voltares para a programação!" # user_not_found: "User Not Found" not_found: "Não Encontrado" not_found_desc: "Hm, não há nada aqui. Visita uma das ligações seguintes para voltares para a programação!" not_allowed: "Método não permitido." timeout: "O Servidor Expirou" conflict: "Conflito de recursos." bad_input: "Má entrada." server_error: "Erro do servidor." unknown: "Erro Desconhecido" error: "ERRO" general_desc: "Algo correu mal, e, provavelmente, a culpa é nossa. Tenta esperar um pouco e depois recarregar a página, ou visita uma das ligações seguintes para voltares para a programação!" resources: level: "Nível" patch: "Atualização" patches: "Atualizações" system: "Sistema" systems: "Sistemas" component: "Componente" components: "Componentes" hero: "Herói" campaigns: "Campanhas" concepts: # advanced_css_rules: "Advanced CSS Rules" # advanced_css_selectors: "Advanced CSS Selectors" # advanced_html_attributes: "Advanced HTML Attributes" # advanced_html_tags: "Advanced HTML Tags" # algorithm_average: "Algorithm Average" # algorithm_find_minmax: "Algorithm Find Min/Max" # algorithm_search_binary: "Algorithm Search Binary" # algorithm_search_graph: "Algorithm Search Graph" # algorithm_sort: "Algorithm Sort" # algorithm_sum: "Algorithm Sum" arguments: "Argumentos" arithmetic: "Aritmética" # array_2d: "2D Array" # array_index: "Array Indexing" # array_iterating: "Iterating Over Arrays" # array_literals: "Array Literals" # array_searching: "Array Searching" # array_sorting: "Array Sorting" arrays: "'Arrays'" # basic_css_rules: "Basic CSS rules" # basic_css_selectors: "Basic CSS selectors" # basic_html_attributes: "Basic HTML Attributes" # basic_html_tags: "Basic HTML Tags" basic_syntax: "Sintaxe Básica" binary: "Binário" # boolean_and: "Boolean And" # boolean_inequality: "Boolean Inequality" # boolean_equality: "Boolean Equality" # boolean_greater_less: "Boolean Greater/Less" # boolean_logic_shortcircuit: "Boolean Logic Shortcircuiting" # boolean_not: "Boolean Not" # boolean_operator_precedence: "Boolean Operator Precedence" # boolean_or: "Boolean Or" # boolean_with_xycoordinates: "Coordinate Comparison" # bootstrap: "Bootstrap" break_statements: "Declarações 'Break'" classes: "Classes" continue_statements: "Declarações 'Continue'" # dom_events: "DOM Events" # dynamic_styling: "Dynamic Styling" events: "Eventos" # event_concurrency: "Event Concurrency" # event_data: "Event Data" # event_handlers: "Event Handlers" # event_spawn: "Spawn Event" for_loops: "'For Loops'" # for_loops_nested: "Nested For Loops" # for_loops_range: "For Loops Range" functions: "Funções" functions_parameters: "Parâmetros" functions_multiple_parameters: "Multiplos Parâmetros" # game_ai: "Game AI" # game_goals: "Game Goals" # game_spawn: "Game Spawn" graphics: "Gráficos" # graphs: "Graphs" # heaps: "Heaps" # if_condition: "Conditional If Statements" # if_else_if: "If/Else If Statements" # if_else_statements: "If/Else Statements" if_statements: "Declarações 'If'" # if_statements_nested: "Nested If Statements" # indexing: "Array Indexes" # input_handling_flags: "Input Handling - Flags" # input_handling_keyboard: "Input Handling - Keyboard" # input_handling_mouse: "Input Handling - Mouse" # intermediate_css_rules: "Intermediate CSS Rules" # intermediate_css_selectors: "Intermediate CSS Selectors" # intermediate_html_attributes: "Intermediate HTML Attributes" # intermediate_html_tags: "Intermediate HTML Tags" jquery: "jQuery" # jquery_animations: "jQuery Animations" # jquery_filtering: "jQuery Element Filtering" # jquery_selectors: "jQuery Selectors" # length: "Array Length" # math_coordinates: "Coordinate Math" math_geometry: "Geometria" math_operations: "Operações Matemáticas" # math_proportions: "Proportion Math" math_trigonometry: "Trigonometria" object_literals: "'Object Literals'" parameters: "Parâmetros" programs: "Programas" properties: "Propriedades" # property_access: "Accessing Properties" # property_assignment: "Assigning Properties" # property_coordinate: "Coordinate Property" # queues: "Data Structures - Queues" # reading_docs: "Reading the Docs" recursion: "Recursão" # return_statements: "Return Statements" # stacks: "Data Structures - Stacks" strings: "'Strings'" # strings_concatenation: "String Concatenation" # strings_substrings: "Substring" trees: "Estruturas de Dados - Árvores" variables: "Variáveis" vectors: "Vetores" # while_condition_loops: "While Loops with Conditionals" # while_loops_simple: "While Loops" # while_loops_nested: "Nested While Loops" xy_coordinates: "Pares de Coordenadas" advanced_strings: "'Strings' Avançadas" # Rest of concepts are deprecated algorithms: "Algoritmos" boolean_logic: "Lógica Booleana" basic_html: "HTML Básico" basic_css: "CSS Básico" # basic_web_scripting: "Basic Web Scripting" intermediate_html: "HTML Intermédio" intermediate_css: "CSS Intermédio" # intermediate_web_scripting: "Intermediate Web Scripting" advanced_html: "HTML Avançado" advanced_css: "CSS Avançado" # advanced_web_scripting: "Advanced Web Scripting" input_handling: "Manuseamento de 'Input'" while_loops: "'Loops While'" # place_game_objects: "Place game objects" construct_mazes: "Construir labirintos" # create_playable_game: "Create a playable, sharable game project" # alter_existing_web_pages: "Alter existing web pages" # create_sharable_web_page: "Create a sharable web page" # basic_input_handling: "Basic Input Handling" # basic_game_ai: "Basic Game AI" basic_javascript: "JavaScript Básico" # basic_event_handling: "Basic Event Handling" # create_sharable_interactive_web_page: "Create a sharable interactive web page" anonymous_teacher: # notify_teacher: "Notify Teacher" # create_teacher_account: "Create free teacher account" enter_student_name: "O teu nome:" enter_teacher_email: "O e-mail do teu professor:" teacher_email_placeholder: "<EMAIL>" student_name_placeholder: "escreve o teu nome aqui" teachers_section: "Professores:" students_section: "Estudantes:" # teacher_notified: "We've notified your teacher that you want to play more CodeCombat in your classroom!" delta: added: "Adicionado" modified: "Modificado" not_modified: "Não Modificado" deleted: "Eliminado" moved_index: "Índice Movido" text_diff: "Diferença de Texto" merge_conflict_with: "FUNDIR CONFLITO COM" no_changes: "Sem Alterações" legal: page_title: "Legal" opensource_introduction: "O CodeCombat faz parte da comunidade open source." opensource_description_prefix: "Confere " github_url: "o nosso GitHub" opensource_description_center: "e ajuda se quiseres! O CodeCombat é construído tendo por base dezenas de projetos open source, os quais nós amamos. Vê " archmage_wiki_url: "a nossa wiki dos Arcomagos" opensource_description_suffix: "para uma lista do software que faz com que este jogo seja possível." practices_title: "Melhores Práticas Respeitosas" practices_description: "Estas são as nossas promessas para contigo, o jogador, com um pouco menos de politiquices." privacy_title: "Privacidade" privacy_description: "Nós não vamos vender nenhuma das tuas informações pessoais." security_title: "Segurança" security_description: "Nós lutamos para manter as tuas informações pessoais seguras. Sendo um projeto open source, o nosso sítio tem o código disponível, pelo que qualquer pessoa pode rever e melhorar os nossos sistemas de segurança." email_title: "E-mail" email_description_prefix: "Nós não te inundaremos com spam. Através das" email_settings_url: "tuas definições de e-mail" email_description_suffix: "ou através de ligações presentes nos e-mails que enviamos, podes mudar as tuas preferências e parar a tua subscrição facilmente, em qualquer momento." cost_title: "Custo" cost_description: "O CodeCombat é gratuito para os níveis fundamentais, com uma subscrição de ${{price}} USD/mês para acederes a ramos de níveis extra e {{gems}} gemas de bónus por mês. Podes cancelar com um clique, e oferecemos uma garantia de 100% de devolução do dinheiro." copyrights_title: "Direitos Autorais e Licensas" contributor_title: "Contrato de Licença do Contribuinte (CLA)" contributor_description_prefix: "Todas as contribuições, tanto no sítio como no nosso repositório GitHub, estão sujeitas ao nosso" cla_url: "CLA" contributor_description_suffix: "com o qual deves concordar antes de contribuir." # code_title: "Client-Side Code - MIT" # client_code_description_prefix: "All client-side code for codecombat.com in the public GitHub repository and in the codecombat.com database, is licensed under the" mit_license_url: "Licença do MIT" code_description_suffix: "Isto inclui todo o código dentro dos Sistemas e dos Componentes, o qual é disponibilizado pelo CodeCombat para a criação de níveis." art_title: "Arte/Música - Creative Commons " art_description_prefix: "Todos os conteúdos comuns estão disponíveis à luz da" cc_license_url: "Licença 'Creative Commons Attribution 4.0 International'" art_description_suffix: "Conteúdo comum é, geralmente, qualquer coisa disponibilizada pelo CodeCombat com o propósito de criar Níveis. Isto inclui:" art_music: "Música" art_sound: "Som" art_artwork: "Arte" art_sprites: "Sprites" art_other: "Quaisquer e todos os trabalhos criativos não-código que são disponibilizados aquando da criação de Níveis." # art_access: "Currently there is no universal, easy system for fetching these assets. In general, fetch them from the URLs as used by the site, contact us for assistance, or help us in extending the site to make these assets more easily accessible." # art_paragraph_1: "For attribution, please name and link to codecombat.com near where the source is used or where appropriate for the medium. For example:" use_list_1: "Se usado num filme ou noutro jogo, inclui 'codecombat.com' nos créditos." # use_list_2: "If used on a website, include a link near the usage, for example underneath an image, or in a general attributions page where you might also mention other Creative Commons works and open source software being used on the site. Something that's already clearly referencing CodeCombat, such as a blog post mentioning CodeCombat, does not need some separate attribution." # art_paragraph_2: "If the content being used is created not by CodeCombat but instead by a user of codecombat.com, attribute them instead, and follow attribution directions provided in that resource's description if there are any." rights_title: "Direitos Reservados" rights_desc: "Todos os direitos estão reservados aos próprios Níveis. Isto inclui" rights_scripts: "Scripts" rights_unit: "Configurações das unidades" rights_writings: "Textos" rights_media: "Mídia (sons, música) e quaisquer outros conteúdos criativos feitos especificamente para esse Nível e que não foram disponibilizados para a criação de Níveis." # rights_clarification: "To clarify, anything that is made available in the Level Editor for the purpose of making levels is under CC, whereas the content created with the Level Editor or uploaded in the course of creation of Levels is not." nutshell_title: "Resumidamente" nutshell_description: "Qualquer um dos recursos que fornecemos no Editor de Níveis são de uso livre para criares Níveis. Mas reservamos o direito de distribuição restrita dos próprios Níveis (que são criados em codecombat.com) pelo que podemos cobrar por eles no futuro, se for isso que acabar por acontecer." # nutshell_see_also: "See also:" canonical: "A versão Inglesa deste documento é a versão definitiva e soberana. Se houver discrepâncias entre traduções, o documento Inglês prevalece." third_party_title: "Serviços de Terceiros" third_party_description: "O CodeCombat usa os seguintes serviços de terceiros (entre outros):" cookies_message: "O CodeCombat usa alguns cookies essenciais e não-essenciais." cookies_deny: "Recusar cookies não-essenciais" ladder_prizes: title: "Prémios do Torneio" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Estes prémios serão entregues de acordo com" blurb_2: "as regras do torneio" blurb_3: "aos melhores jogadores humanos e ogres." blurb_4: "Duas equipas significam o dobro dos prémios!" blurb_5: "(Haverá dois vencedores em primeiro lugar, dois em segundo, etc.)" rank: "Classificação" prizes: "Prémios" total_value: "Valor Total" in_cash: "em dinheiro" custom_wizard: "Um Feiticeiro do CodeCombat Personalizado" custom_avatar: "Um Avatar do CodeCombat Personalizado" heap: "para seis meses de acesso \"Startup\"" credits: "créditos" one_month_coupon: "cupão: escolhe Rails ou HTML" one_month_discount: "desconto de 30%: escolhe Rails ou HTML" license: "licença" oreilly: "ebook à tua escolha" calendar: year: "Ano" day: "Dia" month: "Mês" january: "janeiro" february: "fevereiro" march: "março" april: "abril" may: "maio" june: "junho" july: "julho" august: "agosto" september: "setembro" october: "outubro" november: "novembro" december: "dezembro" # code_play_create_account_modal: # title: "You did it!" # This section is only needed in US, UK, Mexico, India, and Germany # body: "You are now on your way to becoming a master coder. Sign up to receive an extra <strong>100 Gems</strong> & you will also be entered for a chance to <strong>win $2,500 & other Lenovo Prizes</strong>." # sign_up: "Sign up & keep coding ▶" # victory_sign_up_poke: "Create a free account to save your code & be entered for a chance to win prizes!" # victory_sign_up: "Sign up & be entered to <strong>win $2,500</strong>" server_error: email_taken: "E-mail já escolhido" username_taken: "Nome <NAME>" esper: line_no: "Linha $1: " # uncaught: "Uncaught $1" # $1 will be an error type, eg "Uncaught SyntaxError" # reference_error: "ReferenceError: " # argument_error: "ArgumentError: " # type_error: "TypeError: " # syntax_error: "SyntaxError: " error: "Erro: " x_not_a_function: "$1 não é uma função" x_not_defined: "$1 não está definido" # spelling_issues: "Look out for spelling issues: did you mean `$1` instead of `$2`?" # capitalization_issues: "Look out for capitalization: `$1` should be `$2`." # py_empty_block: "Empty $1. Put 4 spaces in front of statements inside the $2 statement." # fx_missing_paren: "If you want to call `$1` as a function, you need `()`'s" # unmatched_token: "Unmatched `$1`. Every opening `$2` needs a closing `$3` to match it." # unterminated_string: "Unterminated string. Add a matching `\"` at the end of your string." # missing_semicolon: "Missing semicolon." # missing_quotes: "Missing quotes. Try `$1`" # argument_type: "`$1`'s argument `$2` should have type `$3`, but got `$4`: `$5`." # argument_type2: "`$1`'s argument `$2` should have type `$3`, but got `$4`." # target_a_unit: "Target a unit." # attack_capitalization: "Attack $1, not $2. (Capital letters are important.)" # empty_while: "Empty while statement. Put 4 spaces in front of statements inside the while statement." # line_of_site: "`$1`'s argument `$2` has a problem. Is there an enemy within your line-of-sight yet?" # need_a_after_while: "Need a `$1` after `$2`." # too_much_indentation: "Too much indentation at the beginning of this line." # missing_hero: "Missing `$1` keyword; should be `$2`." # takes_no_arguments: "`$1` takes no arguments." # no_one_named: "There's no one named \"$1\" to target." # separated_by_comma: "Function calls paramaters must be seperated by `,`s" # protected_property: "Can't read protected property: $1" # need_parens_to_call: "If you want to call `$1` as function, you need `()`'s" # expected_an_identifier: "Expected an identifier and instead saw '$1'." # unexpected_identifier: "Unexpected identifier" # unexpected_end_of: "Unexpected end of input" # unnecessary_semicolon: "Unnecessary semicolon." # unexpected_token_expected: "Unexpected token: expected $1 but found $2 while parsing $3" # unexpected_token: "Unexpected token $1" unexpected_token2: "Símbolo inesperado" unexpected_number: "Número inesperado" # unexpected: "Unexpected '$1'." # escape_pressed_code: "Escape pressed; code aborted." # target_an_enemy: "Target an enemy by name, like `$1`, not the string `$2`." # target_an_enemy_2: "Target an enemy by name, like $1." # cannot_read_property: "Cannot read property '$1' of undefined" # attempted_to_assign: "Attempted to assign to readonly property." # unexpected_early_end: "Unexpected early end of program." # you_need_a_string: "You need a string to build; one of $1" # unable_to_get_property: "Unable to get property '$1' of undefined or null reference" # TODO: Do we translate undefined/null? # code_never_finished_its: "Code never finished. It's either really slow or has an infinite loop." # unclosed_string: "Unclosed string." # unmatched: "Unmatched '$1'." # error_you_said_achoo: "You said: $1, but the password is: $2. (Capital letters are important.)" # indentation_error_unindent_does: "Indentation Error: unindent does not match any outer indentation level" # indentation_error: "Indentation error." # need_a_on_the: "Need a `:` on the end of the line following `$1`." # attempt_to_call_undefined: "attempt to call '$1' (a nil value)" # unterminated: "Unterminated `$1`" # target_an_enemy_variable: "Target an $1 variable, not the string $2. (Try using $3.)" # error_use_the_variable: "Use the variable name like `$1` instead of a string like `$2`" # indentation_unindent_does_not: "Indentation unindent does not match any outer indentation level" # unclosed_paren_in_function_arguments: "Unclosed $1 in function arguments." # unexpected_end_of_input: "Unexpected end of input" # there_is_no_enemy: "There is no `$1`. Use `$2` first." # Hints start here try_herofindnearestenemy: "Experimenta `$1`" there_is_no_function: "Não há nenhuma função `$1`, mas `$2` tem um método `$3`." # attacks_argument_enemy_has: "`$1`'s argument `$2` has a problem." # is_there_an_enemy: "Is there an enemy within your line-of-sight yet?" # target_is_null_is: "Target is $1. Is there always a target to attack? (Use $2?)" hero_has_no_method: "`$1` não tem nenhum método `$2`." there_is_a_problem: "Há um problema com o teu código." # did_you_mean: "Did you mean $1? You do not have an item equipped with that skill." # missing_a_quotation_mark: "Missing a quotation mark. " # missing_var_use_var: "Missing `$1`. Use `$2` to make a new variable." # you_do_not_have: "You do not have an item equipped with the $1 skill." # put_each_command_on: "Put each command on a separate line" # are_you_missing_a: "Are you missing a '$1' after '$2'? " # your_parentheses_must_match: "Your parentheses must match." # apcsp: # title: "AP Computer Science Principals | College Board Endorsed" # meta_description: "CodeCombat’s comprehensive curriculum and professional development program are all you need to offer College Board’s newest computer science course to your students." # syllabus: "AP CS Principles Syllabus" # syllabus_description: "Use this resource to plan CodeCombat curriculum for your AP Computer Science Principles class." # computational_thinking_practices: "Computational Thinking Practices" # learning_objectives: "Learning Objectives" # curricular_requirements: "Curricular Requirements" # unit_1: "Unit 1: Creative Technology" # unit_1_activity_1: "Unit 1 Activity: Technology Usability Review" # unit_2: "Unit 2: Computational Thinking" # unit_2_activity_1: "Unit 2 Activity: Binary Sequences" # unit_2_activity_2: "Unit 2 Activity: Computing Lesson Project" # unit_3: "Unit 3: Algorithms" # unit_3_activity_1: "Unit 3 Activity: Algorithms - Hitchhiker's Guide" # unit_3_activity_2: "Unit 3 Activity: Simulation - Predator & Prey" # unit_3_activity_3: "Unit 3 Activity: Algorithms - Pair Design and Programming" # unit_4: "Unit 4: Programming" # unit_4_activity_1: "Unit 4 Activity: Abstractions" # unit_4_activity_2: "Unit 4 Activity: Searching & Sorting" # unit_4_activity_3: "Unit 4 Activity: Refactoring" # unit_5: "Unit 5: The Internet" # unit_5_activity_1: "Unit 5 Activity: How the Internet Works" # unit_5_activity_2: "Unit 5 Activity: Internet Simulator" # unit_5_activity_3: "Unit 5 Activity: Chat Room Simulation" # unit_5_activity_4: "Unit 5 Activity: Cybersecurity" # unit_6: "Unit 6: Data" # unit_6_activity_1: "Unit 6 Activity: Introduction to Data" # unit_6_activity_2: "Unit 6 Activity: Big Data" # unit_6_activity_3: "Unit 6 Activity: Lossy & Lossless Compression" # unit_7: "Unit 7: Personal & Global Impact" # unit_7_activity_1: "Unit 7 Activity: Personal & Global Impact" # unit_7_activity_2: "Unit 7 Activity: Crowdsourcing" # unit_8: "Unit 8: Performance Tasks" # unit_8_description: "Prepare students for the Create Task by building their own games and practicing key concepts." # unit_8_activity_1: "Create Task Practice 1: Game Development 1" # unit_8_activity_2: "Create Task Practice 2: Game Development 2" # unit_8_activity_3: "Create Task Practice 3: Game Development 3" # unit_9: "Unit 9: AP Review" # unit_10: "Unit 10: Post-AP" # unit_10_activity_1: "Unit 10 Activity: Web Quiz" # parent_landing: # slogan_quote: "\"CodeCombat is really fun, and you learn a lot.\"" # quote_attr: "5th Grader, Oakland, CA" # refer_teacher: "Refer a Teacher" # focus_quote: "Unlock your child's future" # value_head1: "The most engaging way to learn typed code" # value_copy1: "CodeCombat is child’s personal tutor. Covering material aligned with national curriculum standards, your child will program algorithms, build websites and even design their own games." # value_head2: "Building critical skills for the 21st century" # value_copy2: "Your kids will learn how to navigate and become citizens in the digital world. CodeCombat is a solution that enhances your child’s critical thinking and resilience." # value_head3: "Heroes that your child will love" # value_copy3: "We know how important fun and engagement is for the developing brain, so we’ve packed in as much learning as we can while wrapping it up in a game they'll love." # dive_head1: "Not just for software engineers" # dive_intro: "Computer science skills have a wide range of applications. Take a look at a few examples below!" # medical_flag: "Medical Applications" # medical_flag_copy: "From mapping of the human genome to MRI machines, coding allows us to understand the body in ways we’ve never been able to before." # explore_flag: "Space Exploration" # explore_flag_copy: "Apollo got to the Moon thanks to hardworking human computers, and scientists use computer programs to analyze the gravity of planets and search for new stars." # filmaking_flag: "Filmmaking and Animation" # filmaking_flag_copy: "From the robotics of Jurassic Park to the incredible animation of Dreamworks and Pixar, films wouldn’t be the same without the digital creatives behind the scenes." # dive_head2: "Games are important for learning" # dive_par1: "Multiple studies have found that game-based learning promotes" # dive_link1: "cognitive development" # dive_par2: "in kids while also proving to be" # dive_link2: "more effective" # dive_par3: "in helping students" # dive_link3: "learn and retain knowledge" # dive_par4: "," # dive_link4: "concentrate" # dive_par5: ", and perform at a higher level of achievement." # dive_par6: "Game based learning is also good for developing" # dive_link5: "resilience" # dive_par7: ", cognitive reasoning, and" # dive_par8: ". Science is just telling us what learners already know. Children learn best by playing." # dive_link6: "executive functions" # dive_head3: "Team up with teachers" # dive_3_par1: "In the future, " # dive_3_link1: "coding is going to be as fundamental as learning to read and write" # dive_3_par2: ". We’ve worked closely with teachers to design and develop our content, and we can't wait to get your kids learning. Educational technology programs like CodeCombat work best when the teachers implement them consistently. Help us make that connection by introducing us to your child’s teachers!" # mission: "Our mission: to teach and engage" # mission1_heading: "Coding for today's generation" # mission2_heading: "Preparing for the future" # mission3_heading: "Supported by parents like you" # mission1_copy: "Our education specialists work closely with teachers to meet children where they are in the educational landscape. Kids learn skills that can be applied outside of the game because they learn how to solve problems, no matter what their learning style is." # mission2_copy: "A 2016 survey showed that 64% of girls in 3-5th grade want to learn how to code. There were 7 million job openings in 2015 required coding skills. We built CodeCombat because every child should be given a chance to create their best future." # mission3_copy: "At CodeCombat, we’re parents. We’re coders. We’re educators. But most of all, we’re people who believe in giving our kids the best opportunity for success in whatever it is they decide to do." # parent_modal: # refer_teacher: "Refer Teacher" # name: "<NAME>" # parent_email: "Your Email" # teacher_email: "Teacher's Email" # message: "Message" # custom_message: "I just found CodeCombat and thought it'd be a great program for your classroom! It's a computer science learning platform with standards-aligned curriculum.\n\nComputer literacy is so important and I think this would be a great way to get students engaged in learning to code." # send: "Send Email" # hoc_2018: # banner: "Welcome to Hour of Code 2019!" # page_heading: "Your students will learn to code by building their own game!" # step_1: "Step 1: Watch Video Overview" # step_2: "Step 2: Try it Yourself" # step_3: "Step 3: Download Lesson Plan" # try_activity: "Try Activity" # download_pdf: "Download PDF" # teacher_signup_heading: "Turn Hour of Code into a Year of Code" # teacher_signup_blurb: "Everything you need to teach computer science, no prior experience needed." # teacher_signup_input_blurb: "Get first course free:" # teacher_signup_input_placeholder: "Teacher email address" # teacher_signup_input_button: "Get CS1 Free" # activities_header: "More Hour of Code Activities" # activity_label_1: "Escape the Dungeon!" # activity_label_2: " Beginner: Build a Game!" # activity_label_3: "Advanced: Build an Arcade Game!" # activity_button_1: "View Lesson" # about: "About CodeCombat" # about_copy: "A game-based, standards-aligned computer science program that teaches real, typed Python and JavaScript." # point1: "✓ Scaffolded" # point2: "✓ Differentiated" # point3: "✓ Assessments" # point4: "✓ Project-based courses" # point5: "✓ Student tracking" # point6: "✓ Full lesson plans" # title: "HOUR OF CODE 2019" # acronym: "HOC" # hoc_2018_interstitial: # welcome: "Welcome to CodeCombat's Hour of Code 2019!" # educator: "I'm an educator" # show_resources: "Show me teacher resources!" # student: "I'm a student" # ready_to_code: "I'm ready to code!" # hoc_2018_completion: # congratulations: "Congratulations on completing <b>Code, Play, Share!</b>" # send: "Send your Hour of Code game to friends and family!" # copy: "Copy URL" # get_certificate: "Get a certificate of completion to celebrate with your class!" # get_cert_btn: "Get Certificate" # first_name: "<NAME>" # last_initial: "Last Initial" # teacher_email: "Teacher's email address" # school_administrator: # title: "School Administrator Dashboard" # my_teachers: "My Teachers" # last_login: "Last Login" # licenses_used: "licenses used" # total_students: "total students" # active_students: "active students" # projects_created: "projects created" # other: "Other" # notice: "The following school administrators have view-only access to your classroom data:" # add_additional_teacher: "Need to add an additional teacher? Contact your CodeCombat Account Manager or email <EMAIL>. " # license_stat_description: "Licenses available accounts for the total number of licenses available to the teacher, including Shared Licenses." # students_stat_description: "Total students accounts for all students across all classrooms, regardless of whether they have licenses applied." # active_students_stat_description: "Active students counts the number of students that have logged into CodeCombat in the last 60 days." # project_stat_description: "Projects created counts the total number of Game and Web development projects that have been created." # no_teachers: "You are not administrating any teachers." # interactives: # phenomenal_job: "Phenomenal Job!" # try_again: "Whoops, try again!" # select_statement_left: "Whoops, select a statement from the left before hitting \"Submit.\"" # fill_boxes: "Whoops, make sure to fill all boxes before hitting \"Submit.\"" # browser_recommendation: # title: "CodeCombat works best on Chrome!" # pitch_body: "For the best CodeCombat experience we recommend using the latest version of Chrome. Download the latest version of chrome by clicking the button below!" # download: "Download Chrome" # ignore: "Ignore"
true
module.exports = nativeDescription: "Português (Portugal)", englishDescription: "Portuguese (Portugal)", translation: new_home: # title: "CodeCombat - Coding games to learn Python and JavaScript" # meta_keywords: "CodeCombat, python, javascript, Coding Games" # meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." # meta_og_url: "https://codecombat.com" # built_for_teachers_title: "A Coding Game Built with Teachers in Mind" # built_for_teachers_blurb: "Teaching kids to code can often feel overwhelming. CodeCombat helps all educators teach students how to code in either JavaScript or Python, two of the most popular programming languages. With a comprehensive curriculum that includes six computer science units and reinforces learning through project-based game development and web development units, kids will progress on a journey from basic syntax to recursion!" # built_for_teachers_subtitle1: "Computer Science" # built_for_teachers_subblurb1: "Starting with our free Introduction to Computer Science course, students master core coding concepts such as while/for loops, functions, and algorithms." # built_for_teachers_subtitle2: "Game Development" # built_for_teachers_subblurb2: "Learners construct mazes and use basic input handling to code their own games that can be shared with friends and family." # built_for_teachers_subtitle3: "Web Development" # built_for_teachers_subblurb3: "Using HTML, CSS, and jQuery, learners flex their creative muscles to program their own webpages with a custom URL to share with their classmates." # century_skills_title: "21st Century Skills" # century_skills_blurb1: "Students Don't Just Level Up Their Hero, They Level Up Themselves" # century_skills_quote1: "You mess up…so then you think about all of the possible ways to fix it, and then try again. I wouldn't be able to get here without trying hard." # century_skills_subtitle1: "Critical Thinking" # century_skills_subblurb1: "With coding puzzles that are naturally scaffolded into increasingly challenging levels, CodeCombat's programming game ensures kids are always practicing critical thinking." # century_skills_quote2: "Everyone else was making mazes, so I thought, ‘capture the flag’ and that’s what I did." # century_skills_subtitle2: "Creativity" # century_skills_subblurb2: "CodeCombat encourages students to showcase their creativity by building and sharing their own games and webpages." # century_skills_quote3: "If I got stuck on a level. I would work with people around me until we were all able to figure it out." # century_skills_subtitle3: "Collaboration" # century_skills_subblurb3: "Throughout the game, there are opportunities for students to collaborate when they get stuck and to work together using our pair programming guide." # century_skills_quote4: "I’ve always had aspirations of designing video games and learning how to code ... this is giving me a great starting point." # century_skills_subtitle4: "Communication" # century_skills_subblurb4: "Coding requires kids to practice new forms of communication, including communicating with the computer itself and conveying their ideas using the most efficient code." # classroom_in_box_title: "We Strive To:" # classroom_in_box_blurb1: "Engage every student so that they believe coding is for them." # classroom_in_box_blurb2: "Empower any educator to feel confident when teaching coding." # classroom_in_box_blurb3: "Inspire all school leaders to create a world-class computer science program." # creativity_rigor_title: "Where Creativity Meets Rigor" # creativity_rigor_subtitle1: "Make coding fun and teach real-world skills" # creativity_rigor_blurb1: "Students type real Python and JavaScript while playing games that encourage trial-and-error, critical thinking, and creativity. Students then apply the coding skills they’ve learned by developing their own games and websites in project-based courses." # creativity_rigor_subtitle2: "Reach students at their level" # creativity_rigor_blurb2: "Every CodeCombat level is scaffolded based on millions of data points and optimized to adapt to each learner. Practice levels and hints help students when they get stuck, and challenge levels assess students' learning throughout the game." # creativity_rigor_subtitle3: "Built for all teachers, regardless of experience" # creativity_rigor_blurb3: "CodeCombat’s self-paced, standards-aligned curriculum makes teaching computer science possible for everyone. CodeCombat equips teachers with the training, instructional resources, and dedicated support to feel confident and successful in the classroom." # featured_partners_title1: "Featured In" # featured_partners_title2: "Awards & Partners" # featured_partners_blurb1: "CollegeBoard Endorsed Provider" # featured_partners_blurb2: "Best Creativity Tool for Students" # featured_partners_blurb3: "Top Pick for Learning" # featured_partners_blurb4: "Code.org Official Partner" # featured_partners_blurb5: "CSforAll Official Member" # featured_partners_blurb6: "Hour of Code Activity Partner" # for_leaders_title: "For School Leaders" # for_leaders_blurb: "A Comprehensive, Standards-Aligned Computer Science Program" # for_leaders_subtitle1: "Easy Implementation" # for_leaders_subblurb1: "A web-based program that requires no IT support. Get started in under 5 minutes using Google or Clever Single Sign-On (SSO)." # for_leaders_subtitle2: "Full Coding Curriculum" # for_leaders_subblurb2: "A standards-aligned curriculum with instructional resources and professional development to enable any teacher to teach computer science." # for_leaders_subtitle3: "Flexible Use Cases" # for_leaders_subblurb3: "Whether you want to build a Middle School coding elective, a CTE pathway, or an AP Computer Science Principles class, CodeCombat is tailored to suit your needs." # for_leaders_subtitle4: "Real-World Skills" # for_leaders_subblurb4: "Students build grit and develop a growth mindset through coding challenges that prepare them for the 500K+ open computing jobs." # for_teachers_title: "For Teachers" # for_teachers_blurb: "Tools to Unlock Student Potential" # for_teachers_subtitle1: "Project-Based Learning" # for_teachers_subblurb1: "Promote creativity, problem-solving, and confidence in project-based courses where students develop their own games and webpages." # for_teachers_subtitle2: "Teacher Dashboard" # for_teachers_subblurb2: "View data on student progress, discover curriculum resources, and access real-time support to empower student learning." # for_teachers_subtitle3: "Built-in Assessments" # for_teachers_subblurb3: "Personalize instruction and ensure students understand core concepts with formative and summative assessments." # for_teachers_subtitle4: "Automatic Differentiation" # for_teachers_subblurb4: "Engage all learners in a diverse classroom with practice levels that adapt to each student's learning needs." # game_based_blurb: "CodeCombat is a game-based computer science program where students type real code and see their characters react in real time." # get_started: "Get started" # global_title: "Join Our Global Community of Learners and Educators" # global_subtitle1: "Learners" # global_subtitle2: "Lines of Code" # global_subtitle3: "Teachers" # global_subtitle4: "Countries" # go_to_my_classes: "Go to my classes" # go_to_my_courses: "Go to my courses" # quotes_quote1: "Name any program online, I’ve tried it. None of them match up to CodeCombat. Any teacher who wants their students to learn how to code... start here!" # quotes_quote2: " I was surprised about how easy and intuitive CodeCombat makes learning computer science. The scores on the AP exam were much higher than I expected and I believe CodeCombat is the reason why this was the case." # quotes_quote3: "CodeCombat has been the most beneficial for teaching my students real-life coding capabilities. My husband is a software engineer and he has tested out all of my programs. He put this as his top choice." # quotes_quote4: "The feedback … has been so positive that we are structuring a computer science class around CodeCombat. The program really engages the students with a gaming style platform that is entertaining and instructional at the same time. Keep up the good work, CodeCombat!" # see_example: "See example" slogan: "A forma mais cativante de aprender código real." # {change} # teach_cs1_free: "Teach CS1 Free" # teachers_love_codecombat_title: "Teachers Love CodeCombat" # teachers_love_codecombat_blurb1: "Report that their students enjoy using CodeCombat to learn how to code" # teachers_love_codecombat_blurb2: "Would recommend CodeCombat to other computer science teachers" # teachers_love_codecombat_blurb3: "Say that CodeCombat helps them support students’ problem solving abilities" # teachers_love_codecombat_subblurb: "In partnership with McREL International, a leader in research-based guidance and evaluations of educational technology." # try_the_game: "Try the game" classroom_edition: "Edição de Turma:" learn_to_code: "Aprender a programar:" play_now: "Jogar Agora" # im_an_educator: "I'm an Educator" im_a_teacher: "Sou um Professor" im_a_student: "Sou um Estudante" learn_more: "Saber mais" classroom_in_a_box: "Uma turma num pacote para ensinar ciências da computação." codecombat_is: "O CodeCombat é uma plataforma <strong>para estudantes</strong> para aprender ciências da computação enquanto se joga um jogo real." our_courses: "Os nossos cursos foram especificamente testados para <strong>terem sucesso na sala de aula</strong>, até para professores com pouca ou nenhuma experiência anterior de programação." watch_how: "Vê como o CodeCombat está a transformar o modo como as pessoas aprendem ciências da computação." top_screenshots_hint: "Os estudantes escrevem código e veem as alterações deles atualizarem em tempo real" designed_with: "Desenhado a pensar nos professores" real_code: "Código real e escrito" from_the_first_level: "desde o primeiro nível" getting_students: "Apresentar código escrito aos estudantes o mais rapidamete possível é crítico para aprenderem a sintaxe e a estrutura adequadas da programação." educator_resources: "Recursos para professores" course_guides: "e guias dos cursos" teaching_computer_science: "Ensinar ciências da computação não requer um curso caro, porque nós fornecemos ferramentas para ajudar todo o tipo de professores." accessible_to: "Acessível a" everyone: "todos" democratizing: "Democratizar o processo de aprender a programar está na base da nossa filosofia. Todos devem poder aprender a programar." forgot_learning: "Acho que eles se esqueceram que estavam a aprender alguma coisa." wanted_to_do: "Programar é algo que sempre quis fazer e nunca pensei que poderia aprender isso na escola." builds_concepts_up: "Gosto da forma como o CodeCombat desenvolve os conceitos. É muito fácil compreendê-los e é divertido descobri-los." why_games: "Porque é que aprender através de jogos é importante?" games_reward: "Os jogos recompensam o esforço produtivo." encourage: "Jogar é algo que encoraja a interação, a descoberta e a tentativa erro. Um bom jogo desafia o jogador a dominar habilidades com o tempo, que é o mesmo processo fundamental que os estudantes atravessam quando aprendem." excel: "Os jogos são excelentes a recompensar o" struggle: "esforço produtivo" kind_of_struggle: "o tipo de esforço que resulta numa aprendizagem que é cativante e" motivating: "motivadora" not_tedious: "não entediante." gaming_is_good: "Estudos sugerem que jogar é bom para o cérebro das crianças. (é verdade!)" # game_based: "When game-based learning systems are" # compared: "compared" # conventional: "against conventional assessment methods, the difference is clear: games are better at helping students retain knowledge, concentrate and" # perform_at_higher_level: "perform at a higher level of achievement" # feedback: "Games also provide real-time feedback that allows students to adjust their solution path and understand concepts more holistically, instead of being limited to just “correct” or “incorrect” answers." real_game: "Um jogo a sério, jogado com código a sério." # great_game: "A great game is more than just badges and achievements - it’s about a player’s journey, well-designed puzzles, and the ability to tackle challenges with agency and confidence." # agency: "CodeCombat is a game that gives players that agency and confidence with our robust typed code engine, which helps beginner and advanced students alike write proper, valid code." # request_demo_title: "Get your students started today!" # request_demo_subtitle: "Request a demo and get your students started in less than an hour." # get_started_title: "Set up your class today" # get_started_subtitle: "Set up a class, add your students, and monitor their progress as they learn computer science." request_demo: "Pedir uma Demonstração" # request_quote: "Request a Quote" setup_a_class: "Configurar uma Turma" have_an_account: "Tens uma conta?" logged_in_as: "Atualmente tens sessão iniciada como" # computer_science: "Our self-paced courses cover basic syntax to advanced concepts" ffa: "Grátis para todos os estudantes" coming_soon: "Mais, brevemente!" courses_available_in: "Os cursos estão disponíveis em JavaScript e Python. Os cursos de Desenvolvimento Web utilizam HTML, CSS e jQuery." # boast: "Boasts riddles that are complex enough to fascinate gamers and coders alike." # winning: "A winning combination of RPG gameplay and programming homework that pulls off making kid-friendly education legitimately enjoyable." run_class: "Tudo o que precisas para teres uma turma de ciências da computação na tua escola hoje, sem serem necessárias bases de CC." goto_classes: "Ir para As Minhas Turmas" view_profile: "Ver o Meu Perfil" view_progress: "Ver Progresso" go_to_courses: "Ir para Os Meus Cursos" want_coco: "Queres o CodeCombat na tua escola?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" map: "Mapa" play: "Níveis" # The top nav bar entry where players choose which levels to play community: "Comunidade" courses: "Cursos" blog: "Blog" forum: "Fórum" account: "PI:NAME:<NAME>END_PI" my_account: "PI:NAME:<NAME>END_PI" profile: "Perfil" home: "Início" contribute: "Contribuir" legal: "Legal" privacy: "Aviso de Privacidade" about: "Sobre" # impact: "Impact" contact: "Contactar" twitter_follow: "Seguir" my_classrooms: "As Minhas Turmas" my_courses: "Os Meus Cursos" # my_teachers: "My Teachers" careers: "PI:NAME:<NAME>END_PI" facebook: "Facebook" twitter: "Twitter" create_a_class: "Criar uma Turma" other: "Outros" learn_to_code: "Aprende a Programar!" toggle_nav: "Alternar navegação" schools: "Escolas" get_involved: "Envolve-te" open_source: "Open source (GitHub)" support: "Suporte" faqs: "FAQs" copyright_prefix: "Direitos" copyright_suffix: "Todos os Direitos Reservados." help_pref: "Precisas de ajuda? Envia um e-mail para" help_suff: "e nós entraremos em contacto!" resource_hub: "Centro de Recursos" # apcsp: "AP CS Principles" parent: "Educadores" # browser_recommendation: "For the best experience we recommend using the latest version of Chrome. Download the browser here!" modal: close: "Fechar" okay: "Ok" # cancel: "Cancel" not_found: page_not_found: "Página não encontrada" diplomat_suggestion: title: "Ajuda a traduzir o CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Precisamos das tuas habilidades linguísticas." pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores de todo o mundo. Muitos deles querem jogar em Português, mas não falam Inglês, por isso, se sabes falar ambas, por favor considera registar-te como Diplomata para ajudares a traduzir o sítio do CodeCombat e todos os níveis para Português." missing_translations: "Até conseguirmos traduzir tudo para Português, irás ver em Inglês o que não estiver disponível em Português." learn_more: "Sabe mais sobre seres um Diplomata" subscribe_as_diplomat: "Subscreve-te como Diplomata" play: # title: "Play CodeCombat Levels - Learn Python, JavaScript, and HTML" # meta_description: "Learn programming with a coding game for beginners. Learn Python or JavaScript as you solve mazes, make your own games, and level up. Challenge your friends in multiplayer arena levels!" # level_title: "__level__ - Learn to Code in Python, JavaScript, HTML" # video_title: "__video__ | Video Level" # game_development_title: "__level__ | Game Development" # web_development_title: "__level__ | Web Development" anon_signup_title_1: "O CodeCombat tem uma" anon_signup_title_2: "Versão para Turmas!" anon_signup_enter_code: "Introduz um Código de Truma:" anon_signup_ask_teacher: "Não tens um? Pede ao teu professor!" anon_signup_create_class: "Queres criar uma turma?" anon_signup_setup_class: "Configura um turma, adiciona estudantes e monitoriza o progresso!" anon_signup_create_teacher: "Criar uma conta de professor gratuita" play_as: "Jogar ComPI:NAME:<NAME>END_PI" # Ladder page # get_course_for_class: "Assign Game Development and more to your classes!" # request_licenses: "Contact our school specialists for details." compete: "Competir!" # Course details page spectate: "Assistir" # Ladder page players: "jogadores" # Hover over a level on /play hours_played: "horas jogadas" # Hover over a level on /play items: "Itens" # Tooltip on item shop button from /play unlock: "Desbloquear" # For purchasing items and heroes confirm: "Confirmar" owned: "Obtido" # For items you own locked: "Bloqueado" available: "Disponível" skills_granted: "Habilidades Garantidas" # Property documentation details heroes: "Heróis" # Tooltip on hero shop button from /play achievements: "Conquistas" # Tooltip on achievement list button from /play settings: "Definições" # Tooltip on settings button from /play poll: "Votações" # Tooltip on poll button from /play next: "Próximo" # Go from choose hero to choose inventory before playing a level change_hero: "Alterar Herói" # Go back from choose inventory to choose hero change_hero_or_language: "Alterar Herói ou Linguagem" buy_gems: "Comprar Gemas" subscribers_only: "Apenas para Subscritores!" subscribe_unlock: "Subscreve-te para Desbloqueares!" subscriber_heroes: "Subscreve-te hoje para desbloqueares de imediato a Amara, a Hushbaum, e o Hattori!" subscriber_gems: "Subscreve-te hoje para adquirires este herói com gemas!" anonymous: "PI:NAME:<NAME>END_PI" level_difficulty: "Dificuldade: " awaiting_levels_adventurer_prefix: "Lançamos novos níveis todas as semanas." awaiting_levels_adventurer: "Regista-te como Aventureiro" awaiting_levels_adventurer_suffix: "para seres o primeiro a jogar níveis novos." adjust_volume: "Ajustar volume" campaign_multiplayer: "Arenas Multijogador" campaign_multiplayer_description: "... nas quais programas contra outros jogadores." # brain_pop_done: "You’ve defeated the Ogres with code! You win!" # brain_pop_challenge: "Challenge yourself to play again using a different programming language!" # replay: "Replay" back_to_classroom: "Voltar à Turma" teacher_button: "Para Professores" # get_more_codecombat: "Get More CodeCombat" code: if: "se" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "senão" elif: "senão se" while: "enquanto" loop: "repetir" for: "para" break: "parar" continue: "continuar" pass: "passar" return: "devolver" then: "então" do: "fazer" end: "fim" function: "função" def: "definir" var: "variável" self: "próprio" hero: "herói" this: "isto" or: "ou" "||": "ou" and: "e" "&&": "e" not: "não" "!": "não" "=": "atribuir" "==": "é igual a" "===": "é estritamente igual a" "!=": "não é igual a" "!==": "não é estritamente igual a" ">": "é maior do que" ">=": "é maior do que ou igual a" "<": "é menor do que" "<=": "é menor do que ou igual a" "*": "multiplicado por" "/": "dividido por" "+": "mais" "-": "menos" "+=": "adicionar e atribuir" "-=": "subtrair e atribuir" True: "Verdadeiro" true: "verdadeiro" False: "Falso" false: "falso" undefined: "não definido" null: "nulo" nil: "nada" None: "Nenhum" share_progress_modal: blurb: "Estás a fazer grandes progressos! Conta ao teu educador o quanto aprendeste com o CodeCombat." email_invalid: "Endereço de e-mail inválido." form_blurb: "Introduz o e-mail do teu educador abaixo e nós vamos mostrar-lhe!" form_label: "Endereço de E-mail" placeholder: "endereço de e-mail" title: "Excelente Trabalho, Aprendiz" login: sign_up: "Criar Conta" email_or_username: "E-PI:NAME:<NAME>END_PI" log_in: "Iniciar Sessão" logging_in: "A Iniciar Sessão" log_out: "Sair" forgot_password: "PI:PASSWORD:<PASSWORD>END_PI?" finishing: "A Terminar" sign_in_with_facebook: "Iniciar sessão com o FB" sign_in_with_gplus: "Iniciar sessão com o Google" signup_switch: "Queres criar uma conta?" signup: # complete_subscription: "Complete Subscription" create_student_header: "Criar Conta de Estudante" create_teacher_header: "Criar Conta de Professor" create_individual_header: "Criar Conta Individual" email_announcements: "Receber anúncios sobre níveis e funcionalidades novos do CodeCombat!" sign_in_to_continue: "Inicia sessão ou cria uma conta para continuares" # teacher_email_announcements: "Keep me updated on new teacher resources, curriculum, and courses!" creating: "A Criar Conta..." sign_up: "Registar" log_in: "iniciar sessão com palavra-passe" # login: "Login" required: "Precisas de iniciar sessão antes de prosseguires." login_switch: "Já tens uma conta?" optional: "opcional" # connected_gplus_header: "You've successfully connected with Google+!" # connected_gplus_p: "Finish signing up so you can log in with your Google+ account." # connected_facebook_header: "You've successfully connected with Facebook!" # connected_facebook_p: "Finish signing up so you can log in with your Facebook account." hey_students: "Estudantes, introduzam o código de turma do vosso professor." birthday: "Aniversário" # parent_email_blurb: "We know you can't wait to learn programming &mdash; we're excited too! Your parents will receive an email with further instructions on how to create an account for you. Email {{email_link}} if you have any questions." # classroom_not_found: "No classes exist with this Class Code. Check your spelling or ask your teacher for help." checking: "A verificar..." account_exists: "Este e-mail já está a ser usado:" sign_in: "Iniciar sessão" email_good: "O e-mail parece bom!" name_taken: "Nome de utilizador já escolhido! Que tal {{suggestedName}}?" name_available: "Nome de utilizador disponível!" name_is_email: "O nome de utilizador não pode ser um e-mail" choose_type: "Escolhe o teu tipo de conta:" teacher_type_1: "Ensina programção usando o CodeCombat!" teacher_type_2: "Configura a tua turma" teacher_type_3: "Acede aos Guias dos Cursos" teacher_type_4: "Vê o progresso dos estudantes" signup_as_teacher: "Registar como Professor" student_type_1: "Aprende a programar enquanto jogas um jogo cativante!" student_type_2: "Joga com a tua turma" student_type_3: "Compete em arenas" student_type_4: "Escolhe o teu herói!" student_type_5: "Prepara o teu Código de Turma!" signup_as_student: "Registar como Estudante" individuals_or_parents: "Individuais e Educadores" individual_type: "Para jogadores a aprender a programar fora de uma turma. Os educadores devem registar-se aqui." signup_as_individual: "Registar como Individual" enter_class_code: "Introduz o teu Código de Turma" enter_birthdate: "Introduz a tua data de nascimento:" parent_use_birthdate: "Educadores, usem a vossa data de nascimento." ask_teacher_1: "Pergunta ao teu professor pelo teu Código de Turma." ask_teacher_2: "Não fazes parte de uma turma? Cria uma " ask_teacher_3: "Conta Individual" ask_teacher_4: " então." about_to_join: "Estás prestes a entrar em:" enter_parent_email: "Introduz o e-mail do teu educador:" # parent_email_error: "Something went wrong when trying to send the email. Check the email address and try again." # parent_email_sent: "We’ve sent an email with further instructions on how to create an account. Ask your parent to check their inbox." account_created: "Conta Criada!" confirm_student_blurb: "Aponta a tua informação para que não a esqueças. O teu professor também te pode ajudar a reiniciar a tua palavra-passe a qualquer altura." confirm_individual_blurb: "Aponta a tua informação de início de sessão caso precises dela mais tarde. Verifica o teu e-mail para que possas recuperar a tua conta se alguma vez esqueceres a tua palavra-passe - verifica a tua caixa de entrada!" write_this_down: "Aponta isto:" start_playing: "Começar a Jogar!" # sso_connected: "Successfully connected with:" select_your_starting_hero: "Escolhe o Teu Herói Inicial:" you_can_always_change_your_hero_later: "Podes sempre alterar o teu herói mais tarde." # finish: "Finish" # teacher_ready_to_create_class: "You're ready to create your first class!" # teacher_students_can_start_now: "Your students will be able to start playing the first course, Introduction to Computer Science, immediately." # teacher_list_create_class: "On the next screen you will be able to create a new class." # teacher_list_add_students: "Add students to the class by clicking the View Class link, then sending your students the Class Code or URL. You can also invite them via email if they have email addresses." # teacher_list_resource_hub_1: "Check out the" # teacher_list_resource_hub_2: "Course Guides" # teacher_list_resource_hub_3: "for solutions to every level, and the" # teacher_list_resource_hub_4: "Resource Hub" # teacher_list_resource_hub_5: "for curriculum guides, activities, and more!" # teacher_additional_questions: "That’s it! If you need additional help or have questions, reach out to __supportEmail__." # dont_use_our_email_silly: "Don't put our email here! Put your parent's email." # want_codecombat_in_school: "Want to play CodeCombat all the time?" # eu_confirmation: "I agree to allow CodeCombat to store my data on US servers." # eu_confirmation_place_of_processing: "Learn more about the possible risks" # eu_confirmation_student: "If you are not sure, ask your teacher." # eu_confirmation_individual: "If you do not want us to store your data on US servers, you can always keep playing anonymously without saving your code." recover: recover_account_title: "Recuperar Conta" send_password: "PI:PASSWORD:<PASSWORD>END_PI" recovery_sent: "E-mail de recuperação enviado." items: primary: "Primários" secondary: "Secundários" armor: "Armadura" accessories: "Acessórios" misc: "Vários" books: "Livros" common: # default_title: "CodeCombat - Coding games to learn Python and JavaScript" # default_meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." back: "Voltar" # When used as an action verb, like "Navigate backward" coming_soon: "Brevemente!" continue: "Continuar" # When used as an action verb, like "Continue forward" next: "Próximo" default_code: "Código Original" loading: "A Carregar..." overview: "Visão Geral" processing: "A processar..." solution: "Solução" table_of_contents: "Tabela de Conteúdos" intro: "Introdução" saving: "A Guardar..." sending: "A Enviar..." send: "Enviar" sent: "Enviado" cancel: "Cancelar" save: "Guardar" publish: "Publicar" create: "Criar" fork: "Bifurcar" play: "Jogar" # When used as an action verb, like "Play next level" retry: "Tentar Novamente" actions: "Ações" info: "Informações" help: "Ajuda" watch: "Vigiar" unwatch: "Desvigiar" submit_patch: "Submeter Atualização" submit_changes: "Submeter Alterações" save_changes: "Guardar Alterações" required_field: "necessário" # submit: "Submit" # replay: "Replay" # complete: "Complete" general: and: "e" name: "Nome" date: "Data" body: "Corpo" version: "Versão" pending: "Pendentes" accepted: "Aceites" rejected: "Rejeitadas" withdrawn: "Canceladas" accept: "Aceitar" accept_and_save: "Aceitar&Guardar" reject: "Rejeitar" withdraw: "Cancelar" submitter: "Submissor" submitted: "Submeteu" commit_msg: "Mensagem da Submissão" version_history: "Histórico de Versões" version_history_for: "Histórico de Versões para: " select_changes: "Seleciona duas das alterações abaixo para veres a diferença." undo_prefix: "Desfazer" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Refazer" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Jogar pré-visualização do nível atual" result: "Resultado" results: "Resultados" description: "Descrição" or: "ou" subject: "Assunto" email: "E-mail" password: "PI:PASSWORD:<PASSWORD>END_PI" confirm_password: "PI:PASSWORD:<PASSWORD>END_PI" message: "Mensagem" code: "Código" ladder: "Classificação" when: "Quando" opponent: "Adversário" rank: "Classificação" score: "Pontuação" win: "Vitória" loss: "Derrota" tie: "Empate" easy: "Fácil" medium: "Médio" hard: "Difícil" player: "PI:NAME:<NAME>END_PI" player_level: "Nível" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Guerreiro" ranger: "Arqueiro" wizard: "Feiticeiro" first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" last_initial: "Última Inicial" username: "Nome de utilizador" contact_us: "Contacta-nos" close_window: "Fechar Janela" learn_more: "Saber Mais" more: "Mais" fewer: "Menos" with: "com" units: second: "segundo" seconds: "segundos" sec: "seg" minute: "minuto" minutes: "minutos" hour: "hora" hours: "horas" day: "dia" days: "dias" week: "semana" weeks: "semanas" month: "mês" months: "meses" year: "ano" years: "anos" play_level: back_to_map: "Voltar ao Mapa" directions: "Direções" edit_level: "Editar Nível" keep_learning: "Continuar a Aprender" explore_codecombat: "Explorar o CodeCombat" finished_hoc: "Terminei a minha Hora do Código" get_certificate: "Obtém o teu certificado!" level_complete: "Nível Completo" completed_level: "Nível Completo:" course: "Curso:" done: "Concluir" next_level: "Próximo Nível" # combo_challenge: "Combo Challenge" # concept_challenge: "Concept Challenge" # challenge_unlocked: "Challenge Unlocked" # combo_challenge_unlocked: "Combo Challenge Unlocked" # concept_challenge_unlocked: "Concept Challenge Unlocked" # concept_challenge_complete: "Concept Challenge Complete!" # combo_challenge_complete: "Combo Challenge Complete!" # combo_challenge_complete_body: "Great job, it looks like you're well on your way to understanding __concept__!" # replay_level: "Replay Level" combo_concepts_used: "__complete__/__total__ Conceitos Usados" # combo_all_concepts_used: "You used all concepts possible to solve the challenge. Great job!" # combo_not_all_concepts_used: "You used __complete__ out of the __total__ concepts possible to solve the challenge. Try to get all __total__ concepts next time!" start_challenge: "Começar Desafio" next_game: "Próximo jogo" languages: "Linguagens" programming_language: "Linguagem de programação" show_menu: "Mostrar o menu do jogo" home: "Início" # Not used any more, will be removed soon. level: "Nível" # Like "Level: Dungeons of Kithgard" skip: "Saltar" game_menu: "Menu do Jogo" restart: "Reiniciar" goals: "Objetivos" goal: "Objetivo" # challenge_level_goals: "Challenge Level Goals" # challenge_level_goal: "Challenge Level Goal" # concept_challenge_goals: "Concept Challenge Goals" # combo_challenge_goals: "Challenge Level Goals" # concept_challenge_goal: "Concept Challenge Goal" # combo_challenge_goal: "Challenge Level Goal" running: "A Executar..." success: "Sucesso!" incomplete: "Incompletos" timed_out: "Ficaste sem tempo" failing: "A falhar" reload: "Recarregar" reload_title: "Recarregar o Código Todo?" reload_really: "Tens a certeza que queres recarregar este nível de volta ao início?" reload_confirm: "Recarregar Tudo" # restart_really: "Are you sure you want to restart the level? You'll loose all the code you've written." # restart_confirm: "Yes, Restart" test_level: "Testar Nível" victory: "Vitória" victory_title_prefix: "" victory_title_suffix: " Concluído" victory_sign_up: "Criar Conta para Guardar Progresso" victory_sign_up_poke: "Queres guardar o teu código? Cria uma conta grátis!" victory_rate_the_level: "Quão divertido foi este nível?" victory_return_to_ladder: "Voltar à Classificação" victory_saving_progress: "A Guardar Progresso" victory_go_home: "Ir para o Início" victory_review: "Conta-nos mais!" victory_review_placeholder: "Como foi o nível?" victory_hour_of_code_done: "Terminaste?" victory_hour_of_code_done_yes: "Sim, terminei a minha Hora do Código™!" victory_experience_gained: "XP Ganho" victory_gems_gained: "Gemas Ganhas" victory_new_item: "Novo Item" victory_new_hero: "Novo Herói" # victory_viking_code_school: "Holy smokes, that was a hard level you just beat! If you aren't already a software developer, you should be. You just got fast-tracked for acceptance with Viking Code School, where you can take your skills to the next level and become a professional web developer in 14 weeks." victory_become_a_viking: "Torna-te um Viking" victory_no_progress_for_teachers: "O progresso não é guardado para professores. Mas podes adicionar à tua turma uma conta de estudante para ti." tome_cast_button_run: "Executar" tome_cast_button_running: "A Executar" tome_cast_button_ran: "Executado" # tome_cast_button_update: "Update" tome_submit_button: "Submeter" tome_reload_method: "Recarregar o código original para recomeçar o nível" tome_available_spells: "Feitiços Disponíveis" tome_your_skills: "As Tuas Habilidades" hints: "Dicas" # videos: "Videos" hints_title: "Dica {{number}}" code_saved: "Código Guardado" skip_tutorial: "Saltar (esc)" keyboard_shortcuts: "Atalhos de Teclado" loading_start: "Iniciar Nível" # loading_start_combo: "Start Combo Challenge" # loading_start_concept: "Start Concept Challenge" problem_alert_title: "Corrige o Teu Código" time_current: "Agora:" time_total: "Máximo:" time_goto: "Ir para:" non_user_code_problem_title: "Impossível Carregar o Nível" infinite_loop_title: "'Loop' Infinito Detetado" infinite_loop_description: "O código inicial para construir o mundo nunca parou de ser executado. Provavelmente é muito lento ou contém um 'loop' infinito. Ou talvez haja um erro. Podes tentar executar este código novamente ou reiniciá-lo para o estado predefinido. Se isso não resultar, avisa-nos, por favor." check_dev_console: "Também podes abrir a consola para programadores para veres o que possa estar a correr mal." check_dev_console_link: "(instruções)" infinite_loop_try_again: "Tentar Novamente" infinite_loop_reset_level: "Reiniciar Nível" infinite_loop_comment_out: "Comentar o Meu Código" tip_toggle_play: "Alterna entre Jogar e Pausar com Ctrl+P." tip_scrub_shortcut: "Usa Ctrl+[ para rebobinar e Ctrl+] para avançar." tip_guide_exists: "Clica no guia, dentro do menu do jogo (no topo da página), para informações úteis." tip_open_source: "O CodeCombat faz parte da comunidade open source!" tip_tell_friends: "Estás a gostar do CodeCombat? Fala de nós aos teus amigos!" tip_beta_launch: "O CodeCombat lançou o seu beta em outubro de 2013." tip_think_solution: "Pensa na solução, não no problema." tip_theory_practice: "Teoricamente, não há diferença entre a teoria e a prática. Mas na prática, há. - PI:NAME:<NAME>END_PI" tip_error_free: "Há duas formas de escrever programas sem erros; apenas a terceira funciona. - PI:NAME:<NAME>END_PI" tip_debugging_program: "Se depurar é o processo de remover erros, então programar deve ser o processo de os introduzir. - PI:NAME:<NAME>END_PI" tip_forums: "Vai aos fóruns e diz-nos o que pensas!" tip_baby_coders: "No futuro, até os bebés serão Arcomagos." tip_morale_improves: "O carregamento vai continuar até que a moral melhore." tip_all_species: "Acreditamos em oportunidades iguais para todas as espécies, em relação a aprenderem a programar." tip_reticulating: "A reticular espinhas." tip_harry: "És um Feiticeiro, " tip_great_responsibility: "Com uma grande habilidade de programação vem uma grande responsabilidade de depuração." tip_munchkin: "Se não comeres os teus vegetais, um ogre virá atrás de ti enquanto estiveres a dormir." tip_binary: "Há apenas 10 tipos de pessoas no mundo: aquelas que percebem binário e aquelas que não." tip_commitment_yoda: "Um programador deve ter o compromisso mais profundo, a mente mais séria. ~ Yoda" tip_no_try: "Fazer. Ou não fazer. Não há nenhum tentar. - Yoda" tip_patience: "Paciência tu deves ter, jovem Padawan. - Yoda" tip_documented_bug: "Um erro documentado não é um erro; é uma funcionalidade." tip_impossible: "Parece sempre impossível até ser feito. - PI:NAME:<NAME>END_PI" tip_talk_is_cheap: "Falar é fácil. Mostra-me o código. - PI:NAME:<NAME>END_PI" tip_first_language: "A coisa mais desastrosa que podes aprender é a tua primeira linguagem de programação. - PI:NAME:<NAME>END_PI" tip_hardware_problem: "P: Quantos programadores são necessários para mudar uma lâmpada? R: Nenhum, é um problema de 'hardware'." tip_hofstadters_law: "PI:NAME:<NAME>END_PI: Tudo demora sempre mais do que pensas, mesmo quando tens em conta a PI:NAME:<NAME>END_PI." tip_premature_optimization: "Uma otimização permatura é a raíz de todo o mal. - PI:NAME:<NAME>END_PI" tip_brute_force: "Quando em dúvida, usa a força bruta. - PI:NAME:<NAME>END_PI" tip_extrapolation: "Há apenas dois tipos de pessoas: aquelas que conseguem tirar uma conclusão a partir de dados reduzidos..." tip_superpower: "A programação é a coisa mais próxima de um superpoder que temos." tip_control_destiny: "Em open source a sério, tens o direito de controlares o teu próprio destino. - PI:NAME:<NAME>END_PI" tip_no_code: "Nenhum código é mais rápido que código não existente." tip_code_never_lies: "O código nunca mente, mas os comentários às vezes sim. — PI:NAME:<NAME>END_PI" tip_reusable_software: "Antes de um software poder ser reutilizável, primeiro tem de ser utilizável." tip_optimization_operator: "Todas as linguagens têm um operador de otimização. Na maior parte delas esse operador é ‘//’." tip_lines_of_code: "Medir o progresso em programação pelo número de linhas de código é como medir o progresso da construção de um avião pelo peso. — PI:NAME:<NAME>END_PI" tip_source_code: "Quero mudar o mundo, mas não há maneira de me darem o código-fonte." tip_javascript_java: "Java é para JavaScript o mesmo que CarPI:NAME:<NAME>END_PI (Car) para Tapete (Carpet). - PI:NAME:<NAME>END_PI" tip_move_forward: "Faças o que fizeres, segue em frente. - PI:NAME:<NAME>END_PI Jr" tip_google: "Tens um problema que não consegues resolver? Vai ao Google!" tip_adding_evil: "A acrescentar uma pitada de mal." tip_hate_computers: "É o problema das pessoas que acham que odeiam coputadores. O que elas odeiam mesmo são maus programadores. - PI:NAME:<NAME>END_PI" tip_open_source_contribute: "Podes ajudar a melhorar o CodeCombat!" tip_recurse: "Iterar é humano, recursar é divino. - PI:NAME:<NAME>END_PI" tip_free_your_mind: "Tens de libertar tudo, Neo. Medo, dúvida e descrença. Liberta a tua mente. - Morpheus" tip_strong_opponents: "Até o mais forte dos adversários tem uma fraqueza. - PI:NAME:<NAME>END_PI" tip_paper_and_pen: "Antes de começares a programar, podes sempre planear com uma folha de papel e uma caneta." tip_solve_then_write: "Primeiro, resolve o problema. Depois, escreve o código. - PI:NAME:<NAME>END_PI" tip_compiler_ignores_comments: "Às vezes acho que o compilador ignora os meus comentários." tip_understand_recursion: "A única forma de entender recursão é entender recursão." # tip_life_and_polymorphism: "Open Source is like a totally polymorphic heterogeneous structure: All types are welcome." # tip_mistakes_proof_of_trying: "Mistakes in your code are just proof that you are trying." # tip_adding_orgres: "Rounding up ogres." # tip_sharpening_swords: "Sharpening the swords." # tip_ratatouille: "You must not let anyone define your limits because of where you come from. Your only limit is your soul. - PI:NAME:<NAME>END_PI, RPI:NAME:<NAME>END_PIille" # tip_nemo: "When life gets you down, want to know what you've gotta do? Just keep swimming, just keep swimming. - PI:NAME:<NAME>END_PI" # tip_internet_weather: "Just move to the internet, it's great here. We get to live inside where the weather is always awesome. - PI:NAME:<NAME>END_PI" # tip_nerds: "Nerds are allowed to love stuff, like jump-up-and-down-in-the-chair-can't-control-yourself love it. - PI:NAME:<NAME>END_PI" # tip_self_taught: "I taught myself 90% of what I've learned. And that's normal! - PI:NAME:<NAME>END_PI" # tip_luna_lovegood: "Don't worry, you're just as sane as I am. - PI:NAME:<NAME>END_PI" # tip_good_idea: "The best way to have a good idea is to have a lot of ideas. - PI:NAME:<NAME>END_PI" # tip_programming_not_about_computers: "Computer Science is no more about computers than astronomy is about telescopes. - Edsger Dijkstra" # tip_mulan: "Believe you can, then you will. - PI:NAME:<NAME>END_PI" project_complete: "Projeto Completado!" # share_this_project: "Share this project with friends or family:" ready_to_share: "Pronto para publicares o teu projeto?" # click_publish: "Click \"Publish\" to make it appear in the class gallery, then check out what your classmates built! You can come back and continue to work on this project. Any further changes will automatically be saved and shared with your classmates." # already_published_prefix: "Your changes have been published to the class gallery." # already_published_suffix: "Keep experimenting and making this project even better, or see what the rest of your class has built! Your changes will automatically be saved and shared with your classmates." view_gallery: "Ver Galeria" project_published_noty: "O teu nível foi publicado!" keep_editing: "Continuar a Editar" # learn_new_concepts: "Learn new concepts" # watch_a_video: "Watch a video on __concept_name__" # concept_unlocked: "Concept Unlocked" # use_at_least_one_concept: "Use at least one concept: " # command_bank: "Command Bank" # learning_goals: "Learning Goals" # start: "Start" # vega_character: "Vega Character" # click_to_continue: "Click to Continue" apis: methods: "Métodos" events: "Eventos" # handlers: "Handlers" properties: "Propriedades" # snippets: "Snippets" # spawnable: "Spawnable" html: "HTML" math: "Matemática" # array: "Array" object: "Objeto" # string: "String" function: "Função" vector: "Vetor" date: "Data" jquery: "jQuery" json: "JSON" number: "Número" webjavascript: "JavaScript" # amazon_hoc: # title: "Keep Learning with Amazon!" # congrats: "Congratulations on conquering that challenging Hour of Code!" # educate_1: "Now, keep learning about coding and cloud computing with AWS Educate, an exciting, free program from Amazon for both students and teachers. With AWS Educate, you can earn cool badges as you learn about the basics of the cloud and cutting-edge technologies such as gaming, virtual reality, and Alexa." # educate_2: "Learn more and sign up here" # future_eng_1: "You can also try to build your own school facts skill for Alexa" # future_eng_2: "here" # future_eng_3: "(device is not required). This Alexa activity is brought to you by the" # future_eng_4: "Amazon Future Engineer" # future_eng_5: "program which creates learning and work opportunities for all K-12 students in the United States who wish to pursue computer science." play_game_dev_level: created_by: "Criado por {{name}}" created_during_hoc: "Criado durante a Hora do Código" restart: "Recomeçar Nível" play: "Jogar Nível" play_more_codecombat: "Jogar Mais CodeCombat" default_student_instructions: "Clica para controlares o teu herói e ganhares o teu jogo!" goal_survive: "Sobrevive." goal_survive_time: "Sobrevive por __seconds__ segundos." goal_defeat: "Derrota todos os inimigos." goal_defeat_amount: "Derrota __amount__ inimigos." # goal_move: "Move to all the red X marks." # goal_collect: "Collect all the items." # goal_collect_amount: "Collect __amount__ items." game_menu: inventory_tab: "Inventário" save_load_tab: "Guardar/Carregar" options_tab: "Opções" guide_tab: "Guia" guide_video_tutorial: "Tutorial em Vídeo" guide_tips: "Dicas" multiplayer_tab: "Multijogador" auth_tab: "Regista-te" inventory_caption: "Equipa o teu herói" choose_hero_caption: "Escolhe o herói, a linguagem" options_caption: "Configura as definições" guide_caption: "Documentos e dicas" multiplayer_caption: "Joga com amigos!" auth_caption: "Guarda o teu progresso." leaderboard: view_other_solutions: "Ver Tabelas de Classificação" scores: "Pontuações" top_players: "Melhores Jogadores por" day: "Hoje" week: "Esta Semana" all: "Sempre" latest: "Mais Recentes" time: "Tempo de Vitória" damage_taken: "Dano Recebido" damage_dealt: "Dano Infligido" difficulty: "Dificuldade" gold_collected: "Ouro Recolhido" # survival_time: "Survived" defeated: "Inimigos Derrotados" code_length: "Linhas de Código" score_display: "__scoreType__: __score__" inventory: equipped_item: "Equipado" required_purchase_title: "Necessário" available_item: "Disponível" restricted_title: "Restrito" should_equip: "(clica duas vezes para equipares)" equipped: "(equipado)" locked: "(bloqueado)" restricted: "(restrito neste nível)" equip: "Equipar" unequip: "Desequipar" warrior_only: "Apenas Guerreiros" ranger_only: "Apenas Arqueiros" wizard_only: "Apenas Feiticeiros" buy_gems: few_gems: "Algumas gemas" pile_gems: "Pilha de gemas" chest_gems: "Arca de gemas" purchasing: "A Adquirir..." declined: "O teu cartão foi recusado." retrying: "Erro do servidor, a tentar novamente." prompt_title: "Sem Gemas Suficientes" prompt_body: "Queres obter mais?" prompt_button: "Entra na Loja" recovered: "A compra de gemas anterior foi recuperada. Por favor atualiza a página." price: "x{{gems}} / mês" buy_premium: "Comprar 'Premium'" purchase: "Adquirir" purchased: "Adquirido" subscribe_for_gems: prompt_title: "Gemas Insuficientes!" # prompt_body: "Subscribe to Premium to get gems and access to even more levels!" earn_gems: prompt_title: "Gemas Insuficientes" prompt_body: "Continua a jogar para receberes mais!" subscribe: # best_deal: "Best Deal!" # confirmation: "Congratulations! You now have a CodeCombat Premium Subscription!" # premium_already_subscribed: "You're already subscribed to Premium!" subscribe_modal_title: "CodeCombat 'Premium'" comparison_blurb: "Torna-te um Programador Mestre - subscreve-te ao <b>'Premium'</b> hoje!" must_be_logged: "Primeiro tens de ter sessão iniciada. Por favor, cria uma conta ou inicia sessão a partir do menu acima." subscribe_title: "Subscrever" # Actually used in subscribe buttons, too unsubscribe: "Cancelar Subscrição" confirm_unsubscribe: "Confirmar Cancelamento da Subscrição" never_mind: "Não Importa, Gostamos de Ti à Mesma" thank_you_months_prefix: "Obrigado por nos teres apoiado neste(s) último(s)" thank_you_months_suffix: "mês(meses)." thank_you: "Obrigado por apoiares o CodeCombat." sorry_to_see_you_go: "Lamentamos ver-te partir! Por favor, diz-nos o que podíamos ter feito melhor." unsubscribe_feedback_placeholder: "Oh, o que fomos fazer?" stripe_description: "Subscrição Mensal" buy_now: "Comprar Agora" subscription_required_to_play: "Precisas de uma subscrição para jogares este nível." unlock_help_videos: "Subscreve-te para desbloqueares todos os tutoriais em vídeo." personal_sub: "Subscrição Pessoal" # Accounts Subscription View below loading_info: "A carregar as informações da subscrição..." managed_by: "Gerida por" will_be_cancelled: "Será cancelada em" currently_free: "Atualmente tens uma subscrição gratuita" currently_free_until: "Atualmente tens uma subscrição até" free_subscription: "Subscrição gratuita" was_free_until: "Tinhas uma subscrição gratuita até" managed_subs: "Subscrições Geridas" subscribing: "A Subscrever..." current_recipients: "Beneficiários Atuais" unsubscribing: "A Cancelar a Subscrição" subscribe_prepaid: "Clica em Subscrever para usares um código pré-pago" using_prepaid: "A usar um código pré-pago para a subscrição mensal" feature_level_access: "Acede a 300+ níveis disponíveis" feature_heroes: "Desbloqueia heróis e animais exclusivos" feature_learn: "Aprende a criar jogos e websites" month_price: "$__price__" first_month_price: "Apenas $__price__ pelo teu primeiro mês!" lifetime: "Acesso Vitalício" lifetime_price: "$__price__" year_subscription: "Subscrição Anual" year_price: "$__price__/ano" support_part1: "Precisas de ajuda com o pagamento ou preferes PayPal? Envia um e-mail para" support_part2: "PI:EMAIL:<EMAIL>END_PI" # announcement: # now_available: "Now available for subscribers!" # subscriber: "subscriber" # cuddly_companions: "Cuddly Companions!" # Pet Announcement Modal # kindling_name: "Kindling Elemental" # kindling_description: "Kindling Elementals just want to keep you warm at night. And during the day. All the time, really." # griffin_name: "PI:NAME:<NAME>END_PI" # griffin_description: "Griffins are half eagle, half lion, all adorable." # raven_name: "Raven" # raven_description: "Ravens are excellent at gathering shiny bottles full of health for you." # mimic_name: "PI:NAME:<NAME>END_PI" # mimic_description: "Mimics can pick up coins for you. Move them on top of coins to increase your gold supply." # cougar_name: "PI:NAME:<NAME>END_PI" # cougar_description: "Cougars like to earn a PhD by PI:NAME:<NAME>END_PI." # fox_name: "Blue Fox" # fox_description: "Blue foxes are very clever and love digging in the dirt and snow!" # pugicorn_name: "Pugicorn" # pugicorn_description: "Pugicorns are some of the rarest creatures and can cast spells!" # wolf_name: "PI:NAME:<NAME>END_PI" # wolf_description: "Wolf pups excel in hunting, gathering, and playing a mean game of hide-and-seek!" # ball_name: "Red Squeaky Ball" # ball_description: "ball.squeak()" # collect_pets: "Collect pets for your heroes!" # each_pet: "Each pet has a unique helper ability!" # upgrade_to_premium: "Become a {{subscriber}} to equip pets." # play_second_kithmaze: "Play {{the_second_kithmaze}} to unlock the Wolf Pup!" # the_second_kithmaze: "The Second Kithmaze" # keep_playing: "Keep playing to discover the first pet!" # coming_soon: "Coming soon" # ritic: "Ritic the Cold" # Ritic Announcement Modal # ritic_description: "Ritic the Cold. Trapped in PI:NAME:<NAME>END_PIvintaph Glacier for countless ages, finally free and ready to tend to the ogres that imprisoned him." # ice_block: "A block of ice" # ice_description: "There appears to be something trapped inside..." # blink_name: "Blink" # blink_description: "Ritic disappears and reappears in a blink of an eye, leaving nothing but a shadow." # shadowStep_name: "Shadowstep" # shadowStep_description: "A master assassin knows how to walk between the shadows." # tornado_name: "Tornado" # tornado_description: "It is good to have a reset button when one's cover is blown." # wallOfDarkness_name: "Wall of Darkness" # wallOfDarkness_description: "Hide behind a wall of shadows to prevent the gaze of prying eyes." # avatar_selection: # pick_an_avatar: "Pick an avatar that will represent you as a player" # premium_features: # get_premium: "Get<br>CodeCombat<br>Premium" # Fit into the banner on the /features page # master_coder: "Become a Master Coder by subscribing today!" # paypal_redirect: "You will be redirected to PayPal to complete the subscription process." # subscribe_now: "Subscribe Now" # hero_blurb_1: "Get access to __premiumHeroesCount__ super-charged subscriber-only heroes! Harness the unstoppable power of Okar Stompfoot, the deadly precision of Naria of the Leaf, or summon \"adorable\" skeletons with Nalfar Cryptor." # hero_blurb_2: "Premium Warriors unlock stunning martial skills like Warcry, Stomp, and Hurl Enemy. Or, play as a Ranger, using stealth and bows, throwing knives, traps! Try your skill as a true coding Wizard, and unleash a powerful array of Primordial, Necromantic or Elemental magic!" # hero_caption: "Exciting new heroes!" # pet_blurb_1: "Pets aren't just adorable companions, they also provide unique functionality and methods. The Baby Griffin can carry units through the air, the Wolf Pup plays catch with enemy arrows, the Cougar is fond of chasing ogres around, and the Mimic attracts coins like a magnet!" # pet_blurb_2: "Collect all the pets to discover their unique abilities!" # pet_caption: "Adopt pets to accompany your hero!" # game_dev_blurb: "Learn game scripting and build new levels to share with your friends! Place the items you want, write code for unit logic and behavior, and see if your friends can beat the level!" # game_dev_caption: "Design your own games to challenge your friends!" # everything_in_premium: "Everything you get in CodeCombat Premium:" # list_gems: "Receive bonus gems to buy gear, pets, and heroes" # list_levels: "Gain access to __premiumLevelsCount__ more levels" # list_heroes: "Unlock exclusive heroes, include Ranger and Wizard classes" # list_game_dev: "Make and share games with friends" # list_web_dev: "Build websites and interactive apps" # list_items: "Equip Premium-only items like pets" # list_support: "Get Premium support to help you debug tricky code" # list_clans: "Create private clans to invite your friends and compete on a group leaderboard" choose_hero: choose_hero: "Escolhe o Teu Herói" programming_language: "Linguagem de Programação" programming_language_description: "Que linguagem de programação queres usar?" default: "Predefinida" experimental: "Experimental" python_blurb: "Simples mas poderoso; ótimo para iniciantes e peritos." javascript_blurb: "A linguagem da web. (Não é o mesmo que Java.)" coffeescript_blurb: "Javascript com sintaxe mais agradável." lua_blurb: "Linguagem para scripts de jogos." java_blurb: "(Apenas para Subscritores) Android e empresas." # cpp_blurb: "(Subscriber Only) Game development and high performance computing." status: "Estado" weapons: "Armas" weapons_warrior: "Espadas - Curto Alcance, Sem Magia" weapons_ranger: "Arcos, Armas - Longo Alcance, Sem Magia" weapons_wizard: "Varinhas, Bastões - Longo Alcance, Magia" attack: "Ataque" # Can also translate as "Attack" health: "Vida" speed: "Velocidade" regeneration: "Regeneração" range: "Alcance" # As in "attack or visual range" blocks: "Bloqueia" # As in "this shield blocks this much damage" backstab: "Colateral" # As in "this dagger does this much backstab damage" skills: "Habilidades" attack_1: "Dá" attack_2: "do dano da arma do" attack_3: "apresentado." health_1: "Ganha" health_2: "da vida da armadura do" health_3: "apresentado." speed_1: "Move a" speed_2: "metros por segundo." available_for_purchase: "Disponível para Aquisição" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nível para desbloquear:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Apenas certos heróis podem jogar este nível." # char_customization_modal: # heading: "Customize Your Hero" # body: "Body" # name_label: "Hero's Name" # hair_label: "Hair Color" # skin_label: "Skin Color" skill_docs: function: "função" # skill types method: "método" snippet: "fragmento" number: "número" array: "'array'" object: "objeto" string: "'string'" writable: "editável" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "apenas leitura" action: "Ação -" spell: "Feitiço -" action_name: "nome" action_cooldown: "Demora" action_specific_cooldown: "Tempo de Recarga" action_damage: "Dano" action_range: "Alcance" action_radius: "Raio" action_duration: "Duração" example: "Exemplo" ex: "ex" # Abbreviation of "example" current_value: "Valor Atual" default_value: "Valor Predefinido" parameters: "Parâmetros" required_parameters: "Parâmetros Necessários" optional_parameters: "Parâmetros Opcionais" returns: "Devolve" granted_by: "Garantido por" # still_undocumented: "Still undocumented, sorry." save_load: granularity_saved_games: "Guardados" granularity_change_history: "Histórico" options: general_options: "Opções Gerais" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volume" music_label: "Música" music_description: "Ativar ou desativar a música de fundo." editor_config_title: "Configurar Editor" editor_config_livecompletion_label: "Auto-completação em Tempo Real" editor_config_livecompletion_description: "Mostrar sugestões de auto-completação aquando da escrita." editor_config_invisibles_label: "Mostrar Invisíveis" editor_config_invisibles_description: "Mostrar invisíveis tais como espaços e tabulações." editor_config_indentguides_label: "Mostrar Guias de Indentação" editor_config_indentguides_description: "Mostrar linhas verticais para se ver melhor a indentação." editor_config_behaviors_label: "Comportamentos Inteligentes" editor_config_behaviors_description: "Auto-completar parênteses, chavetas e aspas." about: # title: "About CodeCombat - Engaging Students, Empowering Teachers, Inspiring Creation" # meta_description: "Our mission is to level computer science through game-based learning and make coding accessible to every learner. We believe programming is magic and want learners to be empowered to to create things from pure imagination." learn_more: "Saber Mais" main_title: "Se queres aprender a programar, precisas de escrever (muito) código." main_description: "No CodeCombat, o nosso trabalho é certificarmo-nos de que estás a fazer isso com um sorriso na cara." mission_link: "Missão" team_link: "Equipa" story_link: "História" press_link: "Imprensa" mission_title: "A nossa missão: tornar a programação acessível a todos os estudantes da Terra." mission_description_1: "<strong>A programação é mágica</strong>. É a capacidade de criar coisas a partir de imaginação pura. Começamos o CodeCombat para dar aos utilizadores a sensação de terem poderes mágicos nas pontas dos dedos ao usarem <strong>código escrito</strong>." # mission_description_2: "As it turns out, that enables them to learn faster too. WAY faster. It's like having a conversation instead of reading a manual. We want to bring that conversation to every school and to <strong>every student</strong>, because everyone should have the chance to learn the magic of programming." team_title: "Conhece a equipa do CodeCombat" # team_values: "We value open and respectful dialog, where the best idea wins. Our decisions are grounded in customer research and our process is focused on delivering tangible results for them. Everyone is hands-on, from our CEO to our GitHub contributors, because we value growth and learning in our team." nick_title: "PI:NAME:<NAME>END_PI, CPI:NAME:<NAME>END_PI" matt_title: "Co-fundador, CTO" cat_title: "Designer de Jogos" scott_title: "Co-fundador, Engenheiro de Software" maka_title: "Defensor dos Clientes" robin_title: "Gestora de Produto Sénior" nolan_title: "Gestor de Vendas" david_title: "Líder de Marketing" titles_csm: "Gerente de Sucesso do Cliente" titles_territory_manager: "Gestora de Território" # lawrence_title: "Customer Success Manager" # sean_title: "Senior Account Executive" # liz_title: "Senior Account Executive" # jane_title: "Account Executive" # shan_title: "Partnership Development Lead, China" # run_title: "Head of Operations, China" # lance_title: "Software Engineer Intern, China" # matias_title: "Senior Software Engineer" # ryan_title: "Customer Support Specialist" # maya_title: "Senior Curriculum Developer" # bill_title: "General Manager, China" # shasha_title: "Product and Visual Designer" # daniela_title: "Marketing Manager" # chelsea_title: "Operations Manager" # claire_title: "Executive Assistant" # bobby_title: "Game Designer" # brian_title: "Lead Game Designer" # andrew_title: "Software Engineer" # stephanie_title: "Customer Support Specialist" # rob_title: "Sales Development Representative" # shubhangi_title: "Senior Software Engineer" retrostyle_title: "Ilustração" retrostyle_blurb: "'RetroStyle Games'" # bryukh_title: "Gameplay Developer" bryukh_blurb: "Constrói puzzles" community_title: "...e a nossa comunidade open source" community_subtitle: "Mais de 500 contribuidores ajudaram a construir o CodeCombat, com mais a se juntarem todas as semanas!" community_description_3: "O CodeCombat é um" community_description_link_2: "projeto comunitário" # community_description_1: "with hundreds of players volunteering to create levels, contribute to our code to add features, fix bugs, playtest, and even translate the game into 50 languages so far. Employees, contributors and the site gain by sharing ideas and pooling effort, as does the open source community in general. The site is built on numerous open source projects, and we are open sourced to give back to the community and provide code-curious players a familiar project to explore and experiment with. Anyone can join the CodeCombat community! Check out our" community_description_link: "página de contribuição" community_description_2: "para mais informações." number_contributors: "Mais de 450 contribuidores deram o seu apoio e tempo a este projeto." story_title: "A nossa história até agora" story_subtitle: "Desde 2013, o CodeCombat cresceu de um mero conjunto de esboços para um jogo palpável e próspero." story_statistic_1a: "5,000,000+" story_statistic_1b: "jogadores no total" story_statistic_1c: "começaram a jornada de programação deles pelo CodeCombat" story_statistic_2a: "Fomos traduzidos para mais de 50 idiomas — os nossos jogadores saudam a partir de" story_statistic_2b: "190+ países" story_statistic_3a: "Juntos, eles escreveram" story_statistic_3b: "mil milhões de linhas de código (e continua a contar)" story_statistic_3c: "em muitas linguagens de programação diferentes" # story_long_way_1: "Though we've come a long way..." # story_sketch_caption: "PI:NAME:<NAME>END_PI's very first sketch depicting a programming game in action." # story_long_way_2: "we still have much to do before we complete our quest, so..." # jobs_title: "Come work with us and help write CodeCombat history!" # jobs_subtitle: "Don't see a good fit but interested in keeping in touch? See our \"Create Your Own\" listing." jobs_benefits: "Benefícios de Empregado" jobs_benefit_4: "Férias ilimitadas" # jobs_benefit_5: "Professional development and continuing education support – free books and games!" # jobs_benefit_6: "Medical (gold), dental, vision, commuter, 401K" # jobs_benefit_7: "Sit-stand desks for all" # jobs_benefit_9: "10-year option exercise window" # jobs_benefit_10: "Maternity leave: 12 weeks paid, next 6 @ 55% salary" # jobs_benefit_11: "Paternity leave: 12 weeks paid" jobs_custom_title: "Cria o Teu Próprio" # jobs_custom_description: "Are you passionate about CodeCombat but don't see a job listed that matches your qualifications? Write us and show how you think you can contribute to our team. We'd love to hear from you!" # jobs_custom_contact_1: "Send us a note at" # jobs_custom_contact_2: "introducing yourself and we might get in touch in the future!" contact_title: "Imprensa e Contactos" contact_subtitle: "Precisas de mais informação? Entra em contacto connosco através de" # screenshots_title: "Game Screenshots" # screenshots_hint: "(click to view full size)" # downloads_title: "Download Assets & Information" about_codecombat: "Sobre o CodeCombat" logo: "Logótipo" # screenshots: "Screenshots" # character_art: "Character Art" # download_all: "Download All" previous: "Anterior" # location_title: "We're located in downtown SF:" teachers: licenses_needed: "Licenças necessárias" special_offer: special_offer: "Oferta Especial" # project_based_title: "Project-Based Courses" # project_based_description: "Web and Game Development courses feature shareable final projects." # great_for_clubs_title: "Great for clubs and electives" # great_for_clubs_description: "Teachers can purchase up to __maxQuantityStarterLicenses__ Starter Licenses." # low_price_title: "Just __starterLicensePrice__ per student" # low_price_description: "Starter Licenses are active for __starterLicenseLengthMonths__ months from purchase." # three_great_courses: "Three great courses included in the Starter License:" # license_limit_description: "Teachers can purchase up to __maxQuantityStarterLicenses__ Starter Licenses. You have already purchased __quantityAlreadyPurchased__. If you need more, contact __supportEmail__. Starter Licenses are valid for __starterLicenseLengthMonths__ months." # student_starter_license: "Student Starter License" # purchase_starter_licenses: "Purchase Starter Licenses" # purchase_starter_licenses_to_grant: "Purchase Starter Licenses to grant access to __starterLicenseCourseList__" # starter_licenses_can_be_used: "Starter Licenses can be used to assign additional courses immediately after purchase." # pay_now: "Pay Now" # we_accept_all_major_credit_cards: "We accept all major credit cards." # cs2_description: "builds on the foundation from Introduction to Computer Science, diving into if-statements, functions, events and more." # wd1_description: "introduces the basics of HTML and CSS while teaching skills needed for students to build their first webpage." # gd1_description: "uses syntax students are already familiar with to show them how to build and share their own playable game levels." # see_an_example_project: "see an example project" # get_started_today: "Get started today!" # want_all_the_courses: "Want all the courses? Request information on our Full Licenses." # compare_license_types: "Compare License Types:" # cs: "Computer Science" # wd: "Web Development" # wd1: "Web Development 1" # gd: "Game Development" # gd1: "Game Development 1" # maximum_students: "Maximum # of Students" # unlimited: "Unlimited" # priority_support: "Priority support" # yes: "Yes" # price_per_student: "__price__ per student" # pricing: "Pricing" # free: "Free" # purchase: "Purchase" # courses_prefix: "Courses" # courses_suffix: "" # course_prefix: "Course" # course_suffix: "" teachers_quote: # subtitle: "Learn more about CodeCombat with an interactive walk through of the product, pricing, and implementation!" # email_exists: "User exists with this email." phone_number: "Número de telemóvel" phone_number_help: "Qual é o melhor número para entrarmos em contacto contigo?" primary_role_label: "O Teu Cargo Principal" role_default: "Selecionar Cargo" # primary_role_default: "Select Primary Role" # purchaser_role_default: "Select Purchaser Role" tech_coordinator: "Coordenador de Tecnologia" # advisor: "Curriculum Specialist/Advisor" principal: "PI:NAME:<NAME>END_PI" superintendent: "Superintendente" parent: "Educador" # purchaser_role_label: "Your Purchaser Role" # influence_advocate: "Influence/Advocate" # evaluate_recommend: "Evaluate/Recommend" # approve_funds: "Approve Funds" # no_purchaser_role: "No role in purchase decisions" district_label: "Distrito" district_name: "Nome do Distrito" district_na: "Escreve N/A se não se aplicar" organization_label: "Escola" school_name: "PI:NAME:<NAME>END_PI EsPI:NAME:<NAME>END_PI" city: "Cidade" state: "Estado" # {change} country: "País" num_students_help: "Quantos estudantes vão usar o CodeCombat?" num_students_default: "Selecionar Intervalo" education_level_label: "Nível de Educação dos Estudantes" education_level_help: "Escolhe todos os que se aplicarem." # elementary_school: "Elementary School" # high_school: "High School" please_explain: "(por favor, explica)" # middle_school: "Middle School" # college_plus: "College or higher" referrer: "Como ouviste falar de nós?" referrer_help: "Por exemplo: através de outro professor, de uma conferência, dos teus estudantes, do Code.org, etc." referrer_default: "Seleciona Um" # referrer_conference: "Conference (e.g. ISTE)" referrer_hoc: "Code.org/Hora do Código" referrer_teacher: "Um professor" referrer_admin: "Um administrador" referrer_student: "Um estudante" # referrer_pd: "Professional trainings/workshops" referrer_web: "Google" referrer_other: "Outro" # anything_else: "What kind of class do you anticipate using CodeCombat for?" # anything_else_helper: "" thanks_header: "Pedido Recebido!" # thanks_sub_header: "Thanks for expressing interest in CodeCombat for your school." # thanks_p: "We'll be in touch soon! If you need to get in contact, you can reach us at:" back_to_classes: "Voltar às Turmas" # finish_signup: "Finish creating your teacher account:" # finish_signup_p: "Create an account to set up a class, add your students, and monitor their progress as they learn computer science." # signup_with: "Sign up with:" connect_with: "Conectar com:" # conversion_warning: "WARNING: Your current account is a <em>Student Account</em>. Once you submit this form, your account will be updated to a Teacher Account." # learn_more_modal: "Teacher accounts on CodeCombat have the ability to monitor student progress, assign licenses and manage classrooms. Teacher accounts cannot be a part of a classroom - if you are currently enrolled in a class using this account, you will no longer be able to access it once you update to a Teacher Account." create_account: "Criar uma Conta de Professor" create_account_subtitle: "Obtém acesso a ferramentas reservadas a professores para usares o CodeCombat na sala de aula. <strong>Cria uma turma</strong>, adiciona os teus estudantes e <strong>monitoriza o progresso deles</strong>!" # convert_account_title: "Update to Teacher Account" # not: "Not" # full_name_required: "First and last name required" versions: save_version_title: "Guardar Nova Versão" new_major_version: "Nova Versão Principal" submitting_patch: "A Submeter Atualização..." cla_prefix: "Para guardares as alterações, precisas de concordar com o nosso" cla_url: "CLA" cla_suffix: "." cla_agree: "EU CONCORDO" owner_approve: "Um administrador terá de aprová-la antes de as tuas alterações ficarem visíveis." contact: contact_us: "Contacta o CodeCombat" welcome: "É bom ter notícias tuas! Usa este formulário para nos enviares um e-mail. " forum_prefix: "Para algo público, por favor usa o " forum_page: "nosso fórum" forum_suffix: " como alternativa." faq_prefix: "Há também uma" faq: "FAQ" subscribe_prefix: "Se precisas de ajuda a perceber um nível, por favor" subscribe: "compra uma subscrição do CodeCombat" subscribe_suffix: "e nós ficaremos felizes por ajudar-te com o teu código." subscriber_support: "Como és um subscritor do CodeCombat, os teus e-mails terão prioridade no nosso suporte." screenshot_included: "Captura de ecrã incluída." where_reply: "Para onde devemos enviar a resposta?" send: "Enviar Feedback" account_settings: title: "Definições da Conta" not_logged_in: "Inicia sessão ou cria uma conta para alterares as tuas definições." me_tab: "Eu" picture_tab: "Fotografia" delete_account_tab: "Elimina a Tua Conta" wrong_email: "E-mail ou Nome de Utilizador Errado" wrong_password: "PI:PASSWORD:<PASSWORD>END_PI" delete_this_account: "Elimina esta conta permanentemente" reset_progress_tab: "Reiniciar Todo o Progresso" reset_your_progress: "Limpar todo o teu progresso e começar de novo" god_mode: "Modo Deus" emails_tab: "E-mails" admin: "Administrador" manage_subscription: "Clica aqui para gerires a tua subscrição." new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" type_in_email: "Escreve o teu e-mail ou nome de utilizador para confirmares a eliminação da conta." type_in_email_progress: "Escreve o teu e-mail para confirmares a eliminação do teu progresso." type_in_password: "PI:PASSWORD:<PASSWORD>END_PI também a tua palavra-PI:PASSWORD:<PASSWORD>END_PI." email_subscriptions: "Subscrições de E-mail" email_subscriptions_none: "Sem Subscições de E-mail." email_announcements: "Anúncios" email_announcements_description: "Recebe e-mails sobre as últimas novidades e desenvolvimentos no CodeCombat." email_notifications: "Notificações" email_notifications_summary: "Controla, de uma forma personalizada e automática, os e-mails de notificações relacionados com a tua atividade no CodeCombat." email_any_notes: "Quaisquer Notificações" email_any_notes_description: "Desativa para parares de receber todos os e-mails de notificação de atividade." email_news: "Notícias" email_recruit_notes: "Oportunidades de Emprego" email_recruit_notes_description: "Se jogas muito bem, podemos contactar-te para te arranjar um (melhor) emprego." contributor_emails: "E-mail Para Contribuintes" contribute_prefix: "Estamos à procura de pessoas para se juntarem a nós! Visita a " contribute_page: "página de contribuição" contribute_suffix: " para mais informações." email_toggle: "Alternar Todos" error_saving: "Erro ao Guardar" saved: "Alterações Guardadas" password_mismatch: "As palavras-passe não coincidem." password_repeat: "Por favor repete a tua palavra-passe." keyboard_shortcuts: keyboard_shortcuts: "Atalhos de Teclado" space: "Espaço" enter: "Enter" press_enter: "pressiona enter" escape: "Esc" shift: "Shift" run_code: "Executar código atual." run_real_time: "Executar em tempo real." continue_script: "Saltar o script atual." skip_scripts: "Saltar todos os scripts saltáveis." toggle_playback: "Alternar entre Jogar e Pausar." scrub_playback: "Andar para a frente e para trás no tempo." single_scrub_playback: "Andar para a frente e para trás no tempo um único frame." scrub_execution: "Analisar a execução do feitiço atual." toggle_debug: "Ativar/desativar a janela de depuração." toggle_grid: "Ativar/desativar a sobreposição da grelha." toggle_pathfinding: "Ativar/desativar a sobreposição do encontrador de caminho." beautify: "Embelezar o código ao estandardizar a formatação." maximize_editor: "Maximizar/minimizar o editor de código." # cinematic: # click_anywhere_continue: "click anywhere to continue" community: main_title: "Comunidade do CodeCombat" introduction: "Confere abaixo as formas de te envolveres e escolhe a que te parece mais divertida. Estamos ansiosos por trabalhar contigo!" level_editor_prefix: "Usa o" level_editor_suffix: "do CodeCombat para criares e editares níveis. Os utilizadores já criaram níveis para aulas, amigos, maratonas hacker, estudantes e familiares. Se criar um nível novo parece intimidante, podes começar por bifurcar um dos nossos!" thang_editor_prefix: "Chamamos 'thangs' às unidades do jogo. Usa o" thang_editor_suffix: "para modificares a arte do CodeCombat. Faz as unidades lançarem projéteis, altera a direção de uma animação, altera os pontos de vida de uma unidade ou anexa as tuas próprias unidades." article_editor_prefix: "Vês um erro em alguns dos nossos documentos? Queres escrever algumas instruções para as tuas próprias criações? Confere o" article_editor_suffix: "e ajuda os jogadores do CodeCombat a obter o máximo do tempo de jogo deles." find_us: "Encontra-nos nestes sítios" social_github: "Confere todo o nosso código no GitHub" social_blog: "Lê o blog do CodeCombat no Sett" social_discource: "Junta-te à discussão no nosso fórum Discourse" social_facebook: "Gosta do CodeCombat no Facebook" social_twitter: "Segue o CodeCombat no Twitter" social_slack: "Fala connosco no canal público do CodeCombat no Slack" contribute_to_the_project: "Contribui para o projeto" clans: # title: "Join CodeCombat Clans - Learn to Code in Python, JavaScript, and HTML" # clan_title: "__clan__ - Join CodeCombat Clans and Learn to Code" # meta_description: "Join a Clan or build your own community of coders. Play multiplayer arena levels and level up your hero and your coding skills." clan: "Clã" clans: "Clãs" new_name: "Nome do novo clã" new_description: "Descrição do novo clã" make_private: "Tornar o clã privado" subs_only: "apenas para subscritores" create_clan: "Criar um Novo Clã" private_preview: "Pré-visualização" private_clans: "Clãs Privados" public_clans: "Clãs Públicos" my_clans: "Os Meus Clãs" clan_name: "Nome do Clã" name: "PI:NAME:<NAME>END_PI" chieftain: "PI:NAME:<NAME>END_PI" edit_clan_name: "Editar Nome do Clã" edit_clan_description: "Editar Descrição do Clã" edit_name: "editar nome" edit_description: "editar descrição" private: "(privado)" summary: "Resumo" average_level: "Nível em Média" average_achievements: "Conquistas em Média" delete_clan: "Eliminar o Clã" leave_clan: "Abandonar o Clã" join_clan: "Entrar no Clã" invite_1: "Convidar:" invite_2: "*Convida jogadores para este Clã enviando-lhes esta ligação." members: "PI:NAME:<NAME>END_PI" progress: "Progresso" not_started_1: "não começado" started_1: "começado" complete_1: "completo" exp_levels: "Expandir os níveis" rem_hero: "RemPI:NAME:<NAME>END_PI HerPI:NAME:<NAME>END_PI" status: "Estado" complete_2: "Completo" started_2: "Começado" not_started_2: "Não Começado" view_solution: "Clica para veres a solução." view_attempt: "Clica para veres a tentativa." latest_achievement: "Última Conquista" playtime: "Tempo de jogo" last_played: "Última vez jogado" leagues_explanation: "Joga numa liga contra outros membros do clã nestas instâncias de arenas multijogador." track_concepts1: "Acompanhe os conceitos" track_concepts2a: "aprendidos por cada estudante" track_concepts2b: "aprendidos por cada membro" track_concepts3a: "Acompanhe os níveis completados por cada estudante" track_concepts3b: "Acompanhe os níveis completados por cada membro" track_concepts4a: "Veja, dos seus estudantes, as" track_concepts4b: "Veja, dos seus membros, as" track_concepts5: "soluções" track_concepts6a: "Ordene os estudantes por nome ou progresso" track_concepts6b: "Ordene os membros por nome ou progresso" track_concepts7: "É necessário um convite" track_concepts8: "para entrar" private_require_sub: "É necessária uma subscrição para criar ou entrar num clã privado." courses: create_new_class: "Criar Turma Nova" # hoc_blurb1: "Try the" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity! Construct four different minigames to learn the basics of game development, then make your own!" solutions_require_licenses: "As soluções dos níveis estão disponíveis para professores que tenham licenças." unnamed_class: "Turma Sem Nome" edit_settings1: "Editar Definições da Turma" add_students: "Adicionar Estudantes" stats: "Estatísticas" # student_email_invite_blurb: "Your students can also use class code <strong>__classCode__</strong> when creating a Student Account, no email required." total_students: "Estudantes no total:" average_time: "Média do tempo de jogo do nível:" total_time: "Tempo de jogo total:" average_levels: "Média de níveis completos:" total_levels: "Total de níveis completos:" students: "Estudantes" concepts: "Conceitos" play_time: "Tempo de jogo:" completed: "Completos:" enter_emails: "Separa cada endereço de e-mail com uma quebra de linha ou vírgulas" send_invites: "Convidar Estudantes" number_programming_students: "Número de Estudantes" number_total_students: "Total de Estudantes na Escola/Distrito" enroll: "Inscrever" enroll_paid: "Inscrever Estudantes em Cursos Pagos" get_enrollments: "Obter Mais Licenças" change_language: "Alterar Linguagem do Curso" keep_using: "Continuar a Usar" switch_to: "Mudar Para" greetings: "Saudações!" back_classrooms: "Voltar às minhas turmas" back_classroom: "Voltar à turma" back_courses: "Voltar aos meus cursos" edit_details: "Editar detalhes da turma" purchase_enrollments: "Adquirir Licenças de Estudante" remove_student: "remover estudante" # assign: "Assign" # to_assign: "to assign paid courses." student: "PI:NAME:<NAME>END_PI" teacher: "PI:NAME:<NAME>END_PI" arena: "Arena" available_levels: "Níveis Disponíveis" started: "começado" complete: "completado" practice: "prática" required: "obrigatório" welcome_to_courses: "Aventureiros, sejam bem-vindos aos Cursos!" ready_to_play: "Pronto para jogar?" start_new_game: "Começar Novo Jogo" play_now_learn_header: "Joga agora para aprenderes" # play_now_learn_1: "basic syntax to control your character" # play_now_learn_2: "while loops to solve pesky puzzles" # play_now_learn_3: "strings & variables to customize actions" # play_now_learn_4: "how to defeat an ogre (important life skills!)" welcome_to_page: "O Meu Painel de Estudante" my_classes: "Turmas Atuais" class_added: "Turma adicionada com sucesso!" # view_map: "view map" # view_videos: "view videos" view_project_gallery: "ver os projetos dos meus colegas" join_class: "Entrar Numa Turma" join_class_2: "Entrar na turma" ask_teacher_for_code: "Pergunta ao teu professor se tens um código de turma do CodeCombat! Se tiveres, introdu-lo abaixo:" enter_c_code: "<Introduzir Código de Turma>" join: "Entrar" joining: "A entrar na turma" course_complete: "Curso Completo" play_arena: "Jogar na Arena" view_project: "Ver Projeto" start: "Começar" last_level: "Último nível jogado" not_you: "Não és tu?" continue_playing: "Continuar a JPI:NAME:<NAME>END_PI" option1_header: "Convidar Estudantes por E-mail" remove_student1: "Remover Estudante" are_you_sure: "Tens a certeza de que queres remover este estudante desta turma?" # remove_description1: "Student will lose access to this classroom and assigned classes. Progress and gameplay is NOT lost, and the student can be added back to the classroom at any time." # remove_description2: "The activated paid license will not be returned." # license_will_revoke: "This student's paid license will be revoked and made available to assign to another student." keep_student: "Manter Estudante" removing_user: "A remover utilizador" subtitle: "Revê visões gerais de cursos e níveis" # Flat style redesign # changelog: "View latest changes to course levels." select_language: "Selecionar linguagem" select_level: "Selecionar nível" play_level: "Jogar Nível" concepts_covered: "Conceitos Abordados" view_guide_online: "Visões Gerais e Soluções do Nível" grants_lifetime_access: "Garante acesso a todos os Cursos." enrollment_credits_available: "Licenças Disponíveis:" language_select: "Seleciona uma linguagem" # ClassroomSettingsModal language_cannot_change: "A linguagem não pode ser alterada depois de estudantes entrarem numa turma." avg_student_exp_label: "Experiência Média de Programação dos Estudantes" avg_student_exp_desc: "Isto vai-nos ajudar a perceber qual o melhor andamento para os cursos." avg_student_exp_select: "Seleciona a melhor opção" avg_student_exp_none: "Nenhuma Experiência - pouca ou nenhuma experiência" avg_student_exp_beginner: "Iniciante - alguma exposição ou baseada em blocos" avg_student_exp_intermediate: "Intermédia - alguma experiência com código escrito" avg_student_exp_advanced: "Avançada - muita experiência com código escrito" avg_student_exp_varied: "Vários Níveis de Experiência" student_age_range_label: "Intervalo de Idades dos Estudantes" student_age_range_younger: "Menos de 6" student_age_range_older: "Mais de 18" student_age_range_to: "até" # estimated_class_dates_label: "Estimated Class Dates" # estimated_class_frequency_label: "Estimated Class Frequency" # classes_per_week: "classes per week" # minutes_per_class: "minutes per class" create_class: "Criar Turma" class_name: "PI:NAME:<NAME>END_PI da Turma" # teacher_account_restricted: "Your account is a teacher account and cannot access student content." account_restricted: "É necessária uma conta de estudante para acederes a esta página." # update_account_login_title: "Log in to update your account" update_account_title: "A tua conta precisa de atenção!" # update_account_blurb: "Before you can access your classes, choose how you want to use this account." # update_account_current_type: "Current Account Type:" # update_account_account_email: "Account Email/Username:" update_account_am_teacher: "Sou um professor" # update_account_keep_access: "Keep access to classes I've created" # update_account_teachers_can: "Teacher accounts can:" # update_account_teachers_can1: "Create/manage/add classes" # update_account_teachers_can2: "Assign/enroll students in courses" # update_account_teachers_can3: "Unlock all course levels to try out" # update_account_teachers_can4: "Access new teacher-only features as we release them" # update_account_teachers_warning: "Warning: You will be removed from all classes that you have previously joined and will not be able to play as a student." # update_account_remain_teacher: "Remain a Teacher" # update_account_update_teacher: "Update to Teacher" update_account_am_student: "Sou um estudante" # update_account_remove_access: "Remove access to classes I have created" # update_account_students_can: "Student accounts can:" # update_account_students_can1: "Join classes" # update_account_students_can2: "Play through courses as a student and track your own progress" # update_account_students_can3: "Compete against classmates in arenas" # update_account_students_can4: "Access new student-only features as we release them" # update_account_students_warning: "Warning: You will not be able to manage any classes that you have previously created or create new classes." # unsubscribe_warning: "Warning: You will be unsubscribed from your monthly subscription." # update_account_remain_student: "Remain a Student" # update_account_update_student: "Update to Student" # need_a_class_code: "You'll need a Class Code for the class you're joining:" # update_account_not_sure: "Not sure which one to choose? Email" # update_account_confirm_update_student: "Are you sure you want to update your account to a Student experience?" # update_account_confirm_update_student2: "You will not be able to manage any classes that you have previously created or create new classes. Your previously created classes will be removed from CodeCombat and cannot be restored." # instructor: "Instructor: " # youve_been_invited_1: "You've been invited to join " # youve_been_invited_2: ", where you'll learn " # youve_been_invited_3: " with your classmates in CodeCombat." # by_joining_1: "By joining " # by_joining_2: "will be able to help reset your password if you forget or lose it. You can also verify your email address so that you can reset the password yourself!" # sent_verification: "We've sent a verification email to:" # you_can_edit: "You can edit your email address in " # account_settings: "Account Settings" select_your_hero: "Seleciona o Teu Herói" select_your_hero_description: "Podes sempre alterar o teu herói ao acederes à tua página de Cursos e clicares em \"Alterar Herói\"" select_this_hero: "Selecionar este herói" current_hero: "Herói Atual:" current_hero_female: "Heroína Atual:" # web_dev_language_transition: "All classes program in HTML / JavaScript for this course. Classes that have been using Python will start with extra JavaScript intro levels to ease the transition. Classes that are already using JavaScript will skip the intro levels." course_membership_required_to_play: "Precisas de te juntar a um curso para jogares este nível." # license_required_to_play: "Ask your teacher to assign a license to you so you can continue to play CodeCombat!" # update_old_classroom: "New school year, new levels!" # update_old_classroom_detail: "To make sure you're getting the most up-to-date levels, make sure you create a new class for this semester by clicking Create a New Class on your" # teacher_dashboard: "teacher dashboard" # update_old_classroom_detail_2: "and giving students the new Class Code that appears." # view_assessments: "View Assessments" # view_challenges: "view challenge levels" # view_ranking: "view ranking" # ranking_position: "Position" # ranking_players: "Players" # ranking_completed_leves: "Completed levels" # challenge: "Challenge:" # challenge_level: "Challenge Level:" status: "Estado:" # assessments: "Assessments" challenges: "Desafios" level_name: "Nome do Nível:" # keep_trying: "Keep Trying" start_challenge: "Começar Desafio" # locked: "Locked" concepts_used: "Conceitos Usados:" # show_change_log: "Show changes to this course's levels" # hide_change_log: "Hide changes to this course's levels" # concept_videos: "Concept Videos" # concept: "Concept:" # basic_syntax: "Basic Syntax" # while_loops: "While Loops" # variables: "Variables" # basic_syntax_desc: "Syntax is how we write code. Just as spelling and grammar are important in writing narratives and essays, syntax is important when writing code. Humans are good at figuring out what something means, even if it isn't exactly correct, but computers aren't that smart, and they need you to write very precisely." # while_loops_desc: "A loop is a way of repeating actions in a program. You can use them so you don't have to keep writing repetitive code, and when you don't know exactly how many times an action will need to occur to accomplish a task." # variables_desc: "Working with variables is like organizing things in shoeboxes. You give the shoebox a name, like \"School Supplies\", and then you put things inside. The exact contents of the box might change over time, but whatever's inside will always be called \"School Supplies\". In programming, variables are symbols used to store data that will change over the course of the program. Variables can hold a variety of data types, including numbers and strings." # locked_videos_desc: "Keep playing the game to unlock the __concept_name__ concept video." # unlocked_videos_desc: "Review the __concept_name__ concept video." # video_shown_before: "shown before __level__" # link_google_classroom: "Link Google Classroom" # select_your_classroom: "Select Your Classroom" # no_classrooms_found: "No classrooms found" # create_classroom_manually: "Create classroom manually" # classes: "Classes" # certificate_btn_print: "Print" # certificate_btn_toggle: "Toggle" # ask_next_course: "Want to play more? Ask your teacher for access to the next course." # set_start_locked_level: "Set start locked level" # no_level_limit: "No limit" project_gallery: no_projects_published: "Sê o primeiro a publicar um projeto neste curso!" view_project: "Ver Projeto" edit_project: "Editar Projeto" teacher: # assigning_course: "Assigning course" back_to_top: "Voltar ao Topo" # click_student_code: "Click on any level that the student has started or completed below to view the code they wrote." code: "Código de __name__" complete_solution: "Solução Completa" # course_not_started: "Student has not started this course yet." # appreciation_week_blurb1: "For <strong>Teacher Appreciation Week 2019</strong>, we are offering free 1-week licenses!<br />Email PI:NAME:<NAME>END_PI (<a href=\"mailto:PI:EMAIL:<EMAIL>END_PI?subject=Teacher Appreciation Week\">PI:EMAIL:<EMAIL>END_PI</a>) with subject line \"<strong>Teacher Appreciation Week</strong>\", and include:" # appreciation_week_blurb2: "the quantity of 1-week licenses you'd like (1 per student)" # appreciation_week_blurb3: "the email address of your CodeCombat teacher account" # appreciation_week_blurb4: "whether you'd like licenses for Week 1 (May 6-10) or Week 2 (May 13-17)" # hoc_happy_ed_week: "Happy Computer Science Education Week!" # hoc_blurb1: "Learn about the free" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity, download a new teacher lesson plan, and tell your students to log in to play!" # hoc_button_text: "View Activity" # no_code_yet: "Student has not written any code for this level yet." # open_ended_level: "Open-Ended Level" partial_solution: "Solução Parcial" # capstone_solution: "Capstone Solution" removing_course: "A remover o curso" # solution_arena_blurb: "Students are encouraged to solve arena levels creatively. The solution provided below meets the requirements of the arena level." # solution_challenge_blurb: "Students are encouraged to solve open-ended challenge levels creatively. One possible solution is displayed below." # solution_project_blurb: "Students are encouraged to build a creative project in this level. Please refer to curriculum guides in the Resource Hub for information on how to evaluate these projects." # students_code_blurb: "A correct solution to each level is provided where appropriate. In some cases, it’s possible for a student to solve a level using different code. Solutions are not shown for levels the student has not started." # course_solution: "Course Solution" # level_overview_solutions: "Level Overview and Solutions" # no_student_assigned: "No students have been assigned this course." # paren_new: "(new)" student_code: "Código de Estudante de __name__" teacher_dashboard: "Painel do Professor" # Navbar my_classes: "As Minhas Turmas" courses: "Guias dos Cursos" enrollments: "Licenças de Estudantes" resources: "Recursos" help: "Ajuda" language: "Linguagem" edit_class_settings: "editar definições da turma" access_restricted: "Atualização de Conta Necessária" teacher_account_required: "É necessária uma conta de professor para acederes a este conteúdo." create_teacher_account: "Criar Conta de Professor" what_is_a_teacher_account: "O que é uma Conta de Professor?" # teacher_account_explanation: "A CodeCombat Teacher account allows you to set up classrooms, monitor students’ progress as they work through courses, manage licenses and access resources to aid in your curriculum-building." current_classes: "Turmas Atuais" archived_classes: "Turmas Arquivadas" archived_classes_blurb: "As turmas podem ser arquivadas para referência futura. Desarquiva uma turma para a veres novamente na lista das Turmas Atuais." view_class: "ver turma" archive_class: "arquivar turma" unarchive_class: "desarquivar turma" unarchive_this_class: "Desarquivar esta turma" no_students_yet: "Esta turma ainda não tem estudantes." no_students_yet_view_class: "Ver turma para adicionar estudantes." try_refreshing: "(Podes precisar de atualizar a página)" create_new_class: "Criar uma Turma Nova" class_overview: "Visão Geral da Turma" # View Class page avg_playtime: "Tempo de jogo médio por nível" total_playtime: "Tempo de jogo total" avg_completed: "Média de níveis completos" total_completed: "Totalidade dos níveis completos" created: "Criada" concepts_covered: "Conceitos abordados" earliest_incomplete: "Nível mais básico incompleto" latest_complete: "Último nível completo" enroll_student: "Inscrever estudante" apply_license: "Aplicar Licença" revoke_license: "Revogar Licença" revoke_licenses: "Revogar Todas as Licenças" course_progress: "Progresso dos Cursos" not_applicable: "N/A" edit: "editar" edit_2: "Editar" remove: "remover" latest_completed: "Último completo:" sort_by: "Ordenar por" progress: "Progresso" concepts_used: "Conceitos usados pelo Estudante:" # concept_checked: "Concept checked:" completed: "Completaram" practice: "Prática" started: "Começaram" no_progress: "Nenhum progresso" # not_required: "Not required" # view_student_code: "Click to view student code" select_course: "Seleciona o curso para ser visto" progress_color_key: "Esquema de cores do progresso:" level_in_progress: "Nível em Progresso" level_not_started: "Nível Não Começado" project_or_arena: "Projeto ou Arena" # students_not_assigned: "Students who have not been assigned {{courseName}}" # course_overview: "Course Overview" copy_class_code: "Copiar Código de Turma" class_code_blurb: "Os estudantes podem entrar na tua turma ao usarem este Código de Turma. Não é necessário nenhum endereço de e-mail aquando da criação de uma conta de Estudante com este Código de Turma." copy_class_url: "Copiar URL da Turma" class_join_url_blurb: "Também podes publicar este URL único da turma numa página web partilhada." add_students_manually: "Convidar Estudantes por E-mail" bulk_assign: "Selecionar curso" # assigned_msg_1: "{{numberAssigned}} students were assigned {{courseName}}." assigned_msg_2: "{{numberEnrolled}} licenças foram aplicadas." # assigned_msg_3: "You now have {{remainingSpots}} available licenses remaining." assign_course: "Atribuir Curso" removed_course_msg: "{{numberRemoved}} estudantes foram removidos de {{courseName}}." remove_course: "Remover Curso" not_assigned_modal_title: "Os cursos não foram atribuídos" # not_assigned_modal_starter_body_1: "This course requires a Starter License. You do not have enough Starter Licenses available to assign this course to all __selected__ selected students." # not_assigned_modal_starter_body_2: "Purchase Starter Licenses to grant access to this course." # not_assigned_modal_full_body_1: "This course requires a Full License. You do not have enough Full Licenses available to assign this course to all __selected__ selected students." # not_assigned_modal_full_body_2: "You only have __numFullLicensesAvailable__ Full Licenses available (__numStudentsWithoutFullLicenses__ students do not currently have a Full License active)." # not_assigned_modal_full_body_3: "Please select fewer students, or reach out to __supportEmail__ for assistance." # assigned: "Assigned" enroll_selected_students: "Inscrever os Estudantes Selecionados" no_students_selected: "Nenhum estudante foi selecionado." # show_students_from: "Show students from" # Enroll students modal apply_licenses_to_the_following_students: "Aplicar Licenças aos Seguintes Estudantes" # students_have_licenses: "The following students already have licenses applied:" all_students: "Todos os Estudantes" apply_licenses: "Aplicar Licenças" not_enough_enrollments: "Não há licenças suficientes disponíveis." enrollments_blurb: "É necessário que os estudantes tenham uma licença para acederem a qualquer conteúdo depois do primeiro curso." how_to_apply_licenses: "Como Aplicar Licenças" export_student_progress: "Exportar Progresso dos Estudantes (CSV)" # send_email_to: "Send Recover Password Email to:" email_sent: "E-mail enviado" send_recovery_email: "Enviar e-mail de recuperação" enter_new_password_below: "Introduz a nova palavra-passe abaixo:" change_password: "PI:PASSWORD:<PASSWORD>END_PI" changed: "Alterada" available_credits: "Licenças Disponíveis" pending_credits: "Licenças Pendentes" # empty_credits: "Exhausted Licenses" license_remaining: "licença restante" licenses_remaining: "licenças restantes" one_license_used: "1 de __totalLicenses__ licenças foi usada" num_licenses_used: "__numLicensesUsed__ de __totalLicenses__ licenças foram usadas" # starter_licenses: "starter licenses" # start_date: "start date:" # end_date: "end date:" get_enrollments_blurb: " Vamos ajudar-te a construir uma solução que satisfaça as necessidades da tua turma, escola ou distrito." # how_to_apply_licenses_blurb_1: "When a teacher assigns a course to a student for the first time, we’ll automatically apply a license. Use the bulk-assign dropdown in your classroom to assign a course to selected students:" # how_to_apply_licenses_blurb_2: "Can I still apply a license without assigning a course?" # how_to_apply_licenses_blurb_3: "Yes — go to the License Status tab in your classroom and click \"Apply License\" to any student who does not have an active license." request_sent: "Pedido Enviado!" # assessments: "Assessments" license_status: "Estado das Licenças" # status_expired: "Expired on {{date}}" status_not_enrolled: "Não Inscrito" # status_enrolled: "Expires on {{date}}" select_all: "Selecionar Todos" project: "Projeto" # project_gallery: "Project Gallery" view_project: "Ver Projeto" unpublished: "(não publicado)" # view_arena_ladder: "View Arena Ladder" resource_hub: "Centro de Recursos" # pacing_guides: "Classroom-in-a-Box Pacing Guides" # pacing_guides_desc: "Learn how to incorporate all of CodeCombat's resources to plan your school year!" # pacing_guides_elem: "Elementary School Pacing Guide" # pacing_guides_middle: "Middle School Pacing Guide" # pacing_guides_high: "High School Pacing Guide" # getting_started: "Getting Started" # educator_faq: "Educator FAQ" # educator_faq_desc: "Frequently asked questions about using CodeCombat in your classroom or school." # teacher_getting_started: "Teacher Getting Started Guide" # teacher_getting_started_desc: "New to CodeCombat? Download this Teacher Getting Started Guide to set up your account, create your first class, and invite students to the first course." # student_getting_started: "Student Quick Start Guide" # student_getting_started_desc: "You can distribute this guide to your students before starting CodeCombat so that they can familiarize themselves with the code editor. This guide can be used for both Python and JavaScript classrooms." # ap_cs_principles: "AP Computer Science Principles" # ap_cs_principles_desc: "AP Computer Science Principles gives students a broad introduction to the power, impact, and possibilities of Computer Science. The course emphasizes computational thinking and problem solving while also teaching the basics of programming." # cs1: "Introduction to Computer Science" # cs2: "Computer Science 2" # cs3: "Computer Science 3" # cs4: "Computer Science 4" # cs5: "Computer Science 5" # cs1_syntax_python: "Course 1 Python Syntax Guide" # cs1_syntax_python_desc: "Cheatsheet with references to common Python syntax that students will learn in Introduction to Computer Science." # cs1_syntax_javascript: "Course 1 JavaScript Syntax Guide" # cs1_syntax_javascript_desc: "Cheatsheet with references to common JavaScript syntax that students will learn in Introduction to Computer Science." coming_soon: "Guias adicionais em breve!" # engineering_cycle_worksheet: "Engineering Cycle Worksheet" # engineering_cycle_worksheet_desc: "Use this worksheet to teach students the basics of the engineering cycle: Assess, Design, Implement and Debug. Refer to the completed example worksheet as a guide." # engineering_cycle_worksheet_link: "View example" # progress_journal: "Progress Journal" # progress_journal_desc: "Encourage students to keep track of their progress via a progress journal." # cs1_curriculum: "Introduction to Computer Science - Curriculum Guide" # cs1_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 1." # arenas_curriculum: "Arena Levels - Teacher Guide" # arenas_curriculum_desc: "Instructions on how to run Wakka Maul, Cross Bones and Power Peak multiplayer arenas with your class." # assessments_curriculum: "Assessment Levels - Teacher Guide" # assessments_curriculum_desc: "Learn how to use Challenge Levels and Combo Challenge levels to assess students' learning outcomes." # cs2_curriculum: "Computer Science 2 - Curriculum Guide" # cs2_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 2." # cs3_curriculum: "Computer Science 3 - Curriculum Guide" # cs3_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 3." # cs4_curriculum: "Computer Science 4 - Curriculum Guide" # cs4_curriculum_desc: "Scope and sequence, lesson plans, activities and more for Course 4." # cs5_curriculum_js: "Computer Science 5 - Curriculum Guide (JavaScript)" # cs5_curriculum_desc_js: "Scope and sequence, lesson plans, activities and more for Course 5 classes using JavaScript." # cs5_curriculum_py: "Computer Science 5 - Curriculum Guide (Python)" # cs5_curriculum_desc_py: "Scope and sequence, lesson plans, activities and more for Course 5 classes using Python." # cs1_pairprogramming: "Pair Programming Activity" # cs1_pairprogramming_desc: "Introduce students to a pair programming exercise that will help them become better listeners and communicators." # gd1: "Game Development 1" # gd1_guide: "Game Development 1 - Project Guide" # gd1_guide_desc: "Use this to guide your students as they create their first shareable game project in 5 days." # gd1_rubric: "Game Development 1 - Project Rubric" # gd1_rubric_desc: "Use this rubric to assess student projects at the end of Game Development 1." # gd2: "Game Development 2" # gd2_curriculum: "Game Development 2 - Curriculum Guide" # gd2_curriculum_desc: "Lesson plans for Game Development 2." # gd3: "Game Development 3" # gd3_curriculum: "Game Development 3 - Curriculum Guide" # gd3_curriculum_desc: "Lesson plans for Game Development 3." # wd1: "Web Development 1" # wd1_curriculum: "Web Development 1 - Curriculum Guide" # wd1_curriculum_desc: "Scope and sequence, lesson plans, activities, and more for Web Development 1." # wd1_headlines: "Headlines & Headers Activity" # wd1_headlines_example: "View sample solution" # wd1_headlines_desc: "Why are paragraph and header tags important? Use this activity to show how well-chosen headers make web pages easier to read. There are many correct solutions to this!" # wd1_html_syntax: "HTML Syntax Guide" # wd1_html_syntax_desc: "One-page reference for the HTML style students will learn in Web Development 1." # wd1_css_syntax: "CSS Syntax Guide" # wd1_css_syntax_desc: "One-page reference for the CSS and Style syntax students will learn in Web Development 1." # wd2: "Web Development 2" # wd2_jquery_syntax: "jQuery Functions Syntax Guide" # wd2_jquery_syntax_desc: "One-page reference for the jQuery functions students will learn in Web Development 2." # wd2_quizlet_worksheet: "Quizlet Planning Worksheet" # wd2_quizlet_worksheet_instructions: "View instructions & examples" # wd2_quizlet_worksheet_desc: "Before your students build their personality quiz project at the end of Web Development 2, they should plan out their quiz questions, outcomes and responses using this worksheet. Teachers can distribute the instructions and examples for students to refer to." student_overview: "Visão Geral" student_details: "Detalhes do Estudante" student_name: "Nome PI:NAME:<NAME>END_PI" no_name: "Nenhum nome fornecido." no_username: "Nenhum nome de utilizador fornecido." no_email: "O estudante não tem nenhum endereço de e-mail definido." student_profile: "Perfil do Estudante" playtime_detail: "Detalhe do Tempo de Jogo" student_completed: "Completo pelo Estudante" student_in_progress: "Em progresso pelo Estudante" class_average: "Média da Turma" # not_assigned: "has not been assigned the following courses" playtime_axis: "Tempo de Jogo em Segundos" levels_axis: "Níveis em" student_state: "Como se está" student_state_2: "a sair?" # student_good: "is doing well in" # student_good_detail: "This student is keeping pace with the class." # student_warn: "might need some help in" # student_warn_detail: "This student might need some help with new concepts that have been introduced in this course." # student_great: "is doing great in" # student_great_detail: "This student might be a good candidate to help other students working through this course." # full_license: "Full License" # starter_license: "Starter License" # trial: "Trial" # hoc_welcome: "Happy Computer Science Education Week" # hoc_title: "Hour of Code Games - Free Activities to Learn Real Coding Languages" # hoc_meta_description: "Make your own game or code your way out of a dungeon! CodeCombat has four different Hour of Code activities and over 60 levels to learn code, play, and create." # hoc_intro: "There are three ways for your class to participate in Hour of Code with CodeCombat" # hoc_self_led: "Self-Led Gameplay" # hoc_self_led_desc: "Students can play through two Hour of Code CodeCombat tutorials on their own" # hoc_game_dev: "Game Development" # hoc_and: "and" # hoc_programming: "JavaScript/Python Programming" # hoc_teacher_led: "Teacher-Led Lessons" # hoc_teacher_led_desc1: "Download our" # hoc_teacher_led_link: "Introduction to Computer Science lesson plans" # hoc_teacher_led_desc2: "to introduce your students to programming concepts using offline activities" # hoc_group: "Group Gameplay" # hoc_group_desc_1: "Teachers can use the lessons in conjunction with our Introduction to Computer Science course to track student progress. See our" # hoc_group_link: "Getting Started Guide" # hoc_group_desc_2: "for more details" # hoc_additional_desc1: "For additional CodeCombat resources and activities, see our" # hoc_additional_desc2: "Questions" # hoc_additional_contact: "Get in touch" # revoke_confirm: "Are you sure you want to revoke a Full License from {{student_name}}? The license will become available to assign to another student." # revoke_all_confirm: "Are you sure you want to revoke Full Licenses from all students in this class?" revoking: "A revogar..." # unused_licenses: "You have unused Licenses that allow you to assign students paid courses when they're ready to learn more!" # remember_new_courses: "Remember to assign new courses!" more_info: "Mais Informação" # how_to_assign_courses: "How to Assign Courses" # select_students: "Select Students" # select_instructions: "Click the checkbox next to each student you want to assign courses to." # choose_course: "Choose Course" # choose_instructions: "Select the course from the dropdown menu you’d like to assign, then click “Assign to Selected Students.”" # push_projects: "We recommend assigning Web Development 1 or Game Development 1 after students have finished Introduction to Computer Science! See our {{resource_hub}} for more details on those courses." # teacher_quest: "Teacher's Quest for Success" # quests_complete: "Quests Complete" # teacher_quest_create_classroom: "Create Classroom" teacher_quest_add_students: "Adicionar Estudantes" # teacher_quest_teach_methods: "Help your students learn how to `call methods`." # teacher_quest_teach_methods_step1: "Get 75% of at least one class through the first level, __Dungeons of Kithgard__" # teacher_quest_teach_methods_step2: "Print out the [Student Quick Start Guide](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) in the Resource Hub." # teacher_quest_teach_strings: "Don't string your students along, teach them `strings`." # teacher_quest_teach_strings_step1: "Get 75% of at least one class through __True Names__" # teacher_quest_teach_strings_step2: "Use the Teacher Level Selector on [Course Guides](/teachers/courses) page to preview __True Names__." # teacher_quest_teach_loops: "Keep your students in the loop about `loops`." # teacher_quest_teach_loops_step1: "Get 75% of at least one class through __Fire Dancing__." # teacher_quest_teach_loops_step2: "Use the __Loops Activity__ in the [CS1 Curriculum guide](/teachers/resources/cs1) to reinforce this concept." # teacher_quest_teach_variables: "Vary it up with `variables`." # teacher_quest_teach_variables_step1: "Get 75% of at least one class through __Known Enemy__." # teacher_quest_teach_variables_step2: "Encourage collaboration by using the [Pair Programming Activity](/teachers/resources/pair-programming)." # teacher_quest_kithgard_gates_100: "Escape the Kithgard Gates with your class." # teacher_quest_kithgard_gates_100_step1: "Get 75% of at least one class through __Kithgard Gates__." # teacher_quest_kithgard_gates_100_step2: "Guide students to think through hard problems using the [Engineering Cycle Worksheet](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." # teacher_quest_wakka_maul_100: "Prepare to duel in Wakka Maul." # teacher_quest_wakka_maul_100_step1: "Get 75% of at least one class to __Wakka Maul__." # teacher_quest_wakka_maul_100_step2: "See the [Arena Guide](/teachers/resources/arenas) in the [Resource Hub](/teachers/resources) for tips on how to run a successful arena day." # teacher_quest_reach_gamedev: "Explore new worlds!" # teacher_quest_reach_gamedev_step1: "[Get licenses](/teachers/licenses) so that your students can explore new worlds, like Game Development and Web Development!" # teacher_quest_done: "Want your students to learn even more code? Get in touch with our [school specialists](mailto:PI:EMAIL:<EMAIL>END_PI) today!" # teacher_quest_keep_going: "Keep going! Here's what you can do next:" # teacher_quest_more: "See all quests" # teacher_quest_less: "See fewer quests" # refresh_to_update: "(refresh the page to see updates)" # view_project_gallery: "View Project Gallery" # office_hours: "Teacher Webinars" # office_hours_detail: "Learn how to keep up with with your students as they create games and embark on their coding journey! Come and attend our" # office_hours_link: "teacher webinar" # office_hours_detail_2: "sessions." # success: "Success" # in_progress: "In Progress" # not_started: "Not Started" # mid_course: "Mid-Course" # end_course: "End of Course" # none: "None detected yet" # explain_open_ended: "Note: Students are encouraged to solve this level creatively — one possible solution is provided below." level_label: "Nível:" time_played_label: "Tempo Jogado:" # back_to_resource_hub: "Back to Resource Hub" # back_to_course_guides: "Back to Course Guides" print_guide: "Imprimir este guia" # combo: "Combo" # combo_explanation: "Students pass Combo challenge levels by using at least one listed concept. Review student code by clicking the progress dot." concept: "Conceito" # sync_google_classroom: "Sync Google Classroom" # try_ozaria_footer: "Try our new adventure game, Ozaria!" # teacher_ozaria_encouragement_modal: # title: "Build Computer Science Skills to Save Ozaria" # sub_title: "You are invited to try the new adventure game from CodeCombat" # cancel: "Back to CodeCombat" # accept: "Try First Unit Free" # bullet1: "Deepen student connection to learning through an epic story and immersive gameplay" # bullet2: "Teach CS fundamentals, Python or JavaScript and 21st century skills" # bullet3: "Unlock creativity through capstone projects" # bullet4: "Support instructions through dedicated curriculum resources" # you_can_return: "You can always return to CodeCombat" share_licenses: share_licenses: "Partilhar Licenças" shared_by: "PartPI:NAME:<NAME>END_PI Por:" # add_teacher_label: "Enter exact teacher email:" add_teacher_button: "Adicionar Professor" # subheader: "You can make your licenses available to other teachers in your organization. Each license can only be used for one student at a time." # teacher_not_found: "Teacher not found. Please make sure this teacher has already created a Teacher Account." # teacher_not_valid: "This is not a valid Teacher Account. Only teacher accounts can share licenses." # already_shared: "You've already shared these licenses with that teacher." # teachers_using_these: "Teachers who can access these licenses:" # footer: "When teachers revoke licenses from students, the licenses will be returned to the shared pool for other teachers in this group to use." you: "(tu)" one_license_used: "(1 licença usada)" licenses_used: "(__licensesUsed__ licenças usadas)" more_info: "Mais informação" sharing: game: "Jogo" webpage: "Página Web" # your_students_preview: "Your students will click here to see their finished projects! Unavailable in teacher preview." # unavailable: "Link sharing not available in teacher preview." share_game: "Partilhar Este Jogo" share_web: "Partilhar Esta Página Web" victory_share_prefix: "Partilha esta ligação para convidares os teus amigos e a tua família para" victory_share_prefix_short: "Convida pessoas para" victory_share_game: "jogarem o teu nível de jogo" victory_share_web: "verem a tua página web" victory_share_suffix: "." victory_course_share_prefix: "Esta ligação vai permitir que os teus amigos e a tua família" victory_course_share_game: "joguem o jogo" victory_course_share_web: "vejam a página web" victory_course_share_suffix: "que acabaste de criar." copy_url: "Copiar URL" share_with_teacher_email: "Envia para o teu professor" game_dev: creator: "Criador" web_dev: image_gallery_title: "Galeria de Imagens" select_an_image: "Seleciona uma imagem que queiras usar" scroll_down_for_more_images: "(Arrasta para baixo para mais imagens)" copy_the_url: "Copiar o URL abaixo" copy_the_url_description: "Útil se quiseres substituir uma imagem existente." copy_the_img_tag: "Copiar a etiqueta <img>" copy_the_img_tag_description: "Útil se quiseres inserir uma imagem nova." copy_url: "Copiar URL" copy_img: "Copiar <img>" how_to_copy_paste: "Como Copiar/Colar" copy: "Copiar" paste: "Colar" back_to_editing: "Voltar à Edição" classes: archmage_title: "Arcomago" archmage_title_description: "(Programador)" archmage_summary: "Se és um programador interessado em programar jogos educacionais, torna-te um Arcomago para nos ajudares a construir o CodeCombat!" artisan_title: "Artesão" artisan_title_description: "(Construtor de Níveis)" artisan_summary: "Constrói e partilha níveis para tu e os teus amigos jogarem. Torna-te um Artesão para aprenderes a arte de ensinar outros a programar." adventurer_title: "Aventureiro" adventurer_title_description: "(Testador de Níveis)" adventurer_summary: "Recebe os nossos novos níveis (até o conteúdo para subscritores) de graça, uma semana antes, e ajuda-nos a descobrir erros antes do lançamento para o público." scribe_title: "Escrivão" scribe_title_description: "(Editor de Artigos)" scribe_summary: "Bom código precisa de uma boa documentação. Escreve, edita e melhora os documentos lidos por milhões de jogadores pelo mundo." diplomat_title: "Diplomata" diplomat_title_description: "(Tradutor)" diplomat_summary: "O CodeCombat está traduzido em 45+ idiomas graças aos nossos Diplomatas. Ajuda-nos e contribui com traduções." ambassador_title: "Embaixador" ambassador_title_description: "(Suporte)" ambassador_summary: "Amansa os nossos utilizadores do fórum e direciona aqueles que têm questões. Os nossos Embaixadores representam o CodeCombat perante o mundo." teacher_title: "PI:NAME:<NAME>END_PI" editor: main_title: "Editores do CodeCombat" article_title: "Editor de Artigos" thang_title: "Editor de Thangs" level_title: "Editor de Níveis" course_title: "Editor de Cursos" achievement_title: "Editor de Conquistas" poll_title: "Editor de Votações" back: "Voltar" revert: "Reverter" revert_models: "Reverter Modelos" pick_a_terrain: "Escolhe Um Terreno" dungeon: "Masmorra" indoor: "Interior" desert: "Deserto" grassy: "Relvado" mountain: "Montanha" glacier: "Glaciar" small: "Pequeno" large: "Grande" fork_title: "Bifurcar Nova Versão" fork_creating: "A Criar Bifurcação..." generate_terrain: "Gerar Terreno" more: "Mais" wiki: "Wiki" live_chat: "Chat ao Vivo" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Cores" level_some_options: "Algumas Opções?" level_tab_thangs: "Thangs" level_tab_scripts: "Scripts" level_tab_components: "Componentes" level_tab_systems: "Sistemas" level_tab_docs: "Documentação" level_tab_thangs_title: "Thangs Atuais" level_tab_thangs_all: "Todos" level_tab_thangs_conditions: "Condições Iniciais" level_tab_thangs_add: "Adicionar Thangs" level_tab_thangs_search: "Pesquisar thangs" add_components: "Adicionar Componentes" component_configs: "Configurações dos Componentes" config_thang: "Clica duas vezes para configurares uma thang" delete: "Eliminar" duplicate: "Duplicar" stop_duplicate: "Parar de Duplicar" rotate: "Rodar" level_component_tab_title: "Componentes Atuais" level_component_btn_new: "Criar Novo Componente" level_systems_tab_title: "Sistemas Atuais" level_systems_btn_new: "Cria Novo Sistema" level_systems_btn_add: "Adicionar Sistema" level_components_title: "Voltar para Todas as Thangs" level_components_type: "Tipo" level_component_edit_title: "Editar Componente" level_component_config_schema: "Configurar Esquema" level_system_edit_title: "Editar Sistema" create_system_title: "Criar Novo Sistema" new_component_title: "Criar Novo Componente" new_component_field_system: "Sistema" new_article_title: "Criar um Novo Artigo" new_thang_title: "Criar um Novo Tipo de Thang" new_level_title: "Criar um Novo Nível" new_article_title_login: "Inicia Sessão para Criares um Novo Artigo" new_thang_title_login: "Inicia Sessão para Criares um Novo Tipo de Thang" new_level_title_login: "Inicia Sessão para Criares um Novo Nível" new_achievement_title: "Criar uma Nova Conquista" new_achievement_title_login: "Inicia Sessão para Criares uma Nova Conquista" new_poll_title: "Criar uma Nova Votação" new_poll_title_login: "Iniciar Sessão para Criar uma Nova Votação" article_search_title: "Procurar Artigos Aqui" thang_search_title: "Procurar Thangs Aqui" level_search_title: "Procurar Níveis Aqui" achievement_search_title: "Procurar Conquistas" poll_search_title: "Procurar Votações" read_only_warning2: "Nota: não podes guardar nenhuma edição feita aqui, porque não tens sessão iniciada." no_achievements: "Ainda não foram adicionadas conquistas a este nível." achievement_query_misc: "Conquista-chave de uma lista de variados" achievement_query_goals: "Conquista-chave dos objetivos do nível" level_completion: "Completação do Nível" pop_i18n: "Propagar I18N" tasks: "Tarefas" clear_storage: "Limpa as tuas alterações locais" add_system_title: "Adicionar Sistemas ao Nível" done_adding: "Adição Concluída" article: edit_btn_preview: "Pré-visualizar" edit_article_title: "Editar Artigo" polls: priority: "Prioridade" contribute: page_title: "Contribuir" intro_blurb: "O CodeCombat faz parte da comunidade open source! Centenas de jogadores dedicados ajudaram-nos a transformar o jogo naquilo que ele é hoje. Junta-te a nós e escreve o próximo capítulo da aventura do CodeCombat para ensinar o mundo a programar!" alert_account_message_intro: "Hey, tu!" alert_account_message: "Para te subscreveres para receber e-mails de classes, necessitarás de iniciar sessão." archmage_introduction: "Uma das melhores partes da construção de jogos é que eles sintetizam muitas coisas diferentes. Gráficos, som, rede em tempo real, redes sociais, e, claro, muitos dos aspectos mais comuns da programação, desde a gestão de bases de dados de baixo nível, e administração do servidor até à construção do design e da interface do utilizador. Há muito a fazer, e se és um programador experiente com um verdadeiro desejo de mergulhar nas entranhas do CodeCombat, esta classe pode ser para ti. Gostaríamos muito de ter a tua ajuda para construir o melhor jogo de programação de sempre." class_attributes: "Atributos da Classe" archmage_attribute_1_pref: "Conhecimento em " archmage_attribute_1_suf: ", ou vontade de aprender. A maioria do nosso código está nesta linguagem. Se és um fã de Ruby ou Python, vais sentir-te em casa. É igual ao JavaScript, mas com uma sintaxe melhor." archmage_attribute_2: "Alguma experiência em programação e iniciativa pessoal. Nós ajudamos-te a orientares-te, mas não podemos gastar muito tempo a treinar-te." how_to_join: "Como Me Junto" join_desc_1: "Qualquer um pode ajudar! Só tens de conferir o nosso " join_desc_2: "para começares, e assinalar a caixa abaixo para te declarares um bravo Arcomago e receberes as últimas notícias por e-mail. Queres falar sobre o que fazer ou como te envolveres mais profundamente no projeto? " join_desc_3: " ou encontra-nos na nossa " join_desc_4: "e começamos a partir daí!" join_url_email: "Contacta-nos" join_url_slack: "canal público no Slack" archmage_subscribe_desc: "Receber e-mails relativos a novas oportunidades de programação e anúncios." artisan_introduction_pref: "Temos de construir mais níveis! As pessoas estão a pedir mais conteúdo, e nós mesmos só podemos construir estes tantos. Neste momento, a tua estação de trabalho é o nível um; o nosso editor de nível é pouco utilizável, até mesmo pelos seus criadores, por isso fica atento. Se tens visões de campanhas que abranjam 'for-loops' para o" artisan_introduction_suf: ", então esta classe pode ser para ti." # artisan_attribute_1: "Any experience in building content like this would be nice, such as using Blizzard's level editors. But not required!" # artisan_attribute_2: "A hankering to do a whole lot of testing and iteration. To make good levels, you need to take it to others and watch them play it, and be prepared to find a lot of things to fix." # artisan_attribute_3: "For the time being, endurance en par with an Adventurer. Our Level Editor is super preliminary and frustrating to use. You have been warned!" artisan_join_desc: "Usa o Editor de Níveis por esta ordem, pegar ou largar:" artisan_join_step1: "Lê a documentação." artisan_join_step2: "Cria um nível novo e explora níveis existentes." artisan_join_step3: "Encontra-nos na nossa sala Slack pública se necessitares de ajuda." artisan_join_step4: "Coloca os teus níveis no fórum para receberes feedback." artisan_subscribe_desc: "Receber e-mails relativos a novidades do editor de níveis e anúncios." # adventurer_introduction: "Let's be clear about your role: you are the tank. You're going to take heavy damage. We need people to try out brand-new levels and help identify how to make things better. The pain will be enormous; making good games is a long process and no one gets it right the first time. If you can endure and have a high constitution score, then this class might be for you." # adventurer_attribute_1: "A thirst for learning. You want to learn how to code and we want to teach you how to code. You'll probably be doing most of the teaching in this case, though." # adventurer_attribute_2: "Charismatic. Be gentle but articulate about what needs improving, and offer suggestions on how to improve." # adventurer_join_pref: "Either get together with (or recruit!) an Artisan and work with them, or check the box below to receive emails when there are new levels to test. We'll also be posting about levels to review on our networks like" # adventurer_forum_url: "our forum" # adventurer_join_suf: "so if you prefer to be notified those ways, sign up there!" adventurer_subscribe_desc: "Receber e-mails quando houver novos níveis para testar." # scribe_introduction_pref: "CodeCombat isn't just going to be a bunch of levels. It will also include a resource for knowledge, a wiki of programming concepts that levels can hook into. That way rather than each Artisan having to describe in detail what a comparison operator is, they can simply link their level to the Article describing them that is already written for the player's edification. Something along the lines of what the " # scribe_introduction_url_mozilla: "Mozilla Developer Network" # scribe_introduction_suf: " has built. If your idea of fun is articulating the concepts of programming in Markdown form, then this class might be for you." scribe_attribute_1: "Habilidade com palavras é basicamente o que precisas. Não apenas gramática e ortografia, mas seres capaz de explicar ideias complicadas a outros." contact_us_url: "Contacta-nos" scribe_join_description: "fala-nos um bocado de ti, da tua experiência com a programação e do tipo de coisas sobre as quais gostarias de escrever. Começamos a partir daí!" scribe_subscribe_desc: "Receber e-mails sobre anúncios relativos à escrita de artigos." diplomat_introduction_pref: "Portanto, se há uma coisa que aprendemos com o nosso " diplomat_launch_url: "lançamento em Outubro" diplomat_introduction_suf: "é que há um interesse considerável no CodeCombat noutros países! Estamos a construir um exército de tradutores dispostos a transformar um conjunto de palavras num outro conjuto de palavras, para conseguir que o CodeCombat fique o mais acessível quanto posível em todo o mundo. Se gostas de dar espreitadelas a conteúdos futuros e disponibilizar os níveis para os teus colegas nacionais o mais depressa possível, então esta classe talvez seja para ti." diplomat_attribute_1: "Fluência em Inglês e no idioma para o qual gostarias de traduzir. Quando são tentadas passar ideias complicadas, é importante uma excelente compreensão das duas!" diplomat_i18n_page_prefix: "Podes começar a traduzir os nossos níveis se fores à nossa" diplomat_i18n_page: "página de traduções" diplomat_i18n_page_suffix: ", ou a nossa interface e website no GitHub." diplomat_join_pref_github: "Encontra o ficheiro 'locale' do teu idioma " diplomat_github_url: "no GitHub" diplomat_join_suf_github: ", edita-o online e submete um 'pull request'. Assinala ainda a caixa abaixo para ficares atualizado em relação a novos desenvolvimentos da internacionalização!" diplomat_subscribe_desc: "Receber e-mails sobre desenvolvimentos da i18n e níveis para traduzir." # ambassador_introduction: "This is a community we're building, and you are the connections. We've got forums, emails, and social networks with lots of people to talk with and help get acquainted with the game and learn from. If you want to help people get involved and have fun, and get a good feel of the pulse of CodeCombat and where we're going, then this class might be for you." # ambassador_attribute_1: "Communication skills. Be able to identify the problems players are having and help them solve them. Also, keep the rest of us informed about what players are saying, what they like and don't like and want more of!" # ambassador_join_desc: "tell us a little about yourself, what you've done and what you'd be interested in doing. We'll go from there!" ambassador_join_note_strong: "Nota" ambassador_join_note_desc: "Uma das nossas maiores prioridades é construir níveis multijogador onde os jogadores com dificuldade para passar níveis possam invocar feiticeiros mais experientes para os ajudarem. Esta será uma ótima forma de os embaixadores fazerem o que sabem. Vamos manter-te atualizado!" ambassador_subscribe_desc: "Receber e-mails relativos a novidades do suporte e desenvolvimentos do modo multijogador." teacher_subscribe_desc: "Receber e-mails sobre atualizações e anúncios para professores." changes_auto_save: "As alterações são guardadas automaticamente quando clicas nas caixas." diligent_scribes: "Os Nossos Dedicados Escrivões:" powerful_archmages: "Os Nossos Poderosos Arcomagos:" creative_artisans: "Os Nossos Creativos Artesãos:" brave_adventurers: "Os Nossos Bravos Aventureiros:" translating_diplomats: "Os Nossos Tradutores Diplomatas:" helpful_ambassadors: "Os Nossos Prestáveis Embaixadores:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Os Meus Jogos" simulate: "Simular" simulation_explanation: "Ao simulares jogos podes ter o teu jogo classificado mais rapidamente!" simulation_explanation_leagues: "Principalmente, vais ajudar a simular jogos para jogadores aliados nos teus clâs e cursos." simulate_games: "Simular Jogos!" games_simulated_by: "Jogos simulados por ti:" games_simulated_for: "Jogos simulados para ti:" games_in_queue: "Jogos na fila de espera atualmente:" games_simulated: "Jogos simulados" games_played: "Jogos jogados" ratio: "Rácio" leaderboard: "Tabela de Classificação" battle_as: "Lutar como " summary_your: "As Tuas " summary_matches: "Partidas - " summary_wins: " Vitórias, " summary_losses: " Derrotas" rank_no_code: "Sem Código Novo para Classificar" rank_my_game: "Classificar o Meu Jogo!" rank_submitting: "A submeter..." rank_submitted: "Submetido para Classificação" rank_failed: "A Classificação Falhou" rank_being_ranked: "Jogo a ser Classificado" rank_last_submitted: "submetido " help_simulate: "Ajudar a simular jogos?" code_being_simulated: "O teu novo código está a ser simulado por outros jogadores, para ser classificado. Isto será atualizado quando surgirem novas partidas." no_ranked_matches_pre: "Sem jogos classificados pela equipa " no_ranked_matches_post: "! Joga contra alguns adversários e volta aqui para veres o teu jogo classificado." choose_opponent: "Escolhe um Adversário" select_your_language: "Seleciona a tua linguagem!" tutorial_play: "Jogar Tutorial" tutorial_recommended: "Recomendado se nunca jogaste antes" tutorial_skip: "Saltar Tutorial" tutorial_not_sure: "Não tens a certeza do que se passa?" tutorial_play_first: "Joga o Tutorial primeiro." simple_ai: "CPU Simples" warmup: "Aquecimento" friends_playing: "Amigos a Jogar" log_in_for_friends: "Inicia sessão para jogares com os teus amigos!" social_connect_blurb: "Conecta-te e joga contra os teus amigos!" invite_friends_to_battle: "Convida os teus amigos para se juntarem a ti em batalha!" fight: "Lutar!" watch_victory: "Vê a tua vitória" defeat_the: "Derrota o" watch_battle: "Ver a batalha" tournament_started: ", começou" tournament_ends: "O Torneio acaba" tournament_ended: "O Torneio acabou" tournament_rules: "Regras do Torneio" tournament_blurb: "Escreve código, recolhe ouro, constrói exércitos, esmaga inimigos, ganha prémios e melhora a tua carreira no nosso torneio $40,000 Greed! Confere os detalhes" tournament_blurb_criss_cross: "Ganha ofertas, constrói caminhos, supera os adversários, apanha gemas e melhore a tua carreira no nosso torneio Criss-Cross! Confere os detalhes" tournament_blurb_zero_sum: "Liberta a tua criatividade de programação tanto na recolha de ouro como em táticas de combate nesta batalha-espelhada na montanha, entre o feiticeiro vermelho e o feiticeiro azul. O torneio começou na Sexta-feira, 27 de Março, e decorrerá até às 00:00 de Terça-feira, 7 de Abril. Compete por diversão e glória! Confere os detalhes" tournament_blurb_ace_of_coders: "Luta no glaciar congelado nesta partida espelhada do estilo domínio! O torneio começou Quarta-feira, 16 de Setembro, e decorrerá até Quarta-feira, 14 de Outubro às 23:00. Confere os detalhes" tournament_blurb_blog: "no nosso blog" rules: "Regras" winners: "Vencedores" league: "Liga" red_ai: "CPU Vermelho" # "Red AI Wins", at end of multiplayer match playback blue_ai: "CPU Azul" wins: "Vence" # At end of multiplayer match playback humans: "Vermelho" # Ladder page display team name ogres: "Azul" # live_tournament: "Live Tournament" # awaiting_tournament_title: "Tournament Inactive" # awaiting_tournament_blurb: "The tournament arena is not currently active." # tournament_end_desc: "The tournament is over, thanks for playing" user: # user_title: "__name__ - Learn to Code with CodeCombat" stats: "Estatísticas" singleplayer_title: "Níveis Um Jogador" multiplayer_title: "Níveis Multijogador" achievements_title: "Conquistas" last_played: "Última Vez Jogado" status: "Estado" status_completed: "Completo" status_unfinished: "Inacabado" no_singleplayer: "Sem jogos Um Jogador jogados." no_multiplayer: "Sem jogos Multijogador jogados." no_achievements: "Sem Conquistas ganhas." favorite_prefix: "A linguagem favorita é " favorite_postfix: "." not_member_of_clans: "Ainda não é membro de nenhum clã." # certificate_view: "view certificate" # certificate_click_to_view: "click to view certificate" # certificate_course_incomplete: "course incomplete" # certificate_of_completion: "Certificate of Completion" # certificate_endorsed_by: "Endorsed by" # certificate_stats: "Course Stats" # certificate_lines_of: "lines of" # certificate_levels_completed: "levels completed" # certificate_for: "For" # certificate_number: "No." achievements: last_earned: "Último Ganho" amount_achieved: "Quantidade" achievement: "Conquista" current_xp_prefix: "" current_xp_postfix: " no total" new_xp_prefix: "" new_xp_postfix: " ganho" left_xp_prefix: "" left_xp_infix: " até ao nível " left_xp_postfix: "" account: # title: "Account" # settings_title: "Account Settings" # unsubscribe_title: "Unsubscribe" # payments_title: "Payments" # subscription_title: "Subscription" # invoices_title: "Invoices" # prepaids_title: "Prepaids" payments: "Pagamentos" prepaid_codes: "Códigos Pré-pagos" purchased: "Adquirido" # subscribe_for_gems: "Subscribe for gems" subscription: "Subscrição" invoices: "Donativos" service_apple: "Apple" service_web: "Web" paid_on: "Pago Em" service: "Serviço" price: "Preço" gems: "Gemas" active: "Activa" subscribed: "Subscrito(a)" unsubscribed: "Não Subscrito(a)" active_until: "Ativa Até" cost: "Custo" next_payment: "Próximo Pagamento" card: "Cartão" status_unsubscribed_active: "Não estás subscrito e não te vamos cobrar, mas a tua conta ainda está ativa, por agora." status_unsubscribed: "Ganha acesso a novos níveis, heróis, itens e gemas de bónus com uma subscrição do CodeCombat!" not_yet_verified: "Ainda não foi verificado." resend_email: "Reenviar e-mail" email_sent: "E-mail enviado! Verifica a tua caixa de entrada." verifying_email: "A verificar o teu endereço de e-mail..." successfully_verified: "Verificaste o teu endereço de e-mail com sucesso!" verify_error: "Algo correu mal aquando da verificação do teu e-mail :(" # unsubscribe_from_marketing: "Unsubscribe __email__ from all CodeCombat marketing emails?" # unsubscribe_button: "Yes, unsubscribe" # unsubscribe_failed: "Failed" # unsubscribe_success: "Success" account_invoices: amount: "Quantidade em dólares americanos" declined: "O teu cartão foi recusado" invalid_amount: "Por favor introduz uma quantidade de dólares americanos." not_logged_in: "Inicia sessão ou cria uma conta para acederes aos donativos." pay: "Pagar Donativo" purchasing: "A adquirir..." retrying: "Erro do servidor, a tentar novamente." success: "Pago com sucesso. Obrigado!" account_prepaid: purchase_code: "Comprar um Código de Subscrição" # purchase_code1: "Subscription Codes can be redeemed to add premium subscription time to one or more accounts for the Home version of CodeCombat." # purchase_code2: "Each CodeCombat account can only redeem a particular Subscription Code once." # purchase_code3: "Subscription Code months will be added to the end of any existing subscription on the account." # purchase_code4: "Subscription Codes are for accounts playing the Home version of CodeCombat, they cannot be used in place of Student Licenses for the Classroom version." # purchase_code5: "For more information on Student Licenses, reach out to" users: "Utilizadores" months: "Meses" purchase_total: "Total" purchase_button: "Submeter Compra" your_codes: "Os Teus Códigos" redeem_codes: "Resgata um Código de Subscrição" prepaid_code: "Código Pré-pago" lookup_code: "Procurar código pré-pago" apply_account: "Aplicar à tua conta" copy_link: "Podes copiar a ligação do código e enviá-la a alguém." quantity: "Quantidade" redeemed: "Resgatado" no_codes: "Nenhum código ainda!" you_can1: "Podes" you_can2: "adquirir um código pré-pago" you_can3: "que pode ser aplicado à tua conta ou dado a outros." # ozaria_chrome: # sound_off: "Sound Off" # sound_on: "Sound On" # back_to_map: "Back to Map" # level_options: "Level Options" # restart_level: "Restart Level" # impact: # hero_heading: "Building A World-Class Computer Science Program" # hero_subheading: "We Help Empower Educators and Inspire Students Across the Country" # featured_partner_story: "Featured Partner Story" # partner_heading: "Successfully Teaching Coding at a Title I School" # partner_school: "Bobby Duke Middle School" # featured_teacher: "PI:NAME:<NAME>END_PI" # teacher_title: "Technology Teacher Coachella, CA" # implementation: "Implementation" # grades_taught: "Grades Taught" # length_use: "Length of Use" # length_use_time: "3 years" # students_enrolled: "Students Enrolled this Year" # students_enrolled_number: "130" # courses_covered: "Courses Covered" # course1: "CompSci 1" # course2: "CompSci 2" # course3: "CompSci 3" # course4: "CompSci 4" # course5: "GameDev 1" # fav_features: "Favorite Features" # responsive_support: "Responsive Support" # immediate_engagement: "Immediate Engagement" # paragraph1: "Bobby Duke Middle School sits nestled between the Southern California mountains of Coachella Valley to the west and east and the Salton Sea 33 miles south, and boasts a student population of 697 students within Coachella Valley Unified’s district-wide population of 18,861 students." # paragraph2: "The students of Bobby Duke Middle School reflect the socioeconomic challenges facing Coachella Valley’s residents and students within the district. With over 95% of the Bobby Duke Middle School student population qualifying for free and reduced-price meals and over 40% classified as English language learners, the importance of teaching 21st century skills was the top priority of PI:NAME:<NAME>END_PI Middle School Technology teacher, PI:NAME:<NAME>END_PI." # paragraph3: "PI:NAME:<NAME>END_PI knew that teaching his students coding was a key pathway to opportunity in a job landscape that increasingly prioritizes and necessitates computing skills. So, he decided to take on the exciting challenge of creating and teaching the only coding class in the school and finding a solution that was affordable, responsive to feedback, and engaging to students of all learning abilities and backgrounds." # teacher_quote: "When I got my hands on CodeCombat [and] started having my students use it, the light bulb went on. It was just night and day from every other program that we had used. They’re not even close." # quote_attribution: "PI:NAME:<NAME>END_PI, Technology Teacher" # read_full_story: "Read Full Story" # more_stories: "More Partner Stories" # partners_heading_1: "Supporting Multiple CS Pathways in One Class" # partners_school_1: "Preston High School" # partners_heading_2: "Excelling on the AP Exam" # partners_school_2: "River Ridge High School" # partners_heading_3: "Teaching Computer Science Without Prior Experience" # partners_school_3: "Riverdale High School" # download_study: "Download Research Study" # teacher_spotlight: "Teacher & Student Spotlights" # teacher_name_1: "PI:NAME:<NAME>END_PI" # teacher_title_1: "Rehabilitation Instructor" # teacher_location_1: "Morehead, Kentucky" # spotlight_1: "Through her compassion and drive to help those who need second chances, PI:NAME:<NAME>END_PI helped change the lives of students who need positive role models. With no previous computer science experience, PI:NAME:<NAME>END_PI led her students to coding success in a regional coding competition." # teacher_name_2: "PI:NAME:<NAME>END_PI" # teacher_title_2: "Maysville Community & Technical College" # teacher_location_2: "Lexington, Kentucky" # spotlight_2: "Kaila was a student who never thought she would be writing lines of code, let alone enrolled in college with a pathway to a bright future." # teacher_name_3: "PI:NAME:<NAME>END_PI" # teacher_title_3: "Teacher Librarian" # teacher_school_3: "Ruby Bridges Elementary" # teacher_location_3: "Alameda, CA" # spotlight_3: "PI:NAME:<NAME>END_PI promotes an equitable atmosphere in her class where everyone can find success in their own way. Mistakes and struggles are welcomed because everyone learns from a challenge, even the teacher." # continue_reading_blog: "Continue Reading on Blog..." loading_error: could_not_load: "Erro a carregar do servidor. Experimenta atualizar a página." connection_failure: "A Ligação Falhou" connection_failure_desc: "Não parece que estejas ligado à internet! Verifica a tua ligação de rede e depois recarrega esta página." login_required: "Sessão Iniciada Obrigatória" login_required_desc: "Precisas de ter sessão iniciada para acederes a esta página." unauthorized: "Precisas de ter sessão iniciada. Tens os cookies desativados?" forbidden: "Proibido" forbidden_desc: "Oh não, não há nada aqui que te possamos mostrar! Certifica-te de que tens sessão iniciada na conta correta ou visita uma das ligações abaixo para voltares para a programação!" # user_not_found: "User Not Found" not_found: "Não Encontrado" not_found_desc: "Hm, não há nada aqui. Visita uma das ligações seguintes para voltares para a programação!" not_allowed: "Método não permitido." timeout: "O Servidor Expirou" conflict: "Conflito de recursos." bad_input: "Má entrada." server_error: "Erro do servidor." unknown: "Erro Desconhecido" error: "ERRO" general_desc: "Algo correu mal, e, provavelmente, a culpa é nossa. Tenta esperar um pouco e depois recarregar a página, ou visita uma das ligações seguintes para voltares para a programação!" resources: level: "Nível" patch: "Atualização" patches: "Atualizações" system: "Sistema" systems: "Sistemas" component: "Componente" components: "Componentes" hero: "Herói" campaigns: "Campanhas" concepts: # advanced_css_rules: "Advanced CSS Rules" # advanced_css_selectors: "Advanced CSS Selectors" # advanced_html_attributes: "Advanced HTML Attributes" # advanced_html_tags: "Advanced HTML Tags" # algorithm_average: "Algorithm Average" # algorithm_find_minmax: "Algorithm Find Min/Max" # algorithm_search_binary: "Algorithm Search Binary" # algorithm_search_graph: "Algorithm Search Graph" # algorithm_sort: "Algorithm Sort" # algorithm_sum: "Algorithm Sum" arguments: "Argumentos" arithmetic: "Aritmética" # array_2d: "2D Array" # array_index: "Array Indexing" # array_iterating: "Iterating Over Arrays" # array_literals: "Array Literals" # array_searching: "Array Searching" # array_sorting: "Array Sorting" arrays: "'Arrays'" # basic_css_rules: "Basic CSS rules" # basic_css_selectors: "Basic CSS selectors" # basic_html_attributes: "Basic HTML Attributes" # basic_html_tags: "Basic HTML Tags" basic_syntax: "Sintaxe Básica" binary: "Binário" # boolean_and: "Boolean And" # boolean_inequality: "Boolean Inequality" # boolean_equality: "Boolean Equality" # boolean_greater_less: "Boolean Greater/Less" # boolean_logic_shortcircuit: "Boolean Logic Shortcircuiting" # boolean_not: "Boolean Not" # boolean_operator_precedence: "Boolean Operator Precedence" # boolean_or: "Boolean Or" # boolean_with_xycoordinates: "Coordinate Comparison" # bootstrap: "Bootstrap" break_statements: "Declarações 'Break'" classes: "Classes" continue_statements: "Declarações 'Continue'" # dom_events: "DOM Events" # dynamic_styling: "Dynamic Styling" events: "Eventos" # event_concurrency: "Event Concurrency" # event_data: "Event Data" # event_handlers: "Event Handlers" # event_spawn: "Spawn Event" for_loops: "'For Loops'" # for_loops_nested: "Nested For Loops" # for_loops_range: "For Loops Range" functions: "Funções" functions_parameters: "Parâmetros" functions_multiple_parameters: "Multiplos Parâmetros" # game_ai: "Game AI" # game_goals: "Game Goals" # game_spawn: "Game Spawn" graphics: "Gráficos" # graphs: "Graphs" # heaps: "Heaps" # if_condition: "Conditional If Statements" # if_else_if: "If/Else If Statements" # if_else_statements: "If/Else Statements" if_statements: "Declarações 'If'" # if_statements_nested: "Nested If Statements" # indexing: "Array Indexes" # input_handling_flags: "Input Handling - Flags" # input_handling_keyboard: "Input Handling - Keyboard" # input_handling_mouse: "Input Handling - Mouse" # intermediate_css_rules: "Intermediate CSS Rules" # intermediate_css_selectors: "Intermediate CSS Selectors" # intermediate_html_attributes: "Intermediate HTML Attributes" # intermediate_html_tags: "Intermediate HTML Tags" jquery: "jQuery" # jquery_animations: "jQuery Animations" # jquery_filtering: "jQuery Element Filtering" # jquery_selectors: "jQuery Selectors" # length: "Array Length" # math_coordinates: "Coordinate Math" math_geometry: "Geometria" math_operations: "Operações Matemáticas" # math_proportions: "Proportion Math" math_trigonometry: "Trigonometria" object_literals: "'Object Literals'" parameters: "Parâmetros" programs: "Programas" properties: "Propriedades" # property_access: "Accessing Properties" # property_assignment: "Assigning Properties" # property_coordinate: "Coordinate Property" # queues: "Data Structures - Queues" # reading_docs: "Reading the Docs" recursion: "Recursão" # return_statements: "Return Statements" # stacks: "Data Structures - Stacks" strings: "'Strings'" # strings_concatenation: "String Concatenation" # strings_substrings: "Substring" trees: "Estruturas de Dados - Árvores" variables: "Variáveis" vectors: "Vetores" # while_condition_loops: "While Loops with Conditionals" # while_loops_simple: "While Loops" # while_loops_nested: "Nested While Loops" xy_coordinates: "Pares de Coordenadas" advanced_strings: "'Strings' Avançadas" # Rest of concepts are deprecated algorithms: "Algoritmos" boolean_logic: "Lógica Booleana" basic_html: "HTML Básico" basic_css: "CSS Básico" # basic_web_scripting: "Basic Web Scripting" intermediate_html: "HTML Intermédio" intermediate_css: "CSS Intermédio" # intermediate_web_scripting: "Intermediate Web Scripting" advanced_html: "HTML Avançado" advanced_css: "CSS Avançado" # advanced_web_scripting: "Advanced Web Scripting" input_handling: "Manuseamento de 'Input'" while_loops: "'Loops While'" # place_game_objects: "Place game objects" construct_mazes: "Construir labirintos" # create_playable_game: "Create a playable, sharable game project" # alter_existing_web_pages: "Alter existing web pages" # create_sharable_web_page: "Create a sharable web page" # basic_input_handling: "Basic Input Handling" # basic_game_ai: "Basic Game AI" basic_javascript: "JavaScript Básico" # basic_event_handling: "Basic Event Handling" # create_sharable_interactive_web_page: "Create a sharable interactive web page" anonymous_teacher: # notify_teacher: "Notify Teacher" # create_teacher_account: "Create free teacher account" enter_student_name: "O teu nome:" enter_teacher_email: "O e-mail do teu professor:" teacher_email_placeholder: "PI:EMAIL:<EMAIL>END_PI" student_name_placeholder: "escreve o teu nome aqui" teachers_section: "Professores:" students_section: "Estudantes:" # teacher_notified: "We've notified your teacher that you want to play more CodeCombat in your classroom!" delta: added: "Adicionado" modified: "Modificado" not_modified: "Não Modificado" deleted: "Eliminado" moved_index: "Índice Movido" text_diff: "Diferença de Texto" merge_conflict_with: "FUNDIR CONFLITO COM" no_changes: "Sem Alterações" legal: page_title: "Legal" opensource_introduction: "O CodeCombat faz parte da comunidade open source." opensource_description_prefix: "Confere " github_url: "o nosso GitHub" opensource_description_center: "e ajuda se quiseres! O CodeCombat é construído tendo por base dezenas de projetos open source, os quais nós amamos. Vê " archmage_wiki_url: "a nossa wiki dos Arcomagos" opensource_description_suffix: "para uma lista do software que faz com que este jogo seja possível." practices_title: "Melhores Práticas Respeitosas" practices_description: "Estas são as nossas promessas para contigo, o jogador, com um pouco menos de politiquices." privacy_title: "Privacidade" privacy_description: "Nós não vamos vender nenhuma das tuas informações pessoais." security_title: "Segurança" security_description: "Nós lutamos para manter as tuas informações pessoais seguras. Sendo um projeto open source, o nosso sítio tem o código disponível, pelo que qualquer pessoa pode rever e melhorar os nossos sistemas de segurança." email_title: "E-mail" email_description_prefix: "Nós não te inundaremos com spam. Através das" email_settings_url: "tuas definições de e-mail" email_description_suffix: "ou através de ligações presentes nos e-mails que enviamos, podes mudar as tuas preferências e parar a tua subscrição facilmente, em qualquer momento." cost_title: "Custo" cost_description: "O CodeCombat é gratuito para os níveis fundamentais, com uma subscrição de ${{price}} USD/mês para acederes a ramos de níveis extra e {{gems}} gemas de bónus por mês. Podes cancelar com um clique, e oferecemos uma garantia de 100% de devolução do dinheiro." copyrights_title: "Direitos Autorais e Licensas" contributor_title: "Contrato de Licença do Contribuinte (CLA)" contributor_description_prefix: "Todas as contribuições, tanto no sítio como no nosso repositório GitHub, estão sujeitas ao nosso" cla_url: "CLA" contributor_description_suffix: "com o qual deves concordar antes de contribuir." # code_title: "Client-Side Code - MIT" # client_code_description_prefix: "All client-side code for codecombat.com in the public GitHub repository and in the codecombat.com database, is licensed under the" mit_license_url: "Licença do MIT" code_description_suffix: "Isto inclui todo o código dentro dos Sistemas e dos Componentes, o qual é disponibilizado pelo CodeCombat para a criação de níveis." art_title: "Arte/Música - Creative Commons " art_description_prefix: "Todos os conteúdos comuns estão disponíveis à luz da" cc_license_url: "Licença 'Creative Commons Attribution 4.0 International'" art_description_suffix: "Conteúdo comum é, geralmente, qualquer coisa disponibilizada pelo CodeCombat com o propósito de criar Níveis. Isto inclui:" art_music: "Música" art_sound: "Som" art_artwork: "Arte" art_sprites: "Sprites" art_other: "Quaisquer e todos os trabalhos criativos não-código que são disponibilizados aquando da criação de Níveis." # art_access: "Currently there is no universal, easy system for fetching these assets. In general, fetch them from the URLs as used by the site, contact us for assistance, or help us in extending the site to make these assets more easily accessible." # art_paragraph_1: "For attribution, please name and link to codecombat.com near where the source is used or where appropriate for the medium. For example:" use_list_1: "Se usado num filme ou noutro jogo, inclui 'codecombat.com' nos créditos." # use_list_2: "If used on a website, include a link near the usage, for example underneath an image, or in a general attributions page where you might also mention other Creative Commons works and open source software being used on the site. Something that's already clearly referencing CodeCombat, such as a blog post mentioning CodeCombat, does not need some separate attribution." # art_paragraph_2: "If the content being used is created not by CodeCombat but instead by a user of codecombat.com, attribute them instead, and follow attribution directions provided in that resource's description if there are any." rights_title: "Direitos Reservados" rights_desc: "Todos os direitos estão reservados aos próprios Níveis. Isto inclui" rights_scripts: "Scripts" rights_unit: "Configurações das unidades" rights_writings: "Textos" rights_media: "Mídia (sons, música) e quaisquer outros conteúdos criativos feitos especificamente para esse Nível e que não foram disponibilizados para a criação de Níveis." # rights_clarification: "To clarify, anything that is made available in the Level Editor for the purpose of making levels is under CC, whereas the content created with the Level Editor or uploaded in the course of creation of Levels is not." nutshell_title: "Resumidamente" nutshell_description: "Qualquer um dos recursos que fornecemos no Editor de Níveis são de uso livre para criares Níveis. Mas reservamos o direito de distribuição restrita dos próprios Níveis (que são criados em codecombat.com) pelo que podemos cobrar por eles no futuro, se for isso que acabar por acontecer." # nutshell_see_also: "See also:" canonical: "A versão Inglesa deste documento é a versão definitiva e soberana. Se houver discrepâncias entre traduções, o documento Inglês prevalece." third_party_title: "Serviços de Terceiros" third_party_description: "O CodeCombat usa os seguintes serviços de terceiros (entre outros):" cookies_message: "O CodeCombat usa alguns cookies essenciais e não-essenciais." cookies_deny: "Recusar cookies não-essenciais" ladder_prizes: title: "Prémios do Torneio" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Estes prémios serão entregues de acordo com" blurb_2: "as regras do torneio" blurb_3: "aos melhores jogadores humanos e ogres." blurb_4: "Duas equipas significam o dobro dos prémios!" blurb_5: "(Haverá dois vencedores em primeiro lugar, dois em segundo, etc.)" rank: "Classificação" prizes: "Prémios" total_value: "Valor Total" in_cash: "em dinheiro" custom_wizard: "Um Feiticeiro do CodeCombat Personalizado" custom_avatar: "Um Avatar do CodeCombat Personalizado" heap: "para seis meses de acesso \"Startup\"" credits: "créditos" one_month_coupon: "cupão: escolhe Rails ou HTML" one_month_discount: "desconto de 30%: escolhe Rails ou HTML" license: "licença" oreilly: "ebook à tua escolha" calendar: year: "Ano" day: "Dia" month: "Mês" january: "janeiro" february: "fevereiro" march: "março" april: "abril" may: "maio" june: "junho" july: "julho" august: "agosto" september: "setembro" october: "outubro" november: "novembro" december: "dezembro" # code_play_create_account_modal: # title: "You did it!" # This section is only needed in US, UK, Mexico, India, and Germany # body: "You are now on your way to becoming a master coder. Sign up to receive an extra <strong>100 Gems</strong> & you will also be entered for a chance to <strong>win $2,500 & other Lenovo Prizes</strong>." # sign_up: "Sign up & keep coding ▶" # victory_sign_up_poke: "Create a free account to save your code & be entered for a chance to win prizes!" # victory_sign_up: "Sign up & be entered to <strong>win $2,500</strong>" server_error: email_taken: "E-mail já escolhido" username_taken: "Nome PI:NAME:<NAME>END_PI" esper: line_no: "Linha $1: " # uncaught: "Uncaught $1" # $1 will be an error type, eg "Uncaught SyntaxError" # reference_error: "ReferenceError: " # argument_error: "ArgumentError: " # type_error: "TypeError: " # syntax_error: "SyntaxError: " error: "Erro: " x_not_a_function: "$1 não é uma função" x_not_defined: "$1 não está definido" # spelling_issues: "Look out for spelling issues: did you mean `$1` instead of `$2`?" # capitalization_issues: "Look out for capitalization: `$1` should be `$2`." # py_empty_block: "Empty $1. Put 4 spaces in front of statements inside the $2 statement." # fx_missing_paren: "If you want to call `$1` as a function, you need `()`'s" # unmatched_token: "Unmatched `$1`. Every opening `$2` needs a closing `$3` to match it." # unterminated_string: "Unterminated string. Add a matching `\"` at the end of your string." # missing_semicolon: "Missing semicolon." # missing_quotes: "Missing quotes. Try `$1`" # argument_type: "`$1`'s argument `$2` should have type `$3`, but got `$4`: `$5`." # argument_type2: "`$1`'s argument `$2` should have type `$3`, but got `$4`." # target_a_unit: "Target a unit." # attack_capitalization: "Attack $1, not $2. (Capital letters are important.)" # empty_while: "Empty while statement. Put 4 spaces in front of statements inside the while statement." # line_of_site: "`$1`'s argument `$2` has a problem. Is there an enemy within your line-of-sight yet?" # need_a_after_while: "Need a `$1` after `$2`." # too_much_indentation: "Too much indentation at the beginning of this line." # missing_hero: "Missing `$1` keyword; should be `$2`." # takes_no_arguments: "`$1` takes no arguments." # no_one_named: "There's no one named \"$1\" to target." # separated_by_comma: "Function calls paramaters must be seperated by `,`s" # protected_property: "Can't read protected property: $1" # need_parens_to_call: "If you want to call `$1` as function, you need `()`'s" # expected_an_identifier: "Expected an identifier and instead saw '$1'." # unexpected_identifier: "Unexpected identifier" # unexpected_end_of: "Unexpected end of input" # unnecessary_semicolon: "Unnecessary semicolon." # unexpected_token_expected: "Unexpected token: expected $1 but found $2 while parsing $3" # unexpected_token: "Unexpected token $1" unexpected_token2: "Símbolo inesperado" unexpected_number: "Número inesperado" # unexpected: "Unexpected '$1'." # escape_pressed_code: "Escape pressed; code aborted." # target_an_enemy: "Target an enemy by name, like `$1`, not the string `$2`." # target_an_enemy_2: "Target an enemy by name, like $1." # cannot_read_property: "Cannot read property '$1' of undefined" # attempted_to_assign: "Attempted to assign to readonly property." # unexpected_early_end: "Unexpected early end of program." # you_need_a_string: "You need a string to build; one of $1" # unable_to_get_property: "Unable to get property '$1' of undefined or null reference" # TODO: Do we translate undefined/null? # code_never_finished_its: "Code never finished. It's either really slow or has an infinite loop." # unclosed_string: "Unclosed string." # unmatched: "Unmatched '$1'." # error_you_said_achoo: "You said: $1, but the password is: $2. (Capital letters are important.)" # indentation_error_unindent_does: "Indentation Error: unindent does not match any outer indentation level" # indentation_error: "Indentation error." # need_a_on_the: "Need a `:` on the end of the line following `$1`." # attempt_to_call_undefined: "attempt to call '$1' (a nil value)" # unterminated: "Unterminated `$1`" # target_an_enemy_variable: "Target an $1 variable, not the string $2. (Try using $3.)" # error_use_the_variable: "Use the variable name like `$1` instead of a string like `$2`" # indentation_unindent_does_not: "Indentation unindent does not match any outer indentation level" # unclosed_paren_in_function_arguments: "Unclosed $1 in function arguments." # unexpected_end_of_input: "Unexpected end of input" # there_is_no_enemy: "There is no `$1`. Use `$2` first." # Hints start here try_herofindnearestenemy: "Experimenta `$1`" there_is_no_function: "Não há nenhuma função `$1`, mas `$2` tem um método `$3`." # attacks_argument_enemy_has: "`$1`'s argument `$2` has a problem." # is_there_an_enemy: "Is there an enemy within your line-of-sight yet?" # target_is_null_is: "Target is $1. Is there always a target to attack? (Use $2?)" hero_has_no_method: "`$1` não tem nenhum método `$2`." there_is_a_problem: "Há um problema com o teu código." # did_you_mean: "Did you mean $1? You do not have an item equipped with that skill." # missing_a_quotation_mark: "Missing a quotation mark. " # missing_var_use_var: "Missing `$1`. Use `$2` to make a new variable." # you_do_not_have: "You do not have an item equipped with the $1 skill." # put_each_command_on: "Put each command on a separate line" # are_you_missing_a: "Are you missing a '$1' after '$2'? " # your_parentheses_must_match: "Your parentheses must match." # apcsp: # title: "AP Computer Science Principals | College Board Endorsed" # meta_description: "CodeCombat’s comprehensive curriculum and professional development program are all you need to offer College Board’s newest computer science course to your students." # syllabus: "AP CS Principles Syllabus" # syllabus_description: "Use this resource to plan CodeCombat curriculum for your AP Computer Science Principles class." # computational_thinking_practices: "Computational Thinking Practices" # learning_objectives: "Learning Objectives" # curricular_requirements: "Curricular Requirements" # unit_1: "Unit 1: Creative Technology" # unit_1_activity_1: "Unit 1 Activity: Technology Usability Review" # unit_2: "Unit 2: Computational Thinking" # unit_2_activity_1: "Unit 2 Activity: Binary Sequences" # unit_2_activity_2: "Unit 2 Activity: Computing Lesson Project" # unit_3: "Unit 3: Algorithms" # unit_3_activity_1: "Unit 3 Activity: Algorithms - Hitchhiker's Guide" # unit_3_activity_2: "Unit 3 Activity: Simulation - Predator & Prey" # unit_3_activity_3: "Unit 3 Activity: Algorithms - Pair Design and Programming" # unit_4: "Unit 4: Programming" # unit_4_activity_1: "Unit 4 Activity: Abstractions" # unit_4_activity_2: "Unit 4 Activity: Searching & Sorting" # unit_4_activity_3: "Unit 4 Activity: Refactoring" # unit_5: "Unit 5: The Internet" # unit_5_activity_1: "Unit 5 Activity: How the Internet Works" # unit_5_activity_2: "Unit 5 Activity: Internet Simulator" # unit_5_activity_3: "Unit 5 Activity: Chat Room Simulation" # unit_5_activity_4: "Unit 5 Activity: Cybersecurity" # unit_6: "Unit 6: Data" # unit_6_activity_1: "Unit 6 Activity: Introduction to Data" # unit_6_activity_2: "Unit 6 Activity: Big Data" # unit_6_activity_3: "Unit 6 Activity: Lossy & Lossless Compression" # unit_7: "Unit 7: Personal & Global Impact" # unit_7_activity_1: "Unit 7 Activity: Personal & Global Impact" # unit_7_activity_2: "Unit 7 Activity: Crowdsourcing" # unit_8: "Unit 8: Performance Tasks" # unit_8_description: "Prepare students for the Create Task by building their own games and practicing key concepts." # unit_8_activity_1: "Create Task Practice 1: Game Development 1" # unit_8_activity_2: "Create Task Practice 2: Game Development 2" # unit_8_activity_3: "Create Task Practice 3: Game Development 3" # unit_9: "Unit 9: AP Review" # unit_10: "Unit 10: Post-AP" # unit_10_activity_1: "Unit 10 Activity: Web Quiz" # parent_landing: # slogan_quote: "\"CodeCombat is really fun, and you learn a lot.\"" # quote_attr: "5th Grader, Oakland, CA" # refer_teacher: "Refer a Teacher" # focus_quote: "Unlock your child's future" # value_head1: "The most engaging way to learn typed code" # value_copy1: "CodeCombat is child’s personal tutor. Covering material aligned with national curriculum standards, your child will program algorithms, build websites and even design their own games." # value_head2: "Building critical skills for the 21st century" # value_copy2: "Your kids will learn how to navigate and become citizens in the digital world. CodeCombat is a solution that enhances your child’s critical thinking and resilience." # value_head3: "Heroes that your child will love" # value_copy3: "We know how important fun and engagement is for the developing brain, so we’ve packed in as much learning as we can while wrapping it up in a game they'll love." # dive_head1: "Not just for software engineers" # dive_intro: "Computer science skills have a wide range of applications. Take a look at a few examples below!" # medical_flag: "Medical Applications" # medical_flag_copy: "From mapping of the human genome to MRI machines, coding allows us to understand the body in ways we’ve never been able to before." # explore_flag: "Space Exploration" # explore_flag_copy: "Apollo got to the Moon thanks to hardworking human computers, and scientists use computer programs to analyze the gravity of planets and search for new stars." # filmaking_flag: "Filmmaking and Animation" # filmaking_flag_copy: "From the robotics of Jurassic Park to the incredible animation of Dreamworks and Pixar, films wouldn’t be the same without the digital creatives behind the scenes." # dive_head2: "Games are important for learning" # dive_par1: "Multiple studies have found that game-based learning promotes" # dive_link1: "cognitive development" # dive_par2: "in kids while also proving to be" # dive_link2: "more effective" # dive_par3: "in helping students" # dive_link3: "learn and retain knowledge" # dive_par4: "," # dive_link4: "concentrate" # dive_par5: ", and perform at a higher level of achievement." # dive_par6: "Game based learning is also good for developing" # dive_link5: "resilience" # dive_par7: ", cognitive reasoning, and" # dive_par8: ". Science is just telling us what learners already know. Children learn best by playing." # dive_link6: "executive functions" # dive_head3: "Team up with teachers" # dive_3_par1: "In the future, " # dive_3_link1: "coding is going to be as fundamental as learning to read and write" # dive_3_par2: ". We’ve worked closely with teachers to design and develop our content, and we can't wait to get your kids learning. Educational technology programs like CodeCombat work best when the teachers implement them consistently. Help us make that connection by introducing us to your child’s teachers!" # mission: "Our mission: to teach and engage" # mission1_heading: "Coding for today's generation" # mission2_heading: "Preparing for the future" # mission3_heading: "Supported by parents like you" # mission1_copy: "Our education specialists work closely with teachers to meet children where they are in the educational landscape. Kids learn skills that can be applied outside of the game because they learn how to solve problems, no matter what their learning style is." # mission2_copy: "A 2016 survey showed that 64% of girls in 3-5th grade want to learn how to code. There were 7 million job openings in 2015 required coding skills. We built CodeCombat because every child should be given a chance to create their best future." # mission3_copy: "At CodeCombat, we’re parents. We’re coders. We’re educators. But most of all, we’re people who believe in giving our kids the best opportunity for success in whatever it is they decide to do." # parent_modal: # refer_teacher: "Refer Teacher" # name: "PI:NAME:<NAME>END_PI" # parent_email: "Your Email" # teacher_email: "Teacher's Email" # message: "Message" # custom_message: "I just found CodeCombat and thought it'd be a great program for your classroom! It's a computer science learning platform with standards-aligned curriculum.\n\nComputer literacy is so important and I think this would be a great way to get students engaged in learning to code." # send: "Send Email" # hoc_2018: # banner: "Welcome to Hour of Code 2019!" # page_heading: "Your students will learn to code by building their own game!" # step_1: "Step 1: Watch Video Overview" # step_2: "Step 2: Try it Yourself" # step_3: "Step 3: Download Lesson Plan" # try_activity: "Try Activity" # download_pdf: "Download PDF" # teacher_signup_heading: "Turn Hour of Code into a Year of Code" # teacher_signup_blurb: "Everything you need to teach computer science, no prior experience needed." # teacher_signup_input_blurb: "Get first course free:" # teacher_signup_input_placeholder: "Teacher email address" # teacher_signup_input_button: "Get CS1 Free" # activities_header: "More Hour of Code Activities" # activity_label_1: "Escape the Dungeon!" # activity_label_2: " Beginner: Build a Game!" # activity_label_3: "Advanced: Build an Arcade Game!" # activity_button_1: "View Lesson" # about: "About CodeCombat" # about_copy: "A game-based, standards-aligned computer science program that teaches real, typed Python and JavaScript." # point1: "✓ Scaffolded" # point2: "✓ Differentiated" # point3: "✓ Assessments" # point4: "✓ Project-based courses" # point5: "✓ Student tracking" # point6: "✓ Full lesson plans" # title: "HOUR OF CODE 2019" # acronym: "HOC" # hoc_2018_interstitial: # welcome: "Welcome to CodeCombat's Hour of Code 2019!" # educator: "I'm an educator" # show_resources: "Show me teacher resources!" # student: "I'm a student" # ready_to_code: "I'm ready to code!" # hoc_2018_completion: # congratulations: "Congratulations on completing <b>Code, Play, Share!</b>" # send: "Send your Hour of Code game to friends and family!" # copy: "Copy URL" # get_certificate: "Get a certificate of completion to celebrate with your class!" # get_cert_btn: "Get Certificate" # first_name: "PI:NAME:<NAME>END_PI" # last_initial: "Last Initial" # teacher_email: "Teacher's email address" # school_administrator: # title: "School Administrator Dashboard" # my_teachers: "My Teachers" # last_login: "Last Login" # licenses_used: "licenses used" # total_students: "total students" # active_students: "active students" # projects_created: "projects created" # other: "Other" # notice: "The following school administrators have view-only access to your classroom data:" # add_additional_teacher: "Need to add an additional teacher? Contact your CodeCombat Account Manager or email PI:EMAIL:<EMAIL>END_PI. " # license_stat_description: "Licenses available accounts for the total number of licenses available to the teacher, including Shared Licenses." # students_stat_description: "Total students accounts for all students across all classrooms, regardless of whether they have licenses applied." # active_students_stat_description: "Active students counts the number of students that have logged into CodeCombat in the last 60 days." # project_stat_description: "Projects created counts the total number of Game and Web development projects that have been created." # no_teachers: "You are not administrating any teachers." # interactives: # phenomenal_job: "Phenomenal Job!" # try_again: "Whoops, try again!" # select_statement_left: "Whoops, select a statement from the left before hitting \"Submit.\"" # fill_boxes: "Whoops, make sure to fill all boxes before hitting \"Submit.\"" # browser_recommendation: # title: "CodeCombat works best on Chrome!" # pitch_body: "For the best CodeCombat experience we recommend using the latest version of Chrome. Download the latest version of chrome by clicking the button below!" # download: "Download Chrome" # ignore: "Ignore"
[ { "context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nmodule.exports = (func, wa", "end": 35, "score": 0.9997158050537109, "start": 21, "tag": "NAME", "value": "Jesse Grosjean" } ]
atom/packages/foldingtext-for-atom/lib/editor/raf-debounce.coffee
prookie/dotfiles-1
0
# Copyright (c) 2015 Jesse Grosjean. All rights reserved. module.exports = (func, wait, immediate) -> -> args = arguments context = this timeout = null later = -> timeout = null if not immediate func.apply(context, args) callNow = immediate and not timeout if wait is undefined cancelAnimationFrame(timeout) timeout = requestAnimationFrame(later) else clearTimeout(timeout) timeout = setTimeout(later, wait) if callNow func.apply(context, args)
72493
# Copyright (c) 2015 <NAME>. All rights reserved. module.exports = (func, wait, immediate) -> -> args = arguments context = this timeout = null later = -> timeout = null if not immediate func.apply(context, args) callNow = immediate and not timeout if wait is undefined cancelAnimationFrame(timeout) timeout = requestAnimationFrame(later) else clearTimeout(timeout) timeout = setTimeout(later, wait) if callNow func.apply(context, args)
true
# Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. module.exports = (func, wait, immediate) -> -> args = arguments context = this timeout = null later = -> timeout = null if not immediate func.apply(context, args) callNow = immediate and not timeout if wait is undefined cancelAnimationFrame(timeout) timeout = requestAnimationFrame(later) else clearTimeout(timeout) timeout = setTimeout(later, wait) if callNow func.apply(context, args)
[ { "context": "on/json'\n body:\n name: 'first'\n callback: (res, data) ->\n ", "end": 653, "score": 0.9872773885726929, "start": 648, "tag": "NAME", "value": "first" }, { "context": "on/json'\n body:\n name: 'second'\n callback: (res, data) ->\n ", "end": 1344, "score": 0.9858454465866089, "start": 1338, "tag": "NAME", "value": "second" }, { "context": " test\n path: path + \"?where=name%3D'first'\"\n method: 'PUT'\n headers:\n", "end": 1618, "score": 0.7479658126831055, "start": 1613, "tag": "NAME", "value": "first" }, { "context": "on/json'\n body:\n name: 'updatedfirst',\n geom: 'POINT (-48.23456 20.1234", "end": 1772, "score": 0.9686411619186401, "start": 1760, "tag": "NAME", "value": "updatedfirst" } ]
test/specs/resources/rows.coffee
letsface/postgresql-http-server
13
assert = require 'assert' test = require('../utils').test path = '/db/test/schemas/testschema/tables/testtable/rows' describe 'Rows resource', -> it 'should answer first GET with empty recordset', (done) -> test path: path method: 'GET' callback: (res, data) -> assert data.length is 0, '#{data.length} should be 0' done() it 'should answer a POST with status 201', (done) -> test path: path method: 'POST' headers: 'Content-Type': 'application/json' body: name: 'first' callback: (res, data) -> assert res.statusCode is 201, "#{res.statusCode} should be 201" done() it 'should answer second GET with single record in recordset', (done) -> test path: path method: 'GET' callback: (res, data) -> assert data.length is 1, '#{data.length} should be 1' done() it 'should answer a second POST with status 201', (done) -> test path: path method: 'POST' headers: 'Content-Type': 'application/json' body: name: 'second' callback: (res, data) -> assert res.statusCode is 201, "#{res.statusCode} should be 201" done() it 'should answer a PUT with status 200', (done) -> test path: path + "?where=name%3D'first'" method: 'PUT' headers: 'Content-Type': 'application/json' body: name: 'updatedfirst', geom: 'POINT (-48.23456 20.12345)' callback: (res, data) -> assert res.statusCode is 200, "#{res.statusCode} should be 200" done() it 'should answer third GET with single record in recordset', (done) -> test path: path + "?where=name%3D'updatedfirst'" method: 'GET' callback: (res, data) -> assert data.length is 1, "#{data.length} should be 1" done() it 'should DELETE all records', (done) -> test path: path method: 'DELETE' callback: (res, data) -> assert res.statusCode is 200, "#{res.statusCode} should be 200" done()
170403
assert = require 'assert' test = require('../utils').test path = '/db/test/schemas/testschema/tables/testtable/rows' describe 'Rows resource', -> it 'should answer first GET with empty recordset', (done) -> test path: path method: 'GET' callback: (res, data) -> assert data.length is 0, '#{data.length} should be 0' done() it 'should answer a POST with status 201', (done) -> test path: path method: 'POST' headers: 'Content-Type': 'application/json' body: name: '<NAME>' callback: (res, data) -> assert res.statusCode is 201, "#{res.statusCode} should be 201" done() it 'should answer second GET with single record in recordset', (done) -> test path: path method: 'GET' callback: (res, data) -> assert data.length is 1, '#{data.length} should be 1' done() it 'should answer a second POST with status 201', (done) -> test path: path method: 'POST' headers: 'Content-Type': 'application/json' body: name: '<NAME>' callback: (res, data) -> assert res.statusCode is 201, "#{res.statusCode} should be 201" done() it 'should answer a PUT with status 200', (done) -> test path: path + "?where=name%3D'<NAME>'" method: 'PUT' headers: 'Content-Type': 'application/json' body: name: '<NAME>', geom: 'POINT (-48.23456 20.12345)' callback: (res, data) -> assert res.statusCode is 200, "#{res.statusCode} should be 200" done() it 'should answer third GET with single record in recordset', (done) -> test path: path + "?where=name%3D'updatedfirst'" method: 'GET' callback: (res, data) -> assert data.length is 1, "#{data.length} should be 1" done() it 'should DELETE all records', (done) -> test path: path method: 'DELETE' callback: (res, data) -> assert res.statusCode is 200, "#{res.statusCode} should be 200" done()
true
assert = require 'assert' test = require('../utils').test path = '/db/test/schemas/testschema/tables/testtable/rows' describe 'Rows resource', -> it 'should answer first GET with empty recordset', (done) -> test path: path method: 'GET' callback: (res, data) -> assert data.length is 0, '#{data.length} should be 0' done() it 'should answer a POST with status 201', (done) -> test path: path method: 'POST' headers: 'Content-Type': 'application/json' body: name: 'PI:NAME:<NAME>END_PI' callback: (res, data) -> assert res.statusCode is 201, "#{res.statusCode} should be 201" done() it 'should answer second GET with single record in recordset', (done) -> test path: path method: 'GET' callback: (res, data) -> assert data.length is 1, '#{data.length} should be 1' done() it 'should answer a second POST with status 201', (done) -> test path: path method: 'POST' headers: 'Content-Type': 'application/json' body: name: 'PI:NAME:<NAME>END_PI' callback: (res, data) -> assert res.statusCode is 201, "#{res.statusCode} should be 201" done() it 'should answer a PUT with status 200', (done) -> test path: path + "?where=name%3D'PI:NAME:<NAME>END_PI'" method: 'PUT' headers: 'Content-Type': 'application/json' body: name: 'PI:NAME:<NAME>END_PI', geom: 'POINT (-48.23456 20.12345)' callback: (res, data) -> assert res.statusCode is 200, "#{res.statusCode} should be 200" done() it 'should answer third GET with single record in recordset', (done) -> test path: path + "?where=name%3D'updatedfirst'" method: 'GET' callback: (res, data) -> assert data.length is 1, "#{data.length} should be 1" done() it 'should DELETE all records', (done) -> test path: path method: 'DELETE' callback: (res, data) -> assert res.statusCode is 200, "#{res.statusCode} should be 200" done()
[ { "context": "anner contents', ->\n return currentItem({ id: 'damon-zucconi' })\n .then (item) -> item.should.containEql\n", "end": 554, "score": 0.9893999099731445, "start": 541, "tag": "NAME", "value": "damon-zucconi" } ]
apps/artist/test/components/current_eoy_listing/index.coffee
l2succes/force
1
_ = require 'underscore' Q = require 'bluebird-q' data = require '../../../../eoy_2016/fixtures/data.json' rewire = require 'rewire' currentItem = rewire '../../../components/current_eoy_listing/index' currentItem.__set__ 'fetchEOY2016Lists', () -> Q(data) describe 'current EOY listing', -> it 'returs null if the artist is not included in EOY', -> return currentItem({ id: 'o-mitted' }) .then (item) -> _.isNull(item).should.be.true() it 'returns an object describing the banner contents', -> return currentItem({ id: 'damon-zucconi' }) .then (item) -> item.should.containEql type: 'eoy', href: 'https://www.artsy.net/2016-year-in-art', imageUrl: 'http://files.artsy.net/images/eoy-2016.png', heading: 'FEATURED IN' name: 'The Most Influential Artists of 2016', detail: 'Artsy\'s Year in Art 2016',
35280
_ = require 'underscore' Q = require 'bluebird-q' data = require '../../../../eoy_2016/fixtures/data.json' rewire = require 'rewire' currentItem = rewire '../../../components/current_eoy_listing/index' currentItem.__set__ 'fetchEOY2016Lists', () -> Q(data) describe 'current EOY listing', -> it 'returs null if the artist is not included in EOY', -> return currentItem({ id: 'o-mitted' }) .then (item) -> _.isNull(item).should.be.true() it 'returns an object describing the banner contents', -> return currentItem({ id: '<NAME>' }) .then (item) -> item.should.containEql type: 'eoy', href: 'https://www.artsy.net/2016-year-in-art', imageUrl: 'http://files.artsy.net/images/eoy-2016.png', heading: 'FEATURED IN' name: 'The Most Influential Artists of 2016', detail: 'Artsy\'s Year in Art 2016',
true
_ = require 'underscore' Q = require 'bluebird-q' data = require '../../../../eoy_2016/fixtures/data.json' rewire = require 'rewire' currentItem = rewire '../../../components/current_eoy_listing/index' currentItem.__set__ 'fetchEOY2016Lists', () -> Q(data) describe 'current EOY listing', -> it 'returs null if the artist is not included in EOY', -> return currentItem({ id: 'o-mitted' }) .then (item) -> _.isNull(item).should.be.true() it 'returns an object describing the banner contents', -> return currentItem({ id: 'PI:NAME:<NAME>END_PI' }) .then (item) -> item.should.containEql type: 'eoy', href: 'https://www.artsy.net/2016-year-in-art', imageUrl: 'http://files.artsy.net/images/eoy-2016.png', heading: 'FEATURED IN' name: 'The Most Influential Artists of 2016', detail: 'Artsy\'s Year in Art 2016',
[ { "context": "__________.\"\n \"Free as in __________.\"\n \"Hi, I'm Troy McClure. You may remember me from such commit messages as", "end": 532, "score": 0.999707818031311, "start": 520, "tag": "NAME", "value": "Troy McClure" }, { "context": "rastructure? __________. For sure.\"\n \"When I told Jez Humble about our __________, he actually cried.\"\n \"When", "end": 2855, "score": 0.9994232654571533, "start": 2845, "tag": "NAME", "value": "Jez Humble" }, { "context": "\"We should replace the users with __________.\"\n \"Jordan Sissel hates __________ so much that he created a new op", "end": 7721, "score": 0.997484564781189, "start": 7708, "tag": "NAME", "value": "Jordan Sissel" }, { "context": "shed working on my rocket powered __________.\"\n \"Richard Stallman will kill you with his teeth for __________.\"\n \"", "end": 10765, "score": 0.9997337460517883, "start": 10749, "tag": "NAME", "value": "Richard Stallman" }, { "context": "ust first understand __________.\"\n \"__________ @ 127.0.0.1 -p __________\"\n \"__________? You mean __________", "end": 22052, "score": 0.9997696280479431, "start": 22043, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "k anyone was using __________!\"\n \"Good evening Dr Falken, would you like to play __________?\"\n \"IBM just ", "end": 22589, "score": 0.9992167353630066, "start": 22583, "tag": "NAME", "value": "Falken" }, { "context": "e pack that solved the problem of __________.\"\n \"Lennart Poettering's latest project is __________.\"\n \"__________ is", "end": 27092, "score": 0.9797942042350769, "start": 27074, "tag": "NAME", "value": "Lennart Poettering" } ]
src/blackcards.coffee
pkoro/devops-against-humanity
3
module.exports = [ "You saw __________ in prod? Logs or it didn't happen." "s/__________/__________/g" "__________, for some values of __________." "Ask me anything about __________." "Called on account of __________." "Disrupting the established players in __________ via __________." "Doge __________." "Is __________ in the cloud considered Enterprise-ready?" "Epic yak-shave caused by __________." "Facebook has acquired __________ for $10b and __________." "Free as in __________." "Hi, I'm Troy McClure. You may remember me from such commit messages as \"adds __________\" and \"reverts __________\"." "How is __________ even formed?" "I can haz __________." "Our app is like Tinder for __________" "I saw the best minds of my generation destroyed by __________." "If __________ isn't the answer, you are asking the wrong question." "If you're using __________, you're gonna have a bad time." "Nobody ever got fired for buying __________." "Running Windows in production leads to __________." "The Internet is for cat memes and __________." "Our release schedule doesn't have time for __________." "The Internet of Things will be controlled by __________." "The only thing necessary for evil to triumph is __________." "Uber is on surge pricing because of __________." "WARN: __________ has been deprecated." "Will merge pull requests for __________." "__________ was was taken down by a zero-day vulernability." "Time to schedule the postmortem for __________." "__________ - the idiots guide to __________ and __________." "But Google is using __________ so we should too!" "Etsy says we should use __________ for everything." "Have you seen the xkcd about using __________ as a replacement for __________." "This isn't going to be all unicorns and __________." "Apple just patented __________." "When I was a kid we didn't have __________." "__________ is a nice idea, lets found a start-up." "DevOps: Now with a 100% increase in __________!" "Main benefits of automation: __________ and __________." "Chef converge failed due to __________." "Then there was the time I found __________ on the root partition." "We run production on __________ and __________." "Management said it's OK to deploy __________ at 5pm on Friday." "Did you know that we have __________ on pager rotation?" "There was no good solution for __________, so we built our own using __________." "Amazon built a data center on the moon to lessen the risk of __________ causing problems." "In order to improve security, we're upgrading to __________." "The two pillars of our Continuous Deployment pipeline are __________ and __________." "I got paged at 3am because of __________." "The most stable part of our infrastructure? __________. For sure." "When I told Jez Humble about our __________, he actually cried." "When I write a book about my experiences, it'll be called \"__________, the good parts\"." "Restoring from backups failed due to __________." "My two most indispensable tools are __________ and __________." "The production data center burned down because of __________." "It turns out that the button labeled \"Don't Push\" actually kicks off __________." "You should think of your servers like __________ and not like __________." "I find Java to be way too much like __________." "It's like trying to herd __________." "I ended up having to buy a replacement for __________ on eBay." "The RIAA is suing me for downloading __________." "Security? We've got that! We use __________." "sudo pip install __________" "When I hooked the 3D printer up to the Internet, it accidentally created __________." "My next blog post will be about how we used __________ to create __________." "So, I was using Wireshark to check network traffic... Did you know we have __________ in production?" "My eyes started bleeding when I opened the editor and saw __________." "I think maybe I'll leave my experience in __________ off my resumé." "We don't need __________ - we have __________!" "Management just told me I need to get certified in __________." "Our app is like __________, but for __________." "Marketing says we're leaders in __________, but I think it's more accurate to say we specialize in __________." "Our greatest achievement in the last year is __________." "I write my code in vim because of __________." "If we make this deadline, management has promised us __________." "Sweet! I just found a Puppet module for __________!" "Last week, I created a Chef recipe for __________; this week, it's an entire cookbook for __________, Automation FTW!" "We really need to open-source our implementation of __________." "A sales rep just tried to pitch me on __________; I told them we already have __________." "Who would have known that __________ could destroy an entire datacenter?" "sudo apt-get install __________" "Our production backups are stored using __________." "We replaced our __________ with __________." "After __________ came up, the retrospective really went downhill." "You know what our app needs? More __________, and less __________." "It figures - an article about __________ was posted just as we're pivoting to __________." "In the next planning session, we'll cover __________ and __________." "Our competitive advantage is our expertise with __________." "Every time someone brings up __________, I throw up a little in my mouth." "All that we had to do to halve our response times was implement __________." "Our entire app is geared towards providing __________." "Is __________ high availabilty?" "My LinkedIn endorsements include __________ and __________." "The users are using __________ as a workaround for __________." "Robots are going to make __________ obsolete." "An error occurred: __________" "According to the logs, __________ was initially caused by __________." "We can just fix that with __________." "You can have __________, __________, or __________. Pick two." "A monad is just __________ in the category of __________, what's the problem?" "On a scale from 1 to 10, this is __________!" "We don't need configuration management, we have __________!" "__________, now with __________ support." "RedHat has announced that RHEL 8 will ship with __________." "Hey, __________ is down. Can you fix it?" "I grabbed __________ on my way out the door after our paychecks bounced and management stopped answering their phones." "Did you try __________ yet?" "I was 6 beers in when I got the pager alert that __________ was down." "Notice: Building __________ for __________" "I laughed when they said I'd be on call 24/7 but wouldn't receive a stipend for __________." "If it weren't for __________ we'd all be __________." "__________, __________ and just a few lines of Perl." "NoSQL is superior to SQL because __________." "Script kiddies got into __________ because __________." "__________ is better than Hadoop because __________." "WAIT, YOU DELETED __________??!" "It's not web scale, it's __________." "The tech support hotline told me to try __________." "Asynchronous REST API calls are the solution to __________." "Guys, seriously, if we just use __________ it will solve all our problems with __________!" "Facebook changed their profiles today because __________." "Hello. My name is __________ and I am addicted to __________." "__________ dependency hell." "That talk outline said it would be about __________, but it ended up being more like __________." "We should replace the users with __________." "Jordan Sissel hates __________ so much that he created a new opensource project called __________ to work around it." "__________ isn't a job title." "For the next project we are going to use __________ to solve __________." "My editor of choice is __________." "__________ looks good; ship it." "__________-Stack Developer" "It has been __ days since the last __________." "__________ on the server were deleted because __________." "This week, Aphyr runs __________ through jepsen." "The intern just ran __________ on the load balancer." "I need you to do __________ with __________ before __________." "Lambdas are just a lame implementation of __________." "C-x; C-__________" "The users want __________ because __________." "__________ should be deprecated in favour of __________." "__________ mismatch between __________ and __________." "I put __________ on the scripts to make it run faster." "Developers do not get access to production machines, because of __________." "Developers need access to production machines because __________." "We run __________ in a cron job every 15 minutes." "I could hire __________ to do your job!" "My next Velocity talk is called \"__________ops\"." "The RCA for the global outage was __________ compunded by __________." "I was hired to maintain this 20 year old script that runs our critical __________ infrastructure." "I know we use __________, but I wrote this critical program in __________." "I'll just have Ops spin up a couple of __________ environments." "I'm writing my next IRC bot with __________." "I cannot wait until someone makes a cluster out of __________." "C will finally be displaced by __________." "We don't need to worry about __________, we're using MongoDB." "Why is __________ better than Hadoop?" "FC067: __________" "Oh, __________ is just a hack to get __________ to run." "How do I even __________?" "__________ all the things!" "ERROR: __________ NOT FOUND" "We don't need backups, we've got __________." "Fixing your father's computer with __________." "It's always __________ DNS problem." "__________ with this one weird, old trick." "__________ isn't new, we used to do it in the '70s on mainframes." "Puppet is better than Chef because __________ and __________." "How is __________ better than __________?" "Learn __________ the hard way." "Vagrant up __________." "You can fix __________ with __________." "We took the plunge and rewrote __________ in Go." "Implementing __________ should take only 2 lines of code." "Good enough for __________ work." "Yeah, but can it run __________?" "Security through __________." "__________? You can safely ignore that. Usually." "__________ isn't cool. You know what's cool? __________." "640k RAM should be enough for __________." "__________ worked in dev." "You can't fix __________." "How hard could it be to port Linux to __________." "I just finished working on my rocket powered __________." "Richard Stallman will kill you with his teeth for __________." "DB tuning with __________." "Can anyone help me get __________ running on Cisco IOS?" "Real __________ don't use __________." "__________ on XEN." "Please bring back __________. You broke my workflow." "I cut-and-pasted this StackOverflow code for __________." "I'm just finishing up my manifesto on __________." "/r/__________." "We can discuss __________ at the stand-up meeting." "A Beowulf cluster of __________." "We're demoing __________ for __________ at SXSW." "I aliased __________ to git __________." "10 PRINT \"__________\"; GOTO 10" "alt.binaries.__________" "It is completely dark. You are likely to be eaten by __________." "Conway's Game of __________." "Next year I'll start learning to use __________." "__________ is the newest gTLD." "One does not simply open a ticket to fix __________." "Sorry, you'll need to open a ticket before we can fix __________." "ln -s __________ __________" "__________ is dead." "grep __________ | mail __________" "__________ just got pwned." "It's like __________, but with __________ and list comprehensions." "Software defined __________." "I don't have any UNIX Beards in stock, but we do have __________." "Amazon does __________, why can't we?" "I can't believe you're still using __________." "/dev/__________: Device is busy" "I tried __________, the doctors say I'll never walk again." "git --__________" "__________ Public License." "__________ begins with __________." "Couldn't we use __________?" "__________ would be so much better if we rewrote it in Clojure." "So I just found __________ and __________ running in a screen session." "Why is root running __________ under tmux?" "Instead of installing __________, what if we just used __________." "I need a webinar like I need __________." "Fuck it, time to break out the emergency stash of __________." "On the plus side, we finally got rid of __________." "__________ thought leader." "Fuck it: __________ looks good to me." "Hi, I'm Clippy the office assistant. Would you like __________ today?" "zsh: command not found: __________" "How did __________ ever work?" "Whoops, I thought that method was supposed to __________ __________." "I thought you said __________ was secure?" "git: You are in __________ state." "Why don't we just fork __________?" "The network connection dropped out because of __________." "We turned off __________ and everything magically got better." "I found a Samba share full of __________." "Just use __________. What could go wrong?" "I installed __________ by accident." "Read-eval-__________-loop." "We should try it with an actual __________." "Is __________ something we need to optimize for?" "Hack __________ into redis." "According to the W3C __________ is now considered harmful." "Never update __________ before a demonstration." "__________ is used when the CPU is on fire." "modperl can be used to implement __________." "__________ runs Ruby as root." "Larry Wall trained as a missionary then got into __________." "Listening to the fans in the server farm leads to __________." "__________ and __________ are rumoured to be working on a python module for a helicam." "A lot of disk space is needed for __________." "The installer automagically configures __________." "Whoever made the unscheduled change to production on Friday will be forced to use __________." "Never question __________." "I can't wait until we no longer use __________." "I bet if we switch to __________ it will just work." "__________ has just discovered __________. We're doomed." "A neckbeard made of __________." "False alarm, it was just __________ running __________." "__________ running on a rack of __________." "No, __________ being hopelessly broken is NOT an emergency." "Our new startup is __________ for __________." "__________ over IP" "__________ is a hardware problem." "I AM working, I'm waiting for __________ to finish." "The first rule of __________ is: You do not talk about __________." "Google Analytics says 100% of my website visitors are __________." "__________ will never get you a job at Microsoft." "4chan.org is powered by __________." "We can have __________ just like Netflix." "__________ is how I resolve all merge conflicts." "Why does someone keep re-implementing system utilities in __________?" "Remember when you told me to tell you when you were acting like __________ and __________? You're doing it now." "Our only hope at recovering the data is __________." "__________: the gift that keeps on giving." "__________ has been killed with fire. My work is done here." "Problem exists between keyboard and __________." "100% government funded __________!" "__________ certification program." "I just finished writing an API for __________." "__________ is a batch command to shut the heck up." "__________. Failed to cache catalog." "Sorry, I'm all out of __________-fu." "90% of everything is __________." "Given enough __________, all bugs are __________." "The first 90% of development is __________. The second 90% is __________." "When you logged in there, did you see __________ that said __________?" "Purely numeric hostname and not __________ -----rejecting!" "I'm pretty sure __________ isn't thread safe." "We don't have to worry about CAP Theorem because of __________." "I don't always test my code, but when I do I do it in __________." "Those who don't understand __________ are condemned to reinvent it, poorly." "The NSA is really interested in our latest project: __________." "Just change __________, it'll be fine." "Yeah, you need to modprobe __________ to get it to recognize __________." "Oh, we're devops! We have __________ in the office, but only the DBA can touch it." "We're spending 20% of this sprint doing __________." "__________ found a new OpenSSL vulernability people are calling __________." "Management has changed all our job titles to __________." "while true; do __________; done" "The consultant we hired is certain that __________ will drastically increase the performance of __________." "Could you just push this update for __________? It should be a no-op." "If we're all going to get fired, let's get fired for __________." "We can't pay you, but we can offer __________ in compensation." "A soiled napkin with the contents of __________ scribbled on it." "Who thought that __________ was a good idea?" "It's not the recommended configuration to use __________ with __________, but it's in production right now." "We wrote our own build tool based on __________." "I've received a Microsoft MVP award for __________." "We rewrote __________ in __________." "The ticket to install __________? I deletegated it." "Some people, when confronted with a problem, think \"I know, I'll use __________.\" Now they have two problems." "We only use __________, artisanally crafted by Mennonites from Ohio." "The backups are fine, but the restore process is __________." "I can't believe QA filed a bug for __________." "__________ is just one indespensible service that ops provides developers." "Oracle is proud to announce that the next edition of Java features __________." "Moving __________ will definitely break things." "__________: ci or not ci?" "I opened the server cabinet and it was full of __________." "Crossing __________ could lead to total protonic reversal." "The next big thing is __________." "I once made a robot around the concept of __________." "Nine circles of __________ hell." "I once wrote an NPM module called __________.js" "I asked the contractor for __________ and they delivered __________." "Welcome to Programming 101, our first topic will be __________." "The Genius Bar recommends you try __________." "Post-modern coding is defined by __________." "__________ | sudo sh" "__________ has been put under the WTFPLicense." "Here's __________, as I promised." "I'd like __________, __________, and a Fluttershy." "It transpiles __________ to JavaScript." "Only the Enterprise Edition™ has __________." "__________ is a proof of concept and an actual __________ __________." "The trouble with kids these days is __________." "__________ is the new Stalinism." "__________ for the win!" "__________ is the new __________." "I googled \"__________\" and \"__________\" and found conflicting information about every detail of each." "With __________, you write once, run nowhere." "__________ discontinued support for the Linux version." "A manager told me I couldn't remove our dependency on __________, but I got around it with __________." "__________ implements every single standard for __________. Poorly." "Just think of the Internet as __________." "Would you like __________ with that?" "__________? We've got that." "It took over 40 hours to document __________." "//TODO: __________." "npm install __________." "Circular imports import __________." "A firewall rule for __________." "__________ is why the jDBA thought it might be time to go to #mysql on freenode." "__________ is the only reason the jDBA survived typing \"rm -rf /\"." "__________ exists?" "It's like __________ on __________." "I came here to drink milk and deploy __________, and I've just finished my milk." "End-to-end __________." "__________ will help you remember to sanitze your database inputs." "Just RTFM, and then you'll understand __________." "__________ took EBS down again today." "I ssh'd into a server running __________ and promptly noped the fuck out of there." "__________, the final solution." "We're running __________ in production?!" "__________ has root access." "We don't have enough package managers, said __________." "__________ is more reliable than __________." "Of course culture is important to us, that's why we have __________." "I'd trust all my stuff to __________." "My kingdom for __________." "Nice, __________. I'll take it." "Such __________. Wow." "That's funny, I thought __________ used to be here?" "I can't believe you improved __________ by deleting __________." "The only thing more dangerous than __________ is a programmer with __________." "1. __________ 2. __________ 3. Profit." "Monads are easy! Just think of them as __________." "__________: powered by the cloud." "I uploaded my worm to __________." "#!/bin/__________" "make __________ && sudo make install && cowsay yay" "I bet the person who wrote this uses __________." "I'm not __________, my code is compiling." "Don't worry, we have unit tests for __________." "As a product manager, I want __________." "The only non-conformance in this year's audit was __________." "We're blaming interns for __________." "__________ is my favourite thing about __________." "I wish that we had more __________ in our office." "I've once been so drunk that __________ actually made sense." "To understand __________ you must first understand __________." "__________ @ 127.0.0.1 -p __________" "__________? You mean __________!" "__________ is coming out of stealth mode." "__________ ate all my memory!" "__________ is always a good practice." "Don't mind me, I'm just practicing __________." "The intern tripped in the server room and shut down __________." "It's easy! Just run __________." "I assure you __________ is secure!" "Our backup policy is __________." "I ran 'pacman -Syu' and it totally broke __________." "We didn't think anyone was using __________!" "Good evening Dr Falken, would you like to play __________?" "IBM just created JSONxx to encapsulate JSON in XML in __________." "I never truly understood __________ until I encountered __________." "The Agile Manifesto taught me to pick __________ over __________." "__________ should be a singleton!" "Flash is dying because of __________." "Neo, the matrix has one fatal flaw, you must find __________." "Javascript is the best language ever, thanks to __________." "Last night while drunk, the W3C declared __________ as a new web standard." "North Korea finally launched warheads because of __________." "Last night I accidentally ran sudo chmod -R 777 /. I just blamed __________." "During the lunch break I like to think about __________." "Nobody will value your work if you don't use __________." "__________, because scientists don't know how to code." "__________, because Knuth." "The entire system failed because of __________." "The meeting between Europe and the USA was cancelled because of __________." "We missed the launch window due to confusion from __________." "__________ wasted thousands of dollars." "No one can authenticate because of __________." "__________ caused the servers to melt down." "__________ invalidated all the assumptions in our monitoring system." "CAMS is outdated because of __________." "__________: Easy one-step installation" "__________, because even the hobos of Market Street need a cluster scheduler." "We need to update __________." "It's cool, they use __________ at Etsy." "Code as __________." "__________ is how the cloud works." "It looks like __________ in Opera." "__________ shell" "__________ in haskell" "Say __________ one more time; I dare you!" "The cloud runs on __________, with a bit of __________." "__________, because who needs monitoring." "This problem can be completely solved with __________ implemented in __________." "__________ vs __________... FIGHT!" "I regret to inform you your weekend has been revoked due to __________." "All alerts go to __________, which is handled by __________." "__________, it's the new pink." "I've got 99 problems but __________ ain't one." "140 characters is just enough to explain __________." "__________ all the way down." "__________ continuously spawns zombie processes." "Elliptic-Curve Diffie-Helman breaks against __________." "Why isn't my script working? Oh. __________." "ITIL best practices suggest __________ is the next step." "We would have gotten the funding, if only our slide deck included __________." "Have you tried __________ and __________?" "I left __________ in the server room." "I stuck my hand in a sysadmin's beard and pulled out __________." "Before exiting, the program kills __________." "Cookbooks containing __________ have been known to cause __________." "Once we added __________ to the firewall rules, __________ worked perfectly." "My pre-commit hook replaces tab characters with __________." "I was up all night debugging __________." "Error: insufficient __________" "The product team just handed me a spec, they want __________ in the next release of __________." "The malware came from an infected ad on __________.com" "Killing child processes releases resources back to __________." "That regular expression is designed to match __________ but not __________." "The vendor solution didn't have log aggregation, but it did have __________." "Our custom log rotation scripts have the added feature of __________." "This year, Cross-Site Request Forgery was knocked out of the OWASP Top 10, and replaced by __________." "__________ sucks, let's replace it with __________." "My pull request was rejected because it contained __________." "My stacktrace revealed __________." "Chef encountered an error attempting to create __________." "Since the 1950s, engineers have been striving toward a more effective means of generating __________." "Our code was efficient, except for the module containing __________, which was slower than __________." "I need to re-munge the CSV, replacing the commas with __________." "We strive for continuous deployment, continuous delivery, and continuous __________." "Data-driven decisions are to be replaced with __________." "The ruby gem is useless, it's a lesser implementation of __________." "Windows ME had a service pack that solved the problem of __________." "Lennart Poettering's latest project is __________." "__________ is the quickest way to identify what is burning in the server room." "Oh, we store all our docs in __________." "I accidentally deleted the whole database with __________." "It's not a bug it's __________." "__________ totally killed the mood at E3." "To replace camelCase, the new C++ standards mandate variables be named using __________." "I'm sorry __________ isn't numberwang." "I'm sorry __________ isn't wangernum." "__________ became self aware and kidnapped the sysadmins." "That's the first time I've ever seen ProGuard used to obfuscate __________." "Every day at work I implement __________ and my mother still tells her friends I \"do computers\"." "That's the first time I've ever seen comments written in __________." "It's not a problem, I'll just use __________ to fix it later." "I, for one, welcome our new __________ overlords." ]
5243
module.exports = [ "You saw __________ in prod? Logs or it didn't happen." "s/__________/__________/g" "__________, for some values of __________." "Ask me anything about __________." "Called on account of __________." "Disrupting the established players in __________ via __________." "Doge __________." "Is __________ in the cloud considered Enterprise-ready?" "Epic yak-shave caused by __________." "Facebook has acquired __________ for $10b and __________." "Free as in __________." "Hi, I'm <NAME>. You may remember me from such commit messages as \"adds __________\" and \"reverts __________\"." "How is __________ even formed?" "I can haz __________." "Our app is like Tinder for __________" "I saw the best minds of my generation destroyed by __________." "If __________ isn't the answer, you are asking the wrong question." "If you're using __________, you're gonna have a bad time." "Nobody ever got fired for buying __________." "Running Windows in production leads to __________." "The Internet is for cat memes and __________." "Our release schedule doesn't have time for __________." "The Internet of Things will be controlled by __________." "The only thing necessary for evil to triumph is __________." "Uber is on surge pricing because of __________." "WARN: __________ has been deprecated." "Will merge pull requests for __________." "__________ was was taken down by a zero-day vulernability." "Time to schedule the postmortem for __________." "__________ - the idiots guide to __________ and __________." "But Google is using __________ so we should too!" "Etsy says we should use __________ for everything." "Have you seen the xkcd about using __________ as a replacement for __________." "This isn't going to be all unicorns and __________." "Apple just patented __________." "When I was a kid we didn't have __________." "__________ is a nice idea, lets found a start-up." "DevOps: Now with a 100% increase in __________!" "Main benefits of automation: __________ and __________." "Chef converge failed due to __________." "Then there was the time I found __________ on the root partition." "We run production on __________ and __________." "Management said it's OK to deploy __________ at 5pm on Friday." "Did you know that we have __________ on pager rotation?" "There was no good solution for __________, so we built our own using __________." "Amazon built a data center on the moon to lessen the risk of __________ causing problems." "In order to improve security, we're upgrading to __________." "The two pillars of our Continuous Deployment pipeline are __________ and __________." "I got paged at 3am because of __________." "The most stable part of our infrastructure? __________. For sure." "When I told <NAME> about our __________, he actually cried." "When I write a book about my experiences, it'll be called \"__________, the good parts\"." "Restoring from backups failed due to __________." "My two most indispensable tools are __________ and __________." "The production data center burned down because of __________." "It turns out that the button labeled \"Don't Push\" actually kicks off __________." "You should think of your servers like __________ and not like __________." "I find Java to be way too much like __________." "It's like trying to herd __________." "I ended up having to buy a replacement for __________ on eBay." "The RIAA is suing me for downloading __________." "Security? We've got that! We use __________." "sudo pip install __________" "When I hooked the 3D printer up to the Internet, it accidentally created __________." "My next blog post will be about how we used __________ to create __________." "So, I was using Wireshark to check network traffic... Did you know we have __________ in production?" "My eyes started bleeding when I opened the editor and saw __________." "I think maybe I'll leave my experience in __________ off my resumé." "We don't need __________ - we have __________!" "Management just told me I need to get certified in __________." "Our app is like __________, but for __________." "Marketing says we're leaders in __________, but I think it's more accurate to say we specialize in __________." "Our greatest achievement in the last year is __________." "I write my code in vim because of __________." "If we make this deadline, management has promised us __________." "Sweet! I just found a Puppet module for __________!" "Last week, I created a Chef recipe for __________; this week, it's an entire cookbook for __________, Automation FTW!" "We really need to open-source our implementation of __________." "A sales rep just tried to pitch me on __________; I told them we already have __________." "Who would have known that __________ could destroy an entire datacenter?" "sudo apt-get install __________" "Our production backups are stored using __________." "We replaced our __________ with __________." "After __________ came up, the retrospective really went downhill." "You know what our app needs? More __________, and less __________." "It figures - an article about __________ was posted just as we're pivoting to __________." "In the next planning session, we'll cover __________ and __________." "Our competitive advantage is our expertise with __________." "Every time someone brings up __________, I throw up a little in my mouth." "All that we had to do to halve our response times was implement __________." "Our entire app is geared towards providing __________." "Is __________ high availabilty?" "My LinkedIn endorsements include __________ and __________." "The users are using __________ as a workaround for __________." "Robots are going to make __________ obsolete." "An error occurred: __________" "According to the logs, __________ was initially caused by __________." "We can just fix that with __________." "You can have __________, __________, or __________. Pick two." "A monad is just __________ in the category of __________, what's the problem?" "On a scale from 1 to 10, this is __________!" "We don't need configuration management, we have __________!" "__________, now with __________ support." "RedHat has announced that RHEL 8 will ship with __________." "Hey, __________ is down. Can you fix it?" "I grabbed __________ on my way out the door after our paychecks bounced and management stopped answering their phones." "Did you try __________ yet?" "I was 6 beers in when I got the pager alert that __________ was down." "Notice: Building __________ for __________" "I laughed when they said I'd be on call 24/7 but wouldn't receive a stipend for __________." "If it weren't for __________ we'd all be __________." "__________, __________ and just a few lines of Perl." "NoSQL is superior to SQL because __________." "Script kiddies got into __________ because __________." "__________ is better than Hadoop because __________." "WAIT, YOU DELETED __________??!" "It's not web scale, it's __________." "The tech support hotline told me to try __________." "Asynchronous REST API calls are the solution to __________." "Guys, seriously, if we just use __________ it will solve all our problems with __________!" "Facebook changed their profiles today because __________." "Hello. My name is __________ and I am addicted to __________." "__________ dependency hell." "That talk outline said it would be about __________, but it ended up being more like __________." "We should replace the users with __________." "<NAME> hates __________ so much that he created a new opensource project called __________ to work around it." "__________ isn't a job title." "For the next project we are going to use __________ to solve __________." "My editor of choice is __________." "__________ looks good; ship it." "__________-Stack Developer" "It has been __ days since the last __________." "__________ on the server were deleted because __________." "This week, Aphyr runs __________ through jepsen." "The intern just ran __________ on the load balancer." "I need you to do __________ with __________ before __________." "Lambdas are just a lame implementation of __________." "C-x; C-__________" "The users want __________ because __________." "__________ should be deprecated in favour of __________." "__________ mismatch between __________ and __________." "I put __________ on the scripts to make it run faster." "Developers do not get access to production machines, because of __________." "Developers need access to production machines because __________." "We run __________ in a cron job every 15 minutes." "I could hire __________ to do your job!" "My next Velocity talk is called \"__________ops\"." "The RCA for the global outage was __________ compunded by __________." "I was hired to maintain this 20 year old script that runs our critical __________ infrastructure." "I know we use __________, but I wrote this critical program in __________." "I'll just have Ops spin up a couple of __________ environments." "I'm writing my next IRC bot with __________." "I cannot wait until someone makes a cluster out of __________." "C will finally be displaced by __________." "We don't need to worry about __________, we're using MongoDB." "Why is __________ better than Hadoop?" "FC067: __________" "Oh, __________ is just a hack to get __________ to run." "How do I even __________?" "__________ all the things!" "ERROR: __________ NOT FOUND" "We don't need backups, we've got __________." "Fixing your father's computer with __________." "It's always __________ DNS problem." "__________ with this one weird, old trick." "__________ isn't new, we used to do it in the '70s on mainframes." "Puppet is better than Chef because __________ and __________." "How is __________ better than __________?" "Learn __________ the hard way." "Vagrant up __________." "You can fix __________ with __________." "We took the plunge and rewrote __________ in Go." "Implementing __________ should take only 2 lines of code." "Good enough for __________ work." "Yeah, but can it run __________?" "Security through __________." "__________? You can safely ignore that. Usually." "__________ isn't cool. You know what's cool? __________." "640k RAM should be enough for __________." "__________ worked in dev." "You can't fix __________." "How hard could it be to port Linux to __________." "I just finished working on my rocket powered __________." "<NAME> will kill you with his teeth for __________." "DB tuning with __________." "Can anyone help me get __________ running on Cisco IOS?" "Real __________ don't use __________." "__________ on XEN." "Please bring back __________. You broke my workflow." "I cut-and-pasted this StackOverflow code for __________." "I'm just finishing up my manifesto on __________." "/r/__________." "We can discuss __________ at the stand-up meeting." "A Beowulf cluster of __________." "We're demoing __________ for __________ at SXSW." "I aliased __________ to git __________." "10 PRINT \"__________\"; GOTO 10" "alt.binaries.__________" "It is completely dark. You are likely to be eaten by __________." "Conway's Game of __________." "Next year I'll start learning to use __________." "__________ is the newest gTLD." "One does not simply open a ticket to fix __________." "Sorry, you'll need to open a ticket before we can fix __________." "ln -s __________ __________" "__________ is dead." "grep __________ | mail __________" "__________ just got pwned." "It's like __________, but with __________ and list comprehensions." "Software defined __________." "I don't have any UNIX Beards in stock, but we do have __________." "Amazon does __________, why can't we?" "I can't believe you're still using __________." "/dev/__________: Device is busy" "I tried __________, the doctors say I'll never walk again." "git --__________" "__________ Public License." "__________ begins with __________." "Couldn't we use __________?" "__________ would be so much better if we rewrote it in Clojure." "So I just found __________ and __________ running in a screen session." "Why is root running __________ under tmux?" "Instead of installing __________, what if we just used __________." "I need a webinar like I need __________." "Fuck it, time to break out the emergency stash of __________." "On the plus side, we finally got rid of __________." "__________ thought leader." "Fuck it: __________ looks good to me." "Hi, I'm Clippy the office assistant. Would you like __________ today?" "zsh: command not found: __________" "How did __________ ever work?" "Whoops, I thought that method was supposed to __________ __________." "I thought you said __________ was secure?" "git: You are in __________ state." "Why don't we just fork __________?" "The network connection dropped out because of __________." "We turned off __________ and everything magically got better." "I found a Samba share full of __________." "Just use __________. What could go wrong?" "I installed __________ by accident." "Read-eval-__________-loop." "We should try it with an actual __________." "Is __________ something we need to optimize for?" "Hack __________ into redis." "According to the W3C __________ is now considered harmful." "Never update __________ before a demonstration." "__________ is used when the CPU is on fire." "modperl can be used to implement __________." "__________ runs Ruby as root." "Larry Wall trained as a missionary then got into __________." "Listening to the fans in the server farm leads to __________." "__________ and __________ are rumoured to be working on a python module for a helicam." "A lot of disk space is needed for __________." "The installer automagically configures __________." "Whoever made the unscheduled change to production on Friday will be forced to use __________." "Never question __________." "I can't wait until we no longer use __________." "I bet if we switch to __________ it will just work." "__________ has just discovered __________. We're doomed." "A neckbeard made of __________." "False alarm, it was just __________ running __________." "__________ running on a rack of __________." "No, __________ being hopelessly broken is NOT an emergency." "Our new startup is __________ for __________." "__________ over IP" "__________ is a hardware problem." "I AM working, I'm waiting for __________ to finish." "The first rule of __________ is: You do not talk about __________." "Google Analytics says 100% of my website visitors are __________." "__________ will never get you a job at Microsoft." "4chan.org is powered by __________." "We can have __________ just like Netflix." "__________ is how I resolve all merge conflicts." "Why does someone keep re-implementing system utilities in __________?" "Remember when you told me to tell you when you were acting like __________ and __________? You're doing it now." "Our only hope at recovering the data is __________." "__________: the gift that keeps on giving." "__________ has been killed with fire. My work is done here." "Problem exists between keyboard and __________." "100% government funded __________!" "__________ certification program." "I just finished writing an API for __________." "__________ is a batch command to shut the heck up." "__________. Failed to cache catalog." "Sorry, I'm all out of __________-fu." "90% of everything is __________." "Given enough __________, all bugs are __________." "The first 90% of development is __________. The second 90% is __________." "When you logged in there, did you see __________ that said __________?" "Purely numeric hostname and not __________ -----rejecting!" "I'm pretty sure __________ isn't thread safe." "We don't have to worry about CAP Theorem because of __________." "I don't always test my code, but when I do I do it in __________." "Those who don't understand __________ are condemned to reinvent it, poorly." "The NSA is really interested in our latest project: __________." "Just change __________, it'll be fine." "Yeah, you need to modprobe __________ to get it to recognize __________." "Oh, we're devops! We have __________ in the office, but only the DBA can touch it." "We're spending 20% of this sprint doing __________." "__________ found a new OpenSSL vulernability people are calling __________." "Management has changed all our job titles to __________." "while true; do __________; done" "The consultant we hired is certain that __________ will drastically increase the performance of __________." "Could you just push this update for __________? It should be a no-op." "If we're all going to get fired, let's get fired for __________." "We can't pay you, but we can offer __________ in compensation." "A soiled napkin with the contents of __________ scribbled on it." "Who thought that __________ was a good idea?" "It's not the recommended configuration to use __________ with __________, but it's in production right now." "We wrote our own build tool based on __________." "I've received a Microsoft MVP award for __________." "We rewrote __________ in __________." "The ticket to install __________? I deletegated it." "Some people, when confronted with a problem, think \"I know, I'll use __________.\" Now they have two problems." "We only use __________, artisanally crafted by Mennonites from Ohio." "The backups are fine, but the restore process is __________." "I can't believe QA filed a bug for __________." "__________ is just one indespensible service that ops provides developers." "Oracle is proud to announce that the next edition of Java features __________." "Moving __________ will definitely break things." "__________: ci or not ci?" "I opened the server cabinet and it was full of __________." "Crossing __________ could lead to total protonic reversal." "The next big thing is __________." "I once made a robot around the concept of __________." "Nine circles of __________ hell." "I once wrote an NPM module called __________.js" "I asked the contractor for __________ and they delivered __________." "Welcome to Programming 101, our first topic will be __________." "The Genius Bar recommends you try __________." "Post-modern coding is defined by __________." "__________ | sudo sh" "__________ has been put under the WTFPLicense." "Here's __________, as I promised." "I'd like __________, __________, and a Fluttershy." "It transpiles __________ to JavaScript." "Only the Enterprise Edition™ has __________." "__________ is a proof of concept and an actual __________ __________." "The trouble with kids these days is __________." "__________ is the new Stalinism." "__________ for the win!" "__________ is the new __________." "I googled \"__________\" and \"__________\" and found conflicting information about every detail of each." "With __________, you write once, run nowhere." "__________ discontinued support for the Linux version." "A manager told me I couldn't remove our dependency on __________, but I got around it with __________." "__________ implements every single standard for __________. Poorly." "Just think of the Internet as __________." "Would you like __________ with that?" "__________? We've got that." "It took over 40 hours to document __________." "//TODO: __________." "npm install __________." "Circular imports import __________." "A firewall rule for __________." "__________ is why the jDBA thought it might be time to go to #mysql on freenode." "__________ is the only reason the jDBA survived typing \"rm -rf /\"." "__________ exists?" "It's like __________ on __________." "I came here to drink milk and deploy __________, and I've just finished my milk." "End-to-end __________." "__________ will help you remember to sanitze your database inputs." "Just RTFM, and then you'll understand __________." "__________ took EBS down again today." "I ssh'd into a server running __________ and promptly noped the fuck out of there." "__________, the final solution." "We're running __________ in production?!" "__________ has root access." "We don't have enough package managers, said __________." "__________ is more reliable than __________." "Of course culture is important to us, that's why we have __________." "I'd trust all my stuff to __________." "My kingdom for __________." "Nice, __________. I'll take it." "Such __________. Wow." "That's funny, I thought __________ used to be here?" "I can't believe you improved __________ by deleting __________." "The only thing more dangerous than __________ is a programmer with __________." "1. __________ 2. __________ 3. Profit." "Monads are easy! Just think of them as __________." "__________: powered by the cloud." "I uploaded my worm to __________." "#!/bin/__________" "make __________ && sudo make install && cowsay yay" "I bet the person who wrote this uses __________." "I'm not __________, my code is compiling." "Don't worry, we have unit tests for __________." "As a product manager, I want __________." "The only non-conformance in this year's audit was __________." "We're blaming interns for __________." "__________ is my favourite thing about __________." "I wish that we had more __________ in our office." "I've once been so drunk that __________ actually made sense." "To understand __________ you must first understand __________." "__________ @ 127.0.0.1 -p __________" "__________? You mean __________!" "__________ is coming out of stealth mode." "__________ ate all my memory!" "__________ is always a good practice." "Don't mind me, I'm just practicing __________." "The intern tripped in the server room and shut down __________." "It's easy! Just run __________." "I assure you __________ is secure!" "Our backup policy is __________." "I ran 'pacman -Syu' and it totally broke __________." "We didn't think anyone was using __________!" "Good evening Dr <NAME>, would you like to play __________?" "IBM just created JSONxx to encapsulate JSON in XML in __________." "I never truly understood __________ until I encountered __________." "The Agile Manifesto taught me to pick __________ over __________." "__________ should be a singleton!" "Flash is dying because of __________." "Neo, the matrix has one fatal flaw, you must find __________." "Javascript is the best language ever, thanks to __________." "Last night while drunk, the W3C declared __________ as a new web standard." "North Korea finally launched warheads because of __________." "Last night I accidentally ran sudo chmod -R 777 /. I just blamed __________." "During the lunch break I like to think about __________." "Nobody will value your work if you don't use __________." "__________, because scientists don't know how to code." "__________, because Knuth." "The entire system failed because of __________." "The meeting between Europe and the USA was cancelled because of __________." "We missed the launch window due to confusion from __________." "__________ wasted thousands of dollars." "No one can authenticate because of __________." "__________ caused the servers to melt down." "__________ invalidated all the assumptions in our monitoring system." "CAMS is outdated because of __________." "__________: Easy one-step installation" "__________, because even the hobos of Market Street need a cluster scheduler." "We need to update __________." "It's cool, they use __________ at Etsy." "Code as __________." "__________ is how the cloud works." "It looks like __________ in Opera." "__________ shell" "__________ in haskell" "Say __________ one more time; I dare you!" "The cloud runs on __________, with a bit of __________." "__________, because who needs monitoring." "This problem can be completely solved with __________ implemented in __________." "__________ vs __________... FIGHT!" "I regret to inform you your weekend has been revoked due to __________." "All alerts go to __________, which is handled by __________." "__________, it's the new pink." "I've got 99 problems but __________ ain't one." "140 characters is just enough to explain __________." "__________ all the way down." "__________ continuously spawns zombie processes." "Elliptic-Curve Diffie-Helman breaks against __________." "Why isn't my script working? Oh. __________." "ITIL best practices suggest __________ is the next step." "We would have gotten the funding, if only our slide deck included __________." "Have you tried __________ and __________?" "I left __________ in the server room." "I stuck my hand in a sysadmin's beard and pulled out __________." "Before exiting, the program kills __________." "Cookbooks containing __________ have been known to cause __________." "Once we added __________ to the firewall rules, __________ worked perfectly." "My pre-commit hook replaces tab characters with __________." "I was up all night debugging __________." "Error: insufficient __________" "The product team just handed me a spec, they want __________ in the next release of __________." "The malware came from an infected ad on __________.com" "Killing child processes releases resources back to __________." "That regular expression is designed to match __________ but not __________." "The vendor solution didn't have log aggregation, but it did have __________." "Our custom log rotation scripts have the added feature of __________." "This year, Cross-Site Request Forgery was knocked out of the OWASP Top 10, and replaced by __________." "__________ sucks, let's replace it with __________." "My pull request was rejected because it contained __________." "My stacktrace revealed __________." "Chef encountered an error attempting to create __________." "Since the 1950s, engineers have been striving toward a more effective means of generating __________." "Our code was efficient, except for the module containing __________, which was slower than __________." "I need to re-munge the CSV, replacing the commas with __________." "We strive for continuous deployment, continuous delivery, and continuous __________." "Data-driven decisions are to be replaced with __________." "The ruby gem is useless, it's a lesser implementation of __________." "Windows ME had a service pack that solved the problem of __________." "<NAME>'s latest project is __________." "__________ is the quickest way to identify what is burning in the server room." "Oh, we store all our docs in __________." "I accidentally deleted the whole database with __________." "It's not a bug it's __________." "__________ totally killed the mood at E3." "To replace camelCase, the new C++ standards mandate variables be named using __________." "I'm sorry __________ isn't numberwang." "I'm sorry __________ isn't wangernum." "__________ became self aware and kidnapped the sysadmins." "That's the first time I've ever seen ProGuard used to obfuscate __________." "Every day at work I implement __________ and my mother still tells her friends I \"do computers\"." "That's the first time I've ever seen comments written in __________." "It's not a problem, I'll just use __________ to fix it later." "I, for one, welcome our new __________ overlords." ]
true
module.exports = [ "You saw __________ in prod? Logs or it didn't happen." "s/__________/__________/g" "__________, for some values of __________." "Ask me anything about __________." "Called on account of __________." "Disrupting the established players in __________ via __________." "Doge __________." "Is __________ in the cloud considered Enterprise-ready?" "Epic yak-shave caused by __________." "Facebook has acquired __________ for $10b and __________." "Free as in __________." "Hi, I'm PI:NAME:<NAME>END_PI. You may remember me from such commit messages as \"adds __________\" and \"reverts __________\"." "How is __________ even formed?" "I can haz __________." "Our app is like Tinder for __________" "I saw the best minds of my generation destroyed by __________." "If __________ isn't the answer, you are asking the wrong question." "If you're using __________, you're gonna have a bad time." "Nobody ever got fired for buying __________." "Running Windows in production leads to __________." "The Internet is for cat memes and __________." "Our release schedule doesn't have time for __________." "The Internet of Things will be controlled by __________." "The only thing necessary for evil to triumph is __________." "Uber is on surge pricing because of __________." "WARN: __________ has been deprecated." "Will merge pull requests for __________." "__________ was was taken down by a zero-day vulernability." "Time to schedule the postmortem for __________." "__________ - the idiots guide to __________ and __________." "But Google is using __________ so we should too!" "Etsy says we should use __________ for everything." "Have you seen the xkcd about using __________ as a replacement for __________." "This isn't going to be all unicorns and __________." "Apple just patented __________." "When I was a kid we didn't have __________." "__________ is a nice idea, lets found a start-up." "DevOps: Now with a 100% increase in __________!" "Main benefits of automation: __________ and __________." "Chef converge failed due to __________." "Then there was the time I found __________ on the root partition." "We run production on __________ and __________." "Management said it's OK to deploy __________ at 5pm on Friday." "Did you know that we have __________ on pager rotation?" "There was no good solution for __________, so we built our own using __________." "Amazon built a data center on the moon to lessen the risk of __________ causing problems." "In order to improve security, we're upgrading to __________." "The two pillars of our Continuous Deployment pipeline are __________ and __________." "I got paged at 3am because of __________." "The most stable part of our infrastructure? __________. For sure." "When I told PI:NAME:<NAME>END_PI about our __________, he actually cried." "When I write a book about my experiences, it'll be called \"__________, the good parts\"." "Restoring from backups failed due to __________." "My two most indispensable tools are __________ and __________." "The production data center burned down because of __________." "It turns out that the button labeled \"Don't Push\" actually kicks off __________." "You should think of your servers like __________ and not like __________." "I find Java to be way too much like __________." "It's like trying to herd __________." "I ended up having to buy a replacement for __________ on eBay." "The RIAA is suing me for downloading __________." "Security? We've got that! We use __________." "sudo pip install __________" "When I hooked the 3D printer up to the Internet, it accidentally created __________." "My next blog post will be about how we used __________ to create __________." "So, I was using Wireshark to check network traffic... Did you know we have __________ in production?" "My eyes started bleeding when I opened the editor and saw __________." "I think maybe I'll leave my experience in __________ off my resumé." "We don't need __________ - we have __________!" "Management just told me I need to get certified in __________." "Our app is like __________, but for __________." "Marketing says we're leaders in __________, but I think it's more accurate to say we specialize in __________." "Our greatest achievement in the last year is __________." "I write my code in vim because of __________." "If we make this deadline, management has promised us __________." "Sweet! I just found a Puppet module for __________!" "Last week, I created a Chef recipe for __________; this week, it's an entire cookbook for __________, Automation FTW!" "We really need to open-source our implementation of __________." "A sales rep just tried to pitch me on __________; I told them we already have __________." "Who would have known that __________ could destroy an entire datacenter?" "sudo apt-get install __________" "Our production backups are stored using __________." "We replaced our __________ with __________." "After __________ came up, the retrospective really went downhill." "You know what our app needs? More __________, and less __________." "It figures - an article about __________ was posted just as we're pivoting to __________." "In the next planning session, we'll cover __________ and __________." "Our competitive advantage is our expertise with __________." "Every time someone brings up __________, I throw up a little in my mouth." "All that we had to do to halve our response times was implement __________." "Our entire app is geared towards providing __________." "Is __________ high availabilty?" "My LinkedIn endorsements include __________ and __________." "The users are using __________ as a workaround for __________." "Robots are going to make __________ obsolete." "An error occurred: __________" "According to the logs, __________ was initially caused by __________." "We can just fix that with __________." "You can have __________, __________, or __________. Pick two." "A monad is just __________ in the category of __________, what's the problem?" "On a scale from 1 to 10, this is __________!" "We don't need configuration management, we have __________!" "__________, now with __________ support." "RedHat has announced that RHEL 8 will ship with __________." "Hey, __________ is down. Can you fix it?" "I grabbed __________ on my way out the door after our paychecks bounced and management stopped answering their phones." "Did you try __________ yet?" "I was 6 beers in when I got the pager alert that __________ was down." "Notice: Building __________ for __________" "I laughed when they said I'd be on call 24/7 but wouldn't receive a stipend for __________." "If it weren't for __________ we'd all be __________." "__________, __________ and just a few lines of Perl." "NoSQL is superior to SQL because __________." "Script kiddies got into __________ because __________." "__________ is better than Hadoop because __________." "WAIT, YOU DELETED __________??!" "It's not web scale, it's __________." "The tech support hotline told me to try __________." "Asynchronous REST API calls are the solution to __________." "Guys, seriously, if we just use __________ it will solve all our problems with __________!" "Facebook changed their profiles today because __________." "Hello. My name is __________ and I am addicted to __________." "__________ dependency hell." "That talk outline said it would be about __________, but it ended up being more like __________." "We should replace the users with __________." "PI:NAME:<NAME>END_PI hates __________ so much that he created a new opensource project called __________ to work around it." "__________ isn't a job title." "For the next project we are going to use __________ to solve __________." "My editor of choice is __________." "__________ looks good; ship it." "__________-Stack Developer" "It has been __ days since the last __________." "__________ on the server were deleted because __________." "This week, Aphyr runs __________ through jepsen." "The intern just ran __________ on the load balancer." "I need you to do __________ with __________ before __________." "Lambdas are just a lame implementation of __________." "C-x; C-__________" "The users want __________ because __________." "__________ should be deprecated in favour of __________." "__________ mismatch between __________ and __________." "I put __________ on the scripts to make it run faster." "Developers do not get access to production machines, because of __________." "Developers need access to production machines because __________." "We run __________ in a cron job every 15 minutes." "I could hire __________ to do your job!" "My next Velocity talk is called \"__________ops\"." "The RCA for the global outage was __________ compunded by __________." "I was hired to maintain this 20 year old script that runs our critical __________ infrastructure." "I know we use __________, but I wrote this critical program in __________." "I'll just have Ops spin up a couple of __________ environments." "I'm writing my next IRC bot with __________." "I cannot wait until someone makes a cluster out of __________." "C will finally be displaced by __________." "We don't need to worry about __________, we're using MongoDB." "Why is __________ better than Hadoop?" "FC067: __________" "Oh, __________ is just a hack to get __________ to run." "How do I even __________?" "__________ all the things!" "ERROR: __________ NOT FOUND" "We don't need backups, we've got __________." "Fixing your father's computer with __________." "It's always __________ DNS problem." "__________ with this one weird, old trick." "__________ isn't new, we used to do it in the '70s on mainframes." "Puppet is better than Chef because __________ and __________." "How is __________ better than __________?" "Learn __________ the hard way." "Vagrant up __________." "You can fix __________ with __________." "We took the plunge and rewrote __________ in Go." "Implementing __________ should take only 2 lines of code." "Good enough for __________ work." "Yeah, but can it run __________?" "Security through __________." "__________? You can safely ignore that. Usually." "__________ isn't cool. You know what's cool? __________." "640k RAM should be enough for __________." "__________ worked in dev." "You can't fix __________." "How hard could it be to port Linux to __________." "I just finished working on my rocket powered __________." "PI:NAME:<NAME>END_PI will kill you with his teeth for __________." "DB tuning with __________." "Can anyone help me get __________ running on Cisco IOS?" "Real __________ don't use __________." "__________ on XEN." "Please bring back __________. You broke my workflow." "I cut-and-pasted this StackOverflow code for __________." "I'm just finishing up my manifesto on __________." "/r/__________." "We can discuss __________ at the stand-up meeting." "A Beowulf cluster of __________." "We're demoing __________ for __________ at SXSW." "I aliased __________ to git __________." "10 PRINT \"__________\"; GOTO 10" "alt.binaries.__________" "It is completely dark. You are likely to be eaten by __________." "Conway's Game of __________." "Next year I'll start learning to use __________." "__________ is the newest gTLD." "One does not simply open a ticket to fix __________." "Sorry, you'll need to open a ticket before we can fix __________." "ln -s __________ __________" "__________ is dead." "grep __________ | mail __________" "__________ just got pwned." "It's like __________, but with __________ and list comprehensions." "Software defined __________." "I don't have any UNIX Beards in stock, but we do have __________." "Amazon does __________, why can't we?" "I can't believe you're still using __________." "/dev/__________: Device is busy" "I tried __________, the doctors say I'll never walk again." "git --__________" "__________ Public License." "__________ begins with __________." "Couldn't we use __________?" "__________ would be so much better if we rewrote it in Clojure." "So I just found __________ and __________ running in a screen session." "Why is root running __________ under tmux?" "Instead of installing __________, what if we just used __________." "I need a webinar like I need __________." "Fuck it, time to break out the emergency stash of __________." "On the plus side, we finally got rid of __________." "__________ thought leader." "Fuck it: __________ looks good to me." "Hi, I'm Clippy the office assistant. Would you like __________ today?" "zsh: command not found: __________" "How did __________ ever work?" "Whoops, I thought that method was supposed to __________ __________." "I thought you said __________ was secure?" "git: You are in __________ state." "Why don't we just fork __________?" "The network connection dropped out because of __________." "We turned off __________ and everything magically got better." "I found a Samba share full of __________." "Just use __________. What could go wrong?" "I installed __________ by accident." "Read-eval-__________-loop." "We should try it with an actual __________." "Is __________ something we need to optimize for?" "Hack __________ into redis." "According to the W3C __________ is now considered harmful." "Never update __________ before a demonstration." "__________ is used when the CPU is on fire." "modperl can be used to implement __________." "__________ runs Ruby as root." "Larry Wall trained as a missionary then got into __________." "Listening to the fans in the server farm leads to __________." "__________ and __________ are rumoured to be working on a python module for a helicam." "A lot of disk space is needed for __________." "The installer automagically configures __________." "Whoever made the unscheduled change to production on Friday will be forced to use __________." "Never question __________." "I can't wait until we no longer use __________." "I bet if we switch to __________ it will just work." "__________ has just discovered __________. We're doomed." "A neckbeard made of __________." "False alarm, it was just __________ running __________." "__________ running on a rack of __________." "No, __________ being hopelessly broken is NOT an emergency." "Our new startup is __________ for __________." "__________ over IP" "__________ is a hardware problem." "I AM working, I'm waiting for __________ to finish." "The first rule of __________ is: You do not talk about __________." "Google Analytics says 100% of my website visitors are __________." "__________ will never get you a job at Microsoft." "4chan.org is powered by __________." "We can have __________ just like Netflix." "__________ is how I resolve all merge conflicts." "Why does someone keep re-implementing system utilities in __________?" "Remember when you told me to tell you when you were acting like __________ and __________? You're doing it now." "Our only hope at recovering the data is __________." "__________: the gift that keeps on giving." "__________ has been killed with fire. My work is done here." "Problem exists between keyboard and __________." "100% government funded __________!" "__________ certification program." "I just finished writing an API for __________." "__________ is a batch command to shut the heck up." "__________. Failed to cache catalog." "Sorry, I'm all out of __________-fu." "90% of everything is __________." "Given enough __________, all bugs are __________." "The first 90% of development is __________. The second 90% is __________." "When you logged in there, did you see __________ that said __________?" "Purely numeric hostname and not __________ -----rejecting!" "I'm pretty sure __________ isn't thread safe." "We don't have to worry about CAP Theorem because of __________." "I don't always test my code, but when I do I do it in __________." "Those who don't understand __________ are condemned to reinvent it, poorly." "The NSA is really interested in our latest project: __________." "Just change __________, it'll be fine." "Yeah, you need to modprobe __________ to get it to recognize __________." "Oh, we're devops! We have __________ in the office, but only the DBA can touch it." "We're spending 20% of this sprint doing __________." "__________ found a new OpenSSL vulernability people are calling __________." "Management has changed all our job titles to __________." "while true; do __________; done" "The consultant we hired is certain that __________ will drastically increase the performance of __________." "Could you just push this update for __________? It should be a no-op." "If we're all going to get fired, let's get fired for __________." "We can't pay you, but we can offer __________ in compensation." "A soiled napkin with the contents of __________ scribbled on it." "Who thought that __________ was a good idea?" "It's not the recommended configuration to use __________ with __________, but it's in production right now." "We wrote our own build tool based on __________." "I've received a Microsoft MVP award for __________." "We rewrote __________ in __________." "The ticket to install __________? I deletegated it." "Some people, when confronted with a problem, think \"I know, I'll use __________.\" Now they have two problems." "We only use __________, artisanally crafted by Mennonites from Ohio." "The backups are fine, but the restore process is __________." "I can't believe QA filed a bug for __________." "__________ is just one indespensible service that ops provides developers." "Oracle is proud to announce that the next edition of Java features __________." "Moving __________ will definitely break things." "__________: ci or not ci?" "I opened the server cabinet and it was full of __________." "Crossing __________ could lead to total protonic reversal." "The next big thing is __________." "I once made a robot around the concept of __________." "Nine circles of __________ hell." "I once wrote an NPM module called __________.js" "I asked the contractor for __________ and they delivered __________." "Welcome to Programming 101, our first topic will be __________." "The Genius Bar recommends you try __________." "Post-modern coding is defined by __________." "__________ | sudo sh" "__________ has been put under the WTFPLicense." "Here's __________, as I promised." "I'd like __________, __________, and a Fluttershy." "It transpiles __________ to JavaScript." "Only the Enterprise Edition™ has __________." "__________ is a proof of concept and an actual __________ __________." "The trouble with kids these days is __________." "__________ is the new Stalinism." "__________ for the win!" "__________ is the new __________." "I googled \"__________\" and \"__________\" and found conflicting information about every detail of each." "With __________, you write once, run nowhere." "__________ discontinued support for the Linux version." "A manager told me I couldn't remove our dependency on __________, but I got around it with __________." "__________ implements every single standard for __________. Poorly." "Just think of the Internet as __________." "Would you like __________ with that?" "__________? We've got that." "It took over 40 hours to document __________." "//TODO: __________." "npm install __________." "Circular imports import __________." "A firewall rule for __________." "__________ is why the jDBA thought it might be time to go to #mysql on freenode." "__________ is the only reason the jDBA survived typing \"rm -rf /\"." "__________ exists?" "It's like __________ on __________." "I came here to drink milk and deploy __________, and I've just finished my milk." "End-to-end __________." "__________ will help you remember to sanitze your database inputs." "Just RTFM, and then you'll understand __________." "__________ took EBS down again today." "I ssh'd into a server running __________ and promptly noped the fuck out of there." "__________, the final solution." "We're running __________ in production?!" "__________ has root access." "We don't have enough package managers, said __________." "__________ is more reliable than __________." "Of course culture is important to us, that's why we have __________." "I'd trust all my stuff to __________." "My kingdom for __________." "Nice, __________. I'll take it." "Such __________. Wow." "That's funny, I thought __________ used to be here?" "I can't believe you improved __________ by deleting __________." "The only thing more dangerous than __________ is a programmer with __________." "1. __________ 2. __________ 3. Profit." "Monads are easy! Just think of them as __________." "__________: powered by the cloud." "I uploaded my worm to __________." "#!/bin/__________" "make __________ && sudo make install && cowsay yay" "I bet the person who wrote this uses __________." "I'm not __________, my code is compiling." "Don't worry, we have unit tests for __________." "As a product manager, I want __________." "The only non-conformance in this year's audit was __________." "We're blaming interns for __________." "__________ is my favourite thing about __________." "I wish that we had more __________ in our office." "I've once been so drunk that __________ actually made sense." "To understand __________ you must first understand __________." "__________ @ 127.0.0.1 -p __________" "__________? You mean __________!" "__________ is coming out of stealth mode." "__________ ate all my memory!" "__________ is always a good practice." "Don't mind me, I'm just practicing __________." "The intern tripped in the server room and shut down __________." "It's easy! Just run __________." "I assure you __________ is secure!" "Our backup policy is __________." "I ran 'pacman -Syu' and it totally broke __________." "We didn't think anyone was using __________!" "Good evening Dr PI:NAME:<NAME>END_PI, would you like to play __________?" "IBM just created JSONxx to encapsulate JSON in XML in __________." "I never truly understood __________ until I encountered __________." "The Agile Manifesto taught me to pick __________ over __________." "__________ should be a singleton!" "Flash is dying because of __________." "Neo, the matrix has one fatal flaw, you must find __________." "Javascript is the best language ever, thanks to __________." "Last night while drunk, the W3C declared __________ as a new web standard." "North Korea finally launched warheads because of __________." "Last night I accidentally ran sudo chmod -R 777 /. I just blamed __________." "During the lunch break I like to think about __________." "Nobody will value your work if you don't use __________." "__________, because scientists don't know how to code." "__________, because Knuth." "The entire system failed because of __________." "The meeting between Europe and the USA was cancelled because of __________." "We missed the launch window due to confusion from __________." "__________ wasted thousands of dollars." "No one can authenticate because of __________." "__________ caused the servers to melt down." "__________ invalidated all the assumptions in our monitoring system." "CAMS is outdated because of __________." "__________: Easy one-step installation" "__________, because even the hobos of Market Street need a cluster scheduler." "We need to update __________." "It's cool, they use __________ at Etsy." "Code as __________." "__________ is how the cloud works." "It looks like __________ in Opera." "__________ shell" "__________ in haskell" "Say __________ one more time; I dare you!" "The cloud runs on __________, with a bit of __________." "__________, because who needs monitoring." "This problem can be completely solved with __________ implemented in __________." "__________ vs __________... FIGHT!" "I regret to inform you your weekend has been revoked due to __________." "All alerts go to __________, which is handled by __________." "__________, it's the new pink." "I've got 99 problems but __________ ain't one." "140 characters is just enough to explain __________." "__________ all the way down." "__________ continuously spawns zombie processes." "Elliptic-Curve Diffie-Helman breaks against __________." "Why isn't my script working? Oh. __________." "ITIL best practices suggest __________ is the next step." "We would have gotten the funding, if only our slide deck included __________." "Have you tried __________ and __________?" "I left __________ in the server room." "I stuck my hand in a sysadmin's beard and pulled out __________." "Before exiting, the program kills __________." "Cookbooks containing __________ have been known to cause __________." "Once we added __________ to the firewall rules, __________ worked perfectly." "My pre-commit hook replaces tab characters with __________." "I was up all night debugging __________." "Error: insufficient __________" "The product team just handed me a spec, they want __________ in the next release of __________." "The malware came from an infected ad on __________.com" "Killing child processes releases resources back to __________." "That regular expression is designed to match __________ but not __________." "The vendor solution didn't have log aggregation, but it did have __________." "Our custom log rotation scripts have the added feature of __________." "This year, Cross-Site Request Forgery was knocked out of the OWASP Top 10, and replaced by __________." "__________ sucks, let's replace it with __________." "My pull request was rejected because it contained __________." "My stacktrace revealed __________." "Chef encountered an error attempting to create __________." "Since the 1950s, engineers have been striving toward a more effective means of generating __________." "Our code was efficient, except for the module containing __________, which was slower than __________." "I need to re-munge the CSV, replacing the commas with __________." "We strive for continuous deployment, continuous delivery, and continuous __________." "Data-driven decisions are to be replaced with __________." "The ruby gem is useless, it's a lesser implementation of __________." "Windows ME had a service pack that solved the problem of __________." "PI:NAME:<NAME>END_PI's latest project is __________." "__________ is the quickest way to identify what is burning in the server room." "Oh, we store all our docs in __________." "I accidentally deleted the whole database with __________." "It's not a bug it's __________." "__________ totally killed the mood at E3." "To replace camelCase, the new C++ standards mandate variables be named using __________." "I'm sorry __________ isn't numberwang." "I'm sorry __________ isn't wangernum." "__________ became self aware and kidnapped the sysadmins." "That's the first time I've ever seen ProGuard used to obfuscate __________." "Every day at work I implement __________ and my mother still tells her friends I \"do computers\"." "That's the first time I've ever seen comments written in __________." "It's not a problem, I'll just use __________ to fix it later." "I, for one, welcome our new __________ overlords." ]
[ { "context": " @staticObjProp:\n key: 'originalValue'\n\n instanceMethodToBeOverridden: ->\n ", "end": 849, "score": 0.6298562288284302, "start": 836, "tag": "KEY", "value": "originalValue" } ]
spec/copy-class.coffee
shinout/copy-class
1
assert = require 'power-assert' copyClass = require '../src/copy-class' describe 'copy-class', -> describe 'copy', -> class ParentClass constructor: -> @parentConstructed = true @staticProp: 1 @staticPropToBeOverridden: 'parent' @staticObjPropInParent: key: 'value' instanceProp: 1 instanceMethod: -> return 'instanceMethodInParent' instanceMethodToBeOverridden: -> return 12 class OriginalClass extends ParentClass constructor: (a, b, c) -> super @originalConstructed = true @originalStaticProp: 2 @staticPropToBeOverridden: 'original' @staticObjProp: key: 'originalValue' instanceMethodToBeOverridden: -> return @title originalInstanceMethod: -> return 'originalInstanceMethod' it 'creates function with the same length', -> ClonedClass = copyClass.copy(OriginalClass) assert OriginalClass.length is ClonedClass.length describe '[name]', -> it 'has the name the same as orignal by default', -> ClonedClass = copyClass.copy(OriginalClass) assert(ClonedClass.name is 'OriginalClass') it 'can set name with the second argument', -> ClonedClass = copyClass.copy(OriginalClass, 'abcd') assert(ClonedClass.name is 'abcd') describe '[static properties]', -> it 'has original Class\'s own static properties', -> ClonedClass = copyClass.copy(OriginalClass) assert(ClonedClass.originalStaticProp is 2) assert(ClonedClass.staticPropToBeOverridden is 'original') assert(ClonedClass.staticObjProp.key is 'originalValue') assert(ClonedClass.staticObjProp is OriginalClass.staticObjProp) it 'can define new static props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass.foo = 'bar' assert(ClonedClass.foo is 'bar') assert(OriginalClass.foo is undefined) it 'can override static props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass.originalStaticProp = 123 assert(ClonedClass.originalStaticProp is 123) assert(OriginalClass.originalStaticProp isnt 123) describe '[constructor]', -> it 'calls constructors (parent and original)', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert(obj.parentConstructed is true) assert(obj.originalConstructed is true) describe '[instance properties]', -> it 'copies prototypes of original class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() obj.title = 'hello' assert(obj.originalInstanceMethod() is 'originalInstanceMethod') assert(obj.instanceMethodToBeOverridden() is 'hello') it 'inherits prototypes of parent class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() obj.title = 'hello' assert(obj.instanceProp is 1) assert(obj.instanceMethod() is 'instanceMethodInParent') it 'can override instance props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass::originalInstanceMethod = -> return 'hello' obj = new ClonedClass() assert(obj.originalInstanceMethod() is 'hello') orig = new OriginalClass() assert(orig.originalInstanceMethod() isnt 'hello') it 'has the same keys as original object', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() orig = new OriginalClass() assert(Object.keys(obj).length is Object.keys(orig).length) describe '[prototype]', -> it 'prototype has the same key-value', -> ClonedClass = copyClass.copy(OriginalClass) assert Object.keys(ClonedClass.prototype).length is Object.keys(OriginalClass.prototype).length describe '[constructor property]', -> it 'has constructor', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert(obj.constructor is ClonedClass) orig = new OriginalClass() assert(orig.constructor is OriginalClass) it 'has constructor which is not enumerable', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() orig = new OriginalClass() assert(ClonedClass.prototype.propertyIsEnumerable 'constructor') assert(OriginalClass.prototype.propertyIsEnumerable 'constructor') assert(not obj.propertyIsEnumerable 'constructor') assert(not orig.propertyIsEnumerable 'constructor') describe '[instanceof]', -> it 'is not an instance of original class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass it 'not the class of original objects', -> ClonedClass = copyClass.copy(OriginalClass) orig = new OriginalClass() assert orig instanceof OriginalClass assert orig not instanceof ClonedClass it 'is an instance of original parent class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj instanceof ParentClass it 'is not an instance of original parent class when 3rd argument is passed', -> class XXClass ClonedClass = copyClass.copy(OriginalClass, null, XXClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj not instanceof ParentClass assert obj instanceof XXClass it 'is not an instance of original parent class when 3rd argument is passed', -> class XXClass ClonedClass = copyClass.copy(OriginalClass, null, XXClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj not instanceof ParentClass assert obj instanceof XXClass
191004
assert = require 'power-assert' copyClass = require '../src/copy-class' describe 'copy-class', -> describe 'copy', -> class ParentClass constructor: -> @parentConstructed = true @staticProp: 1 @staticPropToBeOverridden: 'parent' @staticObjPropInParent: key: 'value' instanceProp: 1 instanceMethod: -> return 'instanceMethodInParent' instanceMethodToBeOverridden: -> return 12 class OriginalClass extends ParentClass constructor: (a, b, c) -> super @originalConstructed = true @originalStaticProp: 2 @staticPropToBeOverridden: 'original' @staticObjProp: key: '<KEY>' instanceMethodToBeOverridden: -> return @title originalInstanceMethod: -> return 'originalInstanceMethod' it 'creates function with the same length', -> ClonedClass = copyClass.copy(OriginalClass) assert OriginalClass.length is ClonedClass.length describe '[name]', -> it 'has the name the same as orignal by default', -> ClonedClass = copyClass.copy(OriginalClass) assert(ClonedClass.name is 'OriginalClass') it 'can set name with the second argument', -> ClonedClass = copyClass.copy(OriginalClass, 'abcd') assert(ClonedClass.name is 'abcd') describe '[static properties]', -> it 'has original Class\'s own static properties', -> ClonedClass = copyClass.copy(OriginalClass) assert(ClonedClass.originalStaticProp is 2) assert(ClonedClass.staticPropToBeOverridden is 'original') assert(ClonedClass.staticObjProp.key is 'originalValue') assert(ClonedClass.staticObjProp is OriginalClass.staticObjProp) it 'can define new static props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass.foo = 'bar' assert(ClonedClass.foo is 'bar') assert(OriginalClass.foo is undefined) it 'can override static props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass.originalStaticProp = 123 assert(ClonedClass.originalStaticProp is 123) assert(OriginalClass.originalStaticProp isnt 123) describe '[constructor]', -> it 'calls constructors (parent and original)', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert(obj.parentConstructed is true) assert(obj.originalConstructed is true) describe '[instance properties]', -> it 'copies prototypes of original class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() obj.title = 'hello' assert(obj.originalInstanceMethod() is 'originalInstanceMethod') assert(obj.instanceMethodToBeOverridden() is 'hello') it 'inherits prototypes of parent class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() obj.title = 'hello' assert(obj.instanceProp is 1) assert(obj.instanceMethod() is 'instanceMethodInParent') it 'can override instance props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass::originalInstanceMethod = -> return 'hello' obj = new ClonedClass() assert(obj.originalInstanceMethod() is 'hello') orig = new OriginalClass() assert(orig.originalInstanceMethod() isnt 'hello') it 'has the same keys as original object', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() orig = new OriginalClass() assert(Object.keys(obj).length is Object.keys(orig).length) describe '[prototype]', -> it 'prototype has the same key-value', -> ClonedClass = copyClass.copy(OriginalClass) assert Object.keys(ClonedClass.prototype).length is Object.keys(OriginalClass.prototype).length describe '[constructor property]', -> it 'has constructor', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert(obj.constructor is ClonedClass) orig = new OriginalClass() assert(orig.constructor is OriginalClass) it 'has constructor which is not enumerable', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() orig = new OriginalClass() assert(ClonedClass.prototype.propertyIsEnumerable 'constructor') assert(OriginalClass.prototype.propertyIsEnumerable 'constructor') assert(not obj.propertyIsEnumerable 'constructor') assert(not orig.propertyIsEnumerable 'constructor') describe '[instanceof]', -> it 'is not an instance of original class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass it 'not the class of original objects', -> ClonedClass = copyClass.copy(OriginalClass) orig = new OriginalClass() assert orig instanceof OriginalClass assert orig not instanceof ClonedClass it 'is an instance of original parent class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj instanceof ParentClass it 'is not an instance of original parent class when 3rd argument is passed', -> class XXClass ClonedClass = copyClass.copy(OriginalClass, null, XXClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj not instanceof ParentClass assert obj instanceof XXClass it 'is not an instance of original parent class when 3rd argument is passed', -> class XXClass ClonedClass = copyClass.copy(OriginalClass, null, XXClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj not instanceof ParentClass assert obj instanceof XXClass
true
assert = require 'power-assert' copyClass = require '../src/copy-class' describe 'copy-class', -> describe 'copy', -> class ParentClass constructor: -> @parentConstructed = true @staticProp: 1 @staticPropToBeOverridden: 'parent' @staticObjPropInParent: key: 'value' instanceProp: 1 instanceMethod: -> return 'instanceMethodInParent' instanceMethodToBeOverridden: -> return 12 class OriginalClass extends ParentClass constructor: (a, b, c) -> super @originalConstructed = true @originalStaticProp: 2 @staticPropToBeOverridden: 'original' @staticObjProp: key: 'PI:KEY:<KEY>END_PI' instanceMethodToBeOverridden: -> return @title originalInstanceMethod: -> return 'originalInstanceMethod' it 'creates function with the same length', -> ClonedClass = copyClass.copy(OriginalClass) assert OriginalClass.length is ClonedClass.length describe '[name]', -> it 'has the name the same as orignal by default', -> ClonedClass = copyClass.copy(OriginalClass) assert(ClonedClass.name is 'OriginalClass') it 'can set name with the second argument', -> ClonedClass = copyClass.copy(OriginalClass, 'abcd') assert(ClonedClass.name is 'abcd') describe '[static properties]', -> it 'has original Class\'s own static properties', -> ClonedClass = copyClass.copy(OriginalClass) assert(ClonedClass.originalStaticProp is 2) assert(ClonedClass.staticPropToBeOverridden is 'original') assert(ClonedClass.staticObjProp.key is 'originalValue') assert(ClonedClass.staticObjProp is OriginalClass.staticObjProp) it 'can define new static props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass.foo = 'bar' assert(ClonedClass.foo is 'bar') assert(OriginalClass.foo is undefined) it 'can override static props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass.originalStaticProp = 123 assert(ClonedClass.originalStaticProp is 123) assert(OriginalClass.originalStaticProp isnt 123) describe '[constructor]', -> it 'calls constructors (parent and original)', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert(obj.parentConstructed is true) assert(obj.originalConstructed is true) describe '[instance properties]', -> it 'copies prototypes of original class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() obj.title = 'hello' assert(obj.originalInstanceMethod() is 'originalInstanceMethod') assert(obj.instanceMethodToBeOverridden() is 'hello') it 'inherits prototypes of parent class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() obj.title = 'hello' assert(obj.instanceProp is 1) assert(obj.instanceMethod() is 'instanceMethodInParent') it 'can override instance props', -> ClonedClass = copyClass.copy(OriginalClass) ClonedClass::originalInstanceMethod = -> return 'hello' obj = new ClonedClass() assert(obj.originalInstanceMethod() is 'hello') orig = new OriginalClass() assert(orig.originalInstanceMethod() isnt 'hello') it 'has the same keys as original object', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() orig = new OriginalClass() assert(Object.keys(obj).length is Object.keys(orig).length) describe '[prototype]', -> it 'prototype has the same key-value', -> ClonedClass = copyClass.copy(OriginalClass) assert Object.keys(ClonedClass.prototype).length is Object.keys(OriginalClass.prototype).length describe '[constructor property]', -> it 'has constructor', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert(obj.constructor is ClonedClass) orig = new OriginalClass() assert(orig.constructor is OriginalClass) it 'has constructor which is not enumerable', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() orig = new OriginalClass() assert(ClonedClass.prototype.propertyIsEnumerable 'constructor') assert(OriginalClass.prototype.propertyIsEnumerable 'constructor') assert(not obj.propertyIsEnumerable 'constructor') assert(not orig.propertyIsEnumerable 'constructor') describe '[instanceof]', -> it 'is not an instance of original class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass it 'not the class of original objects', -> ClonedClass = copyClass.copy(OriginalClass) orig = new OriginalClass() assert orig instanceof OriginalClass assert orig not instanceof ClonedClass it 'is an instance of original parent class', -> ClonedClass = copyClass.copy(OriginalClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj instanceof ParentClass it 'is not an instance of original parent class when 3rd argument is passed', -> class XXClass ClonedClass = copyClass.copy(OriginalClass, null, XXClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj not instanceof ParentClass assert obj instanceof XXClass it 'is not an instance of original parent class when 3rd argument is passed', -> class XXClass ClonedClass = copyClass.copy(OriginalClass, null, XXClass) obj = new ClonedClass() assert obj instanceof ClonedClass assert obj not instanceof OriginalClass assert obj not instanceof ParentClass assert obj instanceof XXClass
[ { "context": "new TextLayer\n\tparent:playbackBarContainer\n\ttext:\"Gulliver's Travels\"\n\tfontFamily:'sans-serif, fsme-light', ", "end": 3537, "score": 0.7753741145133972, "start": 3529, "tag": "NAME", "value": "Gulliver" } ]
prototypes/percent-nav/app.coffee
Skinny-Malinky/Skinny-Malinky.github.io
0
# Setup Variables document.body.style.cursor = "auto" Screen.backgroundColor = '#000' Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg' youviewBlue = '#00a6ff' youviewBlue2 = '#0F5391' youviewBlue3 = '#032230' youviewGrey1 = '#b6b9bf' youviewGrey2 = '#83858a' darkGrey3 = '#505359' black = '#000' white = '#ebebeb' veryDarkGrey4 = '#171717' veryDarkGrey5 = '#0D0D0D' getNumberSVG = (number) -> return numberSVG = '''<?xml version="1.0" encoding="UTF-8"?> <svg version="1.1" viewBox="0 0 21 20" xmlns="http://www.w3.org/2000/svg"> <g fill="none" fill-rule="evenodd"> <g transform="translate(-805 -645)"> <g transform="translate(271 645)"> <g transform="translate(534.33)"> <path d="m20 10c0 5.523-4.477 10-10 10s-10-4.477-10-10 4.477-10 10-10 10 4.477 10 10" fill="#595959" fill-rule="evenodd"/> <path d="m18 10c0 4.418-3.582 8-8 8s-8-3.582-8-8 3.582-8 8-8 8 3.582 8 8" fill="#000" fill-rule="evenodd"/> <text fill="#EBEBEB" font-family="sans-serif, fsme-Bold, FS Me" font-size="14" font-weight="bold" letter-spacing=".28"> <tspan x="6" y="15">''' + number + '''</tspan></text> </g></g></g></g></svg> ''' Framer.Device.deviceType = "sony-w85Oc" #Playback Bar Layers playbackBarContainer = new Layer width:1280, height:720 backgroundColor:'transparent' topGradient = new Layer # parent:playbackBarContainer width:1280 height:109 image:'images/top-gradient.png' index:0 gradient = new Layer parent:playbackBarContainer y: Align.bottom width:1280, height:390 image:'images/playback-bar-bg.png' opacity:1 index:0 playbackLine = new Layer parent:playbackBarContainer width:798, height:4 x:274, y:617 bufferLine = new Layer parent:playbackLine height:4, width:797 backgroundColor: youviewBlue2 playedLine = new Layer parent:bufferLine height:4, width:0 backgroundColor:'#00a6ff' playheadLine = new Layer parent:playedLine height:10, width:4 y:-3, x:Align.right backgroundColor:'#00a6ff' startTime = new TextLayer parent:playbackBarContainer text:'' width:50, height:16 fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5' color:youviewBlue maxY:playbackLine.maxY+4, x:209 endTime = new TextLayer parent:playbackBarContainer autoWidth:true text:'' width:50, height:16 fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5' maxY:playbackLine.maxY+4, x:playbackLine.maxX + 8 patchBack = new Layer parent:playbackBarContainer image:'images/patch-highlight.png' backgroundColor:'rgba(0,0,0,0.95)' height:129 width:130 y:510, x:64 index:0 patchIconContainer = new Layer parent:playbackBarContainer midX:patchBack.midX y:patchBack.y + 24 height:50, width:50 clip:true backgroundColor: 'transparent' patchIcon = new Layer parent:patchIconContainer image:'images/playback-sprites.png' height:750, width:50 x:-1,y:-22 backgroundColor: 'transparent' svgPatchIcon = new Layer parent:patchIconContainer height:50, width:50 backgroundColor:'' visible:false patchRCNInput = new TextLayer parent:patchBack width:120, height:36, y:30 fontFamily: 'sans-serif, fsme-bold', fontSize: 30, textAlign: 'center', letterSpacing: 1.12 color:'#ebebeb' text:'' patchText = new TextLayer parent:playbackBarContainer text:'Play' midX:patchBack.midX y:startTime.y fontFamily:'sans-serif, fsme-bold', fontSize:16, color:'#ebebeb', textTransform:'uppercase', textAlign:'center' height:16, width:128 clip:true backgroundColor: 'transparent' title = new TextLayer parent:playbackBarContainer text:"Gulliver's Travels" fontFamily:'sans-serif, fsme-light', fontSize:36, color:'#ebebeb' width:848, height:36 x:startTime.x, y:550 remoteNumber = [] remoteNumber.timeOut = 0 for i in [0..9] remoteNumbers = new Layer backgroundColor:'' html:getNumberSVG(i) parent:playbackLine x:80*i-9 height:21, width:20 # backgroundColor:'red' opacity:0 originY:0.2 remoteNumber.push(remoteNumbers) # Instructions instBackground = new Layer width: 500 height: 220 backgroundColor: '#1f1f1f' borderStyle: 'dotted' borderRadius: 20 borderWidth: 2 borderColor: 'white' x: 20, y: 20 instTitle = new TextLayer parent: instBackground text: 'Instructions' x: 30, y: 15, color: white instDesc = new TextLayer parent: instBackground html: '<p style="margin-bottom:5px;">. – fast forward</p> <p style="margin-bottom:5px;">0-9 – number input</p> <p style="margin-bottom:5px;">← or → – D-Pad (move to adjacent number)</p> <p style="margin-bottom:5px;">⏎ – OK / Play</p>', fontSize: 20 x: 30, y: 75, color: white # Clock today = new Date hour = today.getHours() minute = today.getMinutes() Utils.interval 60, -> refreshTime() currentTime = new TextLayer parent:topGradient text:hour + ':' + minute maxX:1216 y:36 fontFamily:'sans-serif, fsme' fontSize:30 color:'#ebebeb' if minute < 10 currentTime.text = hour+':0'+minute else currentTime.text = hour+':'+minute refreshTime = () -> today = new Date hour = today.getHours() minute = today.getMinutes() if minute < 10 currentTime.text = hour+':0'+minute else currentTime.text = hour+':'+minute currentTime.maxX = 1216 refreshTime() #Video Content and Management background = new BackgroundLayer backgroundColor: '#000' recording = new VideoLayer parent:background video:'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4' width:1280, height:720 backgroundColor: '#000' x:0, y:0 # recording.player.autoplay = true # recording.player.muted = true # recording.player.controls = true recording.ignoreEvents = false playTime = recording movePlayhead = () -> # Calculate progress bar position newPos = (playbackLine.width / recording.player.duration) * recording.player.currentTime playheadLine.x = newPos playedLine.width = newPos if getHoursOf(recording.player.duration) > 0 and getHoursOf(recording.player.currentTime) < 1 startTime.text = '0:' + timeParser(recording.player.currentTime) else startTime.text = timeParser(recording.player.currentTime) endTime.text = timeParser(recording.player.duration) recording.player.addEventListener "timeupdate", movePlayhead skipTo = (time, input) -> newPos = playbackLine.width / 10 * input playheadLine.animate x: newPos playedLine.animate width: newPos recording.player.currentTime = time timeParser = (time) -> rationalTime = Math.round(time) if rationalTime < 60 and rationalTime < 10 return '00:0' + rationalTime else if rationalTime < 60 and rationalTime > 9 return '00:' + rationalTime else if rationalTime >= 60 if rationalTime >= 570 if getMinutesOf(rationalTime) < 10 minutes = '0' + getMinutesOf(rationalTime) else minutes = getMinutesOf(rationalTime) else minutes = '0' + getMinutesOf(rationalTime) seconds = getSecondsOf(rationalTime) if seconds < 10 singleDigit = seconds seconds = '0' + singleDigit if rationalTime >= 3600 hours = getHoursOf(rationalTime) return hours + ':' + minutes + ':' + seconds return minutes + ':' + seconds getHoursOf = (rationalTime) -> minutes = rationalTime / 60 hours = Math.floor( minutes / 60 ) return hours getMinutesOf = (rationalTime) -> totalMinutes = rationalTime / 60 minutes = Math.floor( totalMinutes % 60 ) return minutes getSecondsOf = (rationalTime) -> seconds = Math.floor( rationalTime % 60 ) return seconds # Keys del = 8 guide = 9 ok = 13 record = 17 sub = 18 ad = 20 close = 27 pUp = 33 pDown = 34 mainMenu = 36 left = 37 up = 38 right = 39 down = 40 back = 46 zero = 48 one = 49 two = 50 three = 51 four = 52 five = 53 six = 54 seven = 55 eight = 56 nine = 57 info = 73 record = 82 stop = 111 help = 112 myTV = 115 red = 116 green = 117 yellow = 118 blue = 119 pause = 186 rewind = 188 fastForward = 190 stop = 191 mute = 220 play = 222 text = 120 power = 124 search = 192 skipBackward = 219 skipForward = 221 # Key Listener stopKeyInput = () -> document.removeEventListener 'keydown', (event) -> startKeyInput = () -> document.addEventListener 'keydown', (event) -> keyCode = event.which eventHandler(keyCode) event.preventDefault() startKeyInput() barTimeOut = 0 timeOut = 0 eventHandler = Utils.throttle 0.1, (keyCode) -> barTimeOut = 0 showPlaybackBar() switch keyCode when one timeJump(recording.player.duration / 100 * 10, 1) when two timeJump(recording.player.duration / 100 * 20, 2) when three timeJump(recording.player.duration / 100 * 30, 3) when four timeJump(recording.player.duration / 100 * 40, 4) when five timeJump(recording.player.duration / 100 * 50, 5) when six timeJump(recording.player.duration / 100 * 60, 6) when seven timeJump(recording.player.duration / 100 * 70, 7) when eight timeJump(recording.player.duration / 100 * 80, 8) when nine timeJump(recording.player.duration / 100 * 90, 9) when zero timeJump(0, 0) when ok playSpeed(1) timeOut = 5 when fastForward playSpeed(16) when rewind playSpeed(-1) when play playSpeed(1) when red changeVideo() when left findNearest('left') when right findNearest('right') findNearest = (direction) -> #Give or take 5000 now = recording.player.currentTime duration = recording.player.duration currentPercent = now / duration * 100 nearestTenth = Math.round(currentPercent / 10) if (direction == 'right' and nearestTenth <= 8) nearestTenth += 1 timeJump( duration / 100 * nearestTenth * 10, nearestTenth ) else if (now < ( duration / nearestTenth + 5000 ) and nearestTenth > 0) nearestTenth = nearestTenth - 1 timeJump(duration / 100 * nearestTenth*10, nearestTenth) changeVideo = () -> if recording.video == 'video/taboo.mp4' title.text = 'Guardians of the Galaxy' recording.video = 'video/Guardians of the Galaxy_downscale.mp4' recording.player.currentTime = 0 recording.player.play() else if recording.video == 'video/Guardians of the Galaxy_downscale.mp4' recording.video = 'video/taboo.mp4' title.text = 'Taboo' recording.player.currentTime = 0 recording.player.play() clearTimeInput = () -> patchIcon.visible = false patchRCNInput.text = '' patchRCNInput.color = white patchIcon.visible = true patchText.text = 'Play' svgPatchIcon.visible = false Utils.interval 0.5, -> if barTimeOut == 13 hidePlaybackBar() barTimeOut++ timeOut++ timeJump = ( input, label ) -> recording.player.removeEventListener "timeupdate", movePlayhead timeOut = 0 if remoteNumber[0].opacity > 0 jumpToTime(input, label) jumpToTime = ( irrationalTime, label ) -> if irrationalTime < recording.player.duration skipTo( irrationalTime, label ) patchIcon.visible = false svgPatchInserter( label ) for number, i in remoteNumber if i == label selectedNumber = number numberScale = selectedNumber.animate # opacity: 1 # I have no idea why this doesn't work and it's driving me insane. scale: 1.4 options: time:0.4 curve:Spring(damping: 0.3) Utils.delay 1, -> numberScale.reverse().start() else number.scale = 1 number.opacity = 0.6 Utils.delay 2, -> clearTimeInput() startKeyInput() recording.player.addEventListener "timeupdate", movePlayhead playSpeed(1) svgPatchInserter = ( input ) -> patchText.text = 'Jump To' svgPatchIcon.html = getNumberSVG( input ) svgPatchIcon.visible = true playSpeed = (speed) -> recording.player.playbackRate = speed if speed > 1 patchText.text = 'x' + speed recording.player.muted = true showNumbers() else if speed == 1 recording.player.muted = false patchText.text = 'play' if patchText.text != "Jump To" hideNumbers() else if speed < 1 patchText.text = 'x' + -speed showNumbers() Utils.delay 2, -> recording.video = 'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4' recording.player.play() hideNumberAnimations = [] hideNumbers = () -> stopAnimations() for remoteNumbers in remoteNumber hideNumber = remoteNumbers.animate y:18 opacity:0 options: curve:'ease-in-out' time:0.4 delay:5 hideNumberAnimations.push(hideNumber) showNumbers = () -> stopAnimations() if playbackBarContainer.isAnimating playbackBarContainer.onAnimationEnd -> for remoteNumbers in remoteNumber remoteNumbers.animate y:14 opacity:0.6 options: curve:'ease-in-out' time:0.4 else for remoteNumbers in remoteNumber remoteNumbers.animate y:14 opacity:0.6 options: curve:'ease-in-out' time:0.4 stopAnimations = () -> for hideNumber in hideNumberAnimations hideNumber.stop() showPlaybackBar = () -> playbackBarContainer.animate opacity:1 y:0 options: curve:'ease-in-out' time:0.5 topGradient.animate opacity:1 y:0 options: curve:'ease-in-out' time:0.5 hidePlaybackBar = () -> if recording.player.playbackRate == 1 playbackBarContainer.animate opacity:0 y:playbackBarContainer.y+20 options: curve:'ease-in-out' time:0.5 topGradient.animate opacity:0 y:-20 options: curve:'ease-in-out' time:0.5 hideNumbers()
218605
# Setup Variables document.body.style.cursor = "auto" Screen.backgroundColor = '#000' Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg' youviewBlue = '#00a6ff' youviewBlue2 = '#0F5391' youviewBlue3 = '#032230' youviewGrey1 = '#b6b9bf' youviewGrey2 = '#83858a' darkGrey3 = '#505359' black = '#000' white = '#ebebeb' veryDarkGrey4 = '#171717' veryDarkGrey5 = '#0D0D0D' getNumberSVG = (number) -> return numberSVG = '''<?xml version="1.0" encoding="UTF-8"?> <svg version="1.1" viewBox="0 0 21 20" xmlns="http://www.w3.org/2000/svg"> <g fill="none" fill-rule="evenodd"> <g transform="translate(-805 -645)"> <g transform="translate(271 645)"> <g transform="translate(534.33)"> <path d="m20 10c0 5.523-4.477 10-10 10s-10-4.477-10-10 4.477-10 10-10 10 4.477 10 10" fill="#595959" fill-rule="evenodd"/> <path d="m18 10c0 4.418-3.582 8-8 8s-8-3.582-8-8 3.582-8 8-8 8 3.582 8 8" fill="#000" fill-rule="evenodd"/> <text fill="#EBEBEB" font-family="sans-serif, fsme-Bold, FS Me" font-size="14" font-weight="bold" letter-spacing=".28"> <tspan x="6" y="15">''' + number + '''</tspan></text> </g></g></g></g></svg> ''' Framer.Device.deviceType = "sony-w85Oc" #Playback Bar Layers playbackBarContainer = new Layer width:1280, height:720 backgroundColor:'transparent' topGradient = new Layer # parent:playbackBarContainer width:1280 height:109 image:'images/top-gradient.png' index:0 gradient = new Layer parent:playbackBarContainer y: Align.bottom width:1280, height:390 image:'images/playback-bar-bg.png' opacity:1 index:0 playbackLine = new Layer parent:playbackBarContainer width:798, height:4 x:274, y:617 bufferLine = new Layer parent:playbackLine height:4, width:797 backgroundColor: youviewBlue2 playedLine = new Layer parent:bufferLine height:4, width:0 backgroundColor:'#00a6ff' playheadLine = new Layer parent:playedLine height:10, width:4 y:-3, x:Align.right backgroundColor:'#00a6ff' startTime = new TextLayer parent:playbackBarContainer text:'' width:50, height:16 fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5' color:youviewBlue maxY:playbackLine.maxY+4, x:209 endTime = new TextLayer parent:playbackBarContainer autoWidth:true text:'' width:50, height:16 fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5' maxY:playbackLine.maxY+4, x:playbackLine.maxX + 8 patchBack = new Layer parent:playbackBarContainer image:'images/patch-highlight.png' backgroundColor:'rgba(0,0,0,0.95)' height:129 width:130 y:510, x:64 index:0 patchIconContainer = new Layer parent:playbackBarContainer midX:patchBack.midX y:patchBack.y + 24 height:50, width:50 clip:true backgroundColor: 'transparent' patchIcon = new Layer parent:patchIconContainer image:'images/playback-sprites.png' height:750, width:50 x:-1,y:-22 backgroundColor: 'transparent' svgPatchIcon = new Layer parent:patchIconContainer height:50, width:50 backgroundColor:'' visible:false patchRCNInput = new TextLayer parent:patchBack width:120, height:36, y:30 fontFamily: 'sans-serif, fsme-bold', fontSize: 30, textAlign: 'center', letterSpacing: 1.12 color:'#ebebeb' text:'' patchText = new TextLayer parent:playbackBarContainer text:'Play' midX:patchBack.midX y:startTime.y fontFamily:'sans-serif, fsme-bold', fontSize:16, color:'#ebebeb', textTransform:'uppercase', textAlign:'center' height:16, width:128 clip:true backgroundColor: 'transparent' title = new TextLayer parent:playbackBarContainer text:"<NAME>'s Travels" fontFamily:'sans-serif, fsme-light', fontSize:36, color:'#ebebeb' width:848, height:36 x:startTime.x, y:550 remoteNumber = [] remoteNumber.timeOut = 0 for i in [0..9] remoteNumbers = new Layer backgroundColor:'' html:getNumberSVG(i) parent:playbackLine x:80*i-9 height:21, width:20 # backgroundColor:'red' opacity:0 originY:0.2 remoteNumber.push(remoteNumbers) # Instructions instBackground = new Layer width: 500 height: 220 backgroundColor: '#1f1f1f' borderStyle: 'dotted' borderRadius: 20 borderWidth: 2 borderColor: 'white' x: 20, y: 20 instTitle = new TextLayer parent: instBackground text: 'Instructions' x: 30, y: 15, color: white instDesc = new TextLayer parent: instBackground html: '<p style="margin-bottom:5px;">. – fast forward</p> <p style="margin-bottom:5px;">0-9 – number input</p> <p style="margin-bottom:5px;">← or → – D-Pad (move to adjacent number)</p> <p style="margin-bottom:5px;">⏎ – OK / Play</p>', fontSize: 20 x: 30, y: 75, color: white # Clock today = new Date hour = today.getHours() minute = today.getMinutes() Utils.interval 60, -> refreshTime() currentTime = new TextLayer parent:topGradient text:hour + ':' + minute maxX:1216 y:36 fontFamily:'sans-serif, fsme' fontSize:30 color:'#ebebeb' if minute < 10 currentTime.text = hour+':0'+minute else currentTime.text = hour+':'+minute refreshTime = () -> today = new Date hour = today.getHours() minute = today.getMinutes() if minute < 10 currentTime.text = hour+':0'+minute else currentTime.text = hour+':'+minute currentTime.maxX = 1216 refreshTime() #Video Content and Management background = new BackgroundLayer backgroundColor: '#000' recording = new VideoLayer parent:background video:'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4' width:1280, height:720 backgroundColor: '#000' x:0, y:0 # recording.player.autoplay = true # recording.player.muted = true # recording.player.controls = true recording.ignoreEvents = false playTime = recording movePlayhead = () -> # Calculate progress bar position newPos = (playbackLine.width / recording.player.duration) * recording.player.currentTime playheadLine.x = newPos playedLine.width = newPos if getHoursOf(recording.player.duration) > 0 and getHoursOf(recording.player.currentTime) < 1 startTime.text = '0:' + timeParser(recording.player.currentTime) else startTime.text = timeParser(recording.player.currentTime) endTime.text = timeParser(recording.player.duration) recording.player.addEventListener "timeupdate", movePlayhead skipTo = (time, input) -> newPos = playbackLine.width / 10 * input playheadLine.animate x: newPos playedLine.animate width: newPos recording.player.currentTime = time timeParser = (time) -> rationalTime = Math.round(time) if rationalTime < 60 and rationalTime < 10 return '00:0' + rationalTime else if rationalTime < 60 and rationalTime > 9 return '00:' + rationalTime else if rationalTime >= 60 if rationalTime >= 570 if getMinutesOf(rationalTime) < 10 minutes = '0' + getMinutesOf(rationalTime) else minutes = getMinutesOf(rationalTime) else minutes = '0' + getMinutesOf(rationalTime) seconds = getSecondsOf(rationalTime) if seconds < 10 singleDigit = seconds seconds = '0' + singleDigit if rationalTime >= 3600 hours = getHoursOf(rationalTime) return hours + ':' + minutes + ':' + seconds return minutes + ':' + seconds getHoursOf = (rationalTime) -> minutes = rationalTime / 60 hours = Math.floor( minutes / 60 ) return hours getMinutesOf = (rationalTime) -> totalMinutes = rationalTime / 60 minutes = Math.floor( totalMinutes % 60 ) return minutes getSecondsOf = (rationalTime) -> seconds = Math.floor( rationalTime % 60 ) return seconds # Keys del = 8 guide = 9 ok = 13 record = 17 sub = 18 ad = 20 close = 27 pUp = 33 pDown = 34 mainMenu = 36 left = 37 up = 38 right = 39 down = 40 back = 46 zero = 48 one = 49 two = 50 three = 51 four = 52 five = 53 six = 54 seven = 55 eight = 56 nine = 57 info = 73 record = 82 stop = 111 help = 112 myTV = 115 red = 116 green = 117 yellow = 118 blue = 119 pause = 186 rewind = 188 fastForward = 190 stop = 191 mute = 220 play = 222 text = 120 power = 124 search = 192 skipBackward = 219 skipForward = 221 # Key Listener stopKeyInput = () -> document.removeEventListener 'keydown', (event) -> startKeyInput = () -> document.addEventListener 'keydown', (event) -> keyCode = event.which eventHandler(keyCode) event.preventDefault() startKeyInput() barTimeOut = 0 timeOut = 0 eventHandler = Utils.throttle 0.1, (keyCode) -> barTimeOut = 0 showPlaybackBar() switch keyCode when one timeJump(recording.player.duration / 100 * 10, 1) when two timeJump(recording.player.duration / 100 * 20, 2) when three timeJump(recording.player.duration / 100 * 30, 3) when four timeJump(recording.player.duration / 100 * 40, 4) when five timeJump(recording.player.duration / 100 * 50, 5) when six timeJump(recording.player.duration / 100 * 60, 6) when seven timeJump(recording.player.duration / 100 * 70, 7) when eight timeJump(recording.player.duration / 100 * 80, 8) when nine timeJump(recording.player.duration / 100 * 90, 9) when zero timeJump(0, 0) when ok playSpeed(1) timeOut = 5 when fastForward playSpeed(16) when rewind playSpeed(-1) when play playSpeed(1) when red changeVideo() when left findNearest('left') when right findNearest('right') findNearest = (direction) -> #Give or take 5000 now = recording.player.currentTime duration = recording.player.duration currentPercent = now / duration * 100 nearestTenth = Math.round(currentPercent / 10) if (direction == 'right' and nearestTenth <= 8) nearestTenth += 1 timeJump( duration / 100 * nearestTenth * 10, nearestTenth ) else if (now < ( duration / nearestTenth + 5000 ) and nearestTenth > 0) nearestTenth = nearestTenth - 1 timeJump(duration / 100 * nearestTenth*10, nearestTenth) changeVideo = () -> if recording.video == 'video/taboo.mp4' title.text = 'Guardians of the Galaxy' recording.video = 'video/Guardians of the Galaxy_downscale.mp4' recording.player.currentTime = 0 recording.player.play() else if recording.video == 'video/Guardians of the Galaxy_downscale.mp4' recording.video = 'video/taboo.mp4' title.text = 'Taboo' recording.player.currentTime = 0 recording.player.play() clearTimeInput = () -> patchIcon.visible = false patchRCNInput.text = '' patchRCNInput.color = white patchIcon.visible = true patchText.text = 'Play' svgPatchIcon.visible = false Utils.interval 0.5, -> if barTimeOut == 13 hidePlaybackBar() barTimeOut++ timeOut++ timeJump = ( input, label ) -> recording.player.removeEventListener "timeupdate", movePlayhead timeOut = 0 if remoteNumber[0].opacity > 0 jumpToTime(input, label) jumpToTime = ( irrationalTime, label ) -> if irrationalTime < recording.player.duration skipTo( irrationalTime, label ) patchIcon.visible = false svgPatchInserter( label ) for number, i in remoteNumber if i == label selectedNumber = number numberScale = selectedNumber.animate # opacity: 1 # I have no idea why this doesn't work and it's driving me insane. scale: 1.4 options: time:0.4 curve:Spring(damping: 0.3) Utils.delay 1, -> numberScale.reverse().start() else number.scale = 1 number.opacity = 0.6 Utils.delay 2, -> clearTimeInput() startKeyInput() recording.player.addEventListener "timeupdate", movePlayhead playSpeed(1) svgPatchInserter = ( input ) -> patchText.text = 'Jump To' svgPatchIcon.html = getNumberSVG( input ) svgPatchIcon.visible = true playSpeed = (speed) -> recording.player.playbackRate = speed if speed > 1 patchText.text = 'x' + speed recording.player.muted = true showNumbers() else if speed == 1 recording.player.muted = false patchText.text = 'play' if patchText.text != "Jump To" hideNumbers() else if speed < 1 patchText.text = 'x' + -speed showNumbers() Utils.delay 2, -> recording.video = 'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4' recording.player.play() hideNumberAnimations = [] hideNumbers = () -> stopAnimations() for remoteNumbers in remoteNumber hideNumber = remoteNumbers.animate y:18 opacity:0 options: curve:'ease-in-out' time:0.4 delay:5 hideNumberAnimations.push(hideNumber) showNumbers = () -> stopAnimations() if playbackBarContainer.isAnimating playbackBarContainer.onAnimationEnd -> for remoteNumbers in remoteNumber remoteNumbers.animate y:14 opacity:0.6 options: curve:'ease-in-out' time:0.4 else for remoteNumbers in remoteNumber remoteNumbers.animate y:14 opacity:0.6 options: curve:'ease-in-out' time:0.4 stopAnimations = () -> for hideNumber in hideNumberAnimations hideNumber.stop() showPlaybackBar = () -> playbackBarContainer.animate opacity:1 y:0 options: curve:'ease-in-out' time:0.5 topGradient.animate opacity:1 y:0 options: curve:'ease-in-out' time:0.5 hidePlaybackBar = () -> if recording.player.playbackRate == 1 playbackBarContainer.animate opacity:0 y:playbackBarContainer.y+20 options: curve:'ease-in-out' time:0.5 topGradient.animate opacity:0 y:-20 options: curve:'ease-in-out' time:0.5 hideNumbers()
true
# Setup Variables document.body.style.cursor = "auto" Screen.backgroundColor = '#000' Canvas.image = 'https://struanfraser.co.uk/images/youview-back.jpg' youviewBlue = '#00a6ff' youviewBlue2 = '#0F5391' youviewBlue3 = '#032230' youviewGrey1 = '#b6b9bf' youviewGrey2 = '#83858a' darkGrey3 = '#505359' black = '#000' white = '#ebebeb' veryDarkGrey4 = '#171717' veryDarkGrey5 = '#0D0D0D' getNumberSVG = (number) -> return numberSVG = '''<?xml version="1.0" encoding="UTF-8"?> <svg version="1.1" viewBox="0 0 21 20" xmlns="http://www.w3.org/2000/svg"> <g fill="none" fill-rule="evenodd"> <g transform="translate(-805 -645)"> <g transform="translate(271 645)"> <g transform="translate(534.33)"> <path d="m20 10c0 5.523-4.477 10-10 10s-10-4.477-10-10 4.477-10 10-10 10 4.477 10 10" fill="#595959" fill-rule="evenodd"/> <path d="m18 10c0 4.418-3.582 8-8 8s-8-3.582-8-8 3.582-8 8-8 8 3.582 8 8" fill="#000" fill-rule="evenodd"/> <text fill="#EBEBEB" font-family="sans-serif, fsme-Bold, FS Me" font-size="14" font-weight="bold" letter-spacing=".28"> <tspan x="6" y="15">''' + number + '''</tspan></text> </g></g></g></g></svg> ''' Framer.Device.deviceType = "sony-w85Oc" #Playback Bar Layers playbackBarContainer = new Layer width:1280, height:720 backgroundColor:'transparent' topGradient = new Layer # parent:playbackBarContainer width:1280 height:109 image:'images/top-gradient.png' index:0 gradient = new Layer parent:playbackBarContainer y: Align.bottom width:1280, height:390 image:'images/playback-bar-bg.png' opacity:1 index:0 playbackLine = new Layer parent:playbackBarContainer width:798, height:4 x:274, y:617 bufferLine = new Layer parent:playbackLine height:4, width:797 backgroundColor: youviewBlue2 playedLine = new Layer parent:bufferLine height:4, width:0 backgroundColor:'#00a6ff' playheadLine = new Layer parent:playedLine height:10, width:4 y:-3, x:Align.right backgroundColor:'#00a6ff' startTime = new TextLayer parent:playbackBarContainer text:'' width:50, height:16 fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5' color:youviewBlue maxY:playbackLine.maxY+4, x:209 endTime = new TextLayer parent:playbackBarContainer autoWidth:true text:'' width:50, height:16 fontSize:16, fontFamily:'sans-serif, fsme-bold', letterSpacing:0.3, color:'#b5b5b5' maxY:playbackLine.maxY+4, x:playbackLine.maxX + 8 patchBack = new Layer parent:playbackBarContainer image:'images/patch-highlight.png' backgroundColor:'rgba(0,0,0,0.95)' height:129 width:130 y:510, x:64 index:0 patchIconContainer = new Layer parent:playbackBarContainer midX:patchBack.midX y:patchBack.y + 24 height:50, width:50 clip:true backgroundColor: 'transparent' patchIcon = new Layer parent:patchIconContainer image:'images/playback-sprites.png' height:750, width:50 x:-1,y:-22 backgroundColor: 'transparent' svgPatchIcon = new Layer parent:patchIconContainer height:50, width:50 backgroundColor:'' visible:false patchRCNInput = new TextLayer parent:patchBack width:120, height:36, y:30 fontFamily: 'sans-serif, fsme-bold', fontSize: 30, textAlign: 'center', letterSpacing: 1.12 color:'#ebebeb' text:'' patchText = new TextLayer parent:playbackBarContainer text:'Play' midX:patchBack.midX y:startTime.y fontFamily:'sans-serif, fsme-bold', fontSize:16, color:'#ebebeb', textTransform:'uppercase', textAlign:'center' height:16, width:128 clip:true backgroundColor: 'transparent' title = new TextLayer parent:playbackBarContainer text:"PI:NAME:<NAME>END_PI's Travels" fontFamily:'sans-serif, fsme-light', fontSize:36, color:'#ebebeb' width:848, height:36 x:startTime.x, y:550 remoteNumber = [] remoteNumber.timeOut = 0 for i in [0..9] remoteNumbers = new Layer backgroundColor:'' html:getNumberSVG(i) parent:playbackLine x:80*i-9 height:21, width:20 # backgroundColor:'red' opacity:0 originY:0.2 remoteNumber.push(remoteNumbers) # Instructions instBackground = new Layer width: 500 height: 220 backgroundColor: '#1f1f1f' borderStyle: 'dotted' borderRadius: 20 borderWidth: 2 borderColor: 'white' x: 20, y: 20 instTitle = new TextLayer parent: instBackground text: 'Instructions' x: 30, y: 15, color: white instDesc = new TextLayer parent: instBackground html: '<p style="margin-bottom:5px;">. – fast forward</p> <p style="margin-bottom:5px;">0-9 – number input</p> <p style="margin-bottom:5px;">← or → – D-Pad (move to adjacent number)</p> <p style="margin-bottom:5px;">⏎ – OK / Play</p>', fontSize: 20 x: 30, y: 75, color: white # Clock today = new Date hour = today.getHours() minute = today.getMinutes() Utils.interval 60, -> refreshTime() currentTime = new TextLayer parent:topGradient text:hour + ':' + minute maxX:1216 y:36 fontFamily:'sans-serif, fsme' fontSize:30 color:'#ebebeb' if minute < 10 currentTime.text = hour+':0'+minute else currentTime.text = hour+':'+minute refreshTime = () -> today = new Date hour = today.getHours() minute = today.getMinutes() if minute < 10 currentTime.text = hour+':0'+minute else currentTime.text = hour+':'+minute currentTime.maxX = 1216 refreshTime() #Video Content and Management background = new BackgroundLayer backgroundColor: '#000' recording = new VideoLayer parent:background video:'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4' width:1280, height:720 backgroundColor: '#000' x:0, y:0 # recording.player.autoplay = true # recording.player.muted = true # recording.player.controls = true recording.ignoreEvents = false playTime = recording movePlayhead = () -> # Calculate progress bar position newPos = (playbackLine.width / recording.player.duration) * recording.player.currentTime playheadLine.x = newPos playedLine.width = newPos if getHoursOf(recording.player.duration) > 0 and getHoursOf(recording.player.currentTime) < 1 startTime.text = '0:' + timeParser(recording.player.currentTime) else startTime.text = timeParser(recording.player.currentTime) endTime.text = timeParser(recording.player.duration) recording.player.addEventListener "timeupdate", movePlayhead skipTo = (time, input) -> newPos = playbackLine.width / 10 * input playheadLine.animate x: newPos playedLine.animate width: newPos recording.player.currentTime = time timeParser = (time) -> rationalTime = Math.round(time) if rationalTime < 60 and rationalTime < 10 return '00:0' + rationalTime else if rationalTime < 60 and rationalTime > 9 return '00:' + rationalTime else if rationalTime >= 60 if rationalTime >= 570 if getMinutesOf(rationalTime) < 10 minutes = '0' + getMinutesOf(rationalTime) else minutes = getMinutesOf(rationalTime) else minutes = '0' + getMinutesOf(rationalTime) seconds = getSecondsOf(rationalTime) if seconds < 10 singleDigit = seconds seconds = '0' + singleDigit if rationalTime >= 3600 hours = getHoursOf(rationalTime) return hours + ':' + minutes + ':' + seconds return minutes + ':' + seconds getHoursOf = (rationalTime) -> minutes = rationalTime / 60 hours = Math.floor( minutes / 60 ) return hours getMinutesOf = (rationalTime) -> totalMinutes = rationalTime / 60 minutes = Math.floor( totalMinutes % 60 ) return minutes getSecondsOf = (rationalTime) -> seconds = Math.floor( rationalTime % 60 ) return seconds # Keys del = 8 guide = 9 ok = 13 record = 17 sub = 18 ad = 20 close = 27 pUp = 33 pDown = 34 mainMenu = 36 left = 37 up = 38 right = 39 down = 40 back = 46 zero = 48 one = 49 two = 50 three = 51 four = 52 five = 53 six = 54 seven = 55 eight = 56 nine = 57 info = 73 record = 82 stop = 111 help = 112 myTV = 115 red = 116 green = 117 yellow = 118 blue = 119 pause = 186 rewind = 188 fastForward = 190 stop = 191 mute = 220 play = 222 text = 120 power = 124 search = 192 skipBackward = 219 skipForward = 221 # Key Listener stopKeyInput = () -> document.removeEventListener 'keydown', (event) -> startKeyInput = () -> document.addEventListener 'keydown', (event) -> keyCode = event.which eventHandler(keyCode) event.preventDefault() startKeyInput() barTimeOut = 0 timeOut = 0 eventHandler = Utils.throttle 0.1, (keyCode) -> barTimeOut = 0 showPlaybackBar() switch keyCode when one timeJump(recording.player.duration / 100 * 10, 1) when two timeJump(recording.player.duration / 100 * 20, 2) when three timeJump(recording.player.duration / 100 * 30, 3) when four timeJump(recording.player.duration / 100 * 40, 4) when five timeJump(recording.player.duration / 100 * 50, 5) when six timeJump(recording.player.duration / 100 * 60, 6) when seven timeJump(recording.player.duration / 100 * 70, 7) when eight timeJump(recording.player.duration / 100 * 80, 8) when nine timeJump(recording.player.duration / 100 * 90, 9) when zero timeJump(0, 0) when ok playSpeed(1) timeOut = 5 when fastForward playSpeed(16) when rewind playSpeed(-1) when play playSpeed(1) when red changeVideo() when left findNearest('left') when right findNearest('right') findNearest = (direction) -> #Give or take 5000 now = recording.player.currentTime duration = recording.player.duration currentPercent = now / duration * 100 nearestTenth = Math.round(currentPercent / 10) if (direction == 'right' and nearestTenth <= 8) nearestTenth += 1 timeJump( duration / 100 * nearestTenth * 10, nearestTenth ) else if (now < ( duration / nearestTenth + 5000 ) and nearestTenth > 0) nearestTenth = nearestTenth - 1 timeJump(duration / 100 * nearestTenth*10, nearestTenth) changeVideo = () -> if recording.video == 'video/taboo.mp4' title.text = 'Guardians of the Galaxy' recording.video = 'video/Guardians of the Galaxy_downscale.mp4' recording.player.currentTime = 0 recording.player.play() else if recording.video == 'video/Guardians of the Galaxy_downscale.mp4' recording.video = 'video/taboo.mp4' title.text = 'Taboo' recording.player.currentTime = 0 recording.player.play() clearTimeInput = () -> patchIcon.visible = false patchRCNInput.text = '' patchRCNInput.color = white patchIcon.visible = true patchText.text = 'Play' svgPatchIcon.visible = false Utils.interval 0.5, -> if barTimeOut == 13 hidePlaybackBar() barTimeOut++ timeOut++ timeJump = ( input, label ) -> recording.player.removeEventListener "timeupdate", movePlayhead timeOut = 0 if remoteNumber[0].opacity > 0 jumpToTime(input, label) jumpToTime = ( irrationalTime, label ) -> if irrationalTime < recording.player.duration skipTo( irrationalTime, label ) patchIcon.visible = false svgPatchInserter( label ) for number, i in remoteNumber if i == label selectedNumber = number numberScale = selectedNumber.animate # opacity: 1 # I have no idea why this doesn't work and it's driving me insane. scale: 1.4 options: time:0.4 curve:Spring(damping: 0.3) Utils.delay 1, -> numberScale.reverse().start() else number.scale = 1 number.opacity = 0.6 Utils.delay 2, -> clearTimeInput() startKeyInput() recording.player.addEventListener "timeupdate", movePlayhead playSpeed(1) svgPatchInserter = ( input ) -> patchText.text = 'Jump To' svgPatchIcon.html = getNumberSVG( input ) svgPatchIcon.visible = true playSpeed = (speed) -> recording.player.playbackRate = speed if speed > 1 patchText.text = 'x' + speed recording.player.muted = true showNumbers() else if speed == 1 recording.player.muted = false patchText.text = 'play' if patchText.text != "Jump To" hideNumbers() else if speed < 1 patchText.text = 'x' + -speed showNumbers() Utils.delay 2, -> recording.video = 'https://ia800207.us.archive.org/10/items/GulliversTravels720p/GulliversTravels1939_512kb.mp4' recording.player.play() hideNumberAnimations = [] hideNumbers = () -> stopAnimations() for remoteNumbers in remoteNumber hideNumber = remoteNumbers.animate y:18 opacity:0 options: curve:'ease-in-out' time:0.4 delay:5 hideNumberAnimations.push(hideNumber) showNumbers = () -> stopAnimations() if playbackBarContainer.isAnimating playbackBarContainer.onAnimationEnd -> for remoteNumbers in remoteNumber remoteNumbers.animate y:14 opacity:0.6 options: curve:'ease-in-out' time:0.4 else for remoteNumbers in remoteNumber remoteNumbers.animate y:14 opacity:0.6 options: curve:'ease-in-out' time:0.4 stopAnimations = () -> for hideNumber in hideNumberAnimations hideNumber.stop() showPlaybackBar = () -> playbackBarContainer.animate opacity:1 y:0 options: curve:'ease-in-out' time:0.5 topGradient.animate opacity:1 y:0 options: curve:'ease-in-out' time:0.5 hidePlaybackBar = () -> if recording.player.playbackRate == 1 playbackBarContainer.animate opacity:0 y:playbackBarContainer.y+20 options: curve:'ease-in-out' time:0.5 topGradient.animate opacity:0 y:-20 options: curve:'ease-in-out' time:0.5 hideNumbers()
[ { "context": "\n\n data =\n '1Z6089649053538738':\n name: 'Grag Clerk'\n address: '1885 Hummingbird Way, Winchester", "end": 839, "score": 0.9997916221618652, "start": 829, "tag": "NAME", "value": "Grag Clerk" } ]
app/ng/app.integration.coffee
jluchiji/tranzit
0
# ______ ______ ______ __ __ ______ __ ______ # /\__ _\ /\ == \ /\ __ \ /\ "-.\ \ /\___ \ /\ \ /\__ _\ # \/_/\ \/ \ \ __< \ \ __ \ \ \ \-. \ \/_/ /__ \ \ \ \/_/\ \/ # \ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\\"\_\ /\_____\ \ \_\ \ \_\ # \/_/ \/_/ /_/ \/_/\/_/ \/_/ \/_/ \/_____/ \/_/ \/_/ # # Copyright © 2015 Tranzit Development Team angular.module 'Tranzit.app.integration', [] .service 'AppIntegration', ($state, $q) -> # Fake 3rd party API integration. # In this particular case, we shall pull from hard-coded JSON. # We also add random delays to simulate network lag. random = (min, max) -> Math.floor(Math.random() * (max - min)) + min options = lag: min: 100 max: 1000 data = '1Z6089649053538738': name: 'Grag Clerk' address: '1885 Hummingbird Way, Winchester, MA' self = { } self.getInfo = (tracking) -> deferred = $q.defer() setTimeout (-> console.log data[tracking] if data[tracking] deferred.resolve(data[tracking]) else deferred.reject(src: 'tranzit.app.integration',status: 404, message: 'Package not found.') ), random(options.lag.min, options.lag.max) return deferred.promise return self
137792
# ______ ______ ______ __ __ ______ __ ______ # /\__ _\ /\ == \ /\ __ \ /\ "-.\ \ /\___ \ /\ \ /\__ _\ # \/_/\ \/ \ \ __< \ \ __ \ \ \ \-. \ \/_/ /__ \ \ \ \/_/\ \/ # \ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\\"\_\ /\_____\ \ \_\ \ \_\ # \/_/ \/_/ /_/ \/_/\/_/ \/_/ \/_/ \/_____/ \/_/ \/_/ # # Copyright © 2015 Tranzit Development Team angular.module 'Tranzit.app.integration', [] .service 'AppIntegration', ($state, $q) -> # Fake 3rd party API integration. # In this particular case, we shall pull from hard-coded JSON. # We also add random delays to simulate network lag. random = (min, max) -> Math.floor(Math.random() * (max - min)) + min options = lag: min: 100 max: 1000 data = '1Z6089649053538738': name: '<NAME>' address: '1885 Hummingbird Way, Winchester, MA' self = { } self.getInfo = (tracking) -> deferred = $q.defer() setTimeout (-> console.log data[tracking] if data[tracking] deferred.resolve(data[tracking]) else deferred.reject(src: 'tranzit.app.integration',status: 404, message: 'Package not found.') ), random(options.lag.min, options.lag.max) return deferred.promise return self
true
# ______ ______ ______ __ __ ______ __ ______ # /\__ _\ /\ == \ /\ __ \ /\ "-.\ \ /\___ \ /\ \ /\__ _\ # \/_/\ \/ \ \ __< \ \ __ \ \ \ \-. \ \/_/ /__ \ \ \ \/_/\ \/ # \ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\\"\_\ /\_____\ \ \_\ \ \_\ # \/_/ \/_/ /_/ \/_/\/_/ \/_/ \/_/ \/_____/ \/_/ \/_/ # # Copyright © 2015 Tranzit Development Team angular.module 'Tranzit.app.integration', [] .service 'AppIntegration', ($state, $q) -> # Fake 3rd party API integration. # In this particular case, we shall pull from hard-coded JSON. # We also add random delays to simulate network lag. random = (min, max) -> Math.floor(Math.random() * (max - min)) + min options = lag: min: 100 max: 1000 data = '1Z6089649053538738': name: 'PI:NAME:<NAME>END_PI' address: '1885 Hummingbird Way, Winchester, MA' self = { } self.getInfo = (tracking) -> deferred = $q.defer() setTimeout (-> console.log data[tracking] if data[tracking] deferred.resolve(data[tracking]) else deferred.reject(src: 'tranzit.app.integration',status: 404, message: 'Package not found.') ), random(options.lag.min, options.lag.max) return deferred.promise return self
[ { "context": "hclaw/pawn-sublime-language\n# Converter created by Renato \"Hii\" Garcia\n# Repo: https://github.com/Renato-Ga", "end": 165, "score": 0.9996509552001953, "start": 159, "tag": "NAME", "value": "Renato" }, { "context": "n-sublime-language\n# Converter created by Renato \"Hii\" Garcia\n# Repo: https://github.com/Renato-Garcia/sublime-", "end": 178, "score": 0.9200428128242493, "start": 167, "tag": "NAME", "value": "Hii\" Garcia" }, { "context": "by Renato \"Hii\" Garcia\n# Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets\n'.source.pwn", "end": 219, "score": 0.9931445717811584, "start": 206, "tag": "USERNAME", "value": "Renato-Garcia" }, { "context": " 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'IsValidButton':\n 'prefix': 'IsValidBu", "end": 1295, "score": 0.6607813835144043, "start": 1291, "tag": "USERNAME", "value": "claw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonArea':\n 'prefix': 'SetButton", "end": 1683, "score": 0.9996383786201477, "start": 1674, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonLabel':\n 'prefix': 'SetButto", "end": 1890, "score": 0.9996444582939148, "start": 1881, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'DestroyButtonLabel':\n 'prefix': 'Dest", "end": 2190, "score": 0.999565601348877, "start": 2181, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonPos':\n 'prefix': 'GetButtonP", "end": 2399, "score": 0.9995312690734863, "start": 2390, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonPos':\n 'prefix': 'SetButtonP", "end": 2632, "score": 0.9995844960212708, "start": 2623, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonSize':\n 'prefix': 'GetButton", "end": 2865, "score": 0.9996169209480286, "start": 2856, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonSize':\n 'prefix': 'SetButton", "end": 3059, "score": 0.9991700053215027, "start": 3050, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonWorld':\n 'prefix': 'GetButto", "end": 3270, "score": 0.9996506571769714, "start": 3261, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonWorld':\n 'prefix': 'SetButto", "end": 3467, "score": 0.9996523857116699, "start": 3458, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonInterior':\n 'prefix': 'GetBu", "end": 3676, "score": 0.999607503414154, "start": 3667, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonInterior':\n 'prefix': 'SetBu", "end": 3882, "score": 0.9995846748352051, "start": 3873, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonLinkedID':\n 'prefix': 'GetBu", "end": 4103, "score": 0.9995630383491516, "start": 4094, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonText':\n 'prefix': 'GetButton", "end": 4309, "score": 0.9994885921478271, "start": 4300, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonText':\n 'prefix': 'SetButton", "end": 4516, "score": 0.9995255470275879, "start": 4507, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'SetButtonExtraData':\n 'prefix': 'SetB", "end": 4723, "score": 0.9986869692802429, "start": 4714, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonExtraData':\n 'prefix': 'GetB", "end": 4943, "score": 0.9996708035469055, "start": 4934, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerPressingButton':\n 'prefix': ", "end": 5152, "score": 0.9996612668037415, "start": 5143, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerButtonID':\n 'prefix': 'GetPl", "end": 5376, "score": 0.9996400475502014, "start": 5367, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerButtonList':\n 'prefix': 'Get", "end": 5582, "score": 0.9996592998504639, "start": 5573, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerAngleToButton':\n 'prefix': '", "end": 5846, "score": 0.9996581077575684, "start": 5837, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetButtonAngleToPlayer':\n 'prefix': '", "end": 6082, "score": 0.9996707439422607, "start": 6073, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'OnButtonPress':\n 'prefix': 'OnButtonP", "end": 6318, "score": 0.9996626973152161, "start": 6309, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'OnButtonRelease':\n 'prefix': 'OnButto", "end": 6527, "score": 0.9996740221977234, "start": 6518, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'OnPlayerEnterButtonArea':\n 'prefix': ", "end": 6742, "score": 0.9996726512908936, "start": 6733, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'OnPlayerLeaveButtonArea':\n 'prefix': ", "end": 6981, "score": 0.9995768070220947, "start": 6972, "tag": "USERNAME", "value": "Southclaw" }, { "context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n", "end": 7220, "score": 0.9996926188468933, "start": 7211, "tag": "USERNAME", "value": "Southclaw" } ]
snippets/SIF.Button.pwn.cson
Wuzi/language-pawn
4
# SIF.Button.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by Renato "Hii" Garcia # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'CreateButton': 'prefix': 'CreateButton' 'body': 'CreateButton(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:text[]}, ${5:world = 0}, ${6:interior = 0}, ${7:Float:areasize = 1.0}, ${8:label = 0}, ${9:labeltext[] = \"\"}, ${10:labelcolour = 0xFFFF00FF}, ${11:Float:streamdist = BTN_DEFAULT_STREAMDIST}, ${12:testlos = true})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'DestroyButton': 'prefix': 'DestroyButton' 'body': 'DestroyButton(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'LinkTP': 'prefix': 'LinkTP' 'body': 'LinkTP(${1:buttonid1}, ${2:buttonid2})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'UnLinkTP': 'prefix': 'UnLinkTP' 'body': 'UnLinkTP(${1:buttonid1}, ${2:buttonid2})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'IsValidButton': 'prefix': 'IsValidButton' 'body': 'IsValidButton(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonArea': 'prefix': 'GetButtonArea' 'body': 'GetButtonArea(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonArea': 'prefix': 'SetButtonArea' 'body': 'SetButtonArea(${1:buttonid}, ${2:areaid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonLabel': 'prefix': 'SetButtonLabel' 'body': 'SetButtonLabel(${1:buttonid}, ${2:text[]}, ${3:colour = 0xFFFF00FF}, ${4:Float:range = BTN_DEFAULT_STREAMDIST}, ${5:testlos = true})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'DestroyButtonLabel': 'prefix': 'DestroyButtonLabel' 'body': 'DestroyButtonLabel(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonPos': 'prefix': 'GetButtonPos' 'body': 'GetButtonPos(${1:buttonid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonPos': 'prefix': 'SetButtonPos' 'body': 'SetButtonPos(${1:buttonid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonSize': 'prefix': 'GetButtonSize' 'body': 'GetButtonSize(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonSize': 'prefix': 'SetButtonSize' 'body': 'SetButtonSize(${1:buttonid}, ${2:Float:size})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonWorld': 'prefix': 'GetButtonWorld' 'body': 'GetButtonWorld(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonWorld': 'prefix': 'SetButtonWorld' 'body': 'SetButtonWorld(${1:buttonid}, ${2:world})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonInterior': 'prefix': 'GetButtonInterior' 'body': 'GetButtonInterior(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonInterior': 'prefix': 'SetButtonInterior' 'body': 'SetButtonInterior(${1:buttonid}, ${2:interior})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonLinkedID': 'prefix': 'GetButtonLinkedID' 'body': 'GetButtonLinkedID(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonText': 'prefix': 'GetButtonText' 'body': 'GetButtonText(${1:buttonid}, ${2:text[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonText': 'prefix': 'SetButtonText' 'body': 'SetButtonText(${1:buttonid}, ${2:text[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonExtraData': 'prefix': 'SetButtonExtraData' 'body': 'SetButtonExtraData(${1:buttonid}, ${2:data})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonExtraData': 'prefix': 'GetButtonExtraData' 'body': 'GetButtonExtraData(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerPressingButton': 'prefix': 'GetPlayerPressingButton' 'body': 'GetPlayerPressingButton(${1:playerid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerButtonID': 'prefix': 'GetPlayerButtonID' 'body': 'GetPlayerButtonID(${1:playerid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerButtonList': 'prefix': 'GetPlayerButtonList' 'body': 'GetPlayerButtonList(${1:playerid}, ${2:list[]}, ${3:size}, ${4:bool:validate = false})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerAngleToButton': 'prefix': 'GetPlayerAngleToButton' 'body': 'GetPlayerAngleToButton(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonAngleToPlayer': 'prefix': 'GetButtonAngleToPlayer' 'body': 'GetButtonAngleToPlayer(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnButtonPress': 'prefix': 'OnButtonPress' 'body': 'OnButtonPress(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnButtonRelease': 'prefix': 'OnButtonRelease' 'body': 'OnButtonRelease(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnPlayerEnterButtonArea': 'prefix': 'OnPlayerEnterButtonArea' 'body': 'OnPlayerEnterButtonArea(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnPlayerLeaveButtonArea': 'prefix': 'OnPlayerLeaveButtonArea' 'body': 'OnPlayerLeaveButtonArea(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
87903
# SIF.Button.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by <NAME> "<NAME> # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'CreateButton': 'prefix': 'CreateButton' 'body': 'CreateButton(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:text[]}, ${5:world = 0}, ${6:interior = 0}, ${7:Float:areasize = 1.0}, ${8:label = 0}, ${9:labeltext[] = \"\"}, ${10:labelcolour = 0xFFFF00FF}, ${11:Float:streamdist = BTN_DEFAULT_STREAMDIST}, ${12:testlos = true})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'DestroyButton': 'prefix': 'DestroyButton' 'body': 'DestroyButton(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'LinkTP': 'prefix': 'LinkTP' 'body': 'LinkTP(${1:buttonid1}, ${2:buttonid2})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'UnLinkTP': 'prefix': 'UnLinkTP' 'body': 'UnLinkTP(${1:buttonid1}, ${2:buttonid2})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'IsValidButton': 'prefix': 'IsValidButton' 'body': 'IsValidButton(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonArea': 'prefix': 'GetButtonArea' 'body': 'GetButtonArea(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonArea': 'prefix': 'SetButtonArea' 'body': 'SetButtonArea(${1:buttonid}, ${2:areaid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonLabel': 'prefix': 'SetButtonLabel' 'body': 'SetButtonLabel(${1:buttonid}, ${2:text[]}, ${3:colour = 0xFFFF00FF}, ${4:Float:range = BTN_DEFAULT_STREAMDIST}, ${5:testlos = true})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'DestroyButtonLabel': 'prefix': 'DestroyButtonLabel' 'body': 'DestroyButtonLabel(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonPos': 'prefix': 'GetButtonPos' 'body': 'GetButtonPos(${1:buttonid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonPos': 'prefix': 'SetButtonPos' 'body': 'SetButtonPos(${1:buttonid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonSize': 'prefix': 'GetButtonSize' 'body': 'GetButtonSize(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonSize': 'prefix': 'SetButtonSize' 'body': 'SetButtonSize(${1:buttonid}, ${2:Float:size})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonWorld': 'prefix': 'GetButtonWorld' 'body': 'GetButtonWorld(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonWorld': 'prefix': 'SetButtonWorld' 'body': 'SetButtonWorld(${1:buttonid}, ${2:world})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonInterior': 'prefix': 'GetButtonInterior' 'body': 'GetButtonInterior(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonInterior': 'prefix': 'SetButtonInterior' 'body': 'SetButtonInterior(${1:buttonid}, ${2:interior})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonLinkedID': 'prefix': 'GetButtonLinkedID' 'body': 'GetButtonLinkedID(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonText': 'prefix': 'GetButtonText' 'body': 'GetButtonText(${1:buttonid}, ${2:text[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonText': 'prefix': 'SetButtonText' 'body': 'SetButtonText(${1:buttonid}, ${2:text[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonExtraData': 'prefix': 'SetButtonExtraData' 'body': 'SetButtonExtraData(${1:buttonid}, ${2:data})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonExtraData': 'prefix': 'GetButtonExtraData' 'body': 'GetButtonExtraData(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerPressingButton': 'prefix': 'GetPlayerPressingButton' 'body': 'GetPlayerPressingButton(${1:playerid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerButtonID': 'prefix': 'GetPlayerButtonID' 'body': 'GetPlayerButtonID(${1:playerid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerButtonList': 'prefix': 'GetPlayerButtonList' 'body': 'GetPlayerButtonList(${1:playerid}, ${2:list[]}, ${3:size}, ${4:bool:validate = false})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerAngleToButton': 'prefix': 'GetPlayerAngleToButton' 'body': 'GetPlayerAngleToButton(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonAngleToPlayer': 'prefix': 'GetButtonAngleToPlayer' 'body': 'GetButtonAngleToPlayer(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnButtonPress': 'prefix': 'OnButtonPress' 'body': 'OnButtonPress(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnButtonRelease': 'prefix': 'OnButtonRelease' 'body': 'OnButtonRelease(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnPlayerEnterButtonArea': 'prefix': 'OnPlayerEnterButtonArea' 'body': 'OnPlayerEnterButtonArea(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnPlayerLeaveButtonArea': 'prefix': 'OnPlayerLeaveButtonArea' 'body': 'OnPlayerLeaveButtonArea(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
true
# SIF.Button.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'CreateButton': 'prefix': 'CreateButton' 'body': 'CreateButton(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:text[]}, ${5:world = 0}, ${6:interior = 0}, ${7:Float:areasize = 1.0}, ${8:label = 0}, ${9:labeltext[] = \"\"}, ${10:labelcolour = 0xFFFF00FF}, ${11:Float:streamdist = BTN_DEFAULT_STREAMDIST}, ${12:testlos = true})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'DestroyButton': 'prefix': 'DestroyButton' 'body': 'DestroyButton(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'LinkTP': 'prefix': 'LinkTP' 'body': 'LinkTP(${1:buttonid1}, ${2:buttonid2})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'UnLinkTP': 'prefix': 'UnLinkTP' 'body': 'UnLinkTP(${1:buttonid1}, ${2:buttonid2})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'IsValidButton': 'prefix': 'IsValidButton' 'body': 'IsValidButton(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonArea': 'prefix': 'GetButtonArea' 'body': 'GetButtonArea(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonArea': 'prefix': 'SetButtonArea' 'body': 'SetButtonArea(${1:buttonid}, ${2:areaid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonLabel': 'prefix': 'SetButtonLabel' 'body': 'SetButtonLabel(${1:buttonid}, ${2:text[]}, ${3:colour = 0xFFFF00FF}, ${4:Float:range = BTN_DEFAULT_STREAMDIST}, ${5:testlos = true})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'DestroyButtonLabel': 'prefix': 'DestroyButtonLabel' 'body': 'DestroyButtonLabel(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonPos': 'prefix': 'GetButtonPos' 'body': 'GetButtonPos(${1:buttonid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonPos': 'prefix': 'SetButtonPos' 'body': 'SetButtonPos(${1:buttonid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonSize': 'prefix': 'GetButtonSize' 'body': 'GetButtonSize(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonSize': 'prefix': 'SetButtonSize' 'body': 'SetButtonSize(${1:buttonid}, ${2:Float:size})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonWorld': 'prefix': 'GetButtonWorld' 'body': 'GetButtonWorld(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonWorld': 'prefix': 'SetButtonWorld' 'body': 'SetButtonWorld(${1:buttonid}, ${2:world})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonInterior': 'prefix': 'GetButtonInterior' 'body': 'GetButtonInterior(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonInterior': 'prefix': 'SetButtonInterior' 'body': 'SetButtonInterior(${1:buttonid}, ${2:interior})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonLinkedID': 'prefix': 'GetButtonLinkedID' 'body': 'GetButtonLinkedID(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonText': 'prefix': 'GetButtonText' 'body': 'GetButtonText(${1:buttonid}, ${2:text[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonText': 'prefix': 'SetButtonText' 'body': 'SetButtonText(${1:buttonid}, ${2:text[]})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'SetButtonExtraData': 'prefix': 'SetButtonExtraData' 'body': 'SetButtonExtraData(${1:buttonid}, ${2:data})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonExtraData': 'prefix': 'GetButtonExtraData' 'body': 'GetButtonExtraData(${1:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerPressingButton': 'prefix': 'GetPlayerPressingButton' 'body': 'GetPlayerPressingButton(${1:playerid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerButtonID': 'prefix': 'GetPlayerButtonID' 'body': 'GetPlayerButtonID(${1:playerid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerButtonList': 'prefix': 'GetPlayerButtonList' 'body': 'GetPlayerButtonList(${1:playerid}, ${2:list[]}, ${3:size}, ${4:bool:validate = false})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetPlayerAngleToButton': 'prefix': 'GetPlayerAngleToButton' 'body': 'GetPlayerAngleToButton(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'GetButtonAngleToPlayer': 'prefix': 'GetButtonAngleToPlayer' 'body': 'GetButtonAngleToPlayer(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnButtonPress': 'prefix': 'OnButtonPress' 'body': 'OnButtonPress(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnButtonRelease': 'prefix': 'OnButtonRelease' 'body': 'OnButtonRelease(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnPlayerEnterButtonArea': 'prefix': 'OnPlayerEnterButtonArea' 'body': 'OnPlayerEnterButtonArea(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF' 'OnPlayerLeaveButtonArea': 'prefix': 'OnPlayerLeaveButtonArea' 'body': 'OnPlayerLeaveButtonArea(${1:playerid}, ${2:buttonid})' 'description': 'Function from: SIF' 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
[ { "context": " creds = plain_auth.split(':')\n # authToken = \"Bearer #{creds[0]}\"\n authToken = socket?.handshake?.query?.toke", "end": 1601, "score": 0.9085640907287598, "start": 1585, "tag": "KEY", "value": "Bearer #{creds[0" } ]
src/websocket-publisher.coffee
iti-ict/localstamp
1
sio = require 'socket.io' klogger = require 'k-logger' moment = require 'moment' events = sys = require 'events' EMITTED_EVENTS_NAME = 'ecloud-event' AUTHENTICATION_ERROR = 'Authentication error' class WebsocketPublisher constructor: (@httpServer, @httpAuthenticator) -> @logger = klogger.getLogger 'Websocket' # @logger.debug = console.log # @logger.info = console.log # @logger.error = console.log # @logger.warn = console.log @logger.info 'WebsocketPublisher.constructor' # Setup a Socket.io websocket to listen on the server @socketIO = sio.listen @httpServer # Configure Websocket handshake for authentication @socketIO.use (socket, next) => @sioHandshaker socket, next @socketIO.on 'connection', (socket) => @sioConnectionHandler socket @evtInstanceBuffer = {} @deployed = {} @instanceCreated = {} @socketsByUserId = {} @local = new events.EventEmitter() sioHandshaker: (socket, next) -> meth = 'WSPublisher.handshake' # authHeader = socket?.request?.headers?.authorization # if not authHeader? # @logger.info "#{meth} - Access denied for anonymous request." # return next new Error AUTHENTICATION_ERROR # [protocol, basic] = authHeader.split ' ' # if protocol isnt 'Basic' # @logger.info "#{meth} - Access denied for incorrect protocol \ # #{protocol} request." # return next new Error AUTHENTICATION_ERROR # buf = new Buffer(basic, 'base64') # plain_auth = buf.toString() # creds = plain_auth.split(':') # authToken = "Bearer #{creds[0]}" authToken = socket?.handshake?.query?.token @logger.info "#{meth}" socket.user = {id:'local-stamp'} next() # if (not authToken?) or (authToken is '') # @logger.info "#{meth} - Access denied for anonymous request." # @httpAuthenticator.authenticate "Bearer #{authToken}" # .then (userData) => # socket.user = userData # @logger.info "#{meth} - User authenticated: #{JSON.stringify userData}" # next() # .fail (err) => # @logger.info "#{meth} - Access denied for token #{authToken}." # next new Error AUTHENTICATION_ERROR sioConnectionHandler: (socket) -> meth = 'WSPublisher.onConnection' if not socket.user? @logger.error "#{meth} - Socket not authenticated correctly." socket.emit 'error' ,'Connection not authenticated correctly. Disconnecting.' socket.disconnect() else @logger.info "#{meth} - Socket #{socket.id} connected. User: " + "#{JSON.stringify socket.user}" @addUserSocket socket @configureSocketHandlers socket configureSocketHandlers: (socket) -> socket.on 'disconnect', (reason) => @socketDisconnectionHandler socket, reason socket.on 'error', (error) => @socketErrorHandler socket, error socketDisconnectionHandler: (socket, reason) -> meth = 'WSPublisher.onSocketDisconnection' @logger.info "#{meth} - Socket #{socket.id} - Reason: #{reason}" @removeUserSocket socket socketErrorHandler: (socket, error) -> @logger.info "WSPublisher.onSocketError - User: #{socket.user.id} - " + "Error: #{error.message}" # Add a socket to the user socket list if it's not already there. # # The user socket list is a two-level dictionary, by user ID and socket ID: # { # "user1": { # "sock1" : socketObj1, # "sock2" : socketObj2, # "sock3" : socketObj3 # }, # "user2": { # "sock5" : socketObj5, # "sock23" : socketObj23, # "sock12" : socketObj12 # } # } addUserSocket: (socket) -> meth = 'WebsocketPublisher.addUserSocket' userId = socket.user.id if userId not of @socketsByUserId @socketsByUserId[userId] = {} if socket.id not of @socketsByUserId[userId] @socketsByUserId[userId][socket.id] = socket @logger.debug "#{meth} - Socket #{socket.id} added to #{userId} list." else @logger.debug "#{meth} - Socket #{socket.id} already in #{userId} list." # Removes a socket from the user socket list. removeUserSocket: (socket) -> meth = 'WebsocketPublisher.removeUserSocket' userId = socket.user.id if userId of @socketsByUserId if socket.id of @socketsByUserId[userId] delete @socketsByUserId[userId][socket.id] @logger.debug "#{meth} - Removed #{socket.id} from #{userId} list." if Object.keys(@socketsByUserId[userId]).length is 0 delete @socketsByUserId[userId] @logger.debug "#{meth} - Removed #{userId} from list." else @logger.debug "#{meth} - Socket #{socket.id} not in #{userId} list." else @logger.debug "#{meth} - User #{userId} not in socket list." publish: (evt) -> meth = 'WebsocketPublisher.publish' evtStr = JSON.stringify evt if not evt.owner? @logger.debug "#{meth} - Event data has no owner: #{evtStr}" else if evt.owner not of @socketsByUserId @logger.debug "#{meth} - Event owner has no active sockets: #{evtStr}" else @logger.debug "#{meth} - Emitting event to client sockets: #{evtStr}" for sid, s of @socketsByUserId[evt.owner] @logger.debug "#{meth} - Emitting event to socket #{sid}: #{evtStr}" try s.emit EMITTED_EVENTS_NAME, evt catch err @logger.warn "#{meth} - Error emitting: #{err.message} - #{evtStr}" @local.emit 'event', evt directPublish: (type, evt) -> for sid, s of @socketsByUserId['local-stamp'] s.emit type, evt publishEvt: (type, name, data) -> meth = 'WebsocketPublisher.publishEvt' publish = true evt = timestamp: _getTimeStamp() type: type name: name owner: 'local-stamp' if type is 'instance' publish = false if name is 'status' evt.data = {status: data.status} evt.entity = serviceApp: data.service service: data.deployment role: data.role instance: data.instance @evtInstanceBuffer[data.instance] = evt else if name is 'created' @instanceCreated[data.instance] = true else if name is 'removed' if @instanceCreated[data.instance]? delete @instanceCreated[data.instance] else if type is 'service' if name is 'deploying' or name is 'undeploying' evt.entity = serviceApp: data.service service: data.deployment else if name is 'deployed' or name is 'undeployed' deployment = data.deployment evt.entity = serviceApp: deployment.service service: data.deploymentURN evt.data = instances: {} for r, rinfo of deployment.roles for i, iinfo of rinfo.instances instance = {} instance.component = rinfo.component instance.role = r instance.cnid = iinfo.id evt.data.instances[i] = instance if name is 'deployed' @deployed[evt.entity.service] = true else if name is 'undeployed' delete @deployed[evt.entity.service] else if name is 'link' or name is 'unlink' deployment = data.deployment evt.entity = serviceApp: deployment.service service: data.deploymentURN evt.data = data.linkData else if name is 'scale' deployment = data.manifest evt.entity = serviceApp: deployment.service.name service: deployment.name evt.data = data.event if publish @publish evt else if name isnt 'status' @local.emit 'event', evt for iid, evt of @evtInstanceBuffer if (@instanceCreated[iid] and @deployed[evt.entity.service]) or (evt.entity.serviceApp is 'eslap://eslap.cloud/services/http/inbound/1_0_0') @publish evt delete @evtInstanceBuffer[iid] reconfigure: -> @logger.info 'WebsocketPublisher.reconfigure' # TODO disconnect: -> @logger.info 'WebsocketPublisher.disconnect' terminate: -> @logger.info 'WebsocketPublisher.terminate' _getTimeStamp = () -> now = new Date().getTime() return moment.utc(now).format('YYYYMMDDTHHmmssZ') module.exports = WebsocketPublisher
146017
sio = require 'socket.io' klogger = require 'k-logger' moment = require 'moment' events = sys = require 'events' EMITTED_EVENTS_NAME = 'ecloud-event' AUTHENTICATION_ERROR = 'Authentication error' class WebsocketPublisher constructor: (@httpServer, @httpAuthenticator) -> @logger = klogger.getLogger 'Websocket' # @logger.debug = console.log # @logger.info = console.log # @logger.error = console.log # @logger.warn = console.log @logger.info 'WebsocketPublisher.constructor' # Setup a Socket.io websocket to listen on the server @socketIO = sio.listen @httpServer # Configure Websocket handshake for authentication @socketIO.use (socket, next) => @sioHandshaker socket, next @socketIO.on 'connection', (socket) => @sioConnectionHandler socket @evtInstanceBuffer = {} @deployed = {} @instanceCreated = {} @socketsByUserId = {} @local = new events.EventEmitter() sioHandshaker: (socket, next) -> meth = 'WSPublisher.handshake' # authHeader = socket?.request?.headers?.authorization # if not authHeader? # @logger.info "#{meth} - Access denied for anonymous request." # return next new Error AUTHENTICATION_ERROR # [protocol, basic] = authHeader.split ' ' # if protocol isnt 'Basic' # @logger.info "#{meth} - Access denied for incorrect protocol \ # #{protocol} request." # return next new Error AUTHENTICATION_ERROR # buf = new Buffer(basic, 'base64') # plain_auth = buf.toString() # creds = plain_auth.split(':') # authToken = "<KEY>]}" authToken = socket?.handshake?.query?.token @logger.info "#{meth}" socket.user = {id:'local-stamp'} next() # if (not authToken?) or (authToken is '') # @logger.info "#{meth} - Access denied for anonymous request." # @httpAuthenticator.authenticate "Bearer #{authToken}" # .then (userData) => # socket.user = userData # @logger.info "#{meth} - User authenticated: #{JSON.stringify userData}" # next() # .fail (err) => # @logger.info "#{meth} - Access denied for token #{authToken}." # next new Error AUTHENTICATION_ERROR sioConnectionHandler: (socket) -> meth = 'WSPublisher.onConnection' if not socket.user? @logger.error "#{meth} - Socket not authenticated correctly." socket.emit 'error' ,'Connection not authenticated correctly. Disconnecting.' socket.disconnect() else @logger.info "#{meth} - Socket #{socket.id} connected. User: " + "#{JSON.stringify socket.user}" @addUserSocket socket @configureSocketHandlers socket configureSocketHandlers: (socket) -> socket.on 'disconnect', (reason) => @socketDisconnectionHandler socket, reason socket.on 'error', (error) => @socketErrorHandler socket, error socketDisconnectionHandler: (socket, reason) -> meth = 'WSPublisher.onSocketDisconnection' @logger.info "#{meth} - Socket #{socket.id} - Reason: #{reason}" @removeUserSocket socket socketErrorHandler: (socket, error) -> @logger.info "WSPublisher.onSocketError - User: #{socket.user.id} - " + "Error: #{error.message}" # Add a socket to the user socket list if it's not already there. # # The user socket list is a two-level dictionary, by user ID and socket ID: # { # "user1": { # "sock1" : socketObj1, # "sock2" : socketObj2, # "sock3" : socketObj3 # }, # "user2": { # "sock5" : socketObj5, # "sock23" : socketObj23, # "sock12" : socketObj12 # } # } addUserSocket: (socket) -> meth = 'WebsocketPublisher.addUserSocket' userId = socket.user.id if userId not of @socketsByUserId @socketsByUserId[userId] = {} if socket.id not of @socketsByUserId[userId] @socketsByUserId[userId][socket.id] = socket @logger.debug "#{meth} - Socket #{socket.id} added to #{userId} list." else @logger.debug "#{meth} - Socket #{socket.id} already in #{userId} list." # Removes a socket from the user socket list. removeUserSocket: (socket) -> meth = 'WebsocketPublisher.removeUserSocket' userId = socket.user.id if userId of @socketsByUserId if socket.id of @socketsByUserId[userId] delete @socketsByUserId[userId][socket.id] @logger.debug "#{meth} - Removed #{socket.id} from #{userId} list." if Object.keys(@socketsByUserId[userId]).length is 0 delete @socketsByUserId[userId] @logger.debug "#{meth} - Removed #{userId} from list." else @logger.debug "#{meth} - Socket #{socket.id} not in #{userId} list." else @logger.debug "#{meth} - User #{userId} not in socket list." publish: (evt) -> meth = 'WebsocketPublisher.publish' evtStr = JSON.stringify evt if not evt.owner? @logger.debug "#{meth} - Event data has no owner: #{evtStr}" else if evt.owner not of @socketsByUserId @logger.debug "#{meth} - Event owner has no active sockets: #{evtStr}" else @logger.debug "#{meth} - Emitting event to client sockets: #{evtStr}" for sid, s of @socketsByUserId[evt.owner] @logger.debug "#{meth} - Emitting event to socket #{sid}: #{evtStr}" try s.emit EMITTED_EVENTS_NAME, evt catch err @logger.warn "#{meth} - Error emitting: #{err.message} - #{evtStr}" @local.emit 'event', evt directPublish: (type, evt) -> for sid, s of @socketsByUserId['local-stamp'] s.emit type, evt publishEvt: (type, name, data) -> meth = 'WebsocketPublisher.publishEvt' publish = true evt = timestamp: _getTimeStamp() type: type name: name owner: 'local-stamp' if type is 'instance' publish = false if name is 'status' evt.data = {status: data.status} evt.entity = serviceApp: data.service service: data.deployment role: data.role instance: data.instance @evtInstanceBuffer[data.instance] = evt else if name is 'created' @instanceCreated[data.instance] = true else if name is 'removed' if @instanceCreated[data.instance]? delete @instanceCreated[data.instance] else if type is 'service' if name is 'deploying' or name is 'undeploying' evt.entity = serviceApp: data.service service: data.deployment else if name is 'deployed' or name is 'undeployed' deployment = data.deployment evt.entity = serviceApp: deployment.service service: data.deploymentURN evt.data = instances: {} for r, rinfo of deployment.roles for i, iinfo of rinfo.instances instance = {} instance.component = rinfo.component instance.role = r instance.cnid = iinfo.id evt.data.instances[i] = instance if name is 'deployed' @deployed[evt.entity.service] = true else if name is 'undeployed' delete @deployed[evt.entity.service] else if name is 'link' or name is 'unlink' deployment = data.deployment evt.entity = serviceApp: deployment.service service: data.deploymentURN evt.data = data.linkData else if name is 'scale' deployment = data.manifest evt.entity = serviceApp: deployment.service.name service: deployment.name evt.data = data.event if publish @publish evt else if name isnt 'status' @local.emit 'event', evt for iid, evt of @evtInstanceBuffer if (@instanceCreated[iid] and @deployed[evt.entity.service]) or (evt.entity.serviceApp is 'eslap://eslap.cloud/services/http/inbound/1_0_0') @publish evt delete @evtInstanceBuffer[iid] reconfigure: -> @logger.info 'WebsocketPublisher.reconfigure' # TODO disconnect: -> @logger.info 'WebsocketPublisher.disconnect' terminate: -> @logger.info 'WebsocketPublisher.terminate' _getTimeStamp = () -> now = new Date().getTime() return moment.utc(now).format('YYYYMMDDTHHmmssZ') module.exports = WebsocketPublisher
true
sio = require 'socket.io' klogger = require 'k-logger' moment = require 'moment' events = sys = require 'events' EMITTED_EVENTS_NAME = 'ecloud-event' AUTHENTICATION_ERROR = 'Authentication error' class WebsocketPublisher constructor: (@httpServer, @httpAuthenticator) -> @logger = klogger.getLogger 'Websocket' # @logger.debug = console.log # @logger.info = console.log # @logger.error = console.log # @logger.warn = console.log @logger.info 'WebsocketPublisher.constructor' # Setup a Socket.io websocket to listen on the server @socketIO = sio.listen @httpServer # Configure Websocket handshake for authentication @socketIO.use (socket, next) => @sioHandshaker socket, next @socketIO.on 'connection', (socket) => @sioConnectionHandler socket @evtInstanceBuffer = {} @deployed = {} @instanceCreated = {} @socketsByUserId = {} @local = new events.EventEmitter() sioHandshaker: (socket, next) -> meth = 'WSPublisher.handshake' # authHeader = socket?.request?.headers?.authorization # if not authHeader? # @logger.info "#{meth} - Access denied for anonymous request." # return next new Error AUTHENTICATION_ERROR # [protocol, basic] = authHeader.split ' ' # if protocol isnt 'Basic' # @logger.info "#{meth} - Access denied for incorrect protocol \ # #{protocol} request." # return next new Error AUTHENTICATION_ERROR # buf = new Buffer(basic, 'base64') # plain_auth = buf.toString() # creds = plain_auth.split(':') # authToken = "PI:KEY:<KEY>END_PI]}" authToken = socket?.handshake?.query?.token @logger.info "#{meth}" socket.user = {id:'local-stamp'} next() # if (not authToken?) or (authToken is '') # @logger.info "#{meth} - Access denied for anonymous request." # @httpAuthenticator.authenticate "Bearer #{authToken}" # .then (userData) => # socket.user = userData # @logger.info "#{meth} - User authenticated: #{JSON.stringify userData}" # next() # .fail (err) => # @logger.info "#{meth} - Access denied for token #{authToken}." # next new Error AUTHENTICATION_ERROR sioConnectionHandler: (socket) -> meth = 'WSPublisher.onConnection' if not socket.user? @logger.error "#{meth} - Socket not authenticated correctly." socket.emit 'error' ,'Connection not authenticated correctly. Disconnecting.' socket.disconnect() else @logger.info "#{meth} - Socket #{socket.id} connected. User: " + "#{JSON.stringify socket.user}" @addUserSocket socket @configureSocketHandlers socket configureSocketHandlers: (socket) -> socket.on 'disconnect', (reason) => @socketDisconnectionHandler socket, reason socket.on 'error', (error) => @socketErrorHandler socket, error socketDisconnectionHandler: (socket, reason) -> meth = 'WSPublisher.onSocketDisconnection' @logger.info "#{meth} - Socket #{socket.id} - Reason: #{reason}" @removeUserSocket socket socketErrorHandler: (socket, error) -> @logger.info "WSPublisher.onSocketError - User: #{socket.user.id} - " + "Error: #{error.message}" # Add a socket to the user socket list if it's not already there. # # The user socket list is a two-level dictionary, by user ID and socket ID: # { # "user1": { # "sock1" : socketObj1, # "sock2" : socketObj2, # "sock3" : socketObj3 # }, # "user2": { # "sock5" : socketObj5, # "sock23" : socketObj23, # "sock12" : socketObj12 # } # } addUserSocket: (socket) -> meth = 'WebsocketPublisher.addUserSocket' userId = socket.user.id if userId not of @socketsByUserId @socketsByUserId[userId] = {} if socket.id not of @socketsByUserId[userId] @socketsByUserId[userId][socket.id] = socket @logger.debug "#{meth} - Socket #{socket.id} added to #{userId} list." else @logger.debug "#{meth} - Socket #{socket.id} already in #{userId} list." # Removes a socket from the user socket list. removeUserSocket: (socket) -> meth = 'WebsocketPublisher.removeUserSocket' userId = socket.user.id if userId of @socketsByUserId if socket.id of @socketsByUserId[userId] delete @socketsByUserId[userId][socket.id] @logger.debug "#{meth} - Removed #{socket.id} from #{userId} list." if Object.keys(@socketsByUserId[userId]).length is 0 delete @socketsByUserId[userId] @logger.debug "#{meth} - Removed #{userId} from list." else @logger.debug "#{meth} - Socket #{socket.id} not in #{userId} list." else @logger.debug "#{meth} - User #{userId} not in socket list." publish: (evt) -> meth = 'WebsocketPublisher.publish' evtStr = JSON.stringify evt if not evt.owner? @logger.debug "#{meth} - Event data has no owner: #{evtStr}" else if evt.owner not of @socketsByUserId @logger.debug "#{meth} - Event owner has no active sockets: #{evtStr}" else @logger.debug "#{meth} - Emitting event to client sockets: #{evtStr}" for sid, s of @socketsByUserId[evt.owner] @logger.debug "#{meth} - Emitting event to socket #{sid}: #{evtStr}" try s.emit EMITTED_EVENTS_NAME, evt catch err @logger.warn "#{meth} - Error emitting: #{err.message} - #{evtStr}" @local.emit 'event', evt directPublish: (type, evt) -> for sid, s of @socketsByUserId['local-stamp'] s.emit type, evt publishEvt: (type, name, data) -> meth = 'WebsocketPublisher.publishEvt' publish = true evt = timestamp: _getTimeStamp() type: type name: name owner: 'local-stamp' if type is 'instance' publish = false if name is 'status' evt.data = {status: data.status} evt.entity = serviceApp: data.service service: data.deployment role: data.role instance: data.instance @evtInstanceBuffer[data.instance] = evt else if name is 'created' @instanceCreated[data.instance] = true else if name is 'removed' if @instanceCreated[data.instance]? delete @instanceCreated[data.instance] else if type is 'service' if name is 'deploying' or name is 'undeploying' evt.entity = serviceApp: data.service service: data.deployment else if name is 'deployed' or name is 'undeployed' deployment = data.deployment evt.entity = serviceApp: deployment.service service: data.deploymentURN evt.data = instances: {} for r, rinfo of deployment.roles for i, iinfo of rinfo.instances instance = {} instance.component = rinfo.component instance.role = r instance.cnid = iinfo.id evt.data.instances[i] = instance if name is 'deployed' @deployed[evt.entity.service] = true else if name is 'undeployed' delete @deployed[evt.entity.service] else if name is 'link' or name is 'unlink' deployment = data.deployment evt.entity = serviceApp: deployment.service service: data.deploymentURN evt.data = data.linkData else if name is 'scale' deployment = data.manifest evt.entity = serviceApp: deployment.service.name service: deployment.name evt.data = data.event if publish @publish evt else if name isnt 'status' @local.emit 'event', evt for iid, evt of @evtInstanceBuffer if (@instanceCreated[iid] and @deployed[evt.entity.service]) or (evt.entity.serviceApp is 'eslap://eslap.cloud/services/http/inbound/1_0_0') @publish evt delete @evtInstanceBuffer[iid] reconfigure: -> @logger.info 'WebsocketPublisher.reconfigure' # TODO disconnect: -> @logger.info 'WebsocketPublisher.disconnect' terminate: -> @logger.info 'WebsocketPublisher.terminate' _getTimeStamp = () -> now = new Date().getTime() return moment.utc(now).format('YYYYMMDDTHHmmssZ') module.exports = WebsocketPublisher
[ { "context": "lse 'No') + '\"'\n\n API.mail.send\n to: 'alert@cottagelabs.com'\n subject: 'MS titles bing test complete'\n", "end": 3734, "score": 0.9999298453330994, "start": 3713, "tag": "EMAIL", "value": "alert@cottagelabs.com" } ]
noddy/service/oabutton/scripts/test_bing.coffee
jibe-b/website
0
import fs from 'fs' import Future from 'fibers/future' API.add 'service/oab/scripts/test_bing', get: roleRequired: 'root' action: () -> titles = oab_availability.search 'from:illiad AND discovered.article:false AND NOT url:http* AND NOT url:pmid*', {newest:false, size:1000}, undefined, false console.log titles.hits.total tried = 0 found = 0 matches = 0 outfile = '/home/cloo/static/MS_titles_bing_results_2.csv' fs.writeFileSync outfile, 'title,bing_url,bing_title,title_confirmed,accepted_title,scraped_doi,match' for t in titles.hits.hits tried += 1 console.log tried, found, matches try title = t._source.url.replace('TITLE:','').replace('CITATION:','').replace(/[^a-zA-Z0-9\-]+/g, " ") title = title.replace('pmid','pmid ') if title.indexOf('pmid') is 0 title = title.replace('pmc','pmc ') if title.indexOf('pmc') is 0 if title.length < 250 # there are some titles entered into the system that are too long and cause an error so ignore them fs.appendFileSync outfile, '\n"' + title.replace(/"/g,'') + '",' scraped = {} future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() try bing = API.use.microsoft.bing.search title title = title.replace(/\-/g,'') if bing.data? and bing.data.length > 0 and bing.data[0].url found += 1 fs.appendFileSync outfile, '"' + bing.data[0].url.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' if bing.data? and bing.data.length > 0 and bing.data[0].name fs.appendFileSync outfile, '"' + bing.data[0].name.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' try if bing.data[0].url.toLowerCase().indexOf('.pdf') is -1 scraped = API.service.oab.scrape bing.data[0].url try fs.appendFileSync outfile, '"scraped","' + scraped.title.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' try fs.appendFileSync outfile, '"' + scraped.doi.replace(/"/g,'') + '"' else if title.replace(/[^a-z0-9]+/g, "").indexOf(bing.data[0].url.toLowerCase().split('.pdf')[0].split('/').pop().replace(/[^a-z0-9]+/g, "")) is 0 try fs.appendFileSync outfile, '"url","' + bing.data[0].url.toLowerCase().split('.pdf')[0].split('/').pop() + '"' fs.appendFileSync outfile, ',' else content = API.convert.pdf2txt(bing.data[0].url) content = content.substring(0,1000) if content.length > 1000 content = content.toLowerCase().replace(/[^a-z0-9]+/g, "").replace(/\s\s+/g, '') if content.indexOf(title.replace(/ /g, '').toLowerCase()) isnt -1 try fs.appendFileSync outfile, '"pdf","' + title + '"' else fs.appendFileSync outfile, ',' fs.appendFileSync outfile, ',' catch fs.appendFileSync outfile, ',,' catch fs.appendFileSync outfile, ',,,,' fs.appendFileSync outfile, ',' try matched = title.toLowerCase().replace(/ /g,'').replace(/\s\s+/g, '').indexOf(bing.data[0].name.toLowerCase().replace('(pdf)','').replace(/[^a-z0-9]+/g, "").replace(/\s\s+/g, '')) is 0 matches += 1 if matched fs.appendFileSync outfile, '"' + (if matched then 'Yes' else 'No') + '"' API.mail.send to: 'alert@cottagelabs.com' subject: 'MS titles bing test complete' text: 'Query returned ' + titles.hits.total + '\nTried ' + tried + '\nFound ' + found + '\n Matched ' + matches return tried: tried, found: found, matches: matches
96975
import fs from 'fs' import Future from 'fibers/future' API.add 'service/oab/scripts/test_bing', get: roleRequired: 'root' action: () -> titles = oab_availability.search 'from:illiad AND discovered.article:false AND NOT url:http* AND NOT url:pmid*', {newest:false, size:1000}, undefined, false console.log titles.hits.total tried = 0 found = 0 matches = 0 outfile = '/home/cloo/static/MS_titles_bing_results_2.csv' fs.writeFileSync outfile, 'title,bing_url,bing_title,title_confirmed,accepted_title,scraped_doi,match' for t in titles.hits.hits tried += 1 console.log tried, found, matches try title = t._source.url.replace('TITLE:','').replace('CITATION:','').replace(/[^a-zA-Z0-9\-]+/g, " ") title = title.replace('pmid','pmid ') if title.indexOf('pmid') is 0 title = title.replace('pmc','pmc ') if title.indexOf('pmc') is 0 if title.length < 250 # there are some titles entered into the system that are too long and cause an error so ignore them fs.appendFileSync outfile, '\n"' + title.replace(/"/g,'') + '",' scraped = {} future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() try bing = API.use.microsoft.bing.search title title = title.replace(/\-/g,'') if bing.data? and bing.data.length > 0 and bing.data[0].url found += 1 fs.appendFileSync outfile, '"' + bing.data[0].url.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' if bing.data? and bing.data.length > 0 and bing.data[0].name fs.appendFileSync outfile, '"' + bing.data[0].name.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' try if bing.data[0].url.toLowerCase().indexOf('.pdf') is -1 scraped = API.service.oab.scrape bing.data[0].url try fs.appendFileSync outfile, '"scraped","' + scraped.title.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' try fs.appendFileSync outfile, '"' + scraped.doi.replace(/"/g,'') + '"' else if title.replace(/[^a-z0-9]+/g, "").indexOf(bing.data[0].url.toLowerCase().split('.pdf')[0].split('/').pop().replace(/[^a-z0-9]+/g, "")) is 0 try fs.appendFileSync outfile, '"url","' + bing.data[0].url.toLowerCase().split('.pdf')[0].split('/').pop() + '"' fs.appendFileSync outfile, ',' else content = API.convert.pdf2txt(bing.data[0].url) content = content.substring(0,1000) if content.length > 1000 content = content.toLowerCase().replace(/[^a-z0-9]+/g, "").replace(/\s\s+/g, '') if content.indexOf(title.replace(/ /g, '').toLowerCase()) isnt -1 try fs.appendFileSync outfile, '"pdf","' + title + '"' else fs.appendFileSync outfile, ',' fs.appendFileSync outfile, ',' catch fs.appendFileSync outfile, ',,' catch fs.appendFileSync outfile, ',,,,' fs.appendFileSync outfile, ',' try matched = title.toLowerCase().replace(/ /g,'').replace(/\s\s+/g, '').indexOf(bing.data[0].name.toLowerCase().replace('(pdf)','').replace(/[^a-z0-9]+/g, "").replace(/\s\s+/g, '')) is 0 matches += 1 if matched fs.appendFileSync outfile, '"' + (if matched then 'Yes' else 'No') + '"' API.mail.send to: '<EMAIL>' subject: 'MS titles bing test complete' text: 'Query returned ' + titles.hits.total + '\nTried ' + tried + '\nFound ' + found + '\n Matched ' + matches return tried: tried, found: found, matches: matches
true
import fs from 'fs' import Future from 'fibers/future' API.add 'service/oab/scripts/test_bing', get: roleRequired: 'root' action: () -> titles = oab_availability.search 'from:illiad AND discovered.article:false AND NOT url:http* AND NOT url:pmid*', {newest:false, size:1000}, undefined, false console.log titles.hits.total tried = 0 found = 0 matches = 0 outfile = '/home/cloo/static/MS_titles_bing_results_2.csv' fs.writeFileSync outfile, 'title,bing_url,bing_title,title_confirmed,accepted_title,scraped_doi,match' for t in titles.hits.hits tried += 1 console.log tried, found, matches try title = t._source.url.replace('TITLE:','').replace('CITATION:','').replace(/[^a-zA-Z0-9\-]+/g, " ") title = title.replace('pmid','pmid ') if title.indexOf('pmid') is 0 title = title.replace('pmc','pmc ') if title.indexOf('pmc') is 0 if title.length < 250 # there are some titles entered into the system that are too long and cause an error so ignore them fs.appendFileSync outfile, '\n"' + title.replace(/"/g,'') + '",' scraped = {} future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() try bing = API.use.microsoft.bing.search title title = title.replace(/\-/g,'') if bing.data? and bing.data.length > 0 and bing.data[0].url found += 1 fs.appendFileSync outfile, '"' + bing.data[0].url.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' if bing.data? and bing.data.length > 0 and bing.data[0].name fs.appendFileSync outfile, '"' + bing.data[0].name.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' try if bing.data[0].url.toLowerCase().indexOf('.pdf') is -1 scraped = API.service.oab.scrape bing.data[0].url try fs.appendFileSync outfile, '"scraped","' + scraped.title.replace(/"/g,'') + '"' fs.appendFileSync outfile, ',' try fs.appendFileSync outfile, '"' + scraped.doi.replace(/"/g,'') + '"' else if title.replace(/[^a-z0-9]+/g, "").indexOf(bing.data[0].url.toLowerCase().split('.pdf')[0].split('/').pop().replace(/[^a-z0-9]+/g, "")) is 0 try fs.appendFileSync outfile, '"url","' + bing.data[0].url.toLowerCase().split('.pdf')[0].split('/').pop() + '"' fs.appendFileSync outfile, ',' else content = API.convert.pdf2txt(bing.data[0].url) content = content.substring(0,1000) if content.length > 1000 content = content.toLowerCase().replace(/[^a-z0-9]+/g, "").replace(/\s\s+/g, '') if content.indexOf(title.replace(/ /g, '').toLowerCase()) isnt -1 try fs.appendFileSync outfile, '"pdf","' + title + '"' else fs.appendFileSync outfile, ',' fs.appendFileSync outfile, ',' catch fs.appendFileSync outfile, ',,' catch fs.appendFileSync outfile, ',,,,' fs.appendFileSync outfile, ',' try matched = title.toLowerCase().replace(/ /g,'').replace(/\s\s+/g, '').indexOf(bing.data[0].name.toLowerCase().replace('(pdf)','').replace(/[^a-z0-9]+/g, "").replace(/\s\s+/g, '')) is 0 matches += 1 if matched fs.appendFileSync outfile, '"' + (if matched then 'Yes' else 'No') + '"' API.mail.send to: 'PI:EMAIL:<EMAIL>END_PI' subject: 'MS titles bing test complete' text: 'Query returned ' + titles.hits.total + '\nTried ' + tried + '\nFound ' + found + '\n Matched ' + matches return tried: tried, found: found, matches: matches
[ { "context": "ows'\n q: 'input mock name=\"thurstone\" | head 20'\n }\n ", "end": 32626, "score": 0.4044267237186432, "start": 32624, "tag": "NAME", "value": "th" }, { "context": "ows'\n q: 'input mock name=\"thurstone\" | tail 20'\n }\n ", "end": 33375, "score": 0.7161790728569031, "start": 33366, "tag": "USERNAME", "value": "thurstone" }, { "context": "ck-weight\" | stats p95 = percentile(weight, 95) by Chick'\n }\n ]\n ", "end": 80314, "score": 0.5689452886581421, "start": 80312, "tag": "NAME", "value": "Ch" }, { "context": " q: 'set @test = tostring({ \"id\": 123, \"name\": \"Vin Diesel\" }) // returns {\"id\":123,\"name\":\"Vin Diesel\"}'\n ", "end": 95501, "score": 0.9998528361320496, "start": 95491, "tag": "NAME", "value": "Vin Diesel" }, { "context": "me\": \"Vin Diesel\" }) // returns {\"id\":123,\"name\":\"Vin Diesel\"}'\n }\n {\n ", "end": 95545, "score": 0.9998599290847778, "start": 95535, "tag": "NAME", "value": "Vin Diesel" }, { "context": "ble'\n q: 'input mock name=\"thurstone\" | z = y / x, floor = floor(z)'\n ", "end": 107503, "score": 0.9931840300559998, "start": 107494, "tag": "USERNAME", "value": "thurstone" }, { "context": "implementation reference, see: https://github.com/gga/json-path'\n ]\n exam", "end": 155578, "score": 0.5382053852081299, "start": 155575, "tag": "USERNAME", "value": "gga" }, { "context": " q: 'set @obj = { messages: [{from: \"me@parsec.com\"}, {from: \"you@parsec.com\"}, {from: \"me@parsec.co", "end": 155989, "score": 0.9999204277992249, "start": 155976, "tag": "EMAIL", "value": "me@parsec.com" }, { "context": "j = { messages: [{from: \"me@parsec.com\"}, {from: \"you@parsec.com\"}, {from: \"me@parsec.com\"}] },\\n @results = js", "end": 156015, "score": 0.9999181628227234, "start": 156001, "tag": "EMAIL", "value": "you@parsec.com" }, { "context": "e@parsec.com\"}, {from: \"you@parsec.com\"}, {from: \"me@parsec.com\"}] },\\n @results = jsonpath(@obj, \"$.messages[", "end": 156040, "score": 0.9999135136604309, "start": 156027, "tag": "EMAIL", "value": "me@parsec.com" }, { "context": " }\n {\n name: 'adler32'\n type: 'function'\n ", "end": 180213, "score": 0.9274740815162659, "start": 180206, "tag": "USERNAME", "value": "adler32" }, { "context": " }\n {\n name: 'crc32'\n type: 'function'\n ", "end": 180729, "score": 0.8253830075263977, "start": 180724, "tag": "USERNAME", "value": "crc32" }, { "context": " }\n {\n name: 'gost'\n type: 'function'\n ", "end": 181234, "score": 0.8991013765335083, "start": 181230, "tag": "USERNAME", "value": "gost" }, { "context": " }\n {\n name: 'hmac_gost'\n type: 'function'\n ", "end": 181757, "score": 0.9860858917236328, "start": 181753, "tag": "USERNAME", "value": "gost" }, { "context": " }\n {\n name: 'hmac_md5'\n type: 'function'\n ", "end": 182831, "score": 0.7304384112358093, "start": 182828, "tag": "USERNAME", "value": "md5" }, { "context": " }\n {\n name: 'ripemd128'\n type: 'function'\n ", "end": 183406, "score": 0.972810685634613, "start": 183397, "tag": "USERNAME", "value": "ripemd128" }, { "context": " }\n {\n name: 'hmac_ripemd128'\n type: 'function'\n ", "end": 183983, "score": 0.9267633557319641, "start": 183969, "tag": "USERNAME", "value": "hmac_ripemd128" }, { "context": " }\n {\n name: 'siphash48'\n type: 'function'\n ", "end": 195603, "score": 0.947728157043457, "start": 195594, "tag": "USERNAME", "value": "siphash48" }, { "context": " }\n {\n name: 'tiger'\n type: 'function'\n ", "end": 196323, "score": 0.914059042930603, "start": 196318, "tag": "USERNAME", "value": "tiger" }, { "context": " }\n {\n name: 'hmac_tiger'\n type: 'function'\n ", "end": 196857, "score": 0.9706324338912964, "start": 196847, "tag": "USERNAME", "value": "hmac_tiger" }, { "context": " }\n {\n name: 'whirlpool'\n type: 'function'\n ", "end": 197444, "score": 0.8374879360198975, "start": 197435, "tag": "USERNAME", "value": "whirlpool" }, { "context": " }\n {\n name: 'startofhour'\n type: 'function'\n ", "end": 212159, "score": 0.9970886707305908, "start": 212148, "tag": "USERNAME", "value": "startofhour" }, { "context": " }\n {\n name: 'startofday'\n type: 'function'\n ", "end": 212784, "score": 0.9952470064163208, "start": 212774, "tag": "USERNAME", "value": "startofday" }, { "context": " }\n {\n name: 'startofweek'\n type: 'function'\n ", "end": 213376, "score": 0.9932898283004761, "start": 213365, "tag": "USERNAME", "value": "startofweek" }, { "context": " }\n {\n name: 'startofmonth'\n type: 'function'\n ", "end": 214001, "score": 0.9796953201293945, "start": 213989, "tag": "USERNAME", "value": "startofmonth" }, { "context": " {\n q: 'set @fivemin = period(5, \"minutes\")'\n }\n ", "end": 230631, "score": 0.9745016098022461, "start": 230623, "tag": "USERNAME", "value": "@fivemin" }, { "context": " {\n q: 'input mock name=\"thurstone\"\\n| set @differenceFromAvg = (n, avg) -> abs(n - ", "end": 244205, "score": 0.999432384967804, "start": 244196, "tag": "USERNAME", "value": "thurstone" }, { "context": " 'input jdbc uri=\":uri\" [user | username]=\":username\" password=\":password\" query=\":query\"'\n ", "end": 255206, "score": 0.6558262705802917, "start": 255198, "tag": "USERNAME", "value": "username" }, { "context": "ri=\":uri\" [user | username]=\":username\" password=\":password\" query=\":query\"'\n 'input jdbc ", "end": 255227, "score": 0.7432448863983154, "start": 255219, "tag": "PASSWORD", "value": "password" }, { "context": " 'input jdbc uri=\":uri\" [user | username]=\":username\" password=\":password\" query=\":query\" operation=\":", "end": 255316, "score": 0.6753622889518738, "start": 255308, "tag": "USERNAME", "value": "username" }, { "context": "ri=\":uri\" [user | username]=\":username\" password=\":password\" query=\":query\" operation=\":operation\"'\n ", "end": 255337, "score": 0.8557097911834717, "start": 255329, "tag": "PASSWORD", "value": "password" }, { "context": "mysql-server:3306/database?user=username&password=password\"\\nquery=\"...\"'\n }\n ", "end": 256743, "score": 0.684302568435669, "start": 256735, "tag": "PASSWORD", "value": "password" }, { "context": "mysql-server:3306/database?user=username&password=password\" operation=\"execute\"\\nquery=\"INSERT INTO ... VALU", "end": 256986, "score": 0.8202386498451233, "start": 256978, "tag": "PASSWORD", "value": "password" }, { "context": "my-sql-server:1433;databaseName=database;username=username;password=password\"\\n query=\"...\"'\n ", "end": 257269, "score": 0.9982331395149231, "start": 257261, "tag": "USERNAME", "value": "username" }, { "context": ";databaseName=database;username=username;password=password\"\\n query=\"...\"'\n }\n ", "end": 257287, "score": 0.9994233846664429, "start": 257279, "tag": "PASSWORD", "value": "password" }, { "context": "efault?mapred.job.queue.name=queuename\" username=\"username\" password=\"password\"\\n query=\"show tables\"'\n ", "end": 257553, "score": 0.9947254657745361, "start": 257545, "tag": "USERNAME", "value": "username" }, { "context": "eue.name=queuename\" username=\"username\" password=\"password\"\\n query=\"show tables\"'\n }\n ", "end": 257573, "score": 0.9994980692863464, "start": 257565, "tag": "PASSWORD", "value": "password" }, { "context": "adata-server/database=database,user=user,password=password\"\\n query=\"...\"'\n }\n ", "end": 257824, "score": 0.9495003819465637, "start": 257816, "tag": "PASSWORD", "value": "password" }, { "context": "-db2-server:50001/database:user=username;password=password;\"\\n query=\"...\"'\n }\n ", "end": 258053, "score": 0.9981778264045715, "start": 258045, "tag": "PASSWORD", "value": "password" }, { "context": "dbc:postgresql://my-postgres-server/database?user=username&password=password\"\\n query=\"...\"'\n ", "end": 258506, "score": 0.8384179472923279, "start": 258498, "tag": "USERNAME", "value": "username" }, { "context": "y-postgres-server/database?user=username&password=password\"\\n query=\"...\"'\n }\n\n ", "end": 258524, "score": 0.9992161989212036, "start": 258516, "tag": "PASSWORD", "value": "password" }, { "context": " 'input http uri=\":uri\" user=\":user\" password=\"*****\"'\n 'input http uri=\":uri\" meth", "end": 260154, "score": 0.9554638862609863, "start": 260154, "tag": "PASSWORD", "value": "" }, { "context": "/my-web-server/path\"\\n user=\"readonly\" password=\"readonly\"'\n }\n {\n ", "end": 261967, "score": 0.999322772026062, "start": 261959, "tag": "PASSWORD", "value": "readonly" }, { "context": "rver/path\"\\n auth={ user: \"readonly\", password: \"readonly\", preemptive: true }'\n }\n ", "end": 262240, "score": 0.9994764924049377, "start": 262232, "tag": "PASSWORD", "value": "readonly" }, { "context": "i\" db=\":db\" query=\":query\" user=\":user\" password=\":password\"'\n ]\n description: ", "end": 263757, "score": 0.9973882436752319, "start": 263749, "tag": "PASSWORD", "value": "password" }, { "context": "ri=\"smb://:hostname/:path\" user=\":user\" password=\"*****\"'\n 'input smb uri=\"smb://:user", "end": 270148, "score": 0.9879088997840881, "start": 270148, "tag": "PASSWORD", "value": "" }, { "context": "mba-server/my-share\"\\n user=\"readonly\" password=\"readonly\"'\n }\n {\n ", "end": 271312, "score": 0.9991864562034607, "start": 271304, "tag": "PASSWORD", "value": "readonly" }, { "context": "r/my-share/file.txt\"\\n user=\"readonly\" password=\"readonly\"'\n }\n {\n ", "end": 271544, "score": 0.9989527463912964, "start": 271536, "tag": "PASSWORD", "value": "readonly" }, { "context": "r/my-share/file.txt\"\\n user=\"readonly\" password=\"readonly\" parser=\"json\"'\n }\n ", "end": 271771, "score": 0.999268114566803, "start": 271763, "tag": "PASSWORD", "value": "readonly" } ]
web/app/scripts/services/documentationService.coffee
ExpediaGroup/parsec
1
# Documentation for Parsec Parsec.Services.factory 'documentationService', -> documentation = tokens: [ { name: ';' altName: 'query separator' type: 'symbol' syntax: ['query1; query2', 'query1; query2; query3 ...'] description: [ 'The query separator is used to separate two distinct Parsec queries. The queries will be executed sequentially with a shared context.' ] examples: [ { q: 'input mock; input mock' } ] } { name: '/* */' altName: 'comment block' type: 'symbol' syntax: ['/* ... */'] description: [ 'Comments in Parsec follow the general C style /* ... */ block comment form and are ignored by the parser.' 'Nested comment blocks are supported provided they are balanced.' ] examples: [ { q: '/* My query */ input mock' } { q: 'input mock | /* filter col1 == 1 | */ sort col1 desc' } ] } { name: '//' altName: 'line comment' type: 'symbol' syntax: ['// ...'] description: [ 'Line comments in Parsec follow the general C style // comment form and are ignored by the parser.' 'Line comments must either end in a newline character, or the end of the query.' ] examples: [ { q: '// My query \ninput mock' } { q: 'input mock\n//| filter col1 == 1\n| sort col1 desc' } ] } { name: '()' altName: 'parentheses' type: 'symbol' syntax: ['(expression)'] description: [ 'Parentheses can be used to explicitly specify order the order of evaluation. An expression wrapped in parentheses evaluates to the value of the expression.' 'Parentheses are also used in a function call to contain the arguments to the function.' 'Nested parentheses are supported.' ] examples: [ { q: 'input mock | x = col1 + col2 * col3, y = (col1 + col2) * col3 | select x, y' } { description: 'As a function call' q: 'input mock | x = (col2 * col4) / 2, y = round(x)' } { q: 'input mock | x = sqrt(sin(col1) - cos(col2))' } ] } { name: '*' altName: 'asterisk' type: 'symbol' syntax: ['*'] description: [ 'The asterisk (*) symbol can be used as a wildcard in limited functions. The most notable use case is in the count(*) function to indicate a count of all rows.' 'It is identical in appearance to the multiplication operator.' ] examples: [ { q: 'input mock | stats numRows = count(*)' } ] } { name: '->' altName: 'function' type: 'symbol' syntax: [ ':arg, :arg, .. -> :expression' '(:arg, :arg, ..) -> :expression' ] description: [ 'The function (->) symbol is used to define first-order functions. Any number of arguments can precede it, followed by an expression in terms of those arguments.' 'Functions created with this symbol can be mapped to user-defined functions using the def statement, or they can be stored in variables or passed directly to functions like map().' 'The apply() function can be used to invoke a function, if it isn\'t mapped to a function name using def.' ] examples: [ { q: 'set @cube = (n) -> n*n*n, @cube9 = apply(@cube, 9)' } { q: 'set @isOdd = (n) -> gcd(n,2) != 2\n| input mock | isCol1Odd = apply(@isOdd, col1)' } ] related: ['statement:def', 'function:apply'] } { name: 'null' type: 'literal' syntax: ['null'] description: [ 'The keyword "null" represents the absence of value.' 'Generally, operators and functions applied to null value tend to return null.' ] examples: [ { q: 'set @x = null' } ] } { name: 'true' type: 'literal' syntax: ['true'] description: [ 'The keyword "true" represents the boolean truth value. It can be used in equality/inequality expressions, or assigned to columns or variables.' 'Non-zero numbers are considered true from a boolean perspective.' ] examples: [ { q: 'set @truth = true' } { description: 'Non-zero numbers are considered true from a boolean perspective' q: 'set @truth = (1 == true)' } ] related: ['literal:false'] } { name: 'false' type: 'literal' syntax: ['false'] description: [ 'The keyword "false" represents the boolean falsehood value It can be used in equality/inequality expressions, or assigned to columns or variables.' 'Zero numbers are considered false from a boolean perspective.' ] examples: [ { q: 'set @truth = false' } { description: 'Zero numbers are considered false from a boolean perspective' q: 'set @truth = (0 == false)' } ] related: ['literal:true'] } { name: '"number"' type: 'literal' syntax: [ 'Regex: /[-+]?(0(\.\d*)?|([1-9]\d*\.?\d*)|(\.\d+))([Ee][+-]?\d+)?/' 'Regex: /[-+]?(0(\.\d*)?|([1-9]\d*\.?\d*)|(\.\d+))([Ee][+-]?\d+)?[%]/' ] returns: 'number' description: [ 'Internally, Parsec supports the full range of JVM primitive numbers, as well as BigInteger, BigDecimal, and Ratios.' 'A number that ends with a percent sign indicates a percentage. The numerical value of the number will be divided by 100.' ] examples: [ { description: 'Integer' q: 'set @x = 100' } { description: 'Floating-point (double) number' q: 'set @y = 3.141592' } { description: 'Scientific-notation' q: 'set @a = 1.234e50, @b = 1.234e-10' } { description: 'Percents' q: 'set @a = 50%, @b = 12 * @a' } ] } { name: '"identifier"' type: 'literal' syntax: [ 'Regex: /[a-zA-Z_][a-zA-Z0-9_]*/' 'Regex: /`[^`]+`/' ] description: [ 'Identifiers are alpha-numeric strings used to reference columns in the current dataset.' 'There are two possible forms for identifiers: the primary form must start with a letter or underscore, and may only contain letters, numbers, or underscores. The alternate form uses two backtick (`) characters to enclose any string of characters, including spaces or special characters (except backticks).' 'Identifiers are case-sensitive.' ] examples: [ { description: 'Primary form' q: 'input mock | col6 = col5' } { description: 'Backtick form allows spaces and special characters' q: 'input mock | stats `avg $` = mean(col1 * col2)' } ] } { name: '"variable"' type: 'literal' syntax: ['Regex: /@[a-zA-Z0-9_]+[\']?/'] description: [ 'Variables are alpha-numeric strings prefixed with an at symbol (@). A trailing single-quote character is allowed, representing the prime symbol.' 'Unlike identifiers, variables are not associated with rows in the current dataset. Variables are stored in the context and available throughout the evaluation of a query (once they have been set.' ] examples: [ { description: 'Setting a variable' q: 'set @fruit = "banana"' } { description: 'Storing a calculated value in a variable' q: 'input mock | set @x=mean(col1) | y = col1 - @x' } { description: 'Prime variables' q: 'input mock | set @x = mean(col1), @x\' = @x^2 | stats x=@x, y=@x\'' } ] related: ['statement:set'] } { name: '"string"' type: 'literal' syntax: [ "Regex: /\'(?:.*?([^\\]|\\\\))?\'/s" 'Regex: /\"(?:.*?([^\\]|\\\\))?\"/s' 'Regex: /\'{3}(?:.*?([^\\]|\\\\))?\'{3}/s' ] returns: 'string' description: [ 'Strings can be created by wrapping text in single or double-quote characters. The quote character can be escaped inside a string using \\" or \\\'.' 'Strings can also be created using a triple single-quote, which has the benefit of allowing single and double quote characters to be used unescaped. Naturally, a triple single quote can be escaped inside a string using \\\'\'\'.' 'Standard escape characters can be used inside a string, e.g.: \\n, \\r, \\t, \\\\, etc.' ] examples: [ { description: 'Single-quoted string' q: 'set @msg = \'hello world\'' } { description: 'Double-quoted string' q: 'set @msg = "hello world"' } { description: 'Double-quoted string with escaped characters inside' q: 'set @msg = "\\"I can\'t imagine\\", said the Princess."' } { description: 'Triple-quoted string' q: 'set @query = \'\'\'Parsec query:\\t \'set @msg = "hello world"\'.\'\'\'' } ] } { name: '"list"' type: 'literal' syntax: ['[expr1, expr2, ... ]'] description: ['Lists can be created using the tolist() function or with a list literal: [expr1, expr2, ...].'] examples: [ { description: 'Creating a list with hard-coded values' q: 'set @list = [1, 2, 3]' } { description: 'Creating a list using expressions for each value' q: 'input mock | x = [col1, col2, col3 + col4]' } ] related: ['function:tolist'] } { name: '"map"' type: 'literal' syntax: ['{ key1: expr1, key2: expr2, ... }'] description: ['Maps can be created using the tomap() function or with a map literal: {key1: expr1, key2: expr2, ...}.'] examples: [ { description: 'Creating a map with hard-coded values' q: 'set @map = { a: 1, b: 2 }' } { description: 'Creating a map with strings for keys' q: 'set @map = { "a": 1, "b": 2 }' } { description: 'Creating a map using expressions for each value' q: 'input mock | x = { col1: col1, col2: col2 }' } { description: 'Aggregating into a map' q: 'input mock | stats x = { min: min(col1), max: max(col1) }' } ] related: ['function:tomap'] } { name: '-' altName: 'negation' type: 'operator' subtype: 'arithmetic' syntax: ['-:expression'] returns: 'number' description: [ 'The negation operator toggles the sign of a number: making positive numbers negtive and negative numbers positive.' 'Returns null if the expression is null' 'Since numbers can be parsed with a negative sign, this operator will only be used when preceding a non-numerical expression in the query, e.g. "-x" or "-cos(y)".' ] examples: [ { description: 'Negating a column' q: 'input mock | x = -col1' } ] } { name: '+' altName: 'addition' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 + :expression2'] returns: 'number' description: [ 'The addition operator adds one number to another, or concatenates two strings. If one operand is a string, the other will be coerced into a string, and concatenated.' 'Returns null if either expression is null.' ] examples: [ { description: 'Adding numbers' q: 'input mock | x = col1 + col2' } { description: 'Concatenating strings' q: 'input mock | x = "hello" + " " + "world"' } ] } { name: '-' altName: 'subtraction' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 - :expression2'] returns: 'number' description: [ 'The subtraction operator subtracts one number from another, or creates an interval between two DateTimes.' 'Returns null if either expression is null.' ] examples: [ { description: 'Subtracting numbers' q: 'input mock | x = col1 - col2' } { description: 'Subtracting DateTimes to create an interval' q: 'input mock | x = inminutes(now() - today())' } ] } { name: '*' altName: 'multiplication' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 * :expression2'] returns: 'number' description: [ 'The multiplication operator multiplies two numbers together.' 'Returns null if either expression is null.' 'Multiplying by any non-zero number by infinity gives infinity, while the result of zero times infinity is NaN.' ] examples: [ { description: 'Multiplying numbers' q: 'input mock | x = col1 * col2' } { description: 'Multiplying by infinity' q: 'input mock | x = col1 * infinity()' } ] } { name: '/' altName: 'division' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 / :expression2'] returns: 'number' description: [ 'The division operator divides the value of one number by another. If the value is not an integer, it will be stored as a ratio or floating-point number.' 'Returns null if either expression is null.' 'Dividing a positive number by zero yields infinity, and dividing a negative number by zero yields -infinity. If both numeric expressions are zero, the result is NaN.' ] examples: [ { description: 'Dividing numbers' q: 'input mock | x = col1 / col2' } { description: 'Dividing by zero gives infinity' q: 'input mock | x = col1 / 0, isInfinity = isinfinite(x)' } ] } { name: 'mod' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 mod :expression2'] returns: 'number' description: [ 'The modulus operator finds the amount by which a dividend exceeds the largest integer multiple of the divisor that is not greater than that number. For positive numbers, this is equivalent to the remainder after division of one number by another.' 'Returns null if either expression is null.' 'By definition, 0 mod N yields 0, and N mod 0 yields NaN.' ] examples: [ { q: 'input mock | x = col2 mod col1' } { description: 'Modulus by zero is NaN' q: 'input mock | x = col1 mod 0, isNaN = isnan(x)' } ] } { name: '^' altName: 'exponent' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 ^ :expression2'] returns: 'number' description: [ 'The exponent operator raises a number to the power of another number.' 'Returns null if either expression is null.' 'By definition, N^0 yields 1.' ] examples: [ { q: 'input mock | x = col1 ^ col2' } ] } { name: 'and' type: 'operator' subtype: 'logical' syntax: [':expression1 and :expression2', ':expression1 && :expression2'] returns: 'boolean' description: [ 'The logical and operator compares the value of two expressions and returns true if both values are true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true and true)' } { q: 'input mock | x = (true && false)' } { q: 'input mock | x = isnumber(col1) and col1 > 3' } { q: 'input mock | x = col1 > 1 and null' } ] } { name: 'or' type: 'operator' subtype: 'logical' syntax: [':expression1 or :expression2', ':expression1 || :expression2'] returns: 'boolean' description: [ 'The logical or operator compares the value of two expressions and returns true if at least one value is true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true or false)' } { q: 'input mock | x = (false || false)' } { q: 'input mock | x = col3 == 3 or col1 > 3' } { q: 'input mock | x = col1 > 1 or null' } ] } { name: 'not' type: 'operator' subtype: 'logical' syntax: ['not :expression', '!:expression'] returns: 'boolean' description: [ 'The logical negation operator returns true if the boolean value of :expression is false, else it returns false.' 'Returns null if the expression is null.' ] examples: [ { q: 'input mock | x = not true' } { q: 'input mock | x = !false' } { q: 'input mock | x = !null' } ] } { name: 'xor' type: 'operator' subtype: 'logical' syntax: [':expression1 xor :expression2', ':expression1 ^^ :expression2'] returns: 'boolean' description: [ 'The logical xor operator compares the value of two expressions and returns true if exactly one value is true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true xor false)' } { q: 'input mock | x = (false ^^ false)' } { q: 'input mock | x = true xor null' } ] } { name: '==' altName: 'equals' type: 'operator' subtype: 'equality' syntax: [':expression1 == :expression2'] returns: 'boolean' description: [ 'The equality operator compares the value of two expressions and returns true if they are equal, else false.' ] examples: [ { q: 'input mock | x = (col1 == col2)' } { q: 'input mock | filter col1 == 1 ' } ] } { name: '!=' altName: 'unequals' type: 'operator' subtype: 'equality' syntax: [':expression1 != :expression2'] returns: 'boolean' description: [ 'The inequality operator compares the value of two expressions and returns true if they are unequal, else false.' ] examples: [ { q: 'input mock | x = (col1 != col2)' } { q: 'input mock | filter col1 != 1 ' } ] } { name: '>' altName: 'greater than' type: 'operator' subtype: 'equality' syntax: [':expression1 > :expression2'] returns: 'boolean' description: [ 'The greater-than operator returns true if :expression1 is strictly greater than :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 > col2)' } { q: 'input mock | filter col1 > 1 ' } ] } { name: '<' altName: 'less than' type: 'operator' subtype: 'equality' syntax: [':expression1 < :expression2'] returns: 'boolean' description: [ 'The less-than operator returns true if :expression1 is strictly less than :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 < col2)' } { q: 'input mock | filter col1 < 1 ' } ] } { name: '>=' altName: 'greater or equal' type: 'operator' subtype: 'equality' syntax: [':expression1 >= :expression2'] returns: 'boolean' description: [ 'The greater than or equal operator returns true if :expression1 is greater than or equal to :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 >= col2)' } { q: 'input mock | filter col1 >= 1 ' } ] } { name: '<=' altName: 'less or equal' type: 'operator' subtype: 'equality' syntax: [':expression1 <= :expression2'] returns: 'boolean' description: [ 'The less than or equal operator returns true if :expression1 is less than or equal to :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 <= col2)' } { q: 'input mock | filter col1 <= 1 ' } ] } { name: 'input' type: 'statement' description: ['The input statement loads a dataset from various possible sources. Different input sources are available, like mock, jdbc, and http. Each source has various options for configuring it. If a dataset is already in the pipeline, it will be replaced.'] examples: [ { description: 'Loading mock data from the built-in mock input' q: 'input mock' } { description: 'Several named datasets are included in the mock input' q: 'input mock name="chick-weight"' } ] related: ['input:mock', 'input:datastore', 'input:graphite', 'input:http', 'input:influxdb', 'input:jdbc', 'input:mongodb', 'input:smb', 'input:s3'] } { name: 'output' type: 'statement' syntax: [ 'output name=":name" :options' 'output ignore' ] description: [ 'Outputs the current dataset. This is useful when executing multiple queries at once, in order to return multiple named datasets in the result. Any query which does not end in either an output or temp statement will have an implicit output added. To prevent this, use "output ignore".' 'If the option "temporary=true" is added, the dataset will be stored in the datastore but not returned with the final query results. This is useful for intermediate datasets.' 'If no name is provided, an automatic name will be generated using the index of the dataset in the data store.' 'By default, the dataset is output to the datastore, in the execution context. There is a "type" option to change the default destination.' 'Available output types: "datastore" (default), "ignore".' ] examples: [ { description: 'Returning two named datasets' q: 'input mock | output name="ds1";\ninput mock | output name="ds2"' } { description: 'Creating a temporary dataset' q: 'input mock | output name="ds1" temporary=true;\ninput mock | output name="ds2"' } { description: 'Ignoring the current dataset' q: 'input mock | output ignore' } { description: 'Explicit options' q: 'input mock | output name="results" temporary=false type="datastore" auto=false' } ] related: ['statement:temp'] } { name: 'temp' type: 'statement' syntax: ['temp :name'] description: [ 'The temp statement stores the current dataset in the datastore as a temporary dataset. This means the dataset will be accessible to the rest of the queries, but will not be output as a result dataset.' 'The temp statement is a shortcut for "output name=\'name\' temporary=true".' ] examples: [ { q: 'input mock | temp ds1; input datastore name="ds1"' } ] related: ['statement:output'] } { name: 'head' type: 'statement' syntax: [ 'head' 'head :number' ] description: [ 'Filters the current dataset to the first row or first :number of rows.' ] examples: [ { description: 'Just the first row' q: 'input mock | head' } { description: 'First twenty rows' q: 'input mock name="thurstone" | head 20' } ] related: ['statement:tail'] } { name: 'tail' type: 'statement' syntax: [ 'tail' 'tail :number' ] description: [ 'Filters the current dataset to the last row or last :number of rows.' ] examples: [ { description: 'Just the tail row' q: 'input mock | tail' } { description: 'Last twenty rows' q: 'input mock name="thurstone" | tail 20' } ] related: ['statement:head'] } { name: 'select' type: 'statement' syntax: [ 'select :identifier [, :identifier, ...]' ] description: [ 'Selects the specified columns in each row and removes all other columns.' ] examples: [ { description: 'Creating and selecting a new column' q: 'input mock | sum = col1 + col2 | select sum' } { description: 'Selecting several columns' q: 'input mock name="survey" | select age, income, male' } ] related: ['statement:unselect'] } { name: 'unselect' type: 'statement' syntax: [ 'unselect :identifier [, :identifier, ...]' ] description: [ 'Removes the specified columns in each row, leaving the remaining columns.' ] examples: [ { description: 'Unselecting a specific column' q: 'input mock | unselect col3' } { description: 'Unselecting several columns' q: 'input mock name="survey" | unselect n, intercept, outmig, inmig | head 20' } ] related: ['statement:select'] } { name: 'filter' type: 'statement' syntax: [ 'filter :expression' ] description: [ 'Filters rows in the current dataset by a predicate. Rows for which the predicate evaluates to true will be kept in the dataset.' 'This is the inverse of the remove statement.' ] examples: [ { description: 'Simple predicate' q: 'input mock name="chick-weight" | filter Chick == 1' } { description: 'Predicate with multiple conditions' q: 'input mock name="chick-weight" | filter Chick == 1 and Time == 0' } ] related: ['statement:remove'] } { name: 'remove' type: 'statement' syntax: [ 'remove :expression' ] description: [ 'Removes rows in the current dataset by a predicate. Rows for which the predicate evaluates to true will be removed from the dataset.' 'This is the inverse of the filter statement.' ] examples: [ { description: 'Simple predicate' q: 'input mock name="chick-weight" | remove Chick == 1' } { description: 'Predicate with multiple conditions' q: 'input mock name="chick-weight" | remove Chick > 1 or Time > 0' } ] related: ['statement:filter'] } { name: 'reverse' type: 'statement' syntax: [ 'reverse' ] description: [ 'Reverses the order of the current dataset. That is, sorts the rows by the current index, descending.' ] examples: [ { q: 'input mock name="iran-election" | reverse' } ] } { name: 'union' type: 'statement' syntax: [ 'union :query' 'union (all|distinct) :query' 'union (all|distinct) (:query)' ] description: [ 'Combines the rows of the current dataset with those from another sub-query. If the sub-query is longer than a single input statement, it should be wrapped in parentheses to differentiate from the parent query.' 'The argument ALL or DISTINCT determines which rows are included in the dataset. DISTINCT returns only unique rows, whereas ALL includes all rows from both datasets, even if they are identical. The default behavior is DISTINCT.' 'Rows from the first dataset will preceed those from the sub-query.' ] examples: [ { description: 'Performs a distinct union by default' q: 'input mock | union input mock' } { description: 'Optionally unions all rows' q: 'input mock | union all input mock' } { description: 'Wrap multi-statement sub-queries in parentheses' q: 'input mock | union (input mock | col1 = col2 + col3)' } ] } { name: 'distinct' type: 'statement' syntax: [ 'distinct' ] description: [ 'Filters the current dataset to the set of unique rows. A row is unique if there is no other row in the dataset with the same columns and values.' 'Rows in the resulting dataset will remain in the same order as in the original dataset.' ] examples: [ { q: 'input mock | select col3 | distinct' } { q: 'input mock | union all input mock | distinct' } ] } { name: 'rownumber' type: 'statement' syntax: [ 'rownumber' 'rownumber :identifier' ] description: [ 'Assigns the current row number in the dataset to a column. If a column identifier is not provided, the default value of "_index" will be used.' 'The rank() function implements similar functionality as a function, but has greater overhead and is only preferable when being used in an expression.' ] examples: [ { q: 'input mock | rownumber' } { q: 'input mock | rownumber rowNumber' } { q: 'input mock name="chick-weight" | rownumber rank1 | rank2 = rank() | equal = rank1 == rank2 | stats count = count(*) by equal' } ] related: ['function:rank'] } { name: 'sort' type: 'statement' syntax: [ 'sort :identifier' 'sort :identifier (asc|desc)' 'sort :identifier (asc|desc) [, :identifier (asc|desc), ...]' ] description: [ 'Sorts the current dataset by one or more columns. Each column can be sorted either in ascending (default) or descending order' ] examples: [ { q: 'input mock | sort col1' } { q: 'input mock | sort col1 asc' } { q: 'input mock | sort col1 asc, col2 desc' } ] } { name: 'def' type: 'statement' syntax: [ 'def :function-name = (:arg, :arg, ..) -> :expression, ...' ] description: [ 'Defines one or more user-defined functions and saves into the current query context. Functions can take any number of arguments and return a single value.' 'Def can be used at any point in the query, even before input. user-defined functions must be defined before they are invoked, but can be used recursively or by other functions.' 'It is not possible to override built-in Parsec functions, but user-defined functions can be redefined multiple times.' ] examples: [ { description: 'Calculate the distance between two points' q: 'def distance = (p1, p2) -> \n sqrt((index(p2, 0) - index(p1, 0))^2 + (index(p2, 1) - index(p1, 1))^2)\n| set @d = distance([0,0],[1,1])' } { description: 'Calculate the range of a list' q: 'def range2 = (list) -> lmax(list) - lmin(list)\n| set @range = range2([8, 11, 5, 14, 25])' } { description: 'Calculate the factorial of a number using recursion' q: 'def factorial = (n) -> if(n == 1, 1, n*factorial(n-1))\n| set @f9 = factorial(9)' } { description: 'Calculate the number of permutations of n things, taken r at a time' q: 'def factorial = (n) -> if(n == 1, 1, n*factorial(n-1)), permutations = (n, r) -> factorial(n) / factorial(n - r)\n| set @p = permutations(5, 2)' } ] related: ['symbol:->:function'] } { name: 'set' type: 'statement' syntax: [ 'set @var1 = :expression, [@var2 = :expression, ...]' 'set @var1 = :expression, [@var2 = :expression, ...] where :predicate' ] description: [ 'Sets one or more variables in the context. As variables are not row-based, the expression used cannot reference individual rows in the data set. However, it can use aggregate functions over the data set. An optional predicate argument can be used to filter rows before the aggregation.' 'Set can be used at any point in the query, even before input' 'Variables are assigned from left to right, so later variables can reference previously assigned variables.' 'Existing variables will be overridden.' ] examples: [ { description: 'Set a constant variable' q: 'set @plank = 6.626070040e-34' } { description: 'Set several dependent variables' q: 'set @inches = 66, @centimeters_per_inch = 2.54, @centimeters = @inches * @centimeters_per_inch' } { description: 'Calculate an average and use later in the query' q: 'input mock | set @avg = avg(col1) | filter col1 > @avg' } ] related: ['literal:"variable"'] } { name: 'rename' type: 'statement' syntax: [ 'rename :column=:oldcolumn, ...' 'rename :column=:oldcolumn, ... where :predicate' ] description: [ 'Renames one or more columns in the dataset.' 'If a predicate is specified, the rename will apply only to rows satisfying the predicate.' ] examples: [ { q: 'input mock | rename day = col1, sales = col2, bookings = col3, numberOfNights = col4' } { description: 'With predicate' q: 'input mock | rename col5 = col1 where col1 < 2' } ] } { name: 'assignment' type: 'statement' syntax: [ ':column=:expr, ...' ':column=:expr, ... where :predicate' ] description: [ 'Assigns one or more columns to each row in the dataset, by evaluating an expression for each row. Assignments are made from left to right, so it is possible to reference previously assigned columns in the same assignemnt statement.' 'If a predicate is specified, the assignments will apply only to rows satisfying the predicate.' ] examples: [ { q: 'input mock | ratio = col1 / col2' } { description: 'With predicate' q: 'input mock | col1 = col1 + col2 where col1 < 3' } { description: 'With multiple assignments' q: 'input mock | ratio = col1 / col2, col5 = col3 * ratio' } ] } { name: 'stats' type: 'statement' syntax: [ 'stats :expression, ... ' 'stats :expression, ... by :expression, ...' ] description: [ 'Calculates one or more aggregate expressions across the dataset, optionally grouped by one or more expressions. The resulting dataset will have a single row for each unique value(s) of the grouping expressions.' 'Grouping expressions will be evaluated for each row, and the values used to divide the datasets into subsets. Each grouping expression will become a column in the resulting dataset, containing the values for that subset. If no grouping expressions are provided, the aggregations will run across the entire dataset.' ] examples: [ { q: 'input mock | stats count=count(*) by col2' } { q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick' } { description: 'Expressions can be used to group by' q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick, bucket(Time, 4)' } { q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick, Time = bucket(Time, 4)' } ] } { name: 'sleep' type: 'statement' syntax: [ 'sleep' 'sleep :expression' ] description: [ 'Delays execution of the query for a given number of milliseconds. Defaults to 1000 milliseconds if no argument is given.' ] examples: [ { q: 'input mock | sleep 5000' } ] } { name: 'sample' type: 'statement' syntax: [ 'sample :expr' ] description: [ 'Returns a sample of a given size from the current dataset. The sample size can be either smaller or larger than the current dataset.' ] examples: [ { description: 'Selecting a sample' q: 'input mock n=100 | sample 10' } { description: 'Generating a larger sample from a smaller dataset' q: 'input mock n=10 | sample 100' } ] } { name: 'benchmark' type: 'statement' syntax: [ 'benchmark :expr [:options]' 'bench :expr [:options]' ] description: [ 'Benchmarks a query and returns a single row of the results. The query will be run multiple times and includes a warm-up period for the JIT compiler and forced GC before and after testing.' 'Various options are available to customize the benchmark, but defaults will be used if not provided. The values used will be returned as a map in the "options" column.' ] examples: [ { description: 'Benchmarking a query with default options' q: 'benchmark "input mock"' } { description: 'Providing a sample size' q: 'bench "input mock | head 1" samples=20' } { description: 'Projecting the performance results for each sample' q: 'benchmark "input mock" | project first(performance)' } { description: 'Projecting the text summary of the benchmark' q: 'benchmark "set @x = random()" | project split(first(summary), "\n")' } ] } { name: 'pivot' type: 'statement' description: [ 'Increases the number of columns in the current dataset by "pivoting" values of one or more columns into additional columns. For example, unique values in a column "type" can be converted into separate columns, with the values attributable to each type as their contents.' ] syntax: [ 'pivot :value [, :value ...] per :expression [, :expression ...] by :group-by [, :group-by ...]' 'pivot :identifier=:value [, identifier=:value ...] per :expression [, :expression ...] by :group-by [, :group-by ...]' ] related: ['statement:unpivot'] } { name: 'unpivot' type: 'statement' syntax: ['unpivot :value per :column by :group-by [, :group-by ...]'] description: [ 'Reduces the number of columns in the current dataset by "unpivoting" them into rows of a single column. This is the inverse operation of the pivot statement.' ] examples: [ { q: 'input http uri="http://pastebin.com/raw.php?i=YGN7gWWG" parser="json" | unpivot CrimesCommitted per Type by Year, Population' } ] related: ['statement:pivot'] } { name: 'project' type: 'statement' syntax: ['project :expression'] description: [ 'Replaces the current dataset with the result of an expression. The expression must be either a list or a single map which will be wrapped in a list automatically.' 'Projecting a list of maps replaces the entire dataset verbatim. If the list does not contain maps, each value will be stored in a new column called "value".' 'Can be useful when parsing data from a string.' ] examples: [ { description: 'With a list of maps' q: 'input mock | project [{x:1, y:1},{x:2, y:2}]' } { description: 'With a list of numbers' q: 'input mock | project [4, 8, 15, 16, 23, 42] | stats avg = avg(value)' } { description: 'From a variable' q: 'input mock | x = [{x:1, y:1},{x:2, y:2}] | project first(x)' } { description: 'With a single map' q: 'input mock | project {a: 1, b: 2, c: 3}' } { description: 'With a JSON string' q: 'input mock | x = \'[{"x":1, "y":1},{"x":2, "y":2}]\' | project parsejson(first(x))' } { description: 'With a CSV string' q: 'input http uri="http://pastebin.com/raw.php?i=s6xmiNzx" | project parsecsv(first(body), { strict: true, delimiter: "," })' } ] } { name: 'join' type: 'statement' syntax: [ '[inner] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'left [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'right [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'full [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'cross join :dataset-or-query' ] description: [ 'Joins the current dataset with another dataset. The join statement takes the current dataset as the left dataset, and either accepts the name of a dataset in the context or an inline query in parentheses.' 'Join types available: Inner, Left Outer (Left), Right Outer (Right), Full Outer (Full), and Cross Join. If no join type is specified, inner join will be assumed.' 'The joined dataset is the output of this statement. Columns from joined rows will be merged, with preference given to the value in the Left dataset.' ] examples: [ { description: 'Inner join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }] | inner join types on typeId == types.id' } { description: 'Left outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 3 }] | left outer join types on typeId == types.id' } { description: 'Right outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 1 }] | right outer join types on typeId == types.id' } { description: 'Full outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 4 }] | full outer join types on typeId == types.id' } { description: 'Cross join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x" }, { name: "y" }] | cross join types' } ] related: ['statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'inner join' type: 'statement' syntax: ['[inner] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Inner join is a type of join which requires each row in the joined datasets to satisfy a join predicate.' ] examples: [ { description: 'Inner join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }] | inner join types on typeId == types.id' } ] related: ['statement:join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'left outer join' type: 'statement' syntax: ['left [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Left Outer join is a type of join which always includes all rows of the left-hand dataset, even if they do not satisfy the join predicate.' ] examples: [ { description: 'Left outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 3 }] | left outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'right outer join' type: 'statement' syntax: ['right [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Right Outer join is a type of join which always includes all rows of the right-hand dataset, even if they do not satisfy the join predicate.' ] examples: [ { description: 'Right outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 1 }] | right outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'full outer join' type: 'statement' syntax: ['full [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Full Outer join is a type of join which combines the effects of both left and right outer join. All rows from both left and right datasets will be included in the result.' ] examples: [ { description: 'Full outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 4 }] | full outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:cross join'] } { name: 'cross join' type: 'statement' syntax: ['cross join [:left-alias], :dataset-or-query'] description: [ 'Cross join is a type of join which returns the cartesian product of rows from both datasets.' ] examples: [ { description: 'Cross join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x" }, { name: "y" }] | cross join types' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join'] } { name: 'avg' type: 'function' subtype: 'aggregation' description: [ 'avg() is an alias for mean().' ] aliases: ['function:mean'] } { name: 'count' type: 'function' subtype: 'aggregation' syntax: [ 'count(*)' 'count(:expression)' 'count(:expression, :predicate)' ] returns: 'number' description: [ 'Counts the number of rows where :expression is non-null. An optional predicate argument can be used to filter rows before the aggregation.' 'count(*) is equivalent to count(1); it counts every row.' ] examples: [ { q: 'input mock | stats count = count(*)' } { q: 'input mock | col1 = null where col2 == 2 | stats count = count(col1)' } { q: 'input mock | stats count = count(*, col2 == 2)' } ] related: ['function:distinctcount'] } { name: 'cumulativeavg' type: 'function' subtype: 'aggregation' description: [ 'cumulativeavg() is an alias for cumulativemean().' ] aliases: ['function:cumulativemean'] } { name: 'cumulativemean' type: 'function' subtype: 'aggregation' syntax: [ 'cumulativemean(:expression)' 'cumulativemean(:expression, :predicate)' ] returns: 'list' description: [ 'Returns a list of cumulative means for the current dataset. For example, the first value in the list is the value of the first row; the second value is the mean of the first two rows, the third is the mean of the first three rows, etc.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats c1 = cumulativemean(col1), c2 = cumulativemean(col2)' } ] related: ['function:mean', 'function:geometricmean'] aliases: ['function:cumulativeavg'] } { name: 'distinctcount' type: 'function' subtype: 'aggregation' syntax: [ 'distinctcount(:expression)' 'distinctcount(:expression, :predicate)' ] returns: 'number' description: [ 'Counts the number of rows for which :expression is distinct and non-null. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats col1DistinctCount = distinctcount(col1), col2DistinctCount = distinctcount(col2)' } { q: 'input mock | stats count = count(*, col2 == 2)' } ] related: ['function:count'] } { name: 'geometricmean' type: 'function' subtype: 'aggregation' syntax: [ 'geometricmean(:expression)' 'geometricmean(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the geometric mean of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats geometricmean = geometricmean(col1)' } { q: 'input mock | stats geometricmean = geometricmean(col1 + col2, col3 == 3)' } ] related: ['function:mean', 'function:cumulativemean'] } { name: 'max' type: 'function' subtype: 'aggregation' syntax: [ 'max(:expression)' 'max(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the maximum value of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats max = max(col1)' } { q: 'input mock name="chick-weight" | stats maxWeight = max(weight, Chick == 1)' } ] related: ['function:min'] } { name: 'mean' type: 'function' subtype: 'aggregation' syntax: [ 'mean(:expression)' 'mean(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the arithmetic mean of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats mean = mean(col1)' } { q: 'input mock | stats mean = mean(col1 + col2, col3 == 3)' } ] related: ['function:geometricmean', 'function:cumulativemean'] aliases: ['function:avg'] } { name: 'median' type: 'function' subtype: 'aggregation' syntax: [ 'median(:expression)' 'median(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the median value of :expression, calculated across all rows. If there is no middle value, the median is the mean of the two middle values.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats median = median(col1)' } { q: 'input mock name="chick-weight" | stats medianWeight = median(weight, Chick == 1)' } { q: 'input mock name="airline-passengers" | stats mean = mean(passengers), median = median(passengers)' } ] } { name: 'mode' type: 'function' subtype: 'aggregation' syntax: [ 'mode(:expression)' 'mode(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the mode of :expression, calculated across all rows. If there are multiple modes, one of them will be returned.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats mode = mode(col2)' } { q: 'input mock name="hair-eye-color" | stats mode = mode(hair) by gender' } { q: 'input mock name="survey" | stats medianAge = median(age), modeAge = mode(age)' } ] } { name: 'min' type: 'function' subtype: 'aggregation' syntax: [ 'min(:expression)' 'min(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the minimum value of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats min = min(col1)' } { q: 'input mock name="chick-weight" | stats minWeight = min(weight, Chick == 1)' } ] related: ['function:max'] } { name: 'pluck' type: 'function' subtype: 'aggregation' syntax: ['pluck(expression)'] returns: 'list' description: ['Evaluates an expression against each row in the data set, and returns a list composed of the resulting values. The list maintains the same order as the rows in the data set.'] examples: [ { description: 'Plucking a column' q: 'input mock | stats values = pluck(col1)' } { description: 'Plucking a calculated expression' q: 'input mock | stats values = pluck(col1 + col2)' } ] } { name: 'stddev_pop' type: 'function' subtype: 'aggregation' description: [ 'stddev_pop() is an alias for stddevp().' ] aliases: ['function:stddevp'] } { name: 'stddev_samp' type: 'function' subtype: 'aggregation' description: [ 'stddev_samp() is an alias for stddev().' ] aliases: ['function:stddev'] } { name: 'stddevp' type: 'function' subtype: 'aggregation' syntax: [ 'stddevp(:expression)' 'stddevp(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the population standard deviation of :expression, calculated across all rows in the data set (excluding nulls). An optional predicate argument can be used to filter rows before the aggregation.' 'If the data set is not the complete population, use stddev() instead to calculate the sample standard deviation.' ] examples: [ { description: 'Standard deviation of a column' q: 'input mock | stats sigma = stddevp(col1)' } { description: 'Standard deviation of a calculated value' q: 'input mock | stats sigma = stddevp(col1 + col2)' } ] related: ['function:stddev'] aliases: ['function:stddev_pop'] } { name: 'stddev' type: 'function' subtype: 'aggregation' syntax: [ 'stddev(:expression)' 'stddev(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the sample standard deviation of :expression, calculated across all rows in the data set (excluding nulls). An optional predicate argument can be used to filter rows before the aggregation.' 'If the data set is the complete population, use stddevp() instead to calculate the population standard deviation.' ] examples: [ { description: 'Standard deviation of a column' q: 'input mock | stats sigma = stddev(col1)' } { description: 'Standard deviation of a calculated value' q: 'input mock | stats sigma = stddev(col1 + col2)' } ] related: ['function:stddevp'] aliases: ['function:stddev_samp'] } { name: 'sum' type: 'function' subtype: 'aggregation' syntax: [ 'sum(:expression)' 'sum(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the sum of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats total = sum(col1)' } { q: 'input mock name="airline-passengers" | stats pTotal = sum(passengers), p1960 = sum(passengers, year == 1960)' } ] } { name: 'every' type: 'function' subtype: 'aggregation' syntax: [ 'every(:expression)' 'every(:expression, :predicate)' ] returns: 'boolean' description: [ 'Returns true if :expression is true for all rows in the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats test = every(col1 > 0)' } { q: 'input mock name="chick-weight" | stats hasWeight = every(weight > 0, Chick == 1)' } ] related: ['function:some'] } { name: 'first' type: 'function' subtype: 'aggregation' syntax: [ 'first(:expression)' 'first(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the first non-null value of :expression in the dataset, closest to the top of the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats first = first(col1)' } { q: 'input mock name="chick-weight" | stats firstWeight = min(weight, Chick == 1)' } ] related: ['function:last'] } { name: 'last' type: 'function' subtype: 'aggregation' syntax: [ 'last(:expression)' 'last(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the last non-null value of :expression in the dataset, closest to the bottom of the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats last = last(col1)' } { q: 'input mock name="chick-weight" | stats lastWeight = last(weight, Chick == 1)' } ] related: ['function:first'] } { name: 'percentile' type: 'function' subtype: 'aggregation' syntax: [ 'percentile(:expression, :percentage)' 'percentile(:expression, :percentage, :predicate)' ] returns: 'number' description: [ 'Calculates the percentile of an :expression and a given :percentage. Specifically, it returns the value below which :percentage of values in the dataset are less than the value. The percentage can be a number or calculated value.' 'Uses the linear interpolation method, so the returned value may not be in the original dataset. Excludes nils from the calculation and returns nil if there are no non-nil values.' ] examples: [ { q: 'input mock name="chick-weight" | stats p95 = percentile(weight, 95) by Chick' } ] } { name: 'some' type: 'function' subtype: 'aggregation' syntax: [ 'some(:expression)' 'some(:expression, :predicate)' ] returns: 'boolean' description: [ 'Returns true if :expression is true for some rows in the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats test = some(col1 > 0)' } { q: 'input mock name="chick-weight" | stats hasWeight = some(weight > 0, Chick == 1)' } ] related: ['function:some'] } { name: 'isexist' type: 'function' subtype: 'is-functions' syntax: ['isexist(:column)'] returns: 'boolean' description: [ 'Returns true if its argument exists as a column the current row, else false. It does not check the value of the column, just its existance. As a result, isexist() on a column with a null value will return true.' ] examples: [ { q: 'input mock | col6 = 1 where col2 == 2 | exists = isexist(col6)' } ] } { name: 'isnull' type: 'function' subtype: 'is-functions' syntax: ['isnull(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is null, else false.' ] examples: [ { q: 'set @test = isnull(null)' } ] } { name: 'isnan' type: 'function' subtype: 'is-functions' syntax: ['isnan(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is NaN, else false.' ] examples: [ { q: 'set @test = isnan(0 * infinity())' } ] related: ['function:nan'] } { name: 'isinfinite' type: 'function' subtype: 'is-functions' syntax: ['isinfinite(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is infinite, else false.' ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'isfinite' type: 'function' subtype: 'is-functions' syntax: ['isfinite(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is finite, else false.' ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'isempty' type: 'function' subtype: 'is-functions' syntax: ['isempty(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is "empty", else false.' 'Lists are empty if they have no elements; maps are empty if they have no keys; strings are empty if they have zero length or contain only whitespace. Zero and null are both considered empty.' ] examples: [ { q: 'set @nonempty = isempty("hello"), @empty = isempty(" \n")' } { q: 'set @nonempty = isempty({a: 1}), @empty = isempty(tomap())' } { q: 'set @nonempty = isempty([1, 2, 3]), @empty = isempty([])' } ] } { name: 'isdate' type: 'function' subtype: 'type' syntax: ['isdate(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a DateTime, else false.' 'isdate(null) returns false.' ] examples: [ { q: 'set @test = isdate(now())' } { description: 'Numbers are not DateTimes' q: 'set @test = isdate(101)' } ] } { name: 'isboolean' type: 'function' subtype: 'type' syntax: ['isboolean(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a boolean.' 'isboolean(null) returns false.' ] examples: [ { q: 'set @test = isboolean(true)' } { description: 'Numbers are not booleans' q: 'set @test = isboolean(false)' } { description: 'Equality operators always return booleans' q: 'set @test = isboolean(100 > 0)' } ] } { name: 'isnumber' type: 'function' subtype: 'type' syntax: ['isnumber(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a number. This includes integers, doubles, ratios, etc.' 'isnumber(null) returns false.' ] examples: [ { q: 'set @test = isnumber(0)' } { description: 'Booleans are not numbers' q: 'set @test = isnumber(false)' } { description: 'Numerical strings are not numbers' q: 'set @test = isnumber("3.14")' } ] } { name: 'isinteger' type: 'function' subtype: 'type' syntax: ['isinteger(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is an integer.' 'isinteger(null) returns false.' ] examples: [ { q: 'set @test = isinteger(100)' } { description: 'Floating-point numbers are not integers' q: 'set @test = isinteger(1.5)' } { description: 'Since these numbers can be represented accurately as ratios, their addition yields an integer.' q: 'set @test = isinteger(1.5 + 0.5)' } ] } { name: 'isratio' type: 'function' subtype: 'type' syntax: ['isratio(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a ratio. Parsec will automatically store the result of computations in ratio form if possible, e.g. if two integers are divided.' 'isratio(null) returns false.' ] examples: [ { q: 'set @test = isratio(1/2)' } { description: 'Booleans are not ratios' q: 'set @test = isratio(false)' } { description: 'Numerical strings are not ratios' q: 'set @test = isratio("1/3")' } ] } { name: 'isdouble' type: 'function' subtype: 'type' syntax: ['isdouble(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a double.' 'isdouble(null) returns false.' ] examples: [ { q: 'set @test = isdouble(pi())' } { description: 'Forcing a conversion to double' q: 'input mock | x = todouble(col1), @y = isdouble(x)' } { description: 'Parsec stores exact ratios when possible, which are not considered doubles' q: 'set @test = isdouble(1 / 2)' } ] } { name: 'isstring' type: 'function' subtype: 'type' syntax: ['isstring(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a string.' 'isstring(null) returns false.' ] examples: [ { q: 'set @test = isstring("hello world")' } ] } { name: 'islist' type: 'function' subtype: 'type' syntax: ['islist(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a list.' 'islist(null) returns false.' ] examples: [ { q: 'set @test = islist([1, 2, 3])' } ] } { name: 'ismap' type: 'function' subtype: 'type' syntax: ['ismap(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a map.' 'ismap(null) returns false.' ] examples: [ { q: 'set @test = ismap({ a: 1, y: 2, z: 3})' } ] } { name: 'type' type: 'function' subtype: 'type' syntax: ['istype(:expression)'] returns: 'string' description: [ 'Evaluates :expression and returns its data type name as a string.' ] examples: [ { q: 'input mock | x = type(col1)' } { q: 'input mock | x = tostring(col1), y = type(x)' } { q: 'input mock | stats x = pluck(col1) | y = type(x)' } { q: 'input mock | x=type(null)' } ] } { name: 'toboolean' type: 'function' subtype: 'conversion' syntax: ['toboolean(:expression)'] returns: 'boolean' description: [ 'Attempts to convert :expression to a boolean value, returning null if the conversion is not possible.' 'If :expression is a boolean, it is returned as-is.' 'If :expression is a number, yields true for any non-zero number, else false.' 'If :expression is a string, a case-insensitive "true" or "false" will be converted to true and false respectively, with all other values returning null.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a number' q: 'set @true = toboolean(1),\n @false = toboolean(0)' } { description: 'Converting a string' q: 'set @test = toboolean("TRUE")' } ] related: ['function:isboolean'] } { name: 'tostring' type: 'function' subtype: 'conversion' syntax: [ 'tostring(:expression)' 'tostring(:expression, :format)' ] returns: 'string' description: [ 'Attempts to convert :expression to a string type, returning null if the conversion is not possible.' 'If :expression is a string, it is returned as-is.' 'If :expression is a boolean, "true" or "false" is returned.' 'If :expression is a number, yields a string containing the numeric representation of the number.' 'If :expression is a map or list, yields a string containing the JSON representation of :expression.' 'If :expression is a date, yields an ISO 8601-format string representing the date, unless a format code is provided as the second argument. Joda-Time formatting code are accepted, see here: http://www.joda.org/joda-time/key_format.html' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a number' q: 'set @test = tostring(1) // returns "1"' } { description: 'Converting a boolean' q: 'set @test = tostring(true) // returns "true"' } { description: 'Converting a map' q: 'set @test = tostring({ "id": 123, "name": "Vin Diesel" }) // returns {"id":123,"name":"Vin Diesel"}' } { description: 'Converting a list' q: 'set @test = tostring([1, 2, 3]) // returns "[1,2,3]"' } { description: 'Converting a date into ISO 8601 format' q: 'set @year = tostring(now())' } { description: 'Converting a date with a format' q: 'set @year = tostring(now(), "YYYY")' } ] related: ['function:isboolean'] } { name: 'tonumber' type: 'function' subtype: 'conversion' syntax: ['tonumber(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a numerical type, returning null if the conversion is not possible. This function can return integers, doubles, ratios, etc.' 'If :expression is a number, it is returned as-is.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an integer, double, or ratio. If the parsed value can be represented as a ratio, it will be stored internally as such.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting an integer string' q: 'set @test = tonumber("1") // returns 1' } { description: 'Converting a double string' q: 'set @test = tonumber("3.14") // returns 3.14' } { description: 'Converting a ratio' q: 'set @test = tonumber("1/5") // returns 0.2' } { description: 'Converting a date' q: 'set @test = tonumber(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isnumber', 'function:tointeger', 'function:todouble'] } { name: 'tointeger' type: 'function' subtype: 'conversion' syntax: ['tointeger(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a long integer, returning null if the conversion is not possible.' 'If :expression is an integer, it is returned as-is.' 'If :expression is a non-integer number, it will be rounded down to the nearest integer.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an integer.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a double' q: 'set @test = tointeger(3.14) // returns 3' } { description: 'Converting an integer string' q: 'set @test = tointeger("1") // returns 1' } { description: 'Converting a ratio' q: 'set @test = tointeger("22/3") // returns 7' } { description: 'Converting a date' q: 'set @test = tointeger(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isinteger', 'function:tonumber', 'function:todouble'] } { name: 'todouble' type: 'function' subtype: 'conversion' syntax: ['todouble(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a double, returning null if the conversion is not possible.' 'If :expression is an double, it is returned as-is.' 'If :expression is an number, it will be coerced into a double type internally.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an double.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting an integer' q: 'set @test = todouble(1) // returns 1' } { description: 'Converting a double string' q: 'set @test = todouble("3.14") // returns 3.14' } { description: 'Converting a ratio string' q: 'set @test = todouble("22/3") // returns 7.333333333333333' } { description: 'Converting a date' q: 'set @test = todouble(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isdouble', 'function:tonumber', 'function:tointeger'] } { name: 'todate' type: 'function' subtype: 'conversion' syntax: [ 'todate(:expression)' 'todate(:expression, :format)' ] returns: 'number' description: [ 'Attempts to convert :expression to a date, returning null if the conversion is not possible.' 'If :expression is an date, it is returned as-is.' 'If :expression is a number, it will be coerced to a long and interpreted as the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse using various standard formats. A format argument can optionally be provided to specify the correct format.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting epoch milliseconds' q: 'set @test = todate(1461543510000)' } { description: 'Converting an ISO-8601 date' q: 'set @test = todate("2016-04-25T00:02:05.000Z")' } { description: 'Converting a date with a format code' q: 'set @test = todate("1985-10-31", "yyyy-MM-dd")' } ] related: ['function:isdate'] } { name: 'tolist' type: 'function' subtype: 'conversion' syntax: ['tolist(:expression [, :expression ...])'] returns: 'map' description: ['Creates a list from a series of arguments.'] examples: [ { q: 'input mock | x = tolist(1, 2, 3, 4)' } { q: 'input mock | x = tolist("red", "yellow", "green")' } { description: 'Creating a list from expressions' q: 'input mock | x = tolist(meanmean(col1), meanmean(col2), meanmean(col3))' } ] related: ['literal:"list"', 'function:islist'] } { name: 'tomap' type: 'function' subtype: 'conversion' syntax: ['tomap(:key, :expression [, :key, :expression ...])'] returns: 'map' description: ['Creates a map from a series of key/value pair arguments: tomap(key1, expr1, key2, expr2, ...).'] examples: [ { q: 'input mock | x = tomap("x", 1, "y", 2)' } { description: 'Creating a map from expressions' q: 'input mock | x = tomap("meanmean", mean(col1), "max", max(col1))' } ] related: ['literal:"map"', 'function:ismap'] } { name: 'e' type: 'function' subtype: 'constant' syntax: ['e()'] returns: 'number' description: ['Returns the constant Euler\'s number.'] examples: [ { q: 'input mock | pi = e()' } ] related: ['function:ln'] } { name: 'pi' type: 'function' subtype: 'constant' syntax: ['pi()'] returns: 'number' description: ['Returns the constant Pi.'] examples: [ { q: 'input mock | pi = pi()' } ] } { name: 'nan' type: 'function' subtype: 'constant' syntax: ['nan()'] returns: 'number' description: ['Returns the not-a-number (NaN) numerical value.'] examples: [ { q: 'input mock | x = nan(), isnotanumber = isnan(x)' } ] related: ['function:isnan'] } { name: 'infinity' type: 'function' subtype: 'constant' syntax: ['infinity()'] returns: 'number' description: ['Returns the positive infinite numerical value.'] examples: [ { q: 'input mock | x = infinity(), isInf = isinfinite(x)' } ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'neginfinity' type: 'function' subtype: 'constant' syntax: ['neginfinity()'] description: ['Returns the negative infinite numerical value.'] examples: [ { q: 'input mock | x = neginfinity(), isInf = isinfinite(x)' } ] related: ['function:isfinite', 'function:isinfinite', 'function:infinity'] } { name: 'floor' type: 'function' subtype: 'math' syntax: ['floor(:number)'] description: [ 'Returns the greatest integer less than or equal to :number.' ] examples: [ { description: 'Floor of an double' q: 'input mock name="thurstone" | z = y / x, floor = floor(z)' } { description: 'Floor of an integer' q: 'set @floor = floor(42)' } ] related: ['function:ceil', 'function:round'] } { name: 'ceil' type: 'function' subtype: 'math' syntax: ['ceil(:number)'] description: [ 'Returns the least integer greater than or equal to :number.' ] examples: [ { description: 'Ceiling of an double' q: 'input mock name="thurstone" | z = y / x, ceil = ceil(z)' } { description: 'Ceiling of an integer' q: 'set @ceil = ceil(42)' } ] related: ['function:floor', 'function:round'] } { name: 'abs' type: 'function' subtype: 'math' syntax: ['abs(:number)'] description: [ 'Returns the absolute value of :number.' ] examples: [ { description: 'Absolute value of a positive number' q: 'set @abs = abs(10)' } { description: 'Absolute value of a negative number' q: 'set @abs = abs(-99)' } ] } { name: 'sign' type: 'function' subtype: 'math' syntax: ['sign(:number)'] description: [ 'Returns 1 if :number is greater than zero, -1 if :number is less than zero, and 0 if :number is zero.' 'Returns NaN if :number is NaN.' ] examples: [ { description: 'Sign of a positive number' q: 'set @sign = sign(10)' } { description: 'Sign of a negative number' q: 'set @sign = sign(-99)' } { description: 'Sign of zero' q: 'set @sign = sign(0)' } ] } { name: 'sqrt' type: 'function' subtype: 'math' syntax: ['sqrt(:number)'] description: [ 'Returns the square root of :number.' ] examples: [ { q: 'input mock name="thurstone" | sqrt = sqrt(x + y)' } { description: 'Square root of a perfect square' q: 'set @square = sqrt(64)' } ] related: ['function:pow'] } { name: 'pow' type: 'function' subtype: 'math' syntax: ['pow(:base, :power)'] description: [ 'Returns :base raised to the power of :power.' ] examples: [ { q: 'input mock name="thurstone" | cube = pow(x + y, 3)' } { description: 'Square root of a square' q: 'set @square = sqrt(pow(8, 2))' } ] related: ['function:sqrt'] } { name: 'round' type: 'function' subtype: 'math' syntax: ['round(:number)', 'round(:number, :places)'] description: [ 'Rounds a number to a given number of decimal places.' 'If the 2nd argument is omitted, the number is rounded to an integer (0 decimal places).' ] examples: [ { description: 'Rounding to an integer' q: 'input mock name="thurstone" | stats p90 = percentile(x, 90), r = round(p90)' } { description: 'Rounding to five decimal places' q: 'input mock name="thurstone" | stats z = mean(x / y), r = round(z, 5)' } ] related: ['function:ceil', 'function:floor'] } { name: 'within' type: 'function' subtype: 'math' syntax: ['within(:number, :test, :tolerance)'] description: [ 'Returns true if the difference between :number and :test is less than or equal to :tolerance. That is, it evaluates whether the value of :number is in the range of :test +/- :tolerance (inclusive).' ] examples: [ { q: 'input mock | x = within(col1, col3, 1)' } { description: 'Comparing maximum Chick weights to the average' q: 'input mock name="chick-weight" | stats mean=mean(weight), max=max(weight), stdev = stddev(weight) by Chick | withinOneSigma = within(mean, max, stdev)' } ] related: ['function:within%'] } { name: 'within%' type: 'function' subtype: 'math' syntax: ['within%(:number, :test, :percent)'] description: [ 'Similar to within(), but uses :percent to calculate the tolerance from :test. Returns true if the difference between :number and :test is less than or equal to (:percent * :test).' 'The :percent argument is expected as a decimal or percentage literal: "0.1" or "10%". A value of "10" is interpreted as 1000%, not 10%.' ] examples: [ { q: 'input mock | select col1, col4 | x = within%(col1, col4, 50%)' } { description: 'Comparing maximum Chick weights to the average' q: 'input mock name="chick-weight" | stats avg=avg(weight), max=max(weight) by Chick | test = within%(max, avg, 50%)' } ] related: ['function:within'] } { name: 'greatest' type: 'function' subtype: 'math' syntax: ['greatest(:number, :number, ...)'] description: [ 'Returns the argument with the greatest numerical value, regardless of order.' 'greatest(null) returns null, and non-numerical arguments will cause an exception. If a single argument is provided, it will be returned regardless of its type.' ] examples: [ { q: 'input mock | greatest = greatest(col1, col2, col3)' } ] related: ['function:least'] } { name: 'least' type: 'function' subtype: 'math' syntax: ['least(:number, :number, ...)'] description: [ 'Returns the argument with the smallest numerical value, regardless of order.' 'least(null) returns null, and non-numerical arguments will cause an exception. If a single argument is provided, it will be returned regardless of its type.' ] examples: [ { q: 'input mock | least = least(col1, col2, col3)' } ] related: ['function:greatest'] } { name: 'gcd' type: 'function' subtype: 'math' syntax: ['gcd(:integer, :integer)'] description: [ 'Returns the greatest common divisor of two integers.' 'Returns null if either :integer is null, or if non-integer arguments are passed.' ] examples: [ { q: 'set @gcd = gcd(12, 18)' } ] related: ['function:lcm'] } { name: 'lcm' type: 'function' subtype: 'math' syntax: ['lcm(:integer, :integer)'] description: [ 'Returns the least common multiple of two integers.' 'Returns null if either :integer is null, or if non-integer arguments are passed.' ] examples: [ { q: 'set @lcm = lcm(12, 18)' } ] related: ['function:gcd'] } { name: 'ln' type: 'function' subtype: 'math' syntax: ['ln(:number)'] description: [ 'Returns the natural logarithm (base e) for :number' 'Returns null for non-numerical arguments. If :number is NaN or less than zero, returns NaN. If :number is positive infinity, then returns positive infinity. If :number is positive zero or negative zero, then returns negative infinity.' ] examples: [ { q: 'set @ln = ln(5)' } ] related: ['function:e', 'function:log'] } { name: 'log' type: 'function' subtype: 'math' syntax: ['log(:number)'] description: [ 'Returns the base 10 logarithm for :number' 'Returns null for non-numerical arguments. If :number is NaN or less than zero, returns NaN. If :number is positive infinity, then returns positive infinity. If :number is positive zero or negative zero, then returns negative infinity.' ] examples: [ { q: 'set @log = log(5)' } ] related: ['function:ln'] } { name: 'degrees' type: 'function' subtype: 'trigonometric' syntax: ['degrees(:angle)'] description: [ 'Converts an :angle in radians to degrees.' ] examples: [ { q: 'set @degrees = degrees(pi() / 2)' } ] related: ['function:radians'] } { name: 'radians' type: 'function' subtype: 'trigonometric' syntax: ['radians(:angle)'] description: [ 'Converts an :angle in degrees to radians.' ] examples: [ { q: 'set @radians = radians(45)' } ] related: ['function:degrees'] } { name: 'sin' type: 'function' subtype: 'trigonometric' syntax: ['sin(:number)'] description: [ 'Returns the trigonometric sine of an angle in radians.' 'If :number is NaN or infinity, returns NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @sin = sin(3.1415)' } ] related: ['function:cos', 'function:tan', 'function:asin', 'function:sinh'] } { name: 'cos' type: 'function' subtype: 'trigonometric' syntax: ['cos(:number)'] description: [ 'Returns the trigonometric cosine of an angle in radians.' 'If :number is NaN or infinity, returns NaN.' ] examples: [ { q: 'set @cos = cos(3.1415)' } ] related: ['function:sin', 'function:tan', 'function:acos', 'function:cosh'] } { name: 'tan' type: 'function' subtype: 'trigonometric' syntax: ['tan(:number)'] description: [ 'Returns the trigonometric tangent of an angle in radians.' 'If :number is NaN or infinity, returns NaN. If :number is zero, then the result is a zero with the same sign as :number.' ] examples: [ { q: 'set @tan = tan(3.1415)' } ] related: ['function:sin', 'function:cos', 'function:atan', 'function:atan2', 'function:tanh'] } { name: 'sinh' type: 'function' subtype: 'trigonometric' syntax: ['sinh(:number)'] description: [ 'Returns the hyperbolic sine of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is infinite, then the result is an infinity with the same sign as :number. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @sinh = sinh(3.1415)' } ] related: ['function:sin', 'function:cosh', 'function:tanh', 'function:asin'] } { name: 'cosh' type: 'function' subtype: 'trigonometric' syntax: ['cosh(:number)'] description: [ 'Returns the hyperbolic cosine of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is infinite, then the result then the result is positive infinity. If :number is zero, then the result is 1.' ] examples: [ { q: 'set @cosh = cosh(3.1415)' } ] related: ['function:cos', 'function:sinh', 'function:tanh', 'function:acos'] } { name: 'tanh' type: 'function' subtype: 'trigonometric' syntax: ['tanh(:number)'] description: [ 'Returns the hyperbolic tangent of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is zero, then the result is zero. If :number is positive infinity, then the result is 1. If :number is negative infinity, then the result is -1.0.' ] examples: [ { q: 'set @tanh = tanh(3.1415)' } ] related: ['function:sinh', 'function:cosh', 'function:tan', 'function:atan'] } { name: 'asin' type: 'function' subtype: 'trigonometric' syntax: ['asin(:number)'] description: [ 'Returns the arc sine of an angle in radians.' 'If :number is NaN or its absolute value is greater than 1, then the result is NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @asin = asin(0.5)' } ] related: ['function:sin', 'function:sinh', 'function:acos', 'function:atan'] } { name: 'acos' type: 'function' subtype: 'trigonometric' syntax: ['acos(:number)'] description: [ 'Returns the arc cosine of an angle in radians.' 'If :number is NaN or its absolute value is greater than 1, then the result is NaN.' ] examples: [ { q: 'set @acos = acos(0.5)' } ] related: ['function:cos', 'function:cosh', 'function:asin', 'function:atan'] } { name: 'atan' type: 'function' subtype: 'trigonometric' syntax: ['atan(:number)'] description: [ 'Returns the arc tangent of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @atan = atan(0.5)' } ] related: ['function:tan', 'function:tanh', 'function:asin', 'function:acos'] } { name: 'atan2' type: 'function' subtype: 'trigonometric' syntax: ['atan2(:y, :x)'] description: [ 'Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).' ] examples: [ { q: 'set @atan2 = atan2(1, 1)' } ] related: ['function:tan', 'function:tanh', 'function:tan', 'function:atan'] } { name: 'pdfuniform' type: 'function' subtype: 'probability' syntax: [ 'pdfuniform(:number)' 'pdfuniform(:number, :min, :max)' 'pdfuniform(:list)' 'pdfuniform(:list, :min, :max)' ] description: [ 'Returns the continuous uniform distribution function of the given :number or :list, with default values of min=0, max=1.' 'If a :list is provided, the result will be a list with pdfuniform() applied to each element.' ] examples: [ { q: 'set @pdf = pdfuniform(0.5), @pdf2 = pdfuniform(0.5, 0, 5)' } { description: 'Applying pdfuniform() to a list' q: 'project range(0, 10) | P = pdfnormal(value, 0, 10)' } ] related: ['function:cdfuniform', 'function:pdfnormal', 'function:pdfpoisson'] } { name: 'pdfnormal' type: 'function' subtype: 'probability' syntax: [ 'pdfnormal(:number)' 'pdfnormal(:number, :mean, :sd)' 'pdfnormal(:list)' 'pdfnormal(:list, :mean, :sd)' ] description: [ 'Returns the continuous Normal cumulative distribution function of the given :number or :list, with default values of mean=0, sd=1.' 'If a :list is provided, the result will be a list with pdfnormal() applied to each element.' ] examples: [ { q: 'set @pdf = pdfnormal(0.5), @pdf2 = pdfnormal(0.5, 0, 5)' } { description: 'Applying pdfnormal() to a list' q: 'project range(0, 10) | P = pdfnormal(value, 0, 10)' } ] related: ['function:cdfnormal', 'function:pdfuniform', 'function:pdfpoisson'] } { name: 'pdfpoisson' type: 'function' subtype: 'probability' syntax: [ 'pdfpoisson(:number)' 'pdfpoisson(:number, :lambda)' 'pdfpoisson(:list)' 'pdfpoisson(:list, :lambda)' ] description: [ 'Returns the continuous Poisson cumulative distribution function of the given :number or :list, with default value of lambda=1.' 'If a :list is provided, the result will be a list with pdfpoisson() applied to each element.' ] examples: [ { q: 'set @pdf = pdfpoisson(0.5), @pdf2 = pdfpoisson(0.5, 5)' } { description: 'Applying pdfpoisson() to a list' q: 'project range(0, 10) | P = pdfpoisson(value, 2)' } ] related: ['function:cdfpoisson', 'function:pdfuniform', 'function:pdfnormal'] } { name: 'cdfuniform' type: 'function' subtype: 'probability' syntax: [ 'cdfuniform(:number)' 'cdfuniform(:number, :min, :max)' 'cdfuniform(:list)' 'cdfuniform(:list, :min, :max)' ] description: [ 'Returns the Uniform cumulative distribution function of the given :number or :list, with default values of min=0, max=1.' 'If a :list is provided, the result will be a list with cdfuniform() applied to each element.' ] examples: [ { q: 'set @cdf = cdfuniform(0.5), @cdf2 = cdfuniform(0.5, 0, 5)' } { description: 'If plant weights are equally probable, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfuniform(weight, min(weight), max(weight))' } { description: 'Same as above, but with lists' q: 'input mock name="plant-growth" \n| set @weights = pluck(weight)\n| set @P = cdfuniform(@weights, listmin(@weights), listmax(@weights));' } ] related: ['function:pdfuniform', 'function:cdfnormal', 'function:cdfpoisson'] } { name: 'cdfnormal' type: 'function' subtype: 'probability' syntax: [ 'cdfnormal(:number)' 'cdfnormal(:number, :mean, :sd)' 'cdfnormal(:list)' 'cdfnormal(:list, :mean, :sd)' ] description: [ 'Returns the Normal cumulative distribution function of the given :number or :list, with default values of mean=0, sd=1.' 'If a :list is provided, the result will be a list with cdfnormal() applied to each element.' ] examples: [ { q: 'set @cdf = cdfnormal(0.5), @cdf2 = cdfnormal(0.5, 0, 5)' } { description: 'If plant weights have a normal distribution, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfnormal(weight, mean(weight), stddev(weight))' } { description: 'Same as above, but with lists' q: 'input mock name="plant-growth" \n| set @weights = pluck(weight)\n| set @P = cdfnormal(@weights, listmean(@weights), liststddev(@weights));' } ] related: ['function:pdfnormal', 'function:cdfuniform', 'function:cdfpoisson'] } { name: 'cdfpoisson' type: 'function' subtype: 'probability' syntax: [ 'cdfpoisson(:number)' 'cdfpoisson(:number, :lambda)' 'cdfpoisson(:list)' 'cdfpoisson(:list, :lambda)' ] description: [ 'Returns the Poisson cumulative distribution function of the given :number or :list, with default value of lambda=1.' 'If a :list is provided, the result will be a list with cdfpoisson() applied to each element.' ] examples: [ { q: 'set @cdf = cdfpoisson(3), @cdf2 = cdfpoisson(3, 4)' } { description: 'If plant weights have a normal distribution, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfpoisson(weight, mean(weight), stddev(weight))' } { description: 'Applying cdfpoisson() to a list' q: 'set @l = cdfpoisson([1,2,3,4,5,6,7], 2)' } ] related: ['function:pdfpoisson', 'function:cdfuniform', 'function:cdfnormal'] } { name: 'len' type: 'function' subtype: 'string' description: [ 'len() is an alias for length().' ] aliases: ['function:length'] } { name: 'substring' type: 'function' subtype: 'string' syntax: [ 'substring(:string, :start)' 'substring(:string, :start, :end)' ] description: [ 'Returns a substring of the given :string, beginning with the character at the :start index, and extending either to the end of the string, or to the character before the :end index.' 'The :start and :end indices are inclusive and exclusive, respectively. If the :end index is beyond the end of :string, the substring will extend to the end of the :string.' 'Returns null if :string is either null or not a string.' 'Do not confuse this function with substr(), which takes a :start index and a number of characters.' ] examples: [ { description: 'With start but no end' q: 'set @sub = substring("Parsec is cool!", 10)' } { description: 'With a start and end' q: 'set @sub = substring("Parsec is cool!", 10, 14)' } { description: 'Using indexof()' q: 'set @s = "Hello World", @sub = substring(@s, indexof(@s, "o"), indexof(@s, "r"))' } ] related: ['function:substr'] } { name: 'substr' type: 'function' subtype: 'string' syntax: [ 'substr(:string, :start)' 'substr(:string, :start, :length)' ] description: [ 'Returns a substring of the given :string, beginning with the character at the :start index, and extending either to the end of the string, or to the next :length number of characters.' 'The :start index is inclusive. If the :length extends beyond the end of :string, the substring will extend to the end of the :string.' 'Returns null if :string is either null or not a string.' 'Do not confuse this function with substring(), which takes a :start index and an :end index.' ] examples: [ { description: 'With start but no length' q: 'set @sub = substr("Parsec is cool!", 10)' } { description: 'With a start and length' q: 'set @sub = substr("Parsec is cool!", 10, 4)' } { description: 'Using indexof()' q: 'set @s = "Hello World", @sub = substr(@s, indexof(@s, "W"))' } ] related: ['function:substring', 'function:indexof'] } { name: 'indexof' type: 'function' subtype: 'string' syntax: [ 'indexof(:string, :value)' ] description: [ 'Returns the first index of :value in :string, if it exists. If :value is not found, it will return null.' 'If :value is not a string, it will be converted to a string automatically. This allows indexof() to find numbers in a string, for example.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @index = indexof("Parsec", "s")' } { q: 'set @s = "Hello World", @sub = substr(@s, indexof(@s, "W"))' } ] related: ['function:lastindexof'] } { name: 'lastindexof' type: 'function' subtype: 'string' syntax: [ 'lastindexof(:string, :value)' ] description: [ 'Returns the last index of :value in :string, if it exists. If :value is not found, it will return null.' 'If :value is not a string, it will be converted to a string automatically. This allows lastindexof() to find numbers in a string, for example.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @index = lastindexof("123,445,660.0", ",")' } { q: 'set @s = "Hello World", @sub = substr(@s, lastindexof(@s, "o"))' } ] related: ['function:indexof'] } { name: 'trim' type: 'function' subtype: 'string' syntax: ['trim(:string)'] returns: 'string' description: [ 'The trim() function removes whitespace from both ends of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = trim(" parsec\t ")' } ] related: ['function:ltrim', 'function:rtrim'] } { name: 'ltrim' type: 'function' subtype: 'string' syntax: ['ltrim(:string)'] returns: 'string' description: [ 'The ltrim() function removes whitespace from the left end of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = ltrim(" parsec")' } ] related: ['function:trim', 'function:rtrim'] } { name: 'rtrim' type: 'function' subtype: 'string' syntax: ['rtrim(:string)'] returns: 'string' description: [ 'The rtrim() function removes whitespace from the right end of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = rtrim("parsec ")' } ] related: ['function:trim', 'function:ltrim'] } { name: 'uppercase' type: 'function' subtype: 'string' syntax: ['uppercase(:string)'] returns: 'string' description: [ 'The uppercase() function returns its argument converted to uppercase.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = uppercase("parsec")' } ] related: ['function:lowercase'] } { name: 'lowercase' type: 'function' subtype: 'string' syntax: ['lowercase(:string)'] returns: 'string' description: [ 'The lowercase() function returns its argument converted to lowercase.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = lowercase("parsec")' } ] related: ['function:uppercase'] } { name: 'replace' type: 'function' subtype: 'string' syntax: ['replace(:string, :search, :replacement)'] returns: 'string' description: [ 'Replaces the first instance of :search in :string with :replacement.' 'If either :search or :replacement are not strings, they will be converted to strings automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @string = replace("aaabbbbccc", "a", "x")' } ] related: ['function:replaceall'] } { name: 'replaceall' type: 'function' subtype: 'string' syntax: ['replaceall(:string, :search, :replacement)'] returns: 'string' description: [ 'Replaces all instance of :search in :string with :replacement.' 'If either :search or :replacement are not strings, they will be converted to strings automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @string = replaceall("aaabbbbccc", "a", "x")' } ] related: ['function:replace'] } { name: 'startswith' type: 'function' subtype: 'string' syntax: ['startswith(:string, :search)'] returns: 'string' description: [ 'Returns true if :string begins with :search, else false.' 'If :search is not a string, it will be converted to a string automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @test = startswith("parsec", "p")' } ] related: ['function:endswith'] } { name: 'endswith' type: 'function' subtype: 'string' syntax: ['endswith(:string, :search)'] returns: 'string' description: [ 'Returns true if :string ends with :search, else false.' 'If :search is not a string, it will be converted to a string automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @test = endswith("parsec", "c")' } ] related: ['function:startswith'] } { name: 'join' type: 'function' subtype: 'string' syntax: [ 'join(:list)' 'join(:list, :separator)' ] returns: 'string' description: [ 'Returns a string of all elements in :list, concatenated together with an optional :separator between them.' 'Returns null if :list is either null or not a list.' ] examples: [ { q: 'set @string = join(["a", "b", "c"], ", ")' } { q: 'input mock | set @col1 = join(pluck(col1), "-")' } ] } { name: 'split' type: 'function' subtype: 'string' syntax: ['split(:string, :delimiter)'] returns: 'list' description: [ 'Splits a string into tokens using a delimiter and returns a list of the tokens. A regex can be given as :delimiter.' ] examples: [ { q: 'input mock | x = split("1,2,3", ",")' } { description: 'Using regex to match delimiters' q: 'set @phone = pop(split("(425)555-1234", "[^\d]"))' } ] } { name: 'urlencode' type: 'function' subtype: 'string' syntax: ['urlencode(:string)'] returns: 'string' description: [ 'Translates a string into application/x-www-form-urlencoded format.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = urlencode("x=1&y=2")' } ] related: ['function:urldecode'] } { name: 'urldecode' type: 'function' subtype: 'string' syntax: ['urldecode(:string)'] returns: 'string' description: [ 'Decodes a string encoded in the application/x-www-form-urlencoded format.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = urldecode("x%3D1%26y%3D2")' } ] related: ['function:urlencode'] } { name: 'base64encode' type: 'function' subtype: 'string' syntax: ['base64encode(:string)'] returns: 'string' description: [ 'Encodes a string into a base64 string representation.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = base64encode("hello world"), y = base64decode(x)' } ] related: ['function:base64decode'] } { name: 'base64decode' type: 'function' subtype: 'string' syntax: ['base64decode(:string)'] returns: 'string' description: [ 'Decodes a string from a base64-encoded string.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = base64encode("hello world"), y = base64decode(x)' } ] related: ['function:base64encode'] } { name: 'parsejson' type: 'function' subtype: 'parsing' syntax: [ 'parsejson(:string)' ] description: [ 'Parses a JSON string and returns the result. Any valid JSON data type may be returned, including lists, maps, strings, numbers, and booleans.' ] examples: [ { description: 'Parsing a string' q: 'input mock | x = parsejson(\'"my-json"\')' } { description: 'Parsing a list' q: 'input mock | list = parsejson("[" + col1 + "," + col2 + "," + col3 + "]")' } { description: 'Projecting a JSON list of maps as a new data set' q: 'project parsejson(\'[{ "x": 1, "y": 2 }, {"x": 3, "y": 4 }]\')' } ] related: ['function:jsonpath', 'function:parsecsv', 'function:parsexml'] } { name: 'parsecsv' type: 'function' subtype: 'parsing' syntax: [ 'parsecsv(:string)' 'parsecsv(:string, { delimiter: string, quote: string, eol: string })' ] description: [ 'Parses a CSV string and returns the result (list of maps).' ] examples: [ { description: 'Parsing CSV with default options' q: 'set @text="a,b,c\n1,2,3\n4,5,6\n7,8,9", @parsed = parsecsv(@text)' } { description: 'Using a custom end-of-line and delimiter' q: 'set @text="col1~col2~col3|1~2~3|4~5~6|7~8~9", @parsed = parsecsv(@text, { eol: "|", delimiter: "~" })' } { description: 'Parsing data without a header row' q: 'set @text="1,2,3\n4,5,6\n7,8,9", @parsed = parsecsv(@text, { headers: false })' } { description: 'Parsing a TSV string (tab-separated values)' q: 'set @text="col1\tcol2\tcol3|1\t2\t3|4\t5\t6|7\t8\t9", @parsed = parsecsv(@text, { eol: "|", delimiter: "\t" })' } ] related: ['function:parsejson', 'function:parsexml'] } { name: 'parsexml' type: 'function' subtype: 'parsing' syntax: [ 'parsexml(:string)' 'parsexml(:string, :xpath)' 'parsexml(:string, { xpath: string, raw: boolean, flatten: boolean })' ] description: [ 'Parses an XML string and returns the result (list of maps).' ] examples: [ { description: 'Without an XPath expression, parsing starts at the root element' q: 'input mock | xml = "<root>" + col1 + "</root>", parsed = parsexml(xml)' } { description: 'Attributes are parsed into columns' q: 'input mock | xml = \'<root q="xyz" s="abc">\' + col1 + \'</root>\', parsed = parsexml(xml)' } { description: 'By default, child elements are flattened.' q: 'input mock | xml = "<root><col1>" + col1 + "</col1><col2>" + col2 + "</col2></root>", parsed = parsexml(xml, "/root")' } { description: 'Repeated elements are parsed into multiple rows' q: 'input mock | xml = "<root><val>" + col1 + "</val><val>" + col2 + "</val></root>", parsed = parsexml(xml, "/root/val")' } { description: 'Hacker News' q: 'input http uri="http://news.ycombinator.com/rss" | project parsexml(first(body), "/rss/channel/item")' } ] related: ['function:parsecsv', 'function:parsejson'] } { name: 'jsonpath' type: 'function' subtype: 'parsing' syntax: [ 'jsonpath(:map-or-list, :string)' ] description: [ 'Applies a JsonPath expression to a map or list and returns the result. Any valid JSON data type may be returned, including lists, maps, strings, numbers, and booleans.' 'This function cannot be used on JSON strings. Use parsejson() beforehand to convert the strings into objects.' 'The http input type has a built-in option for using jsonpath().' 'JsonPath reference: http://goessner.net/articles/JsonPath/. For specific implementation reference, see: https://github.com/gga/json-path' ] examples: [ { description: 'Select a field' q: 'set @results = jsonpath({ numbers: [1, 2, 3] }, "$.numbers")' } { description: 'Select a field of all children' q: 'set @obj = { messages: [{from: "me@parsec.com"}, {from: "you@parsec.com"}, {from: "me@parsec.com"}] },\n @results = jsonpath(@obj, "$.messages[*].from")' } ] related: ['input:http', 'function:parsejson'] } { name: 'if' type: 'function' subtype: 'conditional' syntax: [ 'if(:predicate, :when-true)' 'if(:predicate, :when-true, :when-false)' ] description: [ 'Evaluates :predicate and, if true, returns :when-true. Else returns :when-false.' 'If the :when-false clause is omitted, null will be returned' ] examples: [ { q: 'input mock | x = if(col1 < 3, "less than three", "greater than three")' } ] } { name: 'case' type: 'function' subtype: 'conditional' syntax: [ 'case(:predicate1, :result1 [, :predicate2, :result2 ...])' ] description: [ 'Evalutes a series of test expression & result pairs from left to right. The first test expression that evaluates to true will cause its corresponding result expression to be returned. If no test expression evaluates to true, the function will return null.' 'If an odd number of arguments are provided, the last will be treated as an "else" clause, and returned in absense of any other successful test' ] examples: [ { description: 'With two test expressions' q: 'input mock | x = case(col3 == 3, "apples", col3 == 5, "oranges")' } { description: 'With an "else" clause' q: 'input mock | x = case(col1 == 1, "one", col1 == 2, "two", "else")' } { description: 'With a single test expression' q: 'input mock | greaterThanThree = case(col1 >= 3, true)' } ] } { name: 'coalesce' type: 'function' subtype: 'conditional' syntax: [ 'coalesce(:expression1 [, :expression2, ...])' ] description: [ 'Returns the first non-null expression in the argument list.' 'If all expressions are null, coalesce() returns null.' ] examples: [ { q: 'input mock | x = coalesce(null, null, 1)' } ] } { name: 'reverse' type: 'function' subtype: 'list' syntax: [ 'reverse(:string)' 'reverse(:list)' ] returns: 'string | list' description: [ 'Returns the characters in a string, or items in a list. Returns null for all other arguments.' ] examples: [ { description: 'Reversing a string' q: 'set @reversed = reverse("Parsec")' } { description: 'Reversing a list' q: 'set @reversed = reverse([1, 2, 3, 4])' } ] } { name: 'listmean' type: 'function' subtype: 'list' syntax: [ 'listmean(:list)' ] returns: 'number' description: [ 'Returns the arithmetic mean of the list elements in :list.' 'Throws an error if any of the list elements are non-numerical.' ] examples: [ { q: 'set @listmean = listmean([1, 2, 3, 4])' } ] aliases: ['function:lmean'] } { name: 'listmax' type: 'function' subtype: 'list' syntax: [ 'listmax(:list)' ] returns: 'number' description: [ 'Returns the element in :list with the maximal value of all elements.' 'Throws an error if any of the list elements are non-numerical, unless :list has only a single element, in which case that element is returned.' ] examples: [ { q: 'set @listmax = listmax([2, 10, 4, 8, 5])' } ] aliases: ['function:lmax'] } { name: 'listmin' type: 'function' subtype: 'list' syntax: [ 'listmin(:list)' ] returns: 'number' description: [ 'Returns the element in :list with the minimal value of all elements.' 'Throws an error if any of the list elements are non-numerical, unless :list has only a single element, in which case that element is returned.' ] examples: [ { q: 'set @listmin = listmin([2, 10, 4, 8, 5])' } ] aliases: ['function:lmin'] } { name: 'lmean' type: 'function' subtype: 'list' description: [ 'lmean() is an alias for listmean().' ] aliases: ['function:listmean'] } { name: 'lmax' type: 'function' subtype: 'list' description: [ 'lmax() is an alias for listmax().' ] aliases: ['function:listmax'] } { name: 'lmin' type: 'function' subtype: 'list' description: [ 'lmin() is an alias for listmin().' ] aliases: ['function:listmin'] } { name: 'liststddev' type: 'function' subtype: 'list' syntax: [ 'liststddev(:list)' ] returns: 'number' description: [ 'Returns the sample standard deviation of :list.' 'If the list is the complete population, use liststddevp() instead to calculate the population standard deviation.' ] examples: [ { q: 'set @liststddev = liststddev([2, 10, 4, 8, 5])' } ] related: ['function:liststddevp'] } { name: 'liststddevp' type: 'function' subtype: 'list' syntax: [ 'liststddevp(:list)' ] returns: 'number' description: [ 'Returns the population standard deviation of :list.' 'If the list is not the complete population, use liststddev() instead to calculate the sample standard deviation.' ] examples: [ { q: 'set @liststddevp = liststddevp([2, 10, 4, 8, 5])' } ] related: ['function:liststddev'] } { name: 'length' type: 'function' subtype: 'list' syntax: [ 'length(:string)' 'length(:list)' ] returns: 'number' description: [ 'Returns the number of characters in a string, or items in a list. Returns null for all other arguments.' ] examples: [ { description: 'Length of a string' q: 'set @length = length("Parsec")' } { description: 'Length of a list' q: 'set @length = length([1, 2, 3, 4])' } ] aliases: ['function:len'] } { name: 'peek' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'peek(:list)' ] description: [ 'Returns the first item in a list. To retrieve the last item of the list, use peeklast().' 'peek() on an empty list returns null.' ] examples: [ { q: 'set @first = peek([1,2,3])' } ] related: ['function:peeklast', 'function:pop', 'function:push'] } { name: 'peeklast' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'peeklast(:list)' ] description: [ 'Returns the last item in a list. To retrieve the first item of the list, use peek().' 'peeklast() on an empty list returns null.' ] examples: [ { q: 'set @last = peeklast([1,2,3])' } ] related: ['function:peek', 'function:pop', 'function:push'] } { name: 'pop' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'pop(:list)' ] description: [ 'Returns a list without the first item. To retrieve the first value of the list, use peek().' 'pop() on an empty list throws an error.' ] examples: [ { q: 'set @list = pop([1,2,3])' } ] related: ['function:peek', 'function:push'] } { name: 'push' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'push(:list, :value)' 'push(:list, :value, :value, ...)' ] description: [ 'Appends one or more values to the end of a list and returns the updated list.' ] examples: [ { description: 'One value' q: 'set @list = push([1, 2, 3], 4)' } { description: 'Two values' q: 'set @list = push([1, 2, 3], 4, 5)' } ] related: ['function:pop', 'function:concat'] } { name: 'concat' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'concat(:list, :list)' 'concat(:list, :list, :list, ...)' 'concat(:list, :value)' ] description: [ 'Concatenates one or more lists or values together, from left to right.' 'Non-list arguments will be converted into lists and concatenated.' ] examples: [ { description: 'Two lists' q: 'set @list = concat([1, 2, 3], [4, 5, 6])' } { description: 'Three lists' q: 'set @list = concat([1, 2, 3], [4, 5, 6], [7, 8, 9])' } { description: 'Lists and non-lists' q: 'set @list = concat([1, 2, 3], 4, 5, [6, 7])' } ] related: ['function:push'] } { name: 'contains' type: 'function' subtype: 'list' returns: 'boolean' syntax: ['contains(:list, :expr)', 'contains(:string, :expr)'] description: [ 'Returns true if :expr is contained as a member of :list, else false.' 'If :string is given instead of :list, it returns true if :expr is a substring of :string, else false. If necessary, :expr will be automatically converted to a string to perform the comparison.' ] examples: [ { q: 'input mock | set @list = [1, 2, 5] | test = contains(@list, col1)' } { q: 'input mock | str = "hello world", hasWorld = contains(str, "world")' } ] } { name: 'distinct' type: 'function' subtype: 'list' returns: 'list' syntax: ['distinct(:list)'] description: [ 'Returns a list of the elements of :list with duplicates removed.' 'distinct(null) returns null; same for any non-list argument.' ] examples: [ { q: 'input mock | set @list = [1, 1, 2, 3, 2, 3] | test = distinct(@list)' } ] } { name: 'flatten' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'flatten(:list)' ] description: [ 'Flattens a list of lists one level deep.' ] examples: [ { description: 'Two lists' q: 'set @list = flatten([[1, 2, 3], [4, 5, 6]])' } { description: 'Three lists' q: 'set @list = flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]])' } { description: 'Lists and non-lists' q: 'set @list = flatten([0, [1, 2, 3], 4, 5, [6, 7]])' } { description: 'Deeply-nested data' q: 'set @list = flatten([[["red", "blue"], ["apple", "orange"]], [["WA", "CA"], ["Seattle", "San Franscisco"]]])' } ] related: ['function:flattendeep'] } { name: 'flattendeep' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'flattendeep(:list)' ] description: [ 'Flattens a list of lists recursively.' ] examples: [ { description: 'Two lists' q: 'set @list = flattendeep([[1, 2, 3], [4, 5, 6]])' } { description: 'Lists and non-lists' q: 'set @list = flattendeep([0, [1, 2, 3], 4, 5, [6, 7]])' } { description: 'Deeply-nested data' q: 'set @list = flattendeep([[["WA", "OR", "AK"], ["CA", "AZ"]], [["IN", "IL"], ["GA", "TX"]]])' } ] related: ['function:flatten'] } { name: 'index' type: 'function' subtype: 'list' returns: 'any' syntax: [ 'index(:list, :index)' ] description: [ 'Returns the element of :list at the given 0-based :index.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), values = values(map), second = index(values, 1)' } ] } { name: 'range' type: 'function' subtype: 'list' syntax: [ 'range(start,end,step)' ] returns: 'list' description: [ 'Returns a list of numbers from start to end, by step. If only one argument is provided (end), start defaults to 0. If two arguments are provided (start,end), step defaults to 1. If step=0 it will remain the default of 1.' ] examples: [ { q: 'input mock | range = range(10)' } { q: 'input mock | range = range(-10, 10)' } { q: 'input mock | range = range(-10, 10, 2)' } ] } { name: 'get' type: 'function' subtype: 'map' syntax: [ 'get(:map, :key)' 'get(:map, :key, :default)' 'get(:map, [:key, ...])' 'get(:map, [:key, ...], :default)' ] returns: 'any' description: [ 'Retrieves the value for :key in :map. If a list of :keys is given, it will traverse nested maps by applying get() in a recursive fashion.' 'Returns null if :key is not found, or optionally :default if provided.' ] examples: [ { q: 'set @headers = {Accepts: "application/json"}, @accepts = get(@headers, "Accepts")' } { description: 'With a default value' q: 'set @headers = {Accepts: "application/json"}, @accepts = get(@headers, "Accepts")' } ] related: ['function:set', 'function:delete', 'function:merge'] } { name: 'set' type: 'function' subtype: 'map' syntax: [ 'set(:map, :key, :value)' 'set(:map, [:key, ...], :value)' ] returns: 'map' description: [ 'Sets the :value for :key in :map, and returns the modified map.' 'If a list of :keys is given, it will traverse nested maps for each :key, and set the value of the last :key to :value. Any missing keys will be initialized with empty maps. If a key exists but is not a map, an exception will be thrown.' ] examples: [ { q: 'set @headers = {},\n @headers = set(@headers, "Accept", "text/plain")\n @headers = set(@headers, "Content-Type", "application/xml")' } { description: 'Setting nested keys' q: 'set @req = {},\n @req = set(@req, ["headers", "Accept"], "text/plain")\n @req = set(@req, ["headers", "Content-Type"], "application/xml")' } ] related: ['function:get', 'function:delete', 'function:merge'] } { name: 'delete' type: 'function' subtype: 'map' syntax: [ 'delete(:map, :key)' 'delete(:map, [:key, ...])' ] returns: 'map' description: [ 'Deletes the value for :key in :map, and returns the modified map.' 'If a list of :keys is given, it will traverse nested maps and for each :key, and delete the last :key. Any maps which were made empty will be removed.' ] examples: [ { q: 'set @headers = {"Accept": "application/json", "Content-Type": "application/json"},\n @updated = delete(@headers, "Accept")' } { description: 'Deleting a nested key' q: 'set @req = {headers: {"Accept": "application/json", "Content-Type": "application/json"}},\n @updated = delete(@req, ["headers", "Accept"])' } ] related: ['function:get', 'function:set', 'function:merge'] } { name: 'merge' type: 'function' subtype: 'map' syntax: [ 'merge(:map, ...)' ] returns: 'map' description: [ 'Returns a map created by merging the keys of each argument :map together, with subsequent maps overwriting keys of previous maps.' 'Any number of maps can be merged together. Any non-map arguments will be ignored.' ] examples: [ { q: 'set @headers = merge({"Content-Type": "application/json", "Accept-Language": "en-US,en;q=0.8"}, {"Content-Length": 100})' } ] related: ['function:get', 'function:set', 'function:delete', 'function:merge'] } { name: 'keys' type: 'function' subtype: 'map' syntax: [ 'keys(:map)' ] returns: 'list' description: [ 'Returns a list of the keys in :map.' 'keys(null) returns null.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), keys = keys(map)' } ] related: ['function:values'] } { name: 'values' type: 'function' subtype: 'map' syntax: [ 'values(:map)' ] returns: 'list' description: [ 'Returns a list of the values in :map.' 'values(null) returns null.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), values = values(map)' } ] related: ['function:keys'] } { name: 'adler32' type: 'function' subtype: 'digest' returns: 'string' syntax: ['adler32(:string)'] description: ['Computes the Adler-32 checksum of :string'] examples: [ { q: 'set @digest = adler32("hello world")' } ] related: ['function:sha256', 'function:sha1', 'function:sha512'] } { name: 'crc32' type: 'function' subtype: 'digest' returns: 'string' syntax: ['crc32(:string)'] description: ['Computes the CRC-32 cyclic redundancy check of :string'] examples: [ { q: 'set @digest = crc32("hello world")' } ] related: ['function:adler32', 'function:md5'] } { name: 'gost' type: 'function' subtype: 'digest' returns: 'string' syntax: ['gost(:string)'] description: ['Computes the GOST R 34.11-94 hash of :string'] examples: [ { q: 'set @digest = gost("hello world")' } ] related: ['function:hmac_gost', 'function:ripemd128', 'function:sha1'] } { name: 'hmac_gost' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_gost(:string, :secret)'] description: ['Computes the HMAC of :string using the GOST R 34.11-94 hash and :secret'] examples: [ { q: 'set @digest = hmac_gost("hello world", "secret")' } ] related: ['function:gost', 'function:ripemd128'] } { name: 'md5' type: 'function' subtype: 'digest' returns: 'string' syntax: ['md5(:string)'] description: ['Computes the MD5 hash of :string'] examples: [ { q: 'set @digest = md5("hello world")' } ] related: ['function:hmac_md5', 'function:sha256', 'function:sha1', 'function:sha512'] } { name: 'hmac_md5' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_md5(:string, :secret)'] description: ['Computes the HMAC of :string using the MD5 hash and :secret'] examples: [ { q: 'set @digest = hmac_md5("hello world", "secret")' } ] related: ['function:md5', 'function:sha256', 'function:sha1', 'function:sha512'] } { name: 'ripemd128' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd128(:string)'] description: ['Computes the RIPEMD-128 hash of :string'] examples: [ { q: 'set @digest = ripemd128("hello world")' } ] related: ['function:hmac_ripemd128', 'function:gost', 'function:ripemd256', 'function:ripemd320', 'function:sha1'] } { name: 'hmac_ripemd128' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd128(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-128 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd128("hello world", "secret")' } ] related: ['function:ripemd128', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'ripemd256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd256(:string)'] description: ['Computes the RIPEMD-256 hash of :string'] examples: [ { q: 'set @digest = ripemd256("hello world")' } ] related: ['function:hmac_ripemd256', 'function:gost', 'function:ripemd128', 'function:ripemd320', 'function:sha256'] } { name: 'hmac_ripemd256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd256(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd256("hello world", "secret")' } ] related: ['function:ripemd256', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'ripemd320' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd320(:string)'] description: ['Computes the RIPEMD-320 hash of :string'] examples: [ { q: 'set @digest = ripemd320("hello world")' } ] related: ['function:hmac_ripemd320', 'function:gost', 'function:ripemd128', 'function:ripemd256', 'function:sha384'] } { name: 'hmac_ripemd320' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd320(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-320 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd320("hello world", "secret")' } ] related: ['function:ripemd256', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'sha1' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha1(:string)'] description: ['Computes the SHA-1 hash of :string'] examples: [ { q: 'set @digest = sha1("hello world")' } ] related: ['function:hmac_sha1', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'hmac_sha1' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha1(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-1 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha1("hello world", "secret")' } ] related: ['function:sha1', 'function:sha512', 'function:md5'] } { name: 'sha3_224' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_224(:string)'] description: ['Computes the SHA-3-224 hash of :string'] examples: [ { q: 'set @digest = sha3_224("hello world")' } ] related: ['function:hmac_sha3_224', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_224' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_224(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-224 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_224("hello world", "secret")' } ] related: ['function:sha3_224', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_256(:string)'] description: ['Computes the SHA-3-256 hash of :string'] examples: [ { q: 'set @digest = sha3_256("hello world")' } ] related: ['function:hmac_sha3_256', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_256(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_256("hello world", "secret")' } ] related: ['function:sha3_256', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_384' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_384(:string)'] description: ['Computes the SHA-3-384 hash of :string'] examples: [ { q: 'set @digest = sha3_384("hello world")' } ] related: ['function:hmac_sha3_384', 'function:sha1', 'function:sha384', 'function:md5'] } { name: 'hmac_sha3_384' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_384(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-384 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_384("hello world", "secret")' } ] related: ['function:sha3_384', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_512(:string)'] description: ['Computes the SHA-3-224 hash of :string'] examples: [ { q: 'set @digest = sha3_512("hello world")' } ] related: ['function:hmac_sha3_512', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_512(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-512 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_512("hello world", "secret")' } ] related: ['function:sha3_512', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha256(:string)'] description: ['Computes the SHA-256 hash of :string'] examples: [ { q: 'set @digest = sha256("hello world")' } ] related: ['function:hmac_sha256', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'hmac_sha256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha256(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha256("hello world", "secret")' } ] related: ['function:sha256', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'sha512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha512(:string)'] description: ['Computes the SHA-512 hash of :string'] examples: [ { q: 'set @digest = sha512("hello world")' } ] related: ['function:hmac_sha512', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha512(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-512 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha512("hello world", "secret")' } ] related: ['function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'siphash' type: 'function' subtype: 'digest' returns: 'string' syntax: ['siphash(:string, :secret)'] description: [ 'Computes the HMAC of :string using the SipHash-2-4 hash and a 128-bit :secret.' ':secret must be 128-bits, e.g. a 16-character string.' ] examples: [ { q: 'set @digest = siphash("hello world", "abcdefghijklmnop")' } ] related: ['function:siphash48', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'siphash48' type: 'function' subtype: 'digest' returns: 'string' syntax: ['siphash48(:string, :secret)'] description: [ 'Computes the HMAC of :string using the SipHash-4-8 hash and a 128-bit :secret.' ':secret must be 128-bits, e.g. a 16-character string.' ] examples: [ { q: 'set @digest = siphash48("hello world", "abcdefghijklmnop")' } ] related: ['function:siphash', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'tiger' type: 'function' subtype: 'digest' returns: 'string' syntax: ['tiger(:string)'] description: ['Computes the Tiger-192 hash of :string'] examples: [ { q: 'set @digest = tiger("hello world")' } ] related: ['function:hmac_tiger', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_tiger' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_tiger(:string, :secret)'] description: ['Computes the HMAC of :string using the Tiger-192 hash and :secret'] examples: [ { q: 'set @digest = hmac_tiger("hello world", "secret")' } ] related: ['function:tiger', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'whirlpool' type: 'function' subtype: 'digest' returns: 'string' syntax: ['whirlpool(:string)'] description: ['Computes the Whirlpool hash of :string'] examples: [ { q: 'set @digest = whirlpool("hello world")' } ] related: ['function:hmac_whirlpool', 'function:tiger', 'function:sha256', 'function:md5'] } { name: 'hmac_whirlpool' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_whirlpool(:string, :secret)'] description: ['Computes the HMAC of :string using the Whirlpool hash and :secret'] examples: [ { q: 'set @digest = hmac_whirlpool("hello world", "secret")' } ] related: ['function:whirlpool', 'function:hmac_tiger', 'function:hmac_sha1', 'function:md5'] } { name: 'random' type: 'function' subtype: 'math' syntax: [ 'random()' 'random(:upperBound)' 'random(:lowerBound, :upperBound)' ] returns: 'double' description: [ 'Returns a random number between 0 inclusive and 1 exclusive, when no arguments are provided.' 'When called with a single argument, returns a random number between 0 inclusive and :upperBound, exclusive.' 'When called with two arguments, returns a random number between :lowerBound inclusive and :upperBound, exclusive.' ] examples: [ { description: 'Random number between 0 and 1 (exclusive)' q: 'set @rand = random()' } { description: 'Random number between 0 and 10 (exclusive)' q: 'set @rand = floor(random(10))' } { description: 'Random number between 1 and 10 (exclusive)' q: 'set @rand = floor(random(1,10))' } ] } { name: 'rank' type: 'function' syntax: [ 'rank()' ] description: [ 'Returns the current row number in the dataset. The rownumber statement is faster for the general case, but as a function this may be more versatile.' 'Can be used in the assignment statement, stats statement, and pivot statement. Cannot be used in a group-by expression.' ] examples: [ { q: 'input mock | x = rank()' } { q: 'input mock | name = "row " + (rank() + 1)' } { q: 'input mock name="chick-weight" | stats avgWeight = mean(weight), rank=rank() by Chick' } ] related: ['statement:rownumber'] } { name: 'hostname' type: 'function' syntax: [ 'hostname()' ] description: [ 'Returns the current hostname of the Parsec server.' ] examples: [ { q: 'set @hostname = hostname()' } ] related: ['function:ip'] } { name: 'ip' type: 'function' syntax: [ 'ip()' ] description: [ 'Returns the current IP address of the Parsec server.' ] examples: [ { q: 'set @ip = ip()' } ] related: ['function:hostname'] } { name: 'runtime' type: 'function' syntax: [ 'runtime()' ] description: [ 'Returns information about Parsec\'s JVM runtime.' ] examples: [ { q: 'set @runtime = runtime()' } { q: 'project [runtime()]' } ] related: ['function:os'] } { name: 'os' type: 'function' syntax: [ 'os()' ] description: [ 'Returns operating-system level information.' ] examples: [ { q: 'set @os = os()' } { q: 'project [os()]' } ] related: ['function:runtime'] } { name: 'now' type: 'function' subtype: 'date and time' syntax: [ 'now()' ] description: [ 'Returns the current date/time in the time zone of the server.' ] examples: [ { q: 'set @now = now()' } ] related: ['function:nowutc', 'function:today', 'function:yesterday', 'function:tomorrow'] } { name: 'nowutc' type: 'function' subtype: 'date and time' syntax: [ 'nowutc()' ] description: [ 'Returns the current date/time in the UTC time zone.' ] examples: [ { q: 'set @nowutc = nowutc()' } ] related: ['function:nowutc', 'function:todayutc', 'function:yesterdayutc', 'function:tomorrowutc'] } { name: 'today' type: 'function' subtype: 'date and time' syntax: [ 'today()' ] description: [ 'Returns the date/time of midnight of the current day, in the time zone of the server.' ] examples: [ { q: 'set @today = today()' } ] related: ['function:todayutc', 'function:now', 'function:yesterday', 'function:tomorrow'] } { name: 'todayutc' type: 'function' subtype: 'date and time' syntax: [ 'todayutc()' ] description: [ 'Returns the date/time of midnight of the current day, in the UTC time zone.' ] examples: [ { q: 'set @todayutc = todayutc()' } ] related: ['function:today', 'function:nowutc', 'function:yesterdayutc', 'function:tomorrowutc'] } { name: 'yesterday' type: 'function' subtype: 'date and time' syntax: [ 'yesterday()' ] description: [ 'Returns the date/time of midnight yesterday, in the time zone of the server.' ] examples: [ { q: 'set @yesterday = yesterday()' } ] related: ['function:yesterdayutc', 'function:now', 'function:today', 'function:tomorrow'] } { name: 'yesterdayutc' type: 'function' subtype: 'date and time' syntax: [ 'yesterdayutc()' ] description: [ 'Returns the date/time of midnight yesterday, in the UTC time zone.' ] examples: [ { q: 'set @yesterdayutc = yesterdayutc()' } ] related: ['function:yesterday', 'function:todayutc', 'function:nowutc', 'function:tomorrowutc'] } { name: 'tomorrow' type: 'function' subtype: 'date and time' syntax: [ 'tomorrow()' ] description: [ 'Returns the date/time of midnight tomorrow, in the time zone of the server.' ] examples: [ { q: 'set @tomorrow = tomorrow()' } ] related: ['function:todayutc', 'function:now', 'function:yesterday', 'function:tomorrow'] } { name: 'tomorrowutc' type: 'function' subtype: 'date and time' syntax: [ 'tomorrowutc()' ] description: [ 'Returns the date/time of midnight tomorrow, in the UTC time zone.' ] examples: [ { q: 'set @tomorrowutc = tomorrowutc()' } ] related: ['function:tomorrow', 'function:nowutc', 'function:yesterdayutc', 'function:todayutc'] } { name: 'tolocaltime' type: 'function' subtype: 'date and time' syntax: [ 'tolocaltime(:datetime)' ] description: [ 'Converts a date/time to the local time zone of the server.' ] examples: [ { q: 'set @nowutc = nowutc(), @nowlocal = tolocaltime(@nowutc)' } ] related: ['function:toutctime', 'function:totimezone'] } { name: 'toutctime' type: 'function' subtype: 'date and time' syntax: [ 'toutctime(:datetime)' ] description: [ 'Converts a date/time to the UTC time zone.' ] examples: [ { q: 'set @now = now(), @nowutc = toutctime(@now)' } ] related: ['function:tolocaltime', 'function:totimezone'] } { name: 'totimezone' type: 'function' subtype: 'date and time' syntax: [ 'totimezone(:datetime, :timezone)' ] description: [ 'Converts a date/time to another time zone. :timezone must be a long-form time zone, e.g. "America/Matamoros".' 'A list of all valid time zones can be retrieved using timezones().' ] examples: [ { q: 'set @southpole = totimezone(now(), "Antarctica/South_Pole"), @str = tostring(@southpole)' } ] related: ['function:tolocaltime', 'function:totimezone', 'function:timezones'] } { name: 'timezones' type: 'function' subtype: 'date and time' syntax: ['timezones()'] description: [ 'Returns a list of all available time zones, for use with totimezone()' ] examples: [ { q: 'set @tz = timezones()' } { description: 'Project as dataset' q: 'project timezones()' } ] related: ['function:totimezone'] } { name: 'toepoch' type: 'function' subtype: 'date and time' syntax: ['toepoch(:datetime)'] returns: 'number' description: [ 'Converts :datetime into the number of seconds after the Unix epoch.' ] examples: [ q: 'set @timestamp = toepoch(now())' ] related: ['function:toepochmillis'] } { name: 'toepochmillis' type: 'function' subtype: 'date and time' syntax: ['toepochmillis(:datetime)'] returns: 'number' description: [ 'Converts :datetime into the number of milliseconds after the Unix epoch.' ] examples: [ q: 'set @timestamp = toepochmillis(now())' ] related: ['function:toepoch'] } { name: 'startofminute' type: 'function' subtype: 'date and time' syntax: ['startofminute(:datetime)'] returns: 'datetime' description: [ 'Returns :datetime with the number of seconds and milliseconds zeroed.' ] examples: [ q: 'set @time = startofminute(now())' ] related: ['function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofhour' type: 'function' subtype: 'date and time' syntax: ['startofhour(:datetime)'] returns: 'datetime' description: [ 'Returns :datetime with the number of minutes, seconds, and milliseconds zeroed.' ] examples: [ q: 'set @time = startofhour(now())' ] related: ['function:startofminute', 'function:startofday', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofday' type: 'function' subtype: 'date and time' syntax: ['startofday(:datetime)'] returns: 'datetime' description: [ 'Returns midnight on the same day as :datetime.' ] examples: [ q: 'set @time = startofday(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofweek' type: 'function' subtype: 'date and time' syntax: ['startofweek(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the week, in the same week as :datetime.' ] examples: [ q: 'set @time = startofweek(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofmonth', 'function:startofyear'] } { name: 'startofmonth' type: 'function' subtype: 'date and time' syntax: ['startofmonth(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the month, in the same month as :datetime.' ] examples: [ q: 'set @time = startofmonth(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofyear'] } { name: 'startofyear' type: 'function' subtype: 'date and time' syntax: ['startofyear(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the year, in the same year as :datetime.' ] examples: [ q: 'set @time = startofyear(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofmonth'] } { name: 'millisecond' type: 'function' subtype: 'date and time' syntax: ['millisecond(:datetime)'] returns: 'number' description: [ 'Returns the millisecond of second component of the given :datetime.' ] examples: [ q: 'set @millis = millisecond(now())' ] related: ['function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'millisecondofday' type: 'function' subtype: 'date and time' syntax: ['millisecondofday(:datetime)'] returns: 'number' description: [ 'Returns the number of milliseconds elapsed since midnight in :datetime.' ] examples: [ q: 'set @millis = millisecondofday(now())' ] related: ['function:millisecond', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'second' type: 'function' subtype: 'date and time' syntax: ['second(:datetime)'] returns: 'number' description: [ 'Returns the second of minute component of the given :datetime.' ] examples: [ q: 'set @seconds = second(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'secondofday' type: 'function' subtype: 'date and time' syntax: ['secondofday(:datetime)'] returns: 'number' description: [ 'Returns the number of seconds elapsed since midnight in :datetime.' ] examples: [ q: 'set @seconds = secondofday(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'minute' type: 'function' subtype: 'date and time' syntax: ['minute(:datetime)'] returns: 'number' description: [ 'Returns the minute of hour component of the given :datetime.' ] examples: [ q: 'set @minutes = minute(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'minuteofday' type: 'function' subtype: 'date and time' syntax: ['minuteofday(:datetime)'] returns: 'number' description: [ 'Returns the number of minutes elapsed since midnight in :datetime.' ] examples: [ q: 'set @minutes = minuteofday(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'hour' type: 'function' subtype: 'date and time' syntax: ['hour(:datetime)'] returns: 'number' description: [ 'Returns the hour of day component of the given :datetime.' ] examples: [ q: 'set @hours = hour(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'day' type: 'function' subtype: 'date and time' syntax: ['day(:datetime)'] returns: 'number' description: [ 'Returns the day of month component of the given :datetime.' ] examples: [ q: 'set @day = day(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'dayofweek' type: 'function' subtype: 'date and time' syntax: ['dayofweek(:datetime)'] returns: 'number' description: [ 'Returns the day of week component of the given date/time, where Monday is 1 and Sunday is 7.' ] examples: [ q: 'set @day = dayofweek(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'dayofyear' type: 'function' subtype: 'date and time' syntax: ['dayofyear(:datetime)'] returns: 'number' description: [ 'Returns the number of days elapsed since the beginning of the year, including the current day of :datetime.' ] examples: [ q: 'set @days = dayofyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'weekyear' type: 'function' subtype: 'date and time' syntax: ['weekyear(:datetime)'] returns: 'number' description: [ 'Returns the week year for a given date. In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year. The weekyear allows you to query the effective year for that day.' 'The weekyear is used by the function weekofweekyear().' ] examples: [ q: 'set @weekyear = weekyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'weekofweekyear' type: 'function' subtype: 'date and time' syntax: ['weekofweekyear(:datetime)'] returns: 'number' description: [ 'Given a date, returns the number of weeks elapsed since the beginning of the weekyear. In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year.' 'The function weekyear() gives the current weekyear for a given date.' ] examples: [ q: 'set @weeks = weekofweekyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:month', 'function:year'] } { name: 'month' type: 'function' subtype: 'date and time' syntax: ['month(:datetime)'] returns: 'number' description: [ 'Returns the month component of the given :datetime.' ] examples: [ q: 'set @months = month(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:year'] } { name: 'year' type: 'function' subtype: 'date and time' syntax: ['year(:datetime)'] returns: 'number' description: [ 'Returns the year of the given :datetime.' ] examples: [ q: 'set @years = year(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month'] } { name: 'adddays' type: 'function' subtype: 'date and time' } { name: 'addhours' type: 'function' subtype: 'date and time' } { name: 'addmilliseconds' type: 'function' subtype: 'date and time' } { name: 'addminutes' type: 'function' subtype: 'date and time' } { name: 'addmonths' type: 'function' subtype: 'date and time' } { name: 'addseconds' type: 'function' subtype: 'date and time' } { name: 'addweeks' type: 'function' subtype: 'date and time' } { name: 'addyears' type: 'function' subtype: 'date and time' } { name: 'minusdays' type: 'function' subtype: 'date and time' } { name: 'minushours' type: 'function' subtype: 'date and time' } { name: 'minusmilliseconds' type: 'function' subtype: 'date and time' } { name: 'minusminutes' type: 'function' subtype: 'date and time' } { name: 'minusmonths' type: 'function' subtype: 'date and time' } { name: 'minusseconds' type: 'function' subtype: 'date and time' } { name: 'minusweeks' type: 'function' subtype: 'date and time' } { name: 'minusyears' type: 'function' subtype: 'date and time' } { name: 'interval' type: 'function' subtype: 'date and time' } { name: 'inmillis' type: 'function' subtype: 'date and time' } { name: 'inseconds' type: 'function' subtype: 'date and time' } { name: 'inminutes' type: 'function' subtype: 'date and time' } { name: 'inhours' type: 'function' subtype: 'date and time' } { name: 'indays' type: 'function' subtype: 'date and time' } { name: 'inweeks' type: 'function' subtype: 'date and time' } { name: 'inmonths' type: 'function' subtype: 'date and time' } { name: 'inyears' type: 'function' subtype: 'date and time' } { name: 'period' type: 'function' subtype: 'date and time' syntax: [ 'period(:value, :name)' ] description: [ 'Creates a time period representing some number (:value) of a particular time unit (:name).' 'The following units are supported: milliseconds, seconds, minutes, hours, days, weeks, months, years. Both singular/plural forms, as well as some short forms (min, sec) are accepted.' 'The bucket() function uses periods to group data.' ] examples: [ { q: 'set @fivemin = period(5, "minutes")' } { q: 'input mock | mins = period(col1, "minutes")' } { q: 'input mock | onehour = period(1, "hours")' } ], related: ['function:bucket'] } { name: 'earliest' type: 'function' subtype: 'date and time' syntax: [ 'earliest(:datetime, :datetime)' ] description: [ 'Given two dates, returns the date which occurs first chronologically.' ] examples: [ { q: 'set @firstOccurrence = earliest(todate("2015-04-20"), todate("2016-06-01"))' } { q: 'set @earliest = earliest(1462009645000, 1461999645000)' } ] related: ['function:latest'] } { name: 'latest' type: 'function' subtype: 'date and time' syntax: [ 'latest(:datetime, :datetime)' ] description: [ 'Given two dates, returns the date which occurs last chronologically.' ] examples: [ { q: 'set @lastOccurrence = latest(todate("2015-04-20"), todate("2016-06-01"))' } { q: 'set @latest = latest(1462009645000, 1461999645000)' } ] related: ['function:earliest'] } { name: 'isbetween' type: 'function' subtype: 'date and time' syntax: [ 'isbetween(:datetime, :start, :end)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after :start and before or at :end. In other words, the function returns true if :datetime is within the inclusive interval between :start and :end.' ] examples: [ { q: 'set @test = isbetween(now(), minusminutes(now(), 1), addminutes(now(), 1))' } ] } { name: 'istoday' type: 'function' subtype: 'date and time' syntax: [ 'istoday(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current day, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = istoday(now())' } ] related: ['function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'istomorrow' type: 'function' subtype: 'date and time' syntax: [ 'istomorrow(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of tomorrow, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = istomorrow(now())' } ] related: ['function:istoday', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isyesterday' type: 'function' subtype: 'date and time' syntax: [ 'isyesterday(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of yesterday, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isyesterday(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isthisweek' type: 'function' subtype: 'date and time' syntax: [ 'isthisweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isthisweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isnextweek' type: 'function' subtype: 'date and time' syntax: [ 'isnextweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the week after the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isnextweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'islastweek' type: 'function' subtype: 'date and time' syntax: [ 'islastweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the week prior to the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = islastweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isthismonth' type: 'function' subtype: 'date and time' syntax: [ 'isthismonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isthismonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isnextmonth' type: 'function' subtype: 'date and time' syntax: [ 'isnextmonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the month after the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isnextmonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth'] } { name: 'islastmonth' type: 'function' subtype: 'date and time' syntax: [ 'islastmonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the month prior to the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = islastmonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:isnextmonth'] } { name: 'bucket' type: 'function' syntax: [ 'bucket(:expr, :buckets)' ] description: [ 'Assigns buckets to :expr based on the 2nd argument, and returns the bucket for each value. Buckets can be numerical or time-based. The start of the bucket will be returned.' 'Numerical buckets are determined by dividing the set of real numbers into equivalent ranges of a given width. Numbers are then located in the buckets according to their value. For example, bucketing by 5 will yield buckets starting at 0, 5, 10, 15, etc. Numerical buckets can be fractions or decimals.' 'Time-based buckets are determined by dividing the time line into equivalent ranges of a given interval. The :buckets argument must be given as a Period, created by the period() function. For example, bucketing by a period of 5 minutes will yield buckets starting at 12:00, 12:05, 12:10, etc. Buckets are always aligned on the hour.' ] examples: [ { q: 'input mock | buckets = bucket(col1, 2)' } { description: 'Bucket by every 4th number and calculate an average per bucket' q: 'input mock name="chick-weight"\n| timebucket = bucket(Time, 4)\n| stats avgWeight = avg(weight) by timebucket\n| sort timebucket' } { description: 'Bucket by 5 minute periods' q: 'input mock n=20\n| t = minusMinutes(now(), col1)\n| tbuckets = bucket(t, period(5, "minutes"))' } ], related: ['function:period'] } { name: 'apply' type: 'function' subtype: 'functional' syntax: [ 'apply(:function, :args, ...)' ] description: [ 'Invokes a first-order :function with any number of arguments. Commonly used to execute functions stored in variables.' 'Using the def statement will avoid the need to call apply(), as the function will be mapped to a user-defined function name.' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @cube = (n) -> n*n*n, @cube9 = apply(@cube, 9)' } { q: 'input mock name="thurstone"\n| set @differenceFromAvg = (n, avg) -> abs(n - avg)\n| set @avgX = avg(x), @avgY = avg(y)\n| diffX = apply(@differenceFromAvg, x, @avgX)\n| diffY = apply(@differenceFromAvg, y, @avgY)' } ] related: ['symbol:->:function'] } { name: 'map' type: 'function' subtype: 'functional' syntax: [ 'map(:function, :list)' ] returns: 'list' description: [ 'Applies a first-order :function to each item in :list, and returns a list of the return values.' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @x = map(n -> n / 100, [10, 20, 30, 40, 50])' } { description: 'Using a function in a variable' q: 'set @percent = n -> n / 100,\n@x = map(@percent, [10, 20, 30, 40, 50])' } { description: 'Generating a dataset using map() and range()' q: 'project map((x) -> {`x`: x, `square`: x^2, `cube`: x^3, `fourth-power`: x^4}, range(1,10))' } ] related: ['symbol:->:function', 'function:mapcat', 'function:mapvalues', 'function:filter'] } { name: 'mapcat' type: 'function' subtype: 'functional' syntax: [ 'mapcat(:function, :list)' ] returns: 'list' description: [ 'Applies a first-order :function to each item in :list, and applies concat() over the return values.' 'Typically :function should return a list, otherwise it works identically to map().' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @x = mapcat(n -> [n, n^2], [10, 20, 30, 40, 50])' } { description: 'Using a function in a variable' q: 'set @percent = n -> n / 100,\n@x = mapcat(@percent, [10, 20, 30, 40, 50])' } { description: 'Generating a set of ranges using mapcat() and range()' q: 'project mapcat((x) -> range(x, x + 5), [0, 10, 20, 30])' } ] related: ['symbol:->:function', 'function:map'] } { name: 'mapvalues' type: 'function' subtype: 'functional' syntax: [ 'mapvalues(:function, :map)' ] returns: 'map' description: [ 'Applies a first-order :function to the value of each key in :map, and returns a new map containing the keys and their return values.' 'Throws an exception if the first argument is not a function.' ] examples: [ { description: 'Increment each value in the map' q: 'set @map = mapvalues(n -> n+1, { x: 1, y: 2, z: 3 })' } { description: 'Using a function in a variable' q: 'set @inc = n -> n+1,\n@map = mapvalues(@inc, { x: 1, y: 2, z: 3 })' } ] related: ['symbol:->:function', 'function:map'] } { name: 'filter' type: 'function' subtype: 'functional' syntax: [ 'filter(:function, :list)' ] returns: 'list' description: [ 'Returns a list of items in :list for which the first-order :function returns true.' 'Throws an exception if the first argument is not a function.' ] examples: [ { description: 'Filtering for even numbers' q: 'set @x = filter(n -> n mod 2 == 0, range(1,20))' } { description: 'Using a function in a variable' q: 'set @isEven = n -> n mod 2 == 0,\n @x = filter(@isEven, range(1,20))' } ] related: ['symbol:->:function', 'function:map'] } { name: 'exec' type: 'function' subtype: 'execution' syntax: [ 'exec(:query)' 'exec(:query, { dataset: ":dataset-name" })' 'exec(:query, { variable: ":variable-name" })' 'exec(:query, { context: true })' ] returns: 'any' description: [ 'Executes a Parsec query contained in :query, and returns the resulting context object. Any parsing, execution, or type errors will return a context with errors, rather than throwing an exception.' 'A map of :options can be provided to return a specific part of the result, rather than the entire context. Either a single dataset or a single variable can be named in the :options, causing that dataset or variable value to be returned. If the dataset or variable is not found, null is returned. Caution: if an error occurs, the dataset or variable may not exist (depending on when the error occurs), so null may also be returned.' 'By default, uses a new isolated query context. However if the context option is set to true, the current parent context will be used to execute :query, allowing access to variables and datasets. Note this is read-only access; the parent context cannot be modified from within exec().' 'Returns null if :query is null.' ] examples: [ { q: 'set @x = exec("input mock")' } { description: 'Using options to select only the default dataset' q: 'set @dataset = exec("input mock", { dataset: "0" })' } { description: 'Using options to select a specific named dataset' q: 'set @dataset = exec("input mock | output name=\'mock\'; input mock name=\'chick-weight\'", { dataset: "mock" })' } { description: 'Using options to return only the value of a specific variable' q: 'set @avg = exec("input mock | set @avg=avg(col1+col2)", { variable: "@avg" })' } { description: 'Looking at the performance of a query ran with exec()' q: 'set @performance = get(exec("input mock"), "performance")' } { description: 'Using a shared context to access variables' q: 'set @price = 49.95,\n @tax = 9.2%,\n @total = exec("set @total = round(@price * (1 + @tax), 2)", { variable: "@total", context: true })' } ] } { name: 'mock' type: 'input' syntax: [ 'input mock' 'input mock n=:number' 'input mock name=:name' 'input mock name=:name incanterHome=:path' ] description: [ 'The mock input type is for testing and experimental purposes. By default, it returns a fixed dataset of 5 rows and 4 columns. If "n" is provided, the mock dataset will contain n-number of rows, and an additional column.' 'There are also specific test datasets included, which can be loaded using the "name" option. The available named datasets are: "iris", "cars", "survey", "us-arrests", "flow-meter", "co2", "chick-weight", "plant-growth", "pontius", "filip", "longely", "chwirut", "thurstone", "austres", "hair-eye-color", "airline-passengers", "math-prog", "iran-election".' 'By default, test datasets are loaded from GitHub. In order to load them from the local machine, download the Incanter source code (https://github.com/incanter/incanter), and provide the root directory as incanterHome.' ] examples: [ { description: 'Loading mock data' q: 'input mock' } { description: 'Loading lots of mock data' q: 'input mock n=100' } { description: 'Loading a named mock dataset' q: 'input mock name="chick-weight"' } { description: 'Loading a named dataset from disk (requires additional download)' q: 'input mock name="chick-weight" incanterHome="~/Downloads/incanter-master"' } ] related: ['statement:input'] } { name: 'datastore' type: 'input' syntax: [ 'input datastore name=:name' ] description: [ 'The datastore input type retrieves and loads datasets from the datastore in the current execution context. Datasets may have been written previously to the datastore using the temp or output statements.' ] examples: [ { description: 'Storing and loading a dataset' q: 'input mock | output name="ds1"; input datastore name="ds1"' } { description: 'Storing and loading a temporary dataset' q: 'input mock | temp ds2; input datastore name="ds2"' } ] related: ['statement:input'] } { name: 'jdbc' type: 'input' syntax: [ 'input jdbc uri=":uri" query=":query"' 'input jdbc uri=":uri" [user | username]=":username" password=":password" query=":query"' 'input jdbc uri=":uri" [user | username]=":username" password=":password" query=":query" operation=":operation"' ] description: [ 'The jdbc input type connects to various databases using the JDBC api and executes a query. The results of the query will be returned as the current dataset.' 'The default JDBC operation is "query", which is used for selecting data. The operation option can be used to provide another operation to run—currently, only "execute" is implemented. INSERT/UPDATE/DELETE/EXECUTE queries can all be run through the "execute" operation.' 'Caution: The implementation of the URI may vary across JDBC drivers, e.g. some require the username and password in the URI, whereas others as separate options. This is determined by the specific JDBC driver and its implementation, not Parsec. Please check the documentation for the JDBC driver you are using, or check the examples below. There may be multiple valid ways to configure some drivers.' 'The following JDBC drivers are bundled with Parsec: AWS Redshift, DB2, Hive2, HSQLDB, MySQL, PostgreSQL, Presto, Qubole, SQL Server, SQL Server (jTDS), Teradata.' ] examples: [ { description: 'Querying MySQL' q: 'input jdbc uri="jdbc:mysql://my-mysql-server:3306/database?user=username&password=password"\nquery="..."' } { description: 'Inserting data into MySQL' q: 'input jdbc uri="jdbc:mysql://my-mysql-server:3306/database?user=username&password=password" operation="execute"\nquery="INSERT INTO ... VALUES (...)"' } { description: 'Querying SQL Server' q: 'input jdbc uri="jdbc:sqlserver://my-sql-server:1433;databaseName=database;username=username;password=password"\n query="..."' } { description: 'Querying Hive (Hiveserver2)' q: 'input jdbc uri="jdbc:hive2://my-hive-server:10000/default?mapred.job.queue.name=queuename" username="username" password="password"\n query="show tables"' } { description: 'Querying Teradata' q: 'input jdbc uri="jdbc:teradata://my-teradata-server/database=database,user=user,password=password"\n query="..."' } { description: 'Querying DB2' q: 'input jdbc uri="jdbc:db2://my-db2-server:50001/database:user=username;password=password;"\n query="..."' } { description: 'Querying Oracle' q: 'input jdbc uri="jdbc:oracle:thin:username/password@//my-oracle-server:1566/database"\n query="..."' } { description: 'Querying PostgreSQL' q: 'input jdbc uri="jdbc:postgresql://my-postgres-server/database?user=username&password=password"\n query="..."' } ] related: ['statement:input'] } { name: 'graphite' type: 'input' syntax: [ 'input graphite uri=":uri" targets=":target"' 'input graphite uri=":uri" targets=[":target", ":target"]' 'input graphite uri=":uri" targets=[":target", ":target"] from="-24h" until="-10min"' ] description: [ 'The graphite input type retrieves data from Graphite, a time-series database. One or more target metrics can be retrieved; any valid Graphite targets can be used, including functions and wildcards.' 'The :uri option should be set to the Graphite server UI or render API.' ] examples: [ { q: 'input graphite uri="http://my-graphite-server" targets="carbon.agents.*.metricsReceived" from="-4h"' } { description: 'Unpivoting metrics into a row' q: 'input graphite uri="http://my-graphite-server" targets="carbon.agents.*.*" from="-2h"\n| unpivot value per metric by _time\n| filter value != null' } ] related: ['statement:input'] } { name: 'http' type: 'input' syntax: [ 'input http uri=":uri"' 'input http uri=":uri" user=":user" password="*****"' 'input http uri=":uri" method=":method" body=":body"' 'input http uri=":uri" parser=":parser"' 'input http uri=":uri" parser=":parser" jsonpath=":jsonpath"' ] description: [ 'The http input type retrieves data from web servers using the HTTP/HTTPS networking protocol. It defaults to an HTTP GET without authentication, but can be changed to any HTTP method.' 'Optional authentication is available using the user/password options. Preemptive authentication can also be enabled, which sends the authentication in the initial request instead of waiting for a 401 response. This may be required by some web services.' 'Without the :parser option, a single row will be output, containing information about the request and response. If a parser is specified, the body of the file will be parsed and projected as the new data set. The JSON parser has an option jsonpath option, allowing a subsection of the JSON document to be projected.' 'Output columns are: "body", "headers", "status", "msg", "protocol", "content-type"' 'Available options: user, password, method, body, parser, headers, query, timeout, connection-timeout, request-timeout, compression-enabled, and follow-redirects.' ] examples: [ { description: 'Loading a web page' q: 'input http uri="http://www.expedia.com"' } { description: 'Authenticating with username and password' q: 'input http uri="http://my-web-server/path"\n user="readonly" password="readonly"' } { description: 'Preemptive authentication (sending credentials with initial request)' q: 'input http uri="http://my-web-server/path"\n auth={ user: "readonly", password: "readonly", preemptive: true }' } { description: 'Posting data' q: 'input http uri="http://my-web-server/path"\n method="post" body="{ \'key\': 123456 }"\n headers={ "Content-Type": "application/json" }' } { description: 'Providing custom headers' q: 'input http uri="http://my-web-server/path"\n headers={ "Accept": "application/json, text/plain, */*",\n "Accept-Encoding": "en-US,en;q=0.5" }' } { description: 'Parsing an XML file' q: 'input http uri="http://news.ycombinator.com/rss"\n| project parsexml(first(body), { xpath: "/rss/channel/item" })' } { description: 'Parsing a JSON file with JsonPath' q: 'input http uri="http://pastebin.com/raw/wzmy7TMZ" parser="json" jsonpath="$.values[*]"' } ] related: ['statement:input', 'function:parsexml', 'function:parsecsv', 'function:parsejson', 'function:jsonpath'] } { name: 'influxdb' type: 'input' syntax: [ 'input influxdb uri=":uri" db=":db" query=":query"' 'input influxdb uri=":uri" db=":db" query=":query" user=":user" password=":password"' ] description: [ 'The influxdb input type retrieves data from InfluxDB, a time-series database. Supports InfluxDB 0.9 and higher.' 'The :uri option should be set to the Query API endpoint on an InfluxDB server; by default is is on port 8086. The URI of the Admin UI will not work.' 'An error will be thrown if multiple queries are sent in one input statement.' ] examples: [ { q: 'input influxdb uri="http://my-influxdb-server:8086/query"\n db="NOAA_water_database"\n query="SELECT * FROM h2o_feet"' } ] related: ['statement:input'] } { name: 'mongodb' type: 'input' syntax: [ 'input mongodb uri=":uri" query=":query"' ] description: [ 'The mongodb input type retrieves data from MongoDB, a NoSQL document database.' 'The :uri option should follow the standard connection string format, documented here: https://docs.mongodb.com/manual/reference/connection-string/.' 'The :query option accepts a limited subset of the Mongo Shell functionality.' ] examples: [ { q: 'input mongodb uri="mongodb://localhost:27017/testdb" query="show collections"' } { q: 'input mongodb uri="mongodb://localhost:27017/testdb" query="db.testcollection.find({type: \'orders\'}.sort({name: 1})"' } ] related: ['statement:input'] } { name: 's3' type: 'input' syntax: [ 'input s3 accessKeyId=":key-id" secretAccessKey=":secret"' 'input s3 accessKeyId=":key-id" secretAccessKey=":secret" token=":token"' 'input s3 uri="s3://:uri" accessKeyId=":key-id" secretAccessKey=":secret" token=":token" operation=":operation" maxKeys=:max-keys delimiter=:delimiter gzip=:gzip-enabled zip=:zip-enabled' 'input s3 uri="s3://:uri" accessKeyId=":key-id" secretAccessKey=":secret" token=":token" operation=":operation" maxKeys=:max-keys delimiter=:delimiter parser=":parser"' ] description: [ 'The s3 input type retrieves data from Amazon S3. It is designed to either retrieve information about objects stored in S3, or retrieve the contents of those objects.' 'The following operations are supported: "list-buckets", "list-objects", "list-objects-from", "get-objects", "get-objects-from", "get-object". The operation can be specified manually, or auto-detected based on the arguments.' 'Authentication requires AWS credentials of either accessKeyId/secretAccessKey, or accessKeyId/secretAccessKey/token.' '"list-objects" and "get-objects" have a default limit of 10 objects, which can be configured via the maxKeys option' '"list-objects-from" and "get-objects-from" use a marker to retrieve objects only after the given prefix or object. Partial object names are supported.' 'Zip or gzip-compressed objects can be decompressed by setting gzip=true, or zip=true. If neither is set, the object is assumed to be uncompressed' ] examples: [ { description: 'Listing all S3 buckets available for the given credentials' q: 'input s3 accessKeyId="***" secretAccessKey="****"' } { description: 'Listing all S3 objects in the given bucket' q: 'input s3 uri="s3://:bucket" accessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Listing S3 objects in the given bucket with a given prefix (prefix must end in /)' q: 'input s3 uri="s3://:bucket/:prefix/" accessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting the next level of the object hierarchy by using a delimiter.' q: 'input s3 uri="s3://:bucket/:prefix/" accessKeyId=":key-id" secretAccessKey=":secret-key" delimiter="/"' } { description: 'Getting an S3 object' q: 'input s3 uri="s3://:bucket/:prefix/:object.json"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting an S3 object and parsing its contents' q: 'input s3 uri="s3://:bucket/:prefix/:object.json" parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting multiple S3 objects and parsing their contents into a combined dataset' q: 'input s3 uri="s3://:bucket/:prefix/" operation="get-objects" parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Limiting the number of objects returned' q: 'input s3 uri="s3://:bucket/:prefix/" operation="list-objects" maxKeys=100\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting a single S3 object and parsing its contents' q: 'input s3 uri="s3://:bucket/:prefix/:object.json" gzip=true parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } ] related: ['statement:input'] } { name: 'smb' type: 'input' syntax: [ 'input smb uri="smb://:hostname/:path"' 'input smb uri="smb://:hostname/:path" user=":user" password="*****"' 'input smb uri="smb://:user:******@:hostname/:path"' 'input smb uri="smb://:hostname/:path" parser=":parser"' ] description: [ 'The smb input type retrieves data using the SMB/CIFS networking protocol. It can either retrieve directory listings or file contents.' 'Optional NTLM authentication is supported using the user/password options, or by embedding them in the :uri (slightly slower).' 'Without the :parser option, a single row will be output, containing metadata about the directory or file. If a parser is specified, the body of the file will be parsed and projected as the new data set (directories cannot be parsed).' 'Metadata columns are: "name", "path", "isfile", "body", "attributes", "createdTime", "lastmodifiedTime", "length", "files"' ] examples: [ { description: 'Retrieving a directory listing' q: 'input smb uri="smb://my-samba-server/my-share"\n user="readonly" password="readonly"' } { description: 'Retrieving file metadata' q: 'input smb uri="smb://my-samba-server/my-share/file.txt"\n user="readonly" password="readonly"' } { description: 'Parsing a JSON file' q: 'input smb uri="smb://my-samba-server/my-share/file.txt"\n user="readonly" password="readonly" parser="json"' } ] related: ['statement:input'] } ] _.each documentation.tokens, (token) -> token.key = token.type + ':' + token.name token.typeKey = 'type:' + token.type token.subtypeKey = 'subtype:' + token.subtype if token.altName? token.key += ':' + token.altName if !token.description? console.log 'Token without description: ' + token.key if !token.examples? console.log 'Token without examples: ' + token.key return functions = _.sortBy _.filter(documentation.tokens, { type: 'function' }), 'subtype' groups = _.groupBy functions, 'subtype' _.each groups, (functions, name) -> console.log '# ' + name + ' functions' console.log _.sortBy(_.map(functions, 'name')).join('|') return documentation
190111
# Documentation for Parsec Parsec.Services.factory 'documentationService', -> documentation = tokens: [ { name: ';' altName: 'query separator' type: 'symbol' syntax: ['query1; query2', 'query1; query2; query3 ...'] description: [ 'The query separator is used to separate two distinct Parsec queries. The queries will be executed sequentially with a shared context.' ] examples: [ { q: 'input mock; input mock' } ] } { name: '/* */' altName: 'comment block' type: 'symbol' syntax: ['/* ... */'] description: [ 'Comments in Parsec follow the general C style /* ... */ block comment form and are ignored by the parser.' 'Nested comment blocks are supported provided they are balanced.' ] examples: [ { q: '/* My query */ input mock' } { q: 'input mock | /* filter col1 == 1 | */ sort col1 desc' } ] } { name: '//' altName: 'line comment' type: 'symbol' syntax: ['// ...'] description: [ 'Line comments in Parsec follow the general C style // comment form and are ignored by the parser.' 'Line comments must either end in a newline character, or the end of the query.' ] examples: [ { q: '// My query \ninput mock' } { q: 'input mock\n//| filter col1 == 1\n| sort col1 desc' } ] } { name: '()' altName: 'parentheses' type: 'symbol' syntax: ['(expression)'] description: [ 'Parentheses can be used to explicitly specify order the order of evaluation. An expression wrapped in parentheses evaluates to the value of the expression.' 'Parentheses are also used in a function call to contain the arguments to the function.' 'Nested parentheses are supported.' ] examples: [ { q: 'input mock | x = col1 + col2 * col3, y = (col1 + col2) * col3 | select x, y' } { description: 'As a function call' q: 'input mock | x = (col2 * col4) / 2, y = round(x)' } { q: 'input mock | x = sqrt(sin(col1) - cos(col2))' } ] } { name: '*' altName: 'asterisk' type: 'symbol' syntax: ['*'] description: [ 'The asterisk (*) symbol can be used as a wildcard in limited functions. The most notable use case is in the count(*) function to indicate a count of all rows.' 'It is identical in appearance to the multiplication operator.' ] examples: [ { q: 'input mock | stats numRows = count(*)' } ] } { name: '->' altName: 'function' type: 'symbol' syntax: [ ':arg, :arg, .. -> :expression' '(:arg, :arg, ..) -> :expression' ] description: [ 'The function (->) symbol is used to define first-order functions. Any number of arguments can precede it, followed by an expression in terms of those arguments.' 'Functions created with this symbol can be mapped to user-defined functions using the def statement, or they can be stored in variables or passed directly to functions like map().' 'The apply() function can be used to invoke a function, if it isn\'t mapped to a function name using def.' ] examples: [ { q: 'set @cube = (n) -> n*n*n, @cube9 = apply(@cube, 9)' } { q: 'set @isOdd = (n) -> gcd(n,2) != 2\n| input mock | isCol1Odd = apply(@isOdd, col1)' } ] related: ['statement:def', 'function:apply'] } { name: 'null' type: 'literal' syntax: ['null'] description: [ 'The keyword "null" represents the absence of value.' 'Generally, operators and functions applied to null value tend to return null.' ] examples: [ { q: 'set @x = null' } ] } { name: 'true' type: 'literal' syntax: ['true'] description: [ 'The keyword "true" represents the boolean truth value. It can be used in equality/inequality expressions, or assigned to columns or variables.' 'Non-zero numbers are considered true from a boolean perspective.' ] examples: [ { q: 'set @truth = true' } { description: 'Non-zero numbers are considered true from a boolean perspective' q: 'set @truth = (1 == true)' } ] related: ['literal:false'] } { name: 'false' type: 'literal' syntax: ['false'] description: [ 'The keyword "false" represents the boolean falsehood value It can be used in equality/inequality expressions, or assigned to columns or variables.' 'Zero numbers are considered false from a boolean perspective.' ] examples: [ { q: 'set @truth = false' } { description: 'Zero numbers are considered false from a boolean perspective' q: 'set @truth = (0 == false)' } ] related: ['literal:true'] } { name: '"number"' type: 'literal' syntax: [ 'Regex: /[-+]?(0(\.\d*)?|([1-9]\d*\.?\d*)|(\.\d+))([Ee][+-]?\d+)?/' 'Regex: /[-+]?(0(\.\d*)?|([1-9]\d*\.?\d*)|(\.\d+))([Ee][+-]?\d+)?[%]/' ] returns: 'number' description: [ 'Internally, Parsec supports the full range of JVM primitive numbers, as well as BigInteger, BigDecimal, and Ratios.' 'A number that ends with a percent sign indicates a percentage. The numerical value of the number will be divided by 100.' ] examples: [ { description: 'Integer' q: 'set @x = 100' } { description: 'Floating-point (double) number' q: 'set @y = 3.141592' } { description: 'Scientific-notation' q: 'set @a = 1.234e50, @b = 1.234e-10' } { description: 'Percents' q: 'set @a = 50%, @b = 12 * @a' } ] } { name: '"identifier"' type: 'literal' syntax: [ 'Regex: /[a-zA-Z_][a-zA-Z0-9_]*/' 'Regex: /`[^`]+`/' ] description: [ 'Identifiers are alpha-numeric strings used to reference columns in the current dataset.' 'There are two possible forms for identifiers: the primary form must start with a letter or underscore, and may only contain letters, numbers, or underscores. The alternate form uses two backtick (`) characters to enclose any string of characters, including spaces or special characters (except backticks).' 'Identifiers are case-sensitive.' ] examples: [ { description: 'Primary form' q: 'input mock | col6 = col5' } { description: 'Backtick form allows spaces and special characters' q: 'input mock | stats `avg $` = mean(col1 * col2)' } ] } { name: '"variable"' type: 'literal' syntax: ['Regex: /@[a-zA-Z0-9_]+[\']?/'] description: [ 'Variables are alpha-numeric strings prefixed with an at symbol (@). A trailing single-quote character is allowed, representing the prime symbol.' 'Unlike identifiers, variables are not associated with rows in the current dataset. Variables are stored in the context and available throughout the evaluation of a query (once they have been set.' ] examples: [ { description: 'Setting a variable' q: 'set @fruit = "banana"' } { description: 'Storing a calculated value in a variable' q: 'input mock | set @x=mean(col1) | y = col1 - @x' } { description: 'Prime variables' q: 'input mock | set @x = mean(col1), @x\' = @x^2 | stats x=@x, y=@x\'' } ] related: ['statement:set'] } { name: '"string"' type: 'literal' syntax: [ "Regex: /\'(?:.*?([^\\]|\\\\))?\'/s" 'Regex: /\"(?:.*?([^\\]|\\\\))?\"/s' 'Regex: /\'{3}(?:.*?([^\\]|\\\\))?\'{3}/s' ] returns: 'string' description: [ 'Strings can be created by wrapping text in single or double-quote characters. The quote character can be escaped inside a string using \\" or \\\'.' 'Strings can also be created using a triple single-quote, which has the benefit of allowing single and double quote characters to be used unescaped. Naturally, a triple single quote can be escaped inside a string using \\\'\'\'.' 'Standard escape characters can be used inside a string, e.g.: \\n, \\r, \\t, \\\\, etc.' ] examples: [ { description: 'Single-quoted string' q: 'set @msg = \'hello world\'' } { description: 'Double-quoted string' q: 'set @msg = "hello world"' } { description: 'Double-quoted string with escaped characters inside' q: 'set @msg = "\\"I can\'t imagine\\", said the Princess."' } { description: 'Triple-quoted string' q: 'set @query = \'\'\'Parsec query:\\t \'set @msg = "hello world"\'.\'\'\'' } ] } { name: '"list"' type: 'literal' syntax: ['[expr1, expr2, ... ]'] description: ['Lists can be created using the tolist() function or with a list literal: [expr1, expr2, ...].'] examples: [ { description: 'Creating a list with hard-coded values' q: 'set @list = [1, 2, 3]' } { description: 'Creating a list using expressions for each value' q: 'input mock | x = [col1, col2, col3 + col4]' } ] related: ['function:tolist'] } { name: '"map"' type: 'literal' syntax: ['{ key1: expr1, key2: expr2, ... }'] description: ['Maps can be created using the tomap() function or with a map literal: {key1: expr1, key2: expr2, ...}.'] examples: [ { description: 'Creating a map with hard-coded values' q: 'set @map = { a: 1, b: 2 }' } { description: 'Creating a map with strings for keys' q: 'set @map = { "a": 1, "b": 2 }' } { description: 'Creating a map using expressions for each value' q: 'input mock | x = { col1: col1, col2: col2 }' } { description: 'Aggregating into a map' q: 'input mock | stats x = { min: min(col1), max: max(col1) }' } ] related: ['function:tomap'] } { name: '-' altName: 'negation' type: 'operator' subtype: 'arithmetic' syntax: ['-:expression'] returns: 'number' description: [ 'The negation operator toggles the sign of a number: making positive numbers negtive and negative numbers positive.' 'Returns null if the expression is null' 'Since numbers can be parsed with a negative sign, this operator will only be used when preceding a non-numerical expression in the query, e.g. "-x" or "-cos(y)".' ] examples: [ { description: 'Negating a column' q: 'input mock | x = -col1' } ] } { name: '+' altName: 'addition' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 + :expression2'] returns: 'number' description: [ 'The addition operator adds one number to another, or concatenates two strings. If one operand is a string, the other will be coerced into a string, and concatenated.' 'Returns null if either expression is null.' ] examples: [ { description: 'Adding numbers' q: 'input mock | x = col1 + col2' } { description: 'Concatenating strings' q: 'input mock | x = "hello" + " " + "world"' } ] } { name: '-' altName: 'subtraction' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 - :expression2'] returns: 'number' description: [ 'The subtraction operator subtracts one number from another, or creates an interval between two DateTimes.' 'Returns null if either expression is null.' ] examples: [ { description: 'Subtracting numbers' q: 'input mock | x = col1 - col2' } { description: 'Subtracting DateTimes to create an interval' q: 'input mock | x = inminutes(now() - today())' } ] } { name: '*' altName: 'multiplication' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 * :expression2'] returns: 'number' description: [ 'The multiplication operator multiplies two numbers together.' 'Returns null if either expression is null.' 'Multiplying by any non-zero number by infinity gives infinity, while the result of zero times infinity is NaN.' ] examples: [ { description: 'Multiplying numbers' q: 'input mock | x = col1 * col2' } { description: 'Multiplying by infinity' q: 'input mock | x = col1 * infinity()' } ] } { name: '/' altName: 'division' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 / :expression2'] returns: 'number' description: [ 'The division operator divides the value of one number by another. If the value is not an integer, it will be stored as a ratio or floating-point number.' 'Returns null if either expression is null.' 'Dividing a positive number by zero yields infinity, and dividing a negative number by zero yields -infinity. If both numeric expressions are zero, the result is NaN.' ] examples: [ { description: 'Dividing numbers' q: 'input mock | x = col1 / col2' } { description: 'Dividing by zero gives infinity' q: 'input mock | x = col1 / 0, isInfinity = isinfinite(x)' } ] } { name: 'mod' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 mod :expression2'] returns: 'number' description: [ 'The modulus operator finds the amount by which a dividend exceeds the largest integer multiple of the divisor that is not greater than that number. For positive numbers, this is equivalent to the remainder after division of one number by another.' 'Returns null if either expression is null.' 'By definition, 0 mod N yields 0, and N mod 0 yields NaN.' ] examples: [ { q: 'input mock | x = col2 mod col1' } { description: 'Modulus by zero is NaN' q: 'input mock | x = col1 mod 0, isNaN = isnan(x)' } ] } { name: '^' altName: 'exponent' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 ^ :expression2'] returns: 'number' description: [ 'The exponent operator raises a number to the power of another number.' 'Returns null if either expression is null.' 'By definition, N^0 yields 1.' ] examples: [ { q: 'input mock | x = col1 ^ col2' } ] } { name: 'and' type: 'operator' subtype: 'logical' syntax: [':expression1 and :expression2', ':expression1 && :expression2'] returns: 'boolean' description: [ 'The logical and operator compares the value of two expressions and returns true if both values are true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true and true)' } { q: 'input mock | x = (true && false)' } { q: 'input mock | x = isnumber(col1) and col1 > 3' } { q: 'input mock | x = col1 > 1 and null' } ] } { name: 'or' type: 'operator' subtype: 'logical' syntax: [':expression1 or :expression2', ':expression1 || :expression2'] returns: 'boolean' description: [ 'The logical or operator compares the value of two expressions and returns true if at least one value is true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true or false)' } { q: 'input mock | x = (false || false)' } { q: 'input mock | x = col3 == 3 or col1 > 3' } { q: 'input mock | x = col1 > 1 or null' } ] } { name: 'not' type: 'operator' subtype: 'logical' syntax: ['not :expression', '!:expression'] returns: 'boolean' description: [ 'The logical negation operator returns true if the boolean value of :expression is false, else it returns false.' 'Returns null if the expression is null.' ] examples: [ { q: 'input mock | x = not true' } { q: 'input mock | x = !false' } { q: 'input mock | x = !null' } ] } { name: 'xor' type: 'operator' subtype: 'logical' syntax: [':expression1 xor :expression2', ':expression1 ^^ :expression2'] returns: 'boolean' description: [ 'The logical xor operator compares the value of two expressions and returns true if exactly one value is true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true xor false)' } { q: 'input mock | x = (false ^^ false)' } { q: 'input mock | x = true xor null' } ] } { name: '==' altName: 'equals' type: 'operator' subtype: 'equality' syntax: [':expression1 == :expression2'] returns: 'boolean' description: [ 'The equality operator compares the value of two expressions and returns true if they are equal, else false.' ] examples: [ { q: 'input mock | x = (col1 == col2)' } { q: 'input mock | filter col1 == 1 ' } ] } { name: '!=' altName: 'unequals' type: 'operator' subtype: 'equality' syntax: [':expression1 != :expression2'] returns: 'boolean' description: [ 'The inequality operator compares the value of two expressions and returns true if they are unequal, else false.' ] examples: [ { q: 'input mock | x = (col1 != col2)' } { q: 'input mock | filter col1 != 1 ' } ] } { name: '>' altName: 'greater than' type: 'operator' subtype: 'equality' syntax: [':expression1 > :expression2'] returns: 'boolean' description: [ 'The greater-than operator returns true if :expression1 is strictly greater than :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 > col2)' } { q: 'input mock | filter col1 > 1 ' } ] } { name: '<' altName: 'less than' type: 'operator' subtype: 'equality' syntax: [':expression1 < :expression2'] returns: 'boolean' description: [ 'The less-than operator returns true if :expression1 is strictly less than :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 < col2)' } { q: 'input mock | filter col1 < 1 ' } ] } { name: '>=' altName: 'greater or equal' type: 'operator' subtype: 'equality' syntax: [':expression1 >= :expression2'] returns: 'boolean' description: [ 'The greater than or equal operator returns true if :expression1 is greater than or equal to :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 >= col2)' } { q: 'input mock | filter col1 >= 1 ' } ] } { name: '<=' altName: 'less or equal' type: 'operator' subtype: 'equality' syntax: [':expression1 <= :expression2'] returns: 'boolean' description: [ 'The less than or equal operator returns true if :expression1 is less than or equal to :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 <= col2)' } { q: 'input mock | filter col1 <= 1 ' } ] } { name: 'input' type: 'statement' description: ['The input statement loads a dataset from various possible sources. Different input sources are available, like mock, jdbc, and http. Each source has various options for configuring it. If a dataset is already in the pipeline, it will be replaced.'] examples: [ { description: 'Loading mock data from the built-in mock input' q: 'input mock' } { description: 'Several named datasets are included in the mock input' q: 'input mock name="chick-weight"' } ] related: ['input:mock', 'input:datastore', 'input:graphite', 'input:http', 'input:influxdb', 'input:jdbc', 'input:mongodb', 'input:smb', 'input:s3'] } { name: 'output' type: 'statement' syntax: [ 'output name=":name" :options' 'output ignore' ] description: [ 'Outputs the current dataset. This is useful when executing multiple queries at once, in order to return multiple named datasets in the result. Any query which does not end in either an output or temp statement will have an implicit output added. To prevent this, use "output ignore".' 'If the option "temporary=true" is added, the dataset will be stored in the datastore but not returned with the final query results. This is useful for intermediate datasets.' 'If no name is provided, an automatic name will be generated using the index of the dataset in the data store.' 'By default, the dataset is output to the datastore, in the execution context. There is a "type" option to change the default destination.' 'Available output types: "datastore" (default), "ignore".' ] examples: [ { description: 'Returning two named datasets' q: 'input mock | output name="ds1";\ninput mock | output name="ds2"' } { description: 'Creating a temporary dataset' q: 'input mock | output name="ds1" temporary=true;\ninput mock | output name="ds2"' } { description: 'Ignoring the current dataset' q: 'input mock | output ignore' } { description: 'Explicit options' q: 'input mock | output name="results" temporary=false type="datastore" auto=false' } ] related: ['statement:temp'] } { name: 'temp' type: 'statement' syntax: ['temp :name'] description: [ 'The temp statement stores the current dataset in the datastore as a temporary dataset. This means the dataset will be accessible to the rest of the queries, but will not be output as a result dataset.' 'The temp statement is a shortcut for "output name=\'name\' temporary=true".' ] examples: [ { q: 'input mock | temp ds1; input datastore name="ds1"' } ] related: ['statement:output'] } { name: 'head' type: 'statement' syntax: [ 'head' 'head :number' ] description: [ 'Filters the current dataset to the first row or first :number of rows.' ] examples: [ { description: 'Just the first row' q: 'input mock | head' } { description: 'First twenty rows' q: 'input mock name="<NAME>urstone" | head 20' } ] related: ['statement:tail'] } { name: 'tail' type: 'statement' syntax: [ 'tail' 'tail :number' ] description: [ 'Filters the current dataset to the last row or last :number of rows.' ] examples: [ { description: 'Just the tail row' q: 'input mock | tail' } { description: 'Last twenty rows' q: 'input mock name="thurstone" | tail 20' } ] related: ['statement:head'] } { name: 'select' type: 'statement' syntax: [ 'select :identifier [, :identifier, ...]' ] description: [ 'Selects the specified columns in each row and removes all other columns.' ] examples: [ { description: 'Creating and selecting a new column' q: 'input mock | sum = col1 + col2 | select sum' } { description: 'Selecting several columns' q: 'input mock name="survey" | select age, income, male' } ] related: ['statement:unselect'] } { name: 'unselect' type: 'statement' syntax: [ 'unselect :identifier [, :identifier, ...]' ] description: [ 'Removes the specified columns in each row, leaving the remaining columns.' ] examples: [ { description: 'Unselecting a specific column' q: 'input mock | unselect col3' } { description: 'Unselecting several columns' q: 'input mock name="survey" | unselect n, intercept, outmig, inmig | head 20' } ] related: ['statement:select'] } { name: 'filter' type: 'statement' syntax: [ 'filter :expression' ] description: [ 'Filters rows in the current dataset by a predicate. Rows for which the predicate evaluates to true will be kept in the dataset.' 'This is the inverse of the remove statement.' ] examples: [ { description: 'Simple predicate' q: 'input mock name="chick-weight" | filter Chick == 1' } { description: 'Predicate with multiple conditions' q: 'input mock name="chick-weight" | filter Chick == 1 and Time == 0' } ] related: ['statement:remove'] } { name: 'remove' type: 'statement' syntax: [ 'remove :expression' ] description: [ 'Removes rows in the current dataset by a predicate. Rows for which the predicate evaluates to true will be removed from the dataset.' 'This is the inverse of the filter statement.' ] examples: [ { description: 'Simple predicate' q: 'input mock name="chick-weight" | remove Chick == 1' } { description: 'Predicate with multiple conditions' q: 'input mock name="chick-weight" | remove Chick > 1 or Time > 0' } ] related: ['statement:filter'] } { name: 'reverse' type: 'statement' syntax: [ 'reverse' ] description: [ 'Reverses the order of the current dataset. That is, sorts the rows by the current index, descending.' ] examples: [ { q: 'input mock name="iran-election" | reverse' } ] } { name: 'union' type: 'statement' syntax: [ 'union :query' 'union (all|distinct) :query' 'union (all|distinct) (:query)' ] description: [ 'Combines the rows of the current dataset with those from another sub-query. If the sub-query is longer than a single input statement, it should be wrapped in parentheses to differentiate from the parent query.' 'The argument ALL or DISTINCT determines which rows are included in the dataset. DISTINCT returns only unique rows, whereas ALL includes all rows from both datasets, even if they are identical. The default behavior is DISTINCT.' 'Rows from the first dataset will preceed those from the sub-query.' ] examples: [ { description: 'Performs a distinct union by default' q: 'input mock | union input mock' } { description: 'Optionally unions all rows' q: 'input mock | union all input mock' } { description: 'Wrap multi-statement sub-queries in parentheses' q: 'input mock | union (input mock | col1 = col2 + col3)' } ] } { name: 'distinct' type: 'statement' syntax: [ 'distinct' ] description: [ 'Filters the current dataset to the set of unique rows. A row is unique if there is no other row in the dataset with the same columns and values.' 'Rows in the resulting dataset will remain in the same order as in the original dataset.' ] examples: [ { q: 'input mock | select col3 | distinct' } { q: 'input mock | union all input mock | distinct' } ] } { name: 'rownumber' type: 'statement' syntax: [ 'rownumber' 'rownumber :identifier' ] description: [ 'Assigns the current row number in the dataset to a column. If a column identifier is not provided, the default value of "_index" will be used.' 'The rank() function implements similar functionality as a function, but has greater overhead and is only preferable when being used in an expression.' ] examples: [ { q: 'input mock | rownumber' } { q: 'input mock | rownumber rowNumber' } { q: 'input mock name="chick-weight" | rownumber rank1 | rank2 = rank() | equal = rank1 == rank2 | stats count = count(*) by equal' } ] related: ['function:rank'] } { name: 'sort' type: 'statement' syntax: [ 'sort :identifier' 'sort :identifier (asc|desc)' 'sort :identifier (asc|desc) [, :identifier (asc|desc), ...]' ] description: [ 'Sorts the current dataset by one or more columns. Each column can be sorted either in ascending (default) or descending order' ] examples: [ { q: 'input mock | sort col1' } { q: 'input mock | sort col1 asc' } { q: 'input mock | sort col1 asc, col2 desc' } ] } { name: 'def' type: 'statement' syntax: [ 'def :function-name = (:arg, :arg, ..) -> :expression, ...' ] description: [ 'Defines one or more user-defined functions and saves into the current query context. Functions can take any number of arguments and return a single value.' 'Def can be used at any point in the query, even before input. user-defined functions must be defined before they are invoked, but can be used recursively or by other functions.' 'It is not possible to override built-in Parsec functions, but user-defined functions can be redefined multiple times.' ] examples: [ { description: 'Calculate the distance between two points' q: 'def distance = (p1, p2) -> \n sqrt((index(p2, 0) - index(p1, 0))^2 + (index(p2, 1) - index(p1, 1))^2)\n| set @d = distance([0,0],[1,1])' } { description: 'Calculate the range of a list' q: 'def range2 = (list) -> lmax(list) - lmin(list)\n| set @range = range2([8, 11, 5, 14, 25])' } { description: 'Calculate the factorial of a number using recursion' q: 'def factorial = (n) -> if(n == 1, 1, n*factorial(n-1))\n| set @f9 = factorial(9)' } { description: 'Calculate the number of permutations of n things, taken r at a time' q: 'def factorial = (n) -> if(n == 1, 1, n*factorial(n-1)), permutations = (n, r) -> factorial(n) / factorial(n - r)\n| set @p = permutations(5, 2)' } ] related: ['symbol:->:function'] } { name: 'set' type: 'statement' syntax: [ 'set @var1 = :expression, [@var2 = :expression, ...]' 'set @var1 = :expression, [@var2 = :expression, ...] where :predicate' ] description: [ 'Sets one or more variables in the context. As variables are not row-based, the expression used cannot reference individual rows in the data set. However, it can use aggregate functions over the data set. An optional predicate argument can be used to filter rows before the aggregation.' 'Set can be used at any point in the query, even before input' 'Variables are assigned from left to right, so later variables can reference previously assigned variables.' 'Existing variables will be overridden.' ] examples: [ { description: 'Set a constant variable' q: 'set @plank = 6.626070040e-34' } { description: 'Set several dependent variables' q: 'set @inches = 66, @centimeters_per_inch = 2.54, @centimeters = @inches * @centimeters_per_inch' } { description: 'Calculate an average and use later in the query' q: 'input mock | set @avg = avg(col1) | filter col1 > @avg' } ] related: ['literal:"variable"'] } { name: 'rename' type: 'statement' syntax: [ 'rename :column=:oldcolumn, ...' 'rename :column=:oldcolumn, ... where :predicate' ] description: [ 'Renames one or more columns in the dataset.' 'If a predicate is specified, the rename will apply only to rows satisfying the predicate.' ] examples: [ { q: 'input mock | rename day = col1, sales = col2, bookings = col3, numberOfNights = col4' } { description: 'With predicate' q: 'input mock | rename col5 = col1 where col1 < 2' } ] } { name: 'assignment' type: 'statement' syntax: [ ':column=:expr, ...' ':column=:expr, ... where :predicate' ] description: [ 'Assigns one or more columns to each row in the dataset, by evaluating an expression for each row. Assignments are made from left to right, so it is possible to reference previously assigned columns in the same assignemnt statement.' 'If a predicate is specified, the assignments will apply only to rows satisfying the predicate.' ] examples: [ { q: 'input mock | ratio = col1 / col2' } { description: 'With predicate' q: 'input mock | col1 = col1 + col2 where col1 < 3' } { description: 'With multiple assignments' q: 'input mock | ratio = col1 / col2, col5 = col3 * ratio' } ] } { name: 'stats' type: 'statement' syntax: [ 'stats :expression, ... ' 'stats :expression, ... by :expression, ...' ] description: [ 'Calculates one or more aggregate expressions across the dataset, optionally grouped by one or more expressions. The resulting dataset will have a single row for each unique value(s) of the grouping expressions.' 'Grouping expressions will be evaluated for each row, and the values used to divide the datasets into subsets. Each grouping expression will become a column in the resulting dataset, containing the values for that subset. If no grouping expressions are provided, the aggregations will run across the entire dataset.' ] examples: [ { q: 'input mock | stats count=count(*) by col2' } { q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick' } { description: 'Expressions can be used to group by' q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick, bucket(Time, 4)' } { q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick, Time = bucket(Time, 4)' } ] } { name: 'sleep' type: 'statement' syntax: [ 'sleep' 'sleep :expression' ] description: [ 'Delays execution of the query for a given number of milliseconds. Defaults to 1000 milliseconds if no argument is given.' ] examples: [ { q: 'input mock | sleep 5000' } ] } { name: 'sample' type: 'statement' syntax: [ 'sample :expr' ] description: [ 'Returns a sample of a given size from the current dataset. The sample size can be either smaller or larger than the current dataset.' ] examples: [ { description: 'Selecting a sample' q: 'input mock n=100 | sample 10' } { description: 'Generating a larger sample from a smaller dataset' q: 'input mock n=10 | sample 100' } ] } { name: 'benchmark' type: 'statement' syntax: [ 'benchmark :expr [:options]' 'bench :expr [:options]' ] description: [ 'Benchmarks a query and returns a single row of the results. The query will be run multiple times and includes a warm-up period for the JIT compiler and forced GC before and after testing.' 'Various options are available to customize the benchmark, but defaults will be used if not provided. The values used will be returned as a map in the "options" column.' ] examples: [ { description: 'Benchmarking a query with default options' q: 'benchmark "input mock"' } { description: 'Providing a sample size' q: 'bench "input mock | head 1" samples=20' } { description: 'Projecting the performance results for each sample' q: 'benchmark "input mock" | project first(performance)' } { description: 'Projecting the text summary of the benchmark' q: 'benchmark "set @x = random()" | project split(first(summary), "\n")' } ] } { name: 'pivot' type: 'statement' description: [ 'Increases the number of columns in the current dataset by "pivoting" values of one or more columns into additional columns. For example, unique values in a column "type" can be converted into separate columns, with the values attributable to each type as their contents.' ] syntax: [ 'pivot :value [, :value ...] per :expression [, :expression ...] by :group-by [, :group-by ...]' 'pivot :identifier=:value [, identifier=:value ...] per :expression [, :expression ...] by :group-by [, :group-by ...]' ] related: ['statement:unpivot'] } { name: 'unpivot' type: 'statement' syntax: ['unpivot :value per :column by :group-by [, :group-by ...]'] description: [ 'Reduces the number of columns in the current dataset by "unpivoting" them into rows of a single column. This is the inverse operation of the pivot statement.' ] examples: [ { q: 'input http uri="http://pastebin.com/raw.php?i=YGN7gWWG" parser="json" | unpivot CrimesCommitted per Type by Year, Population' } ] related: ['statement:pivot'] } { name: 'project' type: 'statement' syntax: ['project :expression'] description: [ 'Replaces the current dataset with the result of an expression. The expression must be either a list or a single map which will be wrapped in a list automatically.' 'Projecting a list of maps replaces the entire dataset verbatim. If the list does not contain maps, each value will be stored in a new column called "value".' 'Can be useful when parsing data from a string.' ] examples: [ { description: 'With a list of maps' q: 'input mock | project [{x:1, y:1},{x:2, y:2}]' } { description: 'With a list of numbers' q: 'input mock | project [4, 8, 15, 16, 23, 42] | stats avg = avg(value)' } { description: 'From a variable' q: 'input mock | x = [{x:1, y:1},{x:2, y:2}] | project first(x)' } { description: 'With a single map' q: 'input mock | project {a: 1, b: 2, c: 3}' } { description: 'With a JSON string' q: 'input mock | x = \'[{"x":1, "y":1},{"x":2, "y":2}]\' | project parsejson(first(x))' } { description: 'With a CSV string' q: 'input http uri="http://pastebin.com/raw.php?i=s6xmiNzx" | project parsecsv(first(body), { strict: true, delimiter: "," })' } ] } { name: 'join' type: 'statement' syntax: [ '[inner] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'left [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'right [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'full [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'cross join :dataset-or-query' ] description: [ 'Joins the current dataset with another dataset. The join statement takes the current dataset as the left dataset, and either accepts the name of a dataset in the context or an inline query in parentheses.' 'Join types available: Inner, Left Outer (Left), Right Outer (Right), Full Outer (Full), and Cross Join. If no join type is specified, inner join will be assumed.' 'The joined dataset is the output of this statement. Columns from joined rows will be merged, with preference given to the value in the Left dataset.' ] examples: [ { description: 'Inner join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }] | inner join types on typeId == types.id' } { description: 'Left outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 3 }] | left outer join types on typeId == types.id' } { description: 'Right outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 1 }] | right outer join types on typeId == types.id' } { description: 'Full outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 4 }] | full outer join types on typeId == types.id' } { description: 'Cross join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x" }, { name: "y" }] | cross join types' } ] related: ['statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'inner join' type: 'statement' syntax: ['[inner] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Inner join is a type of join which requires each row in the joined datasets to satisfy a join predicate.' ] examples: [ { description: 'Inner join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }] | inner join types on typeId == types.id' } ] related: ['statement:join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'left outer join' type: 'statement' syntax: ['left [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Left Outer join is a type of join which always includes all rows of the left-hand dataset, even if they do not satisfy the join predicate.' ] examples: [ { description: 'Left outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 3 }] | left outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'right outer join' type: 'statement' syntax: ['right [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Right Outer join is a type of join which always includes all rows of the right-hand dataset, even if they do not satisfy the join predicate.' ] examples: [ { description: 'Right outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 1 }] | right outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'full outer join' type: 'statement' syntax: ['full [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Full Outer join is a type of join which combines the effects of both left and right outer join. All rows from both left and right datasets will be included in the result.' ] examples: [ { description: 'Full outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 4 }] | full outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:cross join'] } { name: 'cross join' type: 'statement' syntax: ['cross join [:left-alias], :dataset-or-query'] description: [ 'Cross join is a type of join which returns the cartesian product of rows from both datasets.' ] examples: [ { description: 'Cross join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x" }, { name: "y" }] | cross join types' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join'] } { name: 'avg' type: 'function' subtype: 'aggregation' description: [ 'avg() is an alias for mean().' ] aliases: ['function:mean'] } { name: 'count' type: 'function' subtype: 'aggregation' syntax: [ 'count(*)' 'count(:expression)' 'count(:expression, :predicate)' ] returns: 'number' description: [ 'Counts the number of rows where :expression is non-null. An optional predicate argument can be used to filter rows before the aggregation.' 'count(*) is equivalent to count(1); it counts every row.' ] examples: [ { q: 'input mock | stats count = count(*)' } { q: 'input mock | col1 = null where col2 == 2 | stats count = count(col1)' } { q: 'input mock | stats count = count(*, col2 == 2)' } ] related: ['function:distinctcount'] } { name: 'cumulativeavg' type: 'function' subtype: 'aggregation' description: [ 'cumulativeavg() is an alias for cumulativemean().' ] aliases: ['function:cumulativemean'] } { name: 'cumulativemean' type: 'function' subtype: 'aggregation' syntax: [ 'cumulativemean(:expression)' 'cumulativemean(:expression, :predicate)' ] returns: 'list' description: [ 'Returns a list of cumulative means for the current dataset. For example, the first value in the list is the value of the first row; the second value is the mean of the first two rows, the third is the mean of the first three rows, etc.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats c1 = cumulativemean(col1), c2 = cumulativemean(col2)' } ] related: ['function:mean', 'function:geometricmean'] aliases: ['function:cumulativeavg'] } { name: 'distinctcount' type: 'function' subtype: 'aggregation' syntax: [ 'distinctcount(:expression)' 'distinctcount(:expression, :predicate)' ] returns: 'number' description: [ 'Counts the number of rows for which :expression is distinct and non-null. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats col1DistinctCount = distinctcount(col1), col2DistinctCount = distinctcount(col2)' } { q: 'input mock | stats count = count(*, col2 == 2)' } ] related: ['function:count'] } { name: 'geometricmean' type: 'function' subtype: 'aggregation' syntax: [ 'geometricmean(:expression)' 'geometricmean(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the geometric mean of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats geometricmean = geometricmean(col1)' } { q: 'input mock | stats geometricmean = geometricmean(col1 + col2, col3 == 3)' } ] related: ['function:mean', 'function:cumulativemean'] } { name: 'max' type: 'function' subtype: 'aggregation' syntax: [ 'max(:expression)' 'max(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the maximum value of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats max = max(col1)' } { q: 'input mock name="chick-weight" | stats maxWeight = max(weight, Chick == 1)' } ] related: ['function:min'] } { name: 'mean' type: 'function' subtype: 'aggregation' syntax: [ 'mean(:expression)' 'mean(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the arithmetic mean of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats mean = mean(col1)' } { q: 'input mock | stats mean = mean(col1 + col2, col3 == 3)' } ] related: ['function:geometricmean', 'function:cumulativemean'] aliases: ['function:avg'] } { name: 'median' type: 'function' subtype: 'aggregation' syntax: [ 'median(:expression)' 'median(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the median value of :expression, calculated across all rows. If there is no middle value, the median is the mean of the two middle values.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats median = median(col1)' } { q: 'input mock name="chick-weight" | stats medianWeight = median(weight, Chick == 1)' } { q: 'input mock name="airline-passengers" | stats mean = mean(passengers), median = median(passengers)' } ] } { name: 'mode' type: 'function' subtype: 'aggregation' syntax: [ 'mode(:expression)' 'mode(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the mode of :expression, calculated across all rows. If there are multiple modes, one of them will be returned.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats mode = mode(col2)' } { q: 'input mock name="hair-eye-color" | stats mode = mode(hair) by gender' } { q: 'input mock name="survey" | stats medianAge = median(age), modeAge = mode(age)' } ] } { name: 'min' type: 'function' subtype: 'aggregation' syntax: [ 'min(:expression)' 'min(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the minimum value of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats min = min(col1)' } { q: 'input mock name="chick-weight" | stats minWeight = min(weight, Chick == 1)' } ] related: ['function:max'] } { name: 'pluck' type: 'function' subtype: 'aggregation' syntax: ['pluck(expression)'] returns: 'list' description: ['Evaluates an expression against each row in the data set, and returns a list composed of the resulting values. The list maintains the same order as the rows in the data set.'] examples: [ { description: 'Plucking a column' q: 'input mock | stats values = pluck(col1)' } { description: 'Plucking a calculated expression' q: 'input mock | stats values = pluck(col1 + col2)' } ] } { name: 'stddev_pop' type: 'function' subtype: 'aggregation' description: [ 'stddev_pop() is an alias for stddevp().' ] aliases: ['function:stddevp'] } { name: 'stddev_samp' type: 'function' subtype: 'aggregation' description: [ 'stddev_samp() is an alias for stddev().' ] aliases: ['function:stddev'] } { name: 'stddevp' type: 'function' subtype: 'aggregation' syntax: [ 'stddevp(:expression)' 'stddevp(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the population standard deviation of :expression, calculated across all rows in the data set (excluding nulls). An optional predicate argument can be used to filter rows before the aggregation.' 'If the data set is not the complete population, use stddev() instead to calculate the sample standard deviation.' ] examples: [ { description: 'Standard deviation of a column' q: 'input mock | stats sigma = stddevp(col1)' } { description: 'Standard deviation of a calculated value' q: 'input mock | stats sigma = stddevp(col1 + col2)' } ] related: ['function:stddev'] aliases: ['function:stddev_pop'] } { name: 'stddev' type: 'function' subtype: 'aggregation' syntax: [ 'stddev(:expression)' 'stddev(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the sample standard deviation of :expression, calculated across all rows in the data set (excluding nulls). An optional predicate argument can be used to filter rows before the aggregation.' 'If the data set is the complete population, use stddevp() instead to calculate the population standard deviation.' ] examples: [ { description: 'Standard deviation of a column' q: 'input mock | stats sigma = stddev(col1)' } { description: 'Standard deviation of a calculated value' q: 'input mock | stats sigma = stddev(col1 + col2)' } ] related: ['function:stddevp'] aliases: ['function:stddev_samp'] } { name: 'sum' type: 'function' subtype: 'aggregation' syntax: [ 'sum(:expression)' 'sum(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the sum of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats total = sum(col1)' } { q: 'input mock name="airline-passengers" | stats pTotal = sum(passengers), p1960 = sum(passengers, year == 1960)' } ] } { name: 'every' type: 'function' subtype: 'aggregation' syntax: [ 'every(:expression)' 'every(:expression, :predicate)' ] returns: 'boolean' description: [ 'Returns true if :expression is true for all rows in the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats test = every(col1 > 0)' } { q: 'input mock name="chick-weight" | stats hasWeight = every(weight > 0, Chick == 1)' } ] related: ['function:some'] } { name: 'first' type: 'function' subtype: 'aggregation' syntax: [ 'first(:expression)' 'first(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the first non-null value of :expression in the dataset, closest to the top of the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats first = first(col1)' } { q: 'input mock name="chick-weight" | stats firstWeight = min(weight, Chick == 1)' } ] related: ['function:last'] } { name: 'last' type: 'function' subtype: 'aggregation' syntax: [ 'last(:expression)' 'last(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the last non-null value of :expression in the dataset, closest to the bottom of the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats last = last(col1)' } { q: 'input mock name="chick-weight" | stats lastWeight = last(weight, Chick == 1)' } ] related: ['function:first'] } { name: 'percentile' type: 'function' subtype: 'aggregation' syntax: [ 'percentile(:expression, :percentage)' 'percentile(:expression, :percentage, :predicate)' ] returns: 'number' description: [ 'Calculates the percentile of an :expression and a given :percentage. Specifically, it returns the value below which :percentage of values in the dataset are less than the value. The percentage can be a number or calculated value.' 'Uses the linear interpolation method, so the returned value may not be in the original dataset. Excludes nils from the calculation and returns nil if there are no non-nil values.' ] examples: [ { q: 'input mock name="chick-weight" | stats p95 = percentile(weight, 95) by <NAME>ick' } ] } { name: 'some' type: 'function' subtype: 'aggregation' syntax: [ 'some(:expression)' 'some(:expression, :predicate)' ] returns: 'boolean' description: [ 'Returns true if :expression is true for some rows in the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats test = some(col1 > 0)' } { q: 'input mock name="chick-weight" | stats hasWeight = some(weight > 0, Chick == 1)' } ] related: ['function:some'] } { name: 'isexist' type: 'function' subtype: 'is-functions' syntax: ['isexist(:column)'] returns: 'boolean' description: [ 'Returns true if its argument exists as a column the current row, else false. It does not check the value of the column, just its existance. As a result, isexist() on a column with a null value will return true.' ] examples: [ { q: 'input mock | col6 = 1 where col2 == 2 | exists = isexist(col6)' } ] } { name: 'isnull' type: 'function' subtype: 'is-functions' syntax: ['isnull(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is null, else false.' ] examples: [ { q: 'set @test = isnull(null)' } ] } { name: 'isnan' type: 'function' subtype: 'is-functions' syntax: ['isnan(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is NaN, else false.' ] examples: [ { q: 'set @test = isnan(0 * infinity())' } ] related: ['function:nan'] } { name: 'isinfinite' type: 'function' subtype: 'is-functions' syntax: ['isinfinite(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is infinite, else false.' ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'isfinite' type: 'function' subtype: 'is-functions' syntax: ['isfinite(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is finite, else false.' ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'isempty' type: 'function' subtype: 'is-functions' syntax: ['isempty(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is "empty", else false.' 'Lists are empty if they have no elements; maps are empty if they have no keys; strings are empty if they have zero length or contain only whitespace. Zero and null are both considered empty.' ] examples: [ { q: 'set @nonempty = isempty("hello"), @empty = isempty(" \n")' } { q: 'set @nonempty = isempty({a: 1}), @empty = isempty(tomap())' } { q: 'set @nonempty = isempty([1, 2, 3]), @empty = isempty([])' } ] } { name: 'isdate' type: 'function' subtype: 'type' syntax: ['isdate(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a DateTime, else false.' 'isdate(null) returns false.' ] examples: [ { q: 'set @test = isdate(now())' } { description: 'Numbers are not DateTimes' q: 'set @test = isdate(101)' } ] } { name: 'isboolean' type: 'function' subtype: 'type' syntax: ['isboolean(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a boolean.' 'isboolean(null) returns false.' ] examples: [ { q: 'set @test = isboolean(true)' } { description: 'Numbers are not booleans' q: 'set @test = isboolean(false)' } { description: 'Equality operators always return booleans' q: 'set @test = isboolean(100 > 0)' } ] } { name: 'isnumber' type: 'function' subtype: 'type' syntax: ['isnumber(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a number. This includes integers, doubles, ratios, etc.' 'isnumber(null) returns false.' ] examples: [ { q: 'set @test = isnumber(0)' } { description: 'Booleans are not numbers' q: 'set @test = isnumber(false)' } { description: 'Numerical strings are not numbers' q: 'set @test = isnumber("3.14")' } ] } { name: 'isinteger' type: 'function' subtype: 'type' syntax: ['isinteger(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is an integer.' 'isinteger(null) returns false.' ] examples: [ { q: 'set @test = isinteger(100)' } { description: 'Floating-point numbers are not integers' q: 'set @test = isinteger(1.5)' } { description: 'Since these numbers can be represented accurately as ratios, their addition yields an integer.' q: 'set @test = isinteger(1.5 + 0.5)' } ] } { name: 'isratio' type: 'function' subtype: 'type' syntax: ['isratio(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a ratio. Parsec will automatically store the result of computations in ratio form if possible, e.g. if two integers are divided.' 'isratio(null) returns false.' ] examples: [ { q: 'set @test = isratio(1/2)' } { description: 'Booleans are not ratios' q: 'set @test = isratio(false)' } { description: 'Numerical strings are not ratios' q: 'set @test = isratio("1/3")' } ] } { name: 'isdouble' type: 'function' subtype: 'type' syntax: ['isdouble(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a double.' 'isdouble(null) returns false.' ] examples: [ { q: 'set @test = isdouble(pi())' } { description: 'Forcing a conversion to double' q: 'input mock | x = todouble(col1), @y = isdouble(x)' } { description: 'Parsec stores exact ratios when possible, which are not considered doubles' q: 'set @test = isdouble(1 / 2)' } ] } { name: 'isstring' type: 'function' subtype: 'type' syntax: ['isstring(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a string.' 'isstring(null) returns false.' ] examples: [ { q: 'set @test = isstring("hello world")' } ] } { name: 'islist' type: 'function' subtype: 'type' syntax: ['islist(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a list.' 'islist(null) returns false.' ] examples: [ { q: 'set @test = islist([1, 2, 3])' } ] } { name: 'ismap' type: 'function' subtype: 'type' syntax: ['ismap(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a map.' 'ismap(null) returns false.' ] examples: [ { q: 'set @test = ismap({ a: 1, y: 2, z: 3})' } ] } { name: 'type' type: 'function' subtype: 'type' syntax: ['istype(:expression)'] returns: 'string' description: [ 'Evaluates :expression and returns its data type name as a string.' ] examples: [ { q: 'input mock | x = type(col1)' } { q: 'input mock | x = tostring(col1), y = type(x)' } { q: 'input mock | stats x = pluck(col1) | y = type(x)' } { q: 'input mock | x=type(null)' } ] } { name: 'toboolean' type: 'function' subtype: 'conversion' syntax: ['toboolean(:expression)'] returns: 'boolean' description: [ 'Attempts to convert :expression to a boolean value, returning null if the conversion is not possible.' 'If :expression is a boolean, it is returned as-is.' 'If :expression is a number, yields true for any non-zero number, else false.' 'If :expression is a string, a case-insensitive "true" or "false" will be converted to true and false respectively, with all other values returning null.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a number' q: 'set @true = toboolean(1),\n @false = toboolean(0)' } { description: 'Converting a string' q: 'set @test = toboolean("TRUE")' } ] related: ['function:isboolean'] } { name: 'tostring' type: 'function' subtype: 'conversion' syntax: [ 'tostring(:expression)' 'tostring(:expression, :format)' ] returns: 'string' description: [ 'Attempts to convert :expression to a string type, returning null if the conversion is not possible.' 'If :expression is a string, it is returned as-is.' 'If :expression is a boolean, "true" or "false" is returned.' 'If :expression is a number, yields a string containing the numeric representation of the number.' 'If :expression is a map or list, yields a string containing the JSON representation of :expression.' 'If :expression is a date, yields an ISO 8601-format string representing the date, unless a format code is provided as the second argument. Joda-Time formatting code are accepted, see here: http://www.joda.org/joda-time/key_format.html' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a number' q: 'set @test = tostring(1) // returns "1"' } { description: 'Converting a boolean' q: 'set @test = tostring(true) // returns "true"' } { description: 'Converting a map' q: 'set @test = tostring({ "id": 123, "name": "<NAME>" }) // returns {"id":123,"name":"<NAME>"}' } { description: 'Converting a list' q: 'set @test = tostring([1, 2, 3]) // returns "[1,2,3]"' } { description: 'Converting a date into ISO 8601 format' q: 'set @year = tostring(now())' } { description: 'Converting a date with a format' q: 'set @year = tostring(now(), "YYYY")' } ] related: ['function:isboolean'] } { name: 'tonumber' type: 'function' subtype: 'conversion' syntax: ['tonumber(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a numerical type, returning null if the conversion is not possible. This function can return integers, doubles, ratios, etc.' 'If :expression is a number, it is returned as-is.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an integer, double, or ratio. If the parsed value can be represented as a ratio, it will be stored internally as such.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting an integer string' q: 'set @test = tonumber("1") // returns 1' } { description: 'Converting a double string' q: 'set @test = tonumber("3.14") // returns 3.14' } { description: 'Converting a ratio' q: 'set @test = tonumber("1/5") // returns 0.2' } { description: 'Converting a date' q: 'set @test = tonumber(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isnumber', 'function:tointeger', 'function:todouble'] } { name: 'tointeger' type: 'function' subtype: 'conversion' syntax: ['tointeger(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a long integer, returning null if the conversion is not possible.' 'If :expression is an integer, it is returned as-is.' 'If :expression is a non-integer number, it will be rounded down to the nearest integer.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an integer.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a double' q: 'set @test = tointeger(3.14) // returns 3' } { description: 'Converting an integer string' q: 'set @test = tointeger("1") // returns 1' } { description: 'Converting a ratio' q: 'set @test = tointeger("22/3") // returns 7' } { description: 'Converting a date' q: 'set @test = tointeger(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isinteger', 'function:tonumber', 'function:todouble'] } { name: 'todouble' type: 'function' subtype: 'conversion' syntax: ['todouble(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a double, returning null if the conversion is not possible.' 'If :expression is an double, it is returned as-is.' 'If :expression is an number, it will be coerced into a double type internally.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an double.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting an integer' q: 'set @test = todouble(1) // returns 1' } { description: 'Converting a double string' q: 'set @test = todouble("3.14") // returns 3.14' } { description: 'Converting a ratio string' q: 'set @test = todouble("22/3") // returns 7.333333333333333' } { description: 'Converting a date' q: 'set @test = todouble(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isdouble', 'function:tonumber', 'function:tointeger'] } { name: 'todate' type: 'function' subtype: 'conversion' syntax: [ 'todate(:expression)' 'todate(:expression, :format)' ] returns: 'number' description: [ 'Attempts to convert :expression to a date, returning null if the conversion is not possible.' 'If :expression is an date, it is returned as-is.' 'If :expression is a number, it will be coerced to a long and interpreted as the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse using various standard formats. A format argument can optionally be provided to specify the correct format.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting epoch milliseconds' q: 'set @test = todate(1461543510000)' } { description: 'Converting an ISO-8601 date' q: 'set @test = todate("2016-04-25T00:02:05.000Z")' } { description: 'Converting a date with a format code' q: 'set @test = todate("1985-10-31", "yyyy-MM-dd")' } ] related: ['function:isdate'] } { name: 'tolist' type: 'function' subtype: 'conversion' syntax: ['tolist(:expression [, :expression ...])'] returns: 'map' description: ['Creates a list from a series of arguments.'] examples: [ { q: 'input mock | x = tolist(1, 2, 3, 4)' } { q: 'input mock | x = tolist("red", "yellow", "green")' } { description: 'Creating a list from expressions' q: 'input mock | x = tolist(meanmean(col1), meanmean(col2), meanmean(col3))' } ] related: ['literal:"list"', 'function:islist'] } { name: 'tomap' type: 'function' subtype: 'conversion' syntax: ['tomap(:key, :expression [, :key, :expression ...])'] returns: 'map' description: ['Creates a map from a series of key/value pair arguments: tomap(key1, expr1, key2, expr2, ...).'] examples: [ { q: 'input mock | x = tomap("x", 1, "y", 2)' } { description: 'Creating a map from expressions' q: 'input mock | x = tomap("meanmean", mean(col1), "max", max(col1))' } ] related: ['literal:"map"', 'function:ismap'] } { name: 'e' type: 'function' subtype: 'constant' syntax: ['e()'] returns: 'number' description: ['Returns the constant Euler\'s number.'] examples: [ { q: 'input mock | pi = e()' } ] related: ['function:ln'] } { name: 'pi' type: 'function' subtype: 'constant' syntax: ['pi()'] returns: 'number' description: ['Returns the constant Pi.'] examples: [ { q: 'input mock | pi = pi()' } ] } { name: 'nan' type: 'function' subtype: 'constant' syntax: ['nan()'] returns: 'number' description: ['Returns the not-a-number (NaN) numerical value.'] examples: [ { q: 'input mock | x = nan(), isnotanumber = isnan(x)' } ] related: ['function:isnan'] } { name: 'infinity' type: 'function' subtype: 'constant' syntax: ['infinity()'] returns: 'number' description: ['Returns the positive infinite numerical value.'] examples: [ { q: 'input mock | x = infinity(), isInf = isinfinite(x)' } ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'neginfinity' type: 'function' subtype: 'constant' syntax: ['neginfinity()'] description: ['Returns the negative infinite numerical value.'] examples: [ { q: 'input mock | x = neginfinity(), isInf = isinfinite(x)' } ] related: ['function:isfinite', 'function:isinfinite', 'function:infinity'] } { name: 'floor' type: 'function' subtype: 'math' syntax: ['floor(:number)'] description: [ 'Returns the greatest integer less than or equal to :number.' ] examples: [ { description: 'Floor of an double' q: 'input mock name="thurstone" | z = y / x, floor = floor(z)' } { description: 'Floor of an integer' q: 'set @floor = floor(42)' } ] related: ['function:ceil', 'function:round'] } { name: 'ceil' type: 'function' subtype: 'math' syntax: ['ceil(:number)'] description: [ 'Returns the least integer greater than or equal to :number.' ] examples: [ { description: 'Ceiling of an double' q: 'input mock name="thurstone" | z = y / x, ceil = ceil(z)' } { description: 'Ceiling of an integer' q: 'set @ceil = ceil(42)' } ] related: ['function:floor', 'function:round'] } { name: 'abs' type: 'function' subtype: 'math' syntax: ['abs(:number)'] description: [ 'Returns the absolute value of :number.' ] examples: [ { description: 'Absolute value of a positive number' q: 'set @abs = abs(10)' } { description: 'Absolute value of a negative number' q: 'set @abs = abs(-99)' } ] } { name: 'sign' type: 'function' subtype: 'math' syntax: ['sign(:number)'] description: [ 'Returns 1 if :number is greater than zero, -1 if :number is less than zero, and 0 if :number is zero.' 'Returns NaN if :number is NaN.' ] examples: [ { description: 'Sign of a positive number' q: 'set @sign = sign(10)' } { description: 'Sign of a negative number' q: 'set @sign = sign(-99)' } { description: 'Sign of zero' q: 'set @sign = sign(0)' } ] } { name: 'sqrt' type: 'function' subtype: 'math' syntax: ['sqrt(:number)'] description: [ 'Returns the square root of :number.' ] examples: [ { q: 'input mock name="thurstone" | sqrt = sqrt(x + y)' } { description: 'Square root of a perfect square' q: 'set @square = sqrt(64)' } ] related: ['function:pow'] } { name: 'pow' type: 'function' subtype: 'math' syntax: ['pow(:base, :power)'] description: [ 'Returns :base raised to the power of :power.' ] examples: [ { q: 'input mock name="thurstone" | cube = pow(x + y, 3)' } { description: 'Square root of a square' q: 'set @square = sqrt(pow(8, 2))' } ] related: ['function:sqrt'] } { name: 'round' type: 'function' subtype: 'math' syntax: ['round(:number)', 'round(:number, :places)'] description: [ 'Rounds a number to a given number of decimal places.' 'If the 2nd argument is omitted, the number is rounded to an integer (0 decimal places).' ] examples: [ { description: 'Rounding to an integer' q: 'input mock name="thurstone" | stats p90 = percentile(x, 90), r = round(p90)' } { description: 'Rounding to five decimal places' q: 'input mock name="thurstone" | stats z = mean(x / y), r = round(z, 5)' } ] related: ['function:ceil', 'function:floor'] } { name: 'within' type: 'function' subtype: 'math' syntax: ['within(:number, :test, :tolerance)'] description: [ 'Returns true if the difference between :number and :test is less than or equal to :tolerance. That is, it evaluates whether the value of :number is in the range of :test +/- :tolerance (inclusive).' ] examples: [ { q: 'input mock | x = within(col1, col3, 1)' } { description: 'Comparing maximum Chick weights to the average' q: 'input mock name="chick-weight" | stats mean=mean(weight), max=max(weight), stdev = stddev(weight) by Chick | withinOneSigma = within(mean, max, stdev)' } ] related: ['function:within%'] } { name: 'within%' type: 'function' subtype: 'math' syntax: ['within%(:number, :test, :percent)'] description: [ 'Similar to within(), but uses :percent to calculate the tolerance from :test. Returns true if the difference between :number and :test is less than or equal to (:percent * :test).' 'The :percent argument is expected as a decimal or percentage literal: "0.1" or "10%". A value of "10" is interpreted as 1000%, not 10%.' ] examples: [ { q: 'input mock | select col1, col4 | x = within%(col1, col4, 50%)' } { description: 'Comparing maximum Chick weights to the average' q: 'input mock name="chick-weight" | stats avg=avg(weight), max=max(weight) by Chick | test = within%(max, avg, 50%)' } ] related: ['function:within'] } { name: 'greatest' type: 'function' subtype: 'math' syntax: ['greatest(:number, :number, ...)'] description: [ 'Returns the argument with the greatest numerical value, regardless of order.' 'greatest(null) returns null, and non-numerical arguments will cause an exception. If a single argument is provided, it will be returned regardless of its type.' ] examples: [ { q: 'input mock | greatest = greatest(col1, col2, col3)' } ] related: ['function:least'] } { name: 'least' type: 'function' subtype: 'math' syntax: ['least(:number, :number, ...)'] description: [ 'Returns the argument with the smallest numerical value, regardless of order.' 'least(null) returns null, and non-numerical arguments will cause an exception. If a single argument is provided, it will be returned regardless of its type.' ] examples: [ { q: 'input mock | least = least(col1, col2, col3)' } ] related: ['function:greatest'] } { name: 'gcd' type: 'function' subtype: 'math' syntax: ['gcd(:integer, :integer)'] description: [ 'Returns the greatest common divisor of two integers.' 'Returns null if either :integer is null, or if non-integer arguments are passed.' ] examples: [ { q: 'set @gcd = gcd(12, 18)' } ] related: ['function:lcm'] } { name: 'lcm' type: 'function' subtype: 'math' syntax: ['lcm(:integer, :integer)'] description: [ 'Returns the least common multiple of two integers.' 'Returns null if either :integer is null, or if non-integer arguments are passed.' ] examples: [ { q: 'set @lcm = lcm(12, 18)' } ] related: ['function:gcd'] } { name: 'ln' type: 'function' subtype: 'math' syntax: ['ln(:number)'] description: [ 'Returns the natural logarithm (base e) for :number' 'Returns null for non-numerical arguments. If :number is NaN or less than zero, returns NaN. If :number is positive infinity, then returns positive infinity. If :number is positive zero or negative zero, then returns negative infinity.' ] examples: [ { q: 'set @ln = ln(5)' } ] related: ['function:e', 'function:log'] } { name: 'log' type: 'function' subtype: 'math' syntax: ['log(:number)'] description: [ 'Returns the base 10 logarithm for :number' 'Returns null for non-numerical arguments. If :number is NaN or less than zero, returns NaN. If :number is positive infinity, then returns positive infinity. If :number is positive zero or negative zero, then returns negative infinity.' ] examples: [ { q: 'set @log = log(5)' } ] related: ['function:ln'] } { name: 'degrees' type: 'function' subtype: 'trigonometric' syntax: ['degrees(:angle)'] description: [ 'Converts an :angle in radians to degrees.' ] examples: [ { q: 'set @degrees = degrees(pi() / 2)' } ] related: ['function:radians'] } { name: 'radians' type: 'function' subtype: 'trigonometric' syntax: ['radians(:angle)'] description: [ 'Converts an :angle in degrees to radians.' ] examples: [ { q: 'set @radians = radians(45)' } ] related: ['function:degrees'] } { name: 'sin' type: 'function' subtype: 'trigonometric' syntax: ['sin(:number)'] description: [ 'Returns the trigonometric sine of an angle in radians.' 'If :number is NaN or infinity, returns NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @sin = sin(3.1415)' } ] related: ['function:cos', 'function:tan', 'function:asin', 'function:sinh'] } { name: 'cos' type: 'function' subtype: 'trigonometric' syntax: ['cos(:number)'] description: [ 'Returns the trigonometric cosine of an angle in radians.' 'If :number is NaN or infinity, returns NaN.' ] examples: [ { q: 'set @cos = cos(3.1415)' } ] related: ['function:sin', 'function:tan', 'function:acos', 'function:cosh'] } { name: 'tan' type: 'function' subtype: 'trigonometric' syntax: ['tan(:number)'] description: [ 'Returns the trigonometric tangent of an angle in radians.' 'If :number is NaN or infinity, returns NaN. If :number is zero, then the result is a zero with the same sign as :number.' ] examples: [ { q: 'set @tan = tan(3.1415)' } ] related: ['function:sin', 'function:cos', 'function:atan', 'function:atan2', 'function:tanh'] } { name: 'sinh' type: 'function' subtype: 'trigonometric' syntax: ['sinh(:number)'] description: [ 'Returns the hyperbolic sine of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is infinite, then the result is an infinity with the same sign as :number. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @sinh = sinh(3.1415)' } ] related: ['function:sin', 'function:cosh', 'function:tanh', 'function:asin'] } { name: 'cosh' type: 'function' subtype: 'trigonometric' syntax: ['cosh(:number)'] description: [ 'Returns the hyperbolic cosine of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is infinite, then the result then the result is positive infinity. If :number is zero, then the result is 1.' ] examples: [ { q: 'set @cosh = cosh(3.1415)' } ] related: ['function:cos', 'function:sinh', 'function:tanh', 'function:acos'] } { name: 'tanh' type: 'function' subtype: 'trigonometric' syntax: ['tanh(:number)'] description: [ 'Returns the hyperbolic tangent of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is zero, then the result is zero. If :number is positive infinity, then the result is 1. If :number is negative infinity, then the result is -1.0.' ] examples: [ { q: 'set @tanh = tanh(3.1415)' } ] related: ['function:sinh', 'function:cosh', 'function:tan', 'function:atan'] } { name: 'asin' type: 'function' subtype: 'trigonometric' syntax: ['asin(:number)'] description: [ 'Returns the arc sine of an angle in radians.' 'If :number is NaN or its absolute value is greater than 1, then the result is NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @asin = asin(0.5)' } ] related: ['function:sin', 'function:sinh', 'function:acos', 'function:atan'] } { name: 'acos' type: 'function' subtype: 'trigonometric' syntax: ['acos(:number)'] description: [ 'Returns the arc cosine of an angle in radians.' 'If :number is NaN or its absolute value is greater than 1, then the result is NaN.' ] examples: [ { q: 'set @acos = acos(0.5)' } ] related: ['function:cos', 'function:cosh', 'function:asin', 'function:atan'] } { name: 'atan' type: 'function' subtype: 'trigonometric' syntax: ['atan(:number)'] description: [ 'Returns the arc tangent of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @atan = atan(0.5)' } ] related: ['function:tan', 'function:tanh', 'function:asin', 'function:acos'] } { name: 'atan2' type: 'function' subtype: 'trigonometric' syntax: ['atan2(:y, :x)'] description: [ 'Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).' ] examples: [ { q: 'set @atan2 = atan2(1, 1)' } ] related: ['function:tan', 'function:tanh', 'function:tan', 'function:atan'] } { name: 'pdfuniform' type: 'function' subtype: 'probability' syntax: [ 'pdfuniform(:number)' 'pdfuniform(:number, :min, :max)' 'pdfuniform(:list)' 'pdfuniform(:list, :min, :max)' ] description: [ 'Returns the continuous uniform distribution function of the given :number or :list, with default values of min=0, max=1.' 'If a :list is provided, the result will be a list with pdfuniform() applied to each element.' ] examples: [ { q: 'set @pdf = pdfuniform(0.5), @pdf2 = pdfuniform(0.5, 0, 5)' } { description: 'Applying pdfuniform() to a list' q: 'project range(0, 10) | P = pdfnormal(value, 0, 10)' } ] related: ['function:cdfuniform', 'function:pdfnormal', 'function:pdfpoisson'] } { name: 'pdfnormal' type: 'function' subtype: 'probability' syntax: [ 'pdfnormal(:number)' 'pdfnormal(:number, :mean, :sd)' 'pdfnormal(:list)' 'pdfnormal(:list, :mean, :sd)' ] description: [ 'Returns the continuous Normal cumulative distribution function of the given :number or :list, with default values of mean=0, sd=1.' 'If a :list is provided, the result will be a list with pdfnormal() applied to each element.' ] examples: [ { q: 'set @pdf = pdfnormal(0.5), @pdf2 = pdfnormal(0.5, 0, 5)' } { description: 'Applying pdfnormal() to a list' q: 'project range(0, 10) | P = pdfnormal(value, 0, 10)' } ] related: ['function:cdfnormal', 'function:pdfuniform', 'function:pdfpoisson'] } { name: 'pdfpoisson' type: 'function' subtype: 'probability' syntax: [ 'pdfpoisson(:number)' 'pdfpoisson(:number, :lambda)' 'pdfpoisson(:list)' 'pdfpoisson(:list, :lambda)' ] description: [ 'Returns the continuous Poisson cumulative distribution function of the given :number or :list, with default value of lambda=1.' 'If a :list is provided, the result will be a list with pdfpoisson() applied to each element.' ] examples: [ { q: 'set @pdf = pdfpoisson(0.5), @pdf2 = pdfpoisson(0.5, 5)' } { description: 'Applying pdfpoisson() to a list' q: 'project range(0, 10) | P = pdfpoisson(value, 2)' } ] related: ['function:cdfpoisson', 'function:pdfuniform', 'function:pdfnormal'] } { name: 'cdfuniform' type: 'function' subtype: 'probability' syntax: [ 'cdfuniform(:number)' 'cdfuniform(:number, :min, :max)' 'cdfuniform(:list)' 'cdfuniform(:list, :min, :max)' ] description: [ 'Returns the Uniform cumulative distribution function of the given :number or :list, with default values of min=0, max=1.' 'If a :list is provided, the result will be a list with cdfuniform() applied to each element.' ] examples: [ { q: 'set @cdf = cdfuniform(0.5), @cdf2 = cdfuniform(0.5, 0, 5)' } { description: 'If plant weights are equally probable, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfuniform(weight, min(weight), max(weight))' } { description: 'Same as above, but with lists' q: 'input mock name="plant-growth" \n| set @weights = pluck(weight)\n| set @P = cdfuniform(@weights, listmin(@weights), listmax(@weights));' } ] related: ['function:pdfuniform', 'function:cdfnormal', 'function:cdfpoisson'] } { name: 'cdfnormal' type: 'function' subtype: 'probability' syntax: [ 'cdfnormal(:number)' 'cdfnormal(:number, :mean, :sd)' 'cdfnormal(:list)' 'cdfnormal(:list, :mean, :sd)' ] description: [ 'Returns the Normal cumulative distribution function of the given :number or :list, with default values of mean=0, sd=1.' 'If a :list is provided, the result will be a list with cdfnormal() applied to each element.' ] examples: [ { q: 'set @cdf = cdfnormal(0.5), @cdf2 = cdfnormal(0.5, 0, 5)' } { description: 'If plant weights have a normal distribution, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfnormal(weight, mean(weight), stddev(weight))' } { description: 'Same as above, but with lists' q: 'input mock name="plant-growth" \n| set @weights = pluck(weight)\n| set @P = cdfnormal(@weights, listmean(@weights), liststddev(@weights));' } ] related: ['function:pdfnormal', 'function:cdfuniform', 'function:cdfpoisson'] } { name: 'cdfpoisson' type: 'function' subtype: 'probability' syntax: [ 'cdfpoisson(:number)' 'cdfpoisson(:number, :lambda)' 'cdfpoisson(:list)' 'cdfpoisson(:list, :lambda)' ] description: [ 'Returns the Poisson cumulative distribution function of the given :number or :list, with default value of lambda=1.' 'If a :list is provided, the result will be a list with cdfpoisson() applied to each element.' ] examples: [ { q: 'set @cdf = cdfpoisson(3), @cdf2 = cdfpoisson(3, 4)' } { description: 'If plant weights have a normal distribution, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfpoisson(weight, mean(weight), stddev(weight))' } { description: 'Applying cdfpoisson() to a list' q: 'set @l = cdfpoisson([1,2,3,4,5,6,7], 2)' } ] related: ['function:pdfpoisson', 'function:cdfuniform', 'function:cdfnormal'] } { name: 'len' type: 'function' subtype: 'string' description: [ 'len() is an alias for length().' ] aliases: ['function:length'] } { name: 'substring' type: 'function' subtype: 'string' syntax: [ 'substring(:string, :start)' 'substring(:string, :start, :end)' ] description: [ 'Returns a substring of the given :string, beginning with the character at the :start index, and extending either to the end of the string, or to the character before the :end index.' 'The :start and :end indices are inclusive and exclusive, respectively. If the :end index is beyond the end of :string, the substring will extend to the end of the :string.' 'Returns null if :string is either null or not a string.' 'Do not confuse this function with substr(), which takes a :start index and a number of characters.' ] examples: [ { description: 'With start but no end' q: 'set @sub = substring("Parsec is cool!", 10)' } { description: 'With a start and end' q: 'set @sub = substring("Parsec is cool!", 10, 14)' } { description: 'Using indexof()' q: 'set @s = "Hello World", @sub = substring(@s, indexof(@s, "o"), indexof(@s, "r"))' } ] related: ['function:substr'] } { name: 'substr' type: 'function' subtype: 'string' syntax: [ 'substr(:string, :start)' 'substr(:string, :start, :length)' ] description: [ 'Returns a substring of the given :string, beginning with the character at the :start index, and extending either to the end of the string, or to the next :length number of characters.' 'The :start index is inclusive. If the :length extends beyond the end of :string, the substring will extend to the end of the :string.' 'Returns null if :string is either null or not a string.' 'Do not confuse this function with substring(), which takes a :start index and an :end index.' ] examples: [ { description: 'With start but no length' q: 'set @sub = substr("Parsec is cool!", 10)' } { description: 'With a start and length' q: 'set @sub = substr("Parsec is cool!", 10, 4)' } { description: 'Using indexof()' q: 'set @s = "Hello World", @sub = substr(@s, indexof(@s, "W"))' } ] related: ['function:substring', 'function:indexof'] } { name: 'indexof' type: 'function' subtype: 'string' syntax: [ 'indexof(:string, :value)' ] description: [ 'Returns the first index of :value in :string, if it exists. If :value is not found, it will return null.' 'If :value is not a string, it will be converted to a string automatically. This allows indexof() to find numbers in a string, for example.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @index = indexof("Parsec", "s")' } { q: 'set @s = "Hello World", @sub = substr(@s, indexof(@s, "W"))' } ] related: ['function:lastindexof'] } { name: 'lastindexof' type: 'function' subtype: 'string' syntax: [ 'lastindexof(:string, :value)' ] description: [ 'Returns the last index of :value in :string, if it exists. If :value is not found, it will return null.' 'If :value is not a string, it will be converted to a string automatically. This allows lastindexof() to find numbers in a string, for example.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @index = lastindexof("123,445,660.0", ",")' } { q: 'set @s = "Hello World", @sub = substr(@s, lastindexof(@s, "o"))' } ] related: ['function:indexof'] } { name: 'trim' type: 'function' subtype: 'string' syntax: ['trim(:string)'] returns: 'string' description: [ 'The trim() function removes whitespace from both ends of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = trim(" parsec\t ")' } ] related: ['function:ltrim', 'function:rtrim'] } { name: 'ltrim' type: 'function' subtype: 'string' syntax: ['ltrim(:string)'] returns: 'string' description: [ 'The ltrim() function removes whitespace from the left end of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = ltrim(" parsec")' } ] related: ['function:trim', 'function:rtrim'] } { name: 'rtrim' type: 'function' subtype: 'string' syntax: ['rtrim(:string)'] returns: 'string' description: [ 'The rtrim() function removes whitespace from the right end of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = rtrim("parsec ")' } ] related: ['function:trim', 'function:ltrim'] } { name: 'uppercase' type: 'function' subtype: 'string' syntax: ['uppercase(:string)'] returns: 'string' description: [ 'The uppercase() function returns its argument converted to uppercase.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = uppercase("parsec")' } ] related: ['function:lowercase'] } { name: 'lowercase' type: 'function' subtype: 'string' syntax: ['lowercase(:string)'] returns: 'string' description: [ 'The lowercase() function returns its argument converted to lowercase.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = lowercase("parsec")' } ] related: ['function:uppercase'] } { name: 'replace' type: 'function' subtype: 'string' syntax: ['replace(:string, :search, :replacement)'] returns: 'string' description: [ 'Replaces the first instance of :search in :string with :replacement.' 'If either :search or :replacement are not strings, they will be converted to strings automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @string = replace("aaabbbbccc", "a", "x")' } ] related: ['function:replaceall'] } { name: 'replaceall' type: 'function' subtype: 'string' syntax: ['replaceall(:string, :search, :replacement)'] returns: 'string' description: [ 'Replaces all instance of :search in :string with :replacement.' 'If either :search or :replacement are not strings, they will be converted to strings automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @string = replaceall("aaabbbbccc", "a", "x")' } ] related: ['function:replace'] } { name: 'startswith' type: 'function' subtype: 'string' syntax: ['startswith(:string, :search)'] returns: 'string' description: [ 'Returns true if :string begins with :search, else false.' 'If :search is not a string, it will be converted to a string automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @test = startswith("parsec", "p")' } ] related: ['function:endswith'] } { name: 'endswith' type: 'function' subtype: 'string' syntax: ['endswith(:string, :search)'] returns: 'string' description: [ 'Returns true if :string ends with :search, else false.' 'If :search is not a string, it will be converted to a string automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @test = endswith("parsec", "c")' } ] related: ['function:startswith'] } { name: 'join' type: 'function' subtype: 'string' syntax: [ 'join(:list)' 'join(:list, :separator)' ] returns: 'string' description: [ 'Returns a string of all elements in :list, concatenated together with an optional :separator between them.' 'Returns null if :list is either null or not a list.' ] examples: [ { q: 'set @string = join(["a", "b", "c"], ", ")' } { q: 'input mock | set @col1 = join(pluck(col1), "-")' } ] } { name: 'split' type: 'function' subtype: 'string' syntax: ['split(:string, :delimiter)'] returns: 'list' description: [ 'Splits a string into tokens using a delimiter and returns a list of the tokens. A regex can be given as :delimiter.' ] examples: [ { q: 'input mock | x = split("1,2,3", ",")' } { description: 'Using regex to match delimiters' q: 'set @phone = pop(split("(425)555-1234", "[^\d]"))' } ] } { name: 'urlencode' type: 'function' subtype: 'string' syntax: ['urlencode(:string)'] returns: 'string' description: [ 'Translates a string into application/x-www-form-urlencoded format.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = urlencode("x=1&y=2")' } ] related: ['function:urldecode'] } { name: 'urldecode' type: 'function' subtype: 'string' syntax: ['urldecode(:string)'] returns: 'string' description: [ 'Decodes a string encoded in the application/x-www-form-urlencoded format.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = urldecode("x%3D1%26y%3D2")' } ] related: ['function:urlencode'] } { name: 'base64encode' type: 'function' subtype: 'string' syntax: ['base64encode(:string)'] returns: 'string' description: [ 'Encodes a string into a base64 string representation.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = base64encode("hello world"), y = base64decode(x)' } ] related: ['function:base64decode'] } { name: 'base64decode' type: 'function' subtype: 'string' syntax: ['base64decode(:string)'] returns: 'string' description: [ 'Decodes a string from a base64-encoded string.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = base64encode("hello world"), y = base64decode(x)' } ] related: ['function:base64encode'] } { name: 'parsejson' type: 'function' subtype: 'parsing' syntax: [ 'parsejson(:string)' ] description: [ 'Parses a JSON string and returns the result. Any valid JSON data type may be returned, including lists, maps, strings, numbers, and booleans.' ] examples: [ { description: 'Parsing a string' q: 'input mock | x = parsejson(\'"my-json"\')' } { description: 'Parsing a list' q: 'input mock | list = parsejson("[" + col1 + "," + col2 + "," + col3 + "]")' } { description: 'Projecting a JSON list of maps as a new data set' q: 'project parsejson(\'[{ "x": 1, "y": 2 }, {"x": 3, "y": 4 }]\')' } ] related: ['function:jsonpath', 'function:parsecsv', 'function:parsexml'] } { name: 'parsecsv' type: 'function' subtype: 'parsing' syntax: [ 'parsecsv(:string)' 'parsecsv(:string, { delimiter: string, quote: string, eol: string })' ] description: [ 'Parses a CSV string and returns the result (list of maps).' ] examples: [ { description: 'Parsing CSV with default options' q: 'set @text="a,b,c\n1,2,3\n4,5,6\n7,8,9", @parsed = parsecsv(@text)' } { description: 'Using a custom end-of-line and delimiter' q: 'set @text="col1~col2~col3|1~2~3|4~5~6|7~8~9", @parsed = parsecsv(@text, { eol: "|", delimiter: "~" })' } { description: 'Parsing data without a header row' q: 'set @text="1,2,3\n4,5,6\n7,8,9", @parsed = parsecsv(@text, { headers: false })' } { description: 'Parsing a TSV string (tab-separated values)' q: 'set @text="col1\tcol2\tcol3|1\t2\t3|4\t5\t6|7\t8\t9", @parsed = parsecsv(@text, { eol: "|", delimiter: "\t" })' } ] related: ['function:parsejson', 'function:parsexml'] } { name: 'parsexml' type: 'function' subtype: 'parsing' syntax: [ 'parsexml(:string)' 'parsexml(:string, :xpath)' 'parsexml(:string, { xpath: string, raw: boolean, flatten: boolean })' ] description: [ 'Parses an XML string and returns the result (list of maps).' ] examples: [ { description: 'Without an XPath expression, parsing starts at the root element' q: 'input mock | xml = "<root>" + col1 + "</root>", parsed = parsexml(xml)' } { description: 'Attributes are parsed into columns' q: 'input mock | xml = \'<root q="xyz" s="abc">\' + col1 + \'</root>\', parsed = parsexml(xml)' } { description: 'By default, child elements are flattened.' q: 'input mock | xml = "<root><col1>" + col1 + "</col1><col2>" + col2 + "</col2></root>", parsed = parsexml(xml, "/root")' } { description: 'Repeated elements are parsed into multiple rows' q: 'input mock | xml = "<root><val>" + col1 + "</val><val>" + col2 + "</val></root>", parsed = parsexml(xml, "/root/val")' } { description: 'Hacker News' q: 'input http uri="http://news.ycombinator.com/rss" | project parsexml(first(body), "/rss/channel/item")' } ] related: ['function:parsecsv', 'function:parsejson'] } { name: 'jsonpath' type: 'function' subtype: 'parsing' syntax: [ 'jsonpath(:map-or-list, :string)' ] description: [ 'Applies a JsonPath expression to a map or list and returns the result. Any valid JSON data type may be returned, including lists, maps, strings, numbers, and booleans.' 'This function cannot be used on JSON strings. Use parsejson() beforehand to convert the strings into objects.' 'The http input type has a built-in option for using jsonpath().' 'JsonPath reference: http://goessner.net/articles/JsonPath/. For specific implementation reference, see: https://github.com/gga/json-path' ] examples: [ { description: 'Select a field' q: 'set @results = jsonpath({ numbers: [1, 2, 3] }, "$.numbers")' } { description: 'Select a field of all children' q: 'set @obj = { messages: [{from: "<EMAIL>"}, {from: "<EMAIL>"}, {from: "<EMAIL>"}] },\n @results = jsonpath(@obj, "$.messages[*].from")' } ] related: ['input:http', 'function:parsejson'] } { name: 'if' type: 'function' subtype: 'conditional' syntax: [ 'if(:predicate, :when-true)' 'if(:predicate, :when-true, :when-false)' ] description: [ 'Evaluates :predicate and, if true, returns :when-true. Else returns :when-false.' 'If the :when-false clause is omitted, null will be returned' ] examples: [ { q: 'input mock | x = if(col1 < 3, "less than three", "greater than three")' } ] } { name: 'case' type: 'function' subtype: 'conditional' syntax: [ 'case(:predicate1, :result1 [, :predicate2, :result2 ...])' ] description: [ 'Evalutes a series of test expression & result pairs from left to right. The first test expression that evaluates to true will cause its corresponding result expression to be returned. If no test expression evaluates to true, the function will return null.' 'If an odd number of arguments are provided, the last will be treated as an "else" clause, and returned in absense of any other successful test' ] examples: [ { description: 'With two test expressions' q: 'input mock | x = case(col3 == 3, "apples", col3 == 5, "oranges")' } { description: 'With an "else" clause' q: 'input mock | x = case(col1 == 1, "one", col1 == 2, "two", "else")' } { description: 'With a single test expression' q: 'input mock | greaterThanThree = case(col1 >= 3, true)' } ] } { name: 'coalesce' type: 'function' subtype: 'conditional' syntax: [ 'coalesce(:expression1 [, :expression2, ...])' ] description: [ 'Returns the first non-null expression in the argument list.' 'If all expressions are null, coalesce() returns null.' ] examples: [ { q: 'input mock | x = coalesce(null, null, 1)' } ] } { name: 'reverse' type: 'function' subtype: 'list' syntax: [ 'reverse(:string)' 'reverse(:list)' ] returns: 'string | list' description: [ 'Returns the characters in a string, or items in a list. Returns null for all other arguments.' ] examples: [ { description: 'Reversing a string' q: 'set @reversed = reverse("Parsec")' } { description: 'Reversing a list' q: 'set @reversed = reverse([1, 2, 3, 4])' } ] } { name: 'listmean' type: 'function' subtype: 'list' syntax: [ 'listmean(:list)' ] returns: 'number' description: [ 'Returns the arithmetic mean of the list elements in :list.' 'Throws an error if any of the list elements are non-numerical.' ] examples: [ { q: 'set @listmean = listmean([1, 2, 3, 4])' } ] aliases: ['function:lmean'] } { name: 'listmax' type: 'function' subtype: 'list' syntax: [ 'listmax(:list)' ] returns: 'number' description: [ 'Returns the element in :list with the maximal value of all elements.' 'Throws an error if any of the list elements are non-numerical, unless :list has only a single element, in which case that element is returned.' ] examples: [ { q: 'set @listmax = listmax([2, 10, 4, 8, 5])' } ] aliases: ['function:lmax'] } { name: 'listmin' type: 'function' subtype: 'list' syntax: [ 'listmin(:list)' ] returns: 'number' description: [ 'Returns the element in :list with the minimal value of all elements.' 'Throws an error if any of the list elements are non-numerical, unless :list has only a single element, in which case that element is returned.' ] examples: [ { q: 'set @listmin = listmin([2, 10, 4, 8, 5])' } ] aliases: ['function:lmin'] } { name: 'lmean' type: 'function' subtype: 'list' description: [ 'lmean() is an alias for listmean().' ] aliases: ['function:listmean'] } { name: 'lmax' type: 'function' subtype: 'list' description: [ 'lmax() is an alias for listmax().' ] aliases: ['function:listmax'] } { name: 'lmin' type: 'function' subtype: 'list' description: [ 'lmin() is an alias for listmin().' ] aliases: ['function:listmin'] } { name: 'liststddev' type: 'function' subtype: 'list' syntax: [ 'liststddev(:list)' ] returns: 'number' description: [ 'Returns the sample standard deviation of :list.' 'If the list is the complete population, use liststddevp() instead to calculate the population standard deviation.' ] examples: [ { q: 'set @liststddev = liststddev([2, 10, 4, 8, 5])' } ] related: ['function:liststddevp'] } { name: 'liststddevp' type: 'function' subtype: 'list' syntax: [ 'liststddevp(:list)' ] returns: 'number' description: [ 'Returns the population standard deviation of :list.' 'If the list is not the complete population, use liststddev() instead to calculate the sample standard deviation.' ] examples: [ { q: 'set @liststddevp = liststddevp([2, 10, 4, 8, 5])' } ] related: ['function:liststddev'] } { name: 'length' type: 'function' subtype: 'list' syntax: [ 'length(:string)' 'length(:list)' ] returns: 'number' description: [ 'Returns the number of characters in a string, or items in a list. Returns null for all other arguments.' ] examples: [ { description: 'Length of a string' q: 'set @length = length("Parsec")' } { description: 'Length of a list' q: 'set @length = length([1, 2, 3, 4])' } ] aliases: ['function:len'] } { name: 'peek' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'peek(:list)' ] description: [ 'Returns the first item in a list. To retrieve the last item of the list, use peeklast().' 'peek() on an empty list returns null.' ] examples: [ { q: 'set @first = peek([1,2,3])' } ] related: ['function:peeklast', 'function:pop', 'function:push'] } { name: 'peeklast' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'peeklast(:list)' ] description: [ 'Returns the last item in a list. To retrieve the first item of the list, use peek().' 'peeklast() on an empty list returns null.' ] examples: [ { q: 'set @last = peeklast([1,2,3])' } ] related: ['function:peek', 'function:pop', 'function:push'] } { name: 'pop' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'pop(:list)' ] description: [ 'Returns a list without the first item. To retrieve the first value of the list, use peek().' 'pop() on an empty list throws an error.' ] examples: [ { q: 'set @list = pop([1,2,3])' } ] related: ['function:peek', 'function:push'] } { name: 'push' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'push(:list, :value)' 'push(:list, :value, :value, ...)' ] description: [ 'Appends one or more values to the end of a list and returns the updated list.' ] examples: [ { description: 'One value' q: 'set @list = push([1, 2, 3], 4)' } { description: 'Two values' q: 'set @list = push([1, 2, 3], 4, 5)' } ] related: ['function:pop', 'function:concat'] } { name: 'concat' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'concat(:list, :list)' 'concat(:list, :list, :list, ...)' 'concat(:list, :value)' ] description: [ 'Concatenates one or more lists or values together, from left to right.' 'Non-list arguments will be converted into lists and concatenated.' ] examples: [ { description: 'Two lists' q: 'set @list = concat([1, 2, 3], [4, 5, 6])' } { description: 'Three lists' q: 'set @list = concat([1, 2, 3], [4, 5, 6], [7, 8, 9])' } { description: 'Lists and non-lists' q: 'set @list = concat([1, 2, 3], 4, 5, [6, 7])' } ] related: ['function:push'] } { name: 'contains' type: 'function' subtype: 'list' returns: 'boolean' syntax: ['contains(:list, :expr)', 'contains(:string, :expr)'] description: [ 'Returns true if :expr is contained as a member of :list, else false.' 'If :string is given instead of :list, it returns true if :expr is a substring of :string, else false. If necessary, :expr will be automatically converted to a string to perform the comparison.' ] examples: [ { q: 'input mock | set @list = [1, 2, 5] | test = contains(@list, col1)' } { q: 'input mock | str = "hello world", hasWorld = contains(str, "world")' } ] } { name: 'distinct' type: 'function' subtype: 'list' returns: 'list' syntax: ['distinct(:list)'] description: [ 'Returns a list of the elements of :list with duplicates removed.' 'distinct(null) returns null; same for any non-list argument.' ] examples: [ { q: 'input mock | set @list = [1, 1, 2, 3, 2, 3] | test = distinct(@list)' } ] } { name: 'flatten' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'flatten(:list)' ] description: [ 'Flattens a list of lists one level deep.' ] examples: [ { description: 'Two lists' q: 'set @list = flatten([[1, 2, 3], [4, 5, 6]])' } { description: 'Three lists' q: 'set @list = flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]])' } { description: 'Lists and non-lists' q: 'set @list = flatten([0, [1, 2, 3], 4, 5, [6, 7]])' } { description: 'Deeply-nested data' q: 'set @list = flatten([[["red", "blue"], ["apple", "orange"]], [["WA", "CA"], ["Seattle", "San Franscisco"]]])' } ] related: ['function:flattendeep'] } { name: 'flattendeep' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'flattendeep(:list)' ] description: [ 'Flattens a list of lists recursively.' ] examples: [ { description: 'Two lists' q: 'set @list = flattendeep([[1, 2, 3], [4, 5, 6]])' } { description: 'Lists and non-lists' q: 'set @list = flattendeep([0, [1, 2, 3], 4, 5, [6, 7]])' } { description: 'Deeply-nested data' q: 'set @list = flattendeep([[["WA", "OR", "AK"], ["CA", "AZ"]], [["IN", "IL"], ["GA", "TX"]]])' } ] related: ['function:flatten'] } { name: 'index' type: 'function' subtype: 'list' returns: 'any' syntax: [ 'index(:list, :index)' ] description: [ 'Returns the element of :list at the given 0-based :index.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), values = values(map), second = index(values, 1)' } ] } { name: 'range' type: 'function' subtype: 'list' syntax: [ 'range(start,end,step)' ] returns: 'list' description: [ 'Returns a list of numbers from start to end, by step. If only one argument is provided (end), start defaults to 0. If two arguments are provided (start,end), step defaults to 1. If step=0 it will remain the default of 1.' ] examples: [ { q: 'input mock | range = range(10)' } { q: 'input mock | range = range(-10, 10)' } { q: 'input mock | range = range(-10, 10, 2)' } ] } { name: 'get' type: 'function' subtype: 'map' syntax: [ 'get(:map, :key)' 'get(:map, :key, :default)' 'get(:map, [:key, ...])' 'get(:map, [:key, ...], :default)' ] returns: 'any' description: [ 'Retrieves the value for :key in :map. If a list of :keys is given, it will traverse nested maps by applying get() in a recursive fashion.' 'Returns null if :key is not found, or optionally :default if provided.' ] examples: [ { q: 'set @headers = {Accepts: "application/json"}, @accepts = get(@headers, "Accepts")' } { description: 'With a default value' q: 'set @headers = {Accepts: "application/json"}, @accepts = get(@headers, "Accepts")' } ] related: ['function:set', 'function:delete', 'function:merge'] } { name: 'set' type: 'function' subtype: 'map' syntax: [ 'set(:map, :key, :value)' 'set(:map, [:key, ...], :value)' ] returns: 'map' description: [ 'Sets the :value for :key in :map, and returns the modified map.' 'If a list of :keys is given, it will traverse nested maps for each :key, and set the value of the last :key to :value. Any missing keys will be initialized with empty maps. If a key exists but is not a map, an exception will be thrown.' ] examples: [ { q: 'set @headers = {},\n @headers = set(@headers, "Accept", "text/plain")\n @headers = set(@headers, "Content-Type", "application/xml")' } { description: 'Setting nested keys' q: 'set @req = {},\n @req = set(@req, ["headers", "Accept"], "text/plain")\n @req = set(@req, ["headers", "Content-Type"], "application/xml")' } ] related: ['function:get', 'function:delete', 'function:merge'] } { name: 'delete' type: 'function' subtype: 'map' syntax: [ 'delete(:map, :key)' 'delete(:map, [:key, ...])' ] returns: 'map' description: [ 'Deletes the value for :key in :map, and returns the modified map.' 'If a list of :keys is given, it will traverse nested maps and for each :key, and delete the last :key. Any maps which were made empty will be removed.' ] examples: [ { q: 'set @headers = {"Accept": "application/json", "Content-Type": "application/json"},\n @updated = delete(@headers, "Accept")' } { description: 'Deleting a nested key' q: 'set @req = {headers: {"Accept": "application/json", "Content-Type": "application/json"}},\n @updated = delete(@req, ["headers", "Accept"])' } ] related: ['function:get', 'function:set', 'function:merge'] } { name: 'merge' type: 'function' subtype: 'map' syntax: [ 'merge(:map, ...)' ] returns: 'map' description: [ 'Returns a map created by merging the keys of each argument :map together, with subsequent maps overwriting keys of previous maps.' 'Any number of maps can be merged together. Any non-map arguments will be ignored.' ] examples: [ { q: 'set @headers = merge({"Content-Type": "application/json", "Accept-Language": "en-US,en;q=0.8"}, {"Content-Length": 100})' } ] related: ['function:get', 'function:set', 'function:delete', 'function:merge'] } { name: 'keys' type: 'function' subtype: 'map' syntax: [ 'keys(:map)' ] returns: 'list' description: [ 'Returns a list of the keys in :map.' 'keys(null) returns null.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), keys = keys(map)' } ] related: ['function:values'] } { name: 'values' type: 'function' subtype: 'map' syntax: [ 'values(:map)' ] returns: 'list' description: [ 'Returns a list of the values in :map.' 'values(null) returns null.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), values = values(map)' } ] related: ['function:keys'] } { name: 'adler32' type: 'function' subtype: 'digest' returns: 'string' syntax: ['adler32(:string)'] description: ['Computes the Adler-32 checksum of :string'] examples: [ { q: 'set @digest = adler32("hello world")' } ] related: ['function:sha256', 'function:sha1', 'function:sha512'] } { name: 'crc32' type: 'function' subtype: 'digest' returns: 'string' syntax: ['crc32(:string)'] description: ['Computes the CRC-32 cyclic redundancy check of :string'] examples: [ { q: 'set @digest = crc32("hello world")' } ] related: ['function:adler32', 'function:md5'] } { name: 'gost' type: 'function' subtype: 'digest' returns: 'string' syntax: ['gost(:string)'] description: ['Computes the GOST R 34.11-94 hash of :string'] examples: [ { q: 'set @digest = gost("hello world")' } ] related: ['function:hmac_gost', 'function:ripemd128', 'function:sha1'] } { name: 'hmac_gost' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_gost(:string, :secret)'] description: ['Computes the HMAC of :string using the GOST R 34.11-94 hash and :secret'] examples: [ { q: 'set @digest = hmac_gost("hello world", "secret")' } ] related: ['function:gost', 'function:ripemd128'] } { name: 'md5' type: 'function' subtype: 'digest' returns: 'string' syntax: ['md5(:string)'] description: ['Computes the MD5 hash of :string'] examples: [ { q: 'set @digest = md5("hello world")' } ] related: ['function:hmac_md5', 'function:sha256', 'function:sha1', 'function:sha512'] } { name: 'hmac_md5' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_md5(:string, :secret)'] description: ['Computes the HMAC of :string using the MD5 hash and :secret'] examples: [ { q: 'set @digest = hmac_md5("hello world", "secret")' } ] related: ['function:md5', 'function:sha256', 'function:sha1', 'function:sha512'] } { name: 'ripemd128' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd128(:string)'] description: ['Computes the RIPEMD-128 hash of :string'] examples: [ { q: 'set @digest = ripemd128("hello world")' } ] related: ['function:hmac_ripemd128', 'function:gost', 'function:ripemd256', 'function:ripemd320', 'function:sha1'] } { name: 'hmac_ripemd128' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd128(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-128 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd128("hello world", "secret")' } ] related: ['function:ripemd128', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'ripemd256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd256(:string)'] description: ['Computes the RIPEMD-256 hash of :string'] examples: [ { q: 'set @digest = ripemd256("hello world")' } ] related: ['function:hmac_ripemd256', 'function:gost', 'function:ripemd128', 'function:ripemd320', 'function:sha256'] } { name: 'hmac_ripemd256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd256(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd256("hello world", "secret")' } ] related: ['function:ripemd256', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'ripemd320' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd320(:string)'] description: ['Computes the RIPEMD-320 hash of :string'] examples: [ { q: 'set @digest = ripemd320("hello world")' } ] related: ['function:hmac_ripemd320', 'function:gost', 'function:ripemd128', 'function:ripemd256', 'function:sha384'] } { name: 'hmac_ripemd320' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd320(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-320 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd320("hello world", "secret")' } ] related: ['function:ripemd256', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'sha1' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha1(:string)'] description: ['Computes the SHA-1 hash of :string'] examples: [ { q: 'set @digest = sha1("hello world")' } ] related: ['function:hmac_sha1', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'hmac_sha1' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha1(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-1 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha1("hello world", "secret")' } ] related: ['function:sha1', 'function:sha512', 'function:md5'] } { name: 'sha3_224' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_224(:string)'] description: ['Computes the SHA-3-224 hash of :string'] examples: [ { q: 'set @digest = sha3_224("hello world")' } ] related: ['function:hmac_sha3_224', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_224' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_224(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-224 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_224("hello world", "secret")' } ] related: ['function:sha3_224', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_256(:string)'] description: ['Computes the SHA-3-256 hash of :string'] examples: [ { q: 'set @digest = sha3_256("hello world")' } ] related: ['function:hmac_sha3_256', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_256(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_256("hello world", "secret")' } ] related: ['function:sha3_256', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_384' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_384(:string)'] description: ['Computes the SHA-3-384 hash of :string'] examples: [ { q: 'set @digest = sha3_384("hello world")' } ] related: ['function:hmac_sha3_384', 'function:sha1', 'function:sha384', 'function:md5'] } { name: 'hmac_sha3_384' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_384(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-384 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_384("hello world", "secret")' } ] related: ['function:sha3_384', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_512(:string)'] description: ['Computes the SHA-3-224 hash of :string'] examples: [ { q: 'set @digest = sha3_512("hello world")' } ] related: ['function:hmac_sha3_512', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_512(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-512 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_512("hello world", "secret")' } ] related: ['function:sha3_512', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha256(:string)'] description: ['Computes the SHA-256 hash of :string'] examples: [ { q: 'set @digest = sha256("hello world")' } ] related: ['function:hmac_sha256', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'hmac_sha256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha256(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha256("hello world", "secret")' } ] related: ['function:sha256', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'sha512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha512(:string)'] description: ['Computes the SHA-512 hash of :string'] examples: [ { q: 'set @digest = sha512("hello world")' } ] related: ['function:hmac_sha512', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha512(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-512 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha512("hello world", "secret")' } ] related: ['function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'siphash' type: 'function' subtype: 'digest' returns: 'string' syntax: ['siphash(:string, :secret)'] description: [ 'Computes the HMAC of :string using the SipHash-2-4 hash and a 128-bit :secret.' ':secret must be 128-bits, e.g. a 16-character string.' ] examples: [ { q: 'set @digest = siphash("hello world", "abcdefghijklmnop")' } ] related: ['function:siphash48', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'siphash48' type: 'function' subtype: 'digest' returns: 'string' syntax: ['siphash48(:string, :secret)'] description: [ 'Computes the HMAC of :string using the SipHash-4-8 hash and a 128-bit :secret.' ':secret must be 128-bits, e.g. a 16-character string.' ] examples: [ { q: 'set @digest = siphash48("hello world", "abcdefghijklmnop")' } ] related: ['function:siphash', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'tiger' type: 'function' subtype: 'digest' returns: 'string' syntax: ['tiger(:string)'] description: ['Computes the Tiger-192 hash of :string'] examples: [ { q: 'set @digest = tiger("hello world")' } ] related: ['function:hmac_tiger', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_tiger' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_tiger(:string, :secret)'] description: ['Computes the HMAC of :string using the Tiger-192 hash and :secret'] examples: [ { q: 'set @digest = hmac_tiger("hello world", "secret")' } ] related: ['function:tiger', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'whirlpool' type: 'function' subtype: 'digest' returns: 'string' syntax: ['whirlpool(:string)'] description: ['Computes the Whirlpool hash of :string'] examples: [ { q: 'set @digest = whirlpool("hello world")' } ] related: ['function:hmac_whirlpool', 'function:tiger', 'function:sha256', 'function:md5'] } { name: 'hmac_whirlpool' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_whirlpool(:string, :secret)'] description: ['Computes the HMAC of :string using the Whirlpool hash and :secret'] examples: [ { q: 'set @digest = hmac_whirlpool("hello world", "secret")' } ] related: ['function:whirlpool', 'function:hmac_tiger', 'function:hmac_sha1', 'function:md5'] } { name: 'random' type: 'function' subtype: 'math' syntax: [ 'random()' 'random(:upperBound)' 'random(:lowerBound, :upperBound)' ] returns: 'double' description: [ 'Returns a random number between 0 inclusive and 1 exclusive, when no arguments are provided.' 'When called with a single argument, returns a random number between 0 inclusive and :upperBound, exclusive.' 'When called with two arguments, returns a random number between :lowerBound inclusive and :upperBound, exclusive.' ] examples: [ { description: 'Random number between 0 and 1 (exclusive)' q: 'set @rand = random()' } { description: 'Random number between 0 and 10 (exclusive)' q: 'set @rand = floor(random(10))' } { description: 'Random number between 1 and 10 (exclusive)' q: 'set @rand = floor(random(1,10))' } ] } { name: 'rank' type: 'function' syntax: [ 'rank()' ] description: [ 'Returns the current row number in the dataset. The rownumber statement is faster for the general case, but as a function this may be more versatile.' 'Can be used in the assignment statement, stats statement, and pivot statement. Cannot be used in a group-by expression.' ] examples: [ { q: 'input mock | x = rank()' } { q: 'input mock | name = "row " + (rank() + 1)' } { q: 'input mock name="chick-weight" | stats avgWeight = mean(weight), rank=rank() by Chick' } ] related: ['statement:rownumber'] } { name: 'hostname' type: 'function' syntax: [ 'hostname()' ] description: [ 'Returns the current hostname of the Parsec server.' ] examples: [ { q: 'set @hostname = hostname()' } ] related: ['function:ip'] } { name: 'ip' type: 'function' syntax: [ 'ip()' ] description: [ 'Returns the current IP address of the Parsec server.' ] examples: [ { q: 'set @ip = ip()' } ] related: ['function:hostname'] } { name: 'runtime' type: 'function' syntax: [ 'runtime()' ] description: [ 'Returns information about Parsec\'s JVM runtime.' ] examples: [ { q: 'set @runtime = runtime()' } { q: 'project [runtime()]' } ] related: ['function:os'] } { name: 'os' type: 'function' syntax: [ 'os()' ] description: [ 'Returns operating-system level information.' ] examples: [ { q: 'set @os = os()' } { q: 'project [os()]' } ] related: ['function:runtime'] } { name: 'now' type: 'function' subtype: 'date and time' syntax: [ 'now()' ] description: [ 'Returns the current date/time in the time zone of the server.' ] examples: [ { q: 'set @now = now()' } ] related: ['function:nowutc', 'function:today', 'function:yesterday', 'function:tomorrow'] } { name: 'nowutc' type: 'function' subtype: 'date and time' syntax: [ 'nowutc()' ] description: [ 'Returns the current date/time in the UTC time zone.' ] examples: [ { q: 'set @nowutc = nowutc()' } ] related: ['function:nowutc', 'function:todayutc', 'function:yesterdayutc', 'function:tomorrowutc'] } { name: 'today' type: 'function' subtype: 'date and time' syntax: [ 'today()' ] description: [ 'Returns the date/time of midnight of the current day, in the time zone of the server.' ] examples: [ { q: 'set @today = today()' } ] related: ['function:todayutc', 'function:now', 'function:yesterday', 'function:tomorrow'] } { name: 'todayutc' type: 'function' subtype: 'date and time' syntax: [ 'todayutc()' ] description: [ 'Returns the date/time of midnight of the current day, in the UTC time zone.' ] examples: [ { q: 'set @todayutc = todayutc()' } ] related: ['function:today', 'function:nowutc', 'function:yesterdayutc', 'function:tomorrowutc'] } { name: 'yesterday' type: 'function' subtype: 'date and time' syntax: [ 'yesterday()' ] description: [ 'Returns the date/time of midnight yesterday, in the time zone of the server.' ] examples: [ { q: 'set @yesterday = yesterday()' } ] related: ['function:yesterdayutc', 'function:now', 'function:today', 'function:tomorrow'] } { name: 'yesterdayutc' type: 'function' subtype: 'date and time' syntax: [ 'yesterdayutc()' ] description: [ 'Returns the date/time of midnight yesterday, in the UTC time zone.' ] examples: [ { q: 'set @yesterdayutc = yesterdayutc()' } ] related: ['function:yesterday', 'function:todayutc', 'function:nowutc', 'function:tomorrowutc'] } { name: 'tomorrow' type: 'function' subtype: 'date and time' syntax: [ 'tomorrow()' ] description: [ 'Returns the date/time of midnight tomorrow, in the time zone of the server.' ] examples: [ { q: 'set @tomorrow = tomorrow()' } ] related: ['function:todayutc', 'function:now', 'function:yesterday', 'function:tomorrow'] } { name: 'tomorrowutc' type: 'function' subtype: 'date and time' syntax: [ 'tomorrowutc()' ] description: [ 'Returns the date/time of midnight tomorrow, in the UTC time zone.' ] examples: [ { q: 'set @tomorrowutc = tomorrowutc()' } ] related: ['function:tomorrow', 'function:nowutc', 'function:yesterdayutc', 'function:todayutc'] } { name: 'tolocaltime' type: 'function' subtype: 'date and time' syntax: [ 'tolocaltime(:datetime)' ] description: [ 'Converts a date/time to the local time zone of the server.' ] examples: [ { q: 'set @nowutc = nowutc(), @nowlocal = tolocaltime(@nowutc)' } ] related: ['function:toutctime', 'function:totimezone'] } { name: 'toutctime' type: 'function' subtype: 'date and time' syntax: [ 'toutctime(:datetime)' ] description: [ 'Converts a date/time to the UTC time zone.' ] examples: [ { q: 'set @now = now(), @nowutc = toutctime(@now)' } ] related: ['function:tolocaltime', 'function:totimezone'] } { name: 'totimezone' type: 'function' subtype: 'date and time' syntax: [ 'totimezone(:datetime, :timezone)' ] description: [ 'Converts a date/time to another time zone. :timezone must be a long-form time zone, e.g. "America/Matamoros".' 'A list of all valid time zones can be retrieved using timezones().' ] examples: [ { q: 'set @southpole = totimezone(now(), "Antarctica/South_Pole"), @str = tostring(@southpole)' } ] related: ['function:tolocaltime', 'function:totimezone', 'function:timezones'] } { name: 'timezones' type: 'function' subtype: 'date and time' syntax: ['timezones()'] description: [ 'Returns a list of all available time zones, for use with totimezone()' ] examples: [ { q: 'set @tz = timezones()' } { description: 'Project as dataset' q: 'project timezones()' } ] related: ['function:totimezone'] } { name: 'toepoch' type: 'function' subtype: 'date and time' syntax: ['toepoch(:datetime)'] returns: 'number' description: [ 'Converts :datetime into the number of seconds after the Unix epoch.' ] examples: [ q: 'set @timestamp = toepoch(now())' ] related: ['function:toepochmillis'] } { name: 'toepochmillis' type: 'function' subtype: 'date and time' syntax: ['toepochmillis(:datetime)'] returns: 'number' description: [ 'Converts :datetime into the number of milliseconds after the Unix epoch.' ] examples: [ q: 'set @timestamp = toepochmillis(now())' ] related: ['function:toepoch'] } { name: 'startofminute' type: 'function' subtype: 'date and time' syntax: ['startofminute(:datetime)'] returns: 'datetime' description: [ 'Returns :datetime with the number of seconds and milliseconds zeroed.' ] examples: [ q: 'set @time = startofminute(now())' ] related: ['function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofhour' type: 'function' subtype: 'date and time' syntax: ['startofhour(:datetime)'] returns: 'datetime' description: [ 'Returns :datetime with the number of minutes, seconds, and milliseconds zeroed.' ] examples: [ q: 'set @time = startofhour(now())' ] related: ['function:startofminute', 'function:startofday', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofday' type: 'function' subtype: 'date and time' syntax: ['startofday(:datetime)'] returns: 'datetime' description: [ 'Returns midnight on the same day as :datetime.' ] examples: [ q: 'set @time = startofday(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofweek' type: 'function' subtype: 'date and time' syntax: ['startofweek(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the week, in the same week as :datetime.' ] examples: [ q: 'set @time = startofweek(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofmonth', 'function:startofyear'] } { name: 'startofmonth' type: 'function' subtype: 'date and time' syntax: ['startofmonth(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the month, in the same month as :datetime.' ] examples: [ q: 'set @time = startofmonth(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofyear'] } { name: 'startofyear' type: 'function' subtype: 'date and time' syntax: ['startofyear(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the year, in the same year as :datetime.' ] examples: [ q: 'set @time = startofyear(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofmonth'] } { name: 'millisecond' type: 'function' subtype: 'date and time' syntax: ['millisecond(:datetime)'] returns: 'number' description: [ 'Returns the millisecond of second component of the given :datetime.' ] examples: [ q: 'set @millis = millisecond(now())' ] related: ['function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'millisecondofday' type: 'function' subtype: 'date and time' syntax: ['millisecondofday(:datetime)'] returns: 'number' description: [ 'Returns the number of milliseconds elapsed since midnight in :datetime.' ] examples: [ q: 'set @millis = millisecondofday(now())' ] related: ['function:millisecond', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'second' type: 'function' subtype: 'date and time' syntax: ['second(:datetime)'] returns: 'number' description: [ 'Returns the second of minute component of the given :datetime.' ] examples: [ q: 'set @seconds = second(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'secondofday' type: 'function' subtype: 'date and time' syntax: ['secondofday(:datetime)'] returns: 'number' description: [ 'Returns the number of seconds elapsed since midnight in :datetime.' ] examples: [ q: 'set @seconds = secondofday(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'minute' type: 'function' subtype: 'date and time' syntax: ['minute(:datetime)'] returns: 'number' description: [ 'Returns the minute of hour component of the given :datetime.' ] examples: [ q: 'set @minutes = minute(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'minuteofday' type: 'function' subtype: 'date and time' syntax: ['minuteofday(:datetime)'] returns: 'number' description: [ 'Returns the number of minutes elapsed since midnight in :datetime.' ] examples: [ q: 'set @minutes = minuteofday(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'hour' type: 'function' subtype: 'date and time' syntax: ['hour(:datetime)'] returns: 'number' description: [ 'Returns the hour of day component of the given :datetime.' ] examples: [ q: 'set @hours = hour(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'day' type: 'function' subtype: 'date and time' syntax: ['day(:datetime)'] returns: 'number' description: [ 'Returns the day of month component of the given :datetime.' ] examples: [ q: 'set @day = day(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'dayofweek' type: 'function' subtype: 'date and time' syntax: ['dayofweek(:datetime)'] returns: 'number' description: [ 'Returns the day of week component of the given date/time, where Monday is 1 and Sunday is 7.' ] examples: [ q: 'set @day = dayofweek(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'dayofyear' type: 'function' subtype: 'date and time' syntax: ['dayofyear(:datetime)'] returns: 'number' description: [ 'Returns the number of days elapsed since the beginning of the year, including the current day of :datetime.' ] examples: [ q: 'set @days = dayofyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'weekyear' type: 'function' subtype: 'date and time' syntax: ['weekyear(:datetime)'] returns: 'number' description: [ 'Returns the week year for a given date. In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year. The weekyear allows you to query the effective year for that day.' 'The weekyear is used by the function weekofweekyear().' ] examples: [ q: 'set @weekyear = weekyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'weekofweekyear' type: 'function' subtype: 'date and time' syntax: ['weekofweekyear(:datetime)'] returns: 'number' description: [ 'Given a date, returns the number of weeks elapsed since the beginning of the weekyear. In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year.' 'The function weekyear() gives the current weekyear for a given date.' ] examples: [ q: 'set @weeks = weekofweekyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:month', 'function:year'] } { name: 'month' type: 'function' subtype: 'date and time' syntax: ['month(:datetime)'] returns: 'number' description: [ 'Returns the month component of the given :datetime.' ] examples: [ q: 'set @months = month(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:year'] } { name: 'year' type: 'function' subtype: 'date and time' syntax: ['year(:datetime)'] returns: 'number' description: [ 'Returns the year of the given :datetime.' ] examples: [ q: 'set @years = year(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month'] } { name: 'adddays' type: 'function' subtype: 'date and time' } { name: 'addhours' type: 'function' subtype: 'date and time' } { name: 'addmilliseconds' type: 'function' subtype: 'date and time' } { name: 'addminutes' type: 'function' subtype: 'date and time' } { name: 'addmonths' type: 'function' subtype: 'date and time' } { name: 'addseconds' type: 'function' subtype: 'date and time' } { name: 'addweeks' type: 'function' subtype: 'date and time' } { name: 'addyears' type: 'function' subtype: 'date and time' } { name: 'minusdays' type: 'function' subtype: 'date and time' } { name: 'minushours' type: 'function' subtype: 'date and time' } { name: 'minusmilliseconds' type: 'function' subtype: 'date and time' } { name: 'minusminutes' type: 'function' subtype: 'date and time' } { name: 'minusmonths' type: 'function' subtype: 'date and time' } { name: 'minusseconds' type: 'function' subtype: 'date and time' } { name: 'minusweeks' type: 'function' subtype: 'date and time' } { name: 'minusyears' type: 'function' subtype: 'date and time' } { name: 'interval' type: 'function' subtype: 'date and time' } { name: 'inmillis' type: 'function' subtype: 'date and time' } { name: 'inseconds' type: 'function' subtype: 'date and time' } { name: 'inminutes' type: 'function' subtype: 'date and time' } { name: 'inhours' type: 'function' subtype: 'date and time' } { name: 'indays' type: 'function' subtype: 'date and time' } { name: 'inweeks' type: 'function' subtype: 'date and time' } { name: 'inmonths' type: 'function' subtype: 'date and time' } { name: 'inyears' type: 'function' subtype: 'date and time' } { name: 'period' type: 'function' subtype: 'date and time' syntax: [ 'period(:value, :name)' ] description: [ 'Creates a time period representing some number (:value) of a particular time unit (:name).' 'The following units are supported: milliseconds, seconds, minutes, hours, days, weeks, months, years. Both singular/plural forms, as well as some short forms (min, sec) are accepted.' 'The bucket() function uses periods to group data.' ] examples: [ { q: 'set @fivemin = period(5, "minutes")' } { q: 'input mock | mins = period(col1, "minutes")' } { q: 'input mock | onehour = period(1, "hours")' } ], related: ['function:bucket'] } { name: 'earliest' type: 'function' subtype: 'date and time' syntax: [ 'earliest(:datetime, :datetime)' ] description: [ 'Given two dates, returns the date which occurs first chronologically.' ] examples: [ { q: 'set @firstOccurrence = earliest(todate("2015-04-20"), todate("2016-06-01"))' } { q: 'set @earliest = earliest(1462009645000, 1461999645000)' } ] related: ['function:latest'] } { name: 'latest' type: 'function' subtype: 'date and time' syntax: [ 'latest(:datetime, :datetime)' ] description: [ 'Given two dates, returns the date which occurs last chronologically.' ] examples: [ { q: 'set @lastOccurrence = latest(todate("2015-04-20"), todate("2016-06-01"))' } { q: 'set @latest = latest(1462009645000, 1461999645000)' } ] related: ['function:earliest'] } { name: 'isbetween' type: 'function' subtype: 'date and time' syntax: [ 'isbetween(:datetime, :start, :end)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after :start and before or at :end. In other words, the function returns true if :datetime is within the inclusive interval between :start and :end.' ] examples: [ { q: 'set @test = isbetween(now(), minusminutes(now(), 1), addminutes(now(), 1))' } ] } { name: 'istoday' type: 'function' subtype: 'date and time' syntax: [ 'istoday(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current day, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = istoday(now())' } ] related: ['function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'istomorrow' type: 'function' subtype: 'date and time' syntax: [ 'istomorrow(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of tomorrow, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = istomorrow(now())' } ] related: ['function:istoday', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isyesterday' type: 'function' subtype: 'date and time' syntax: [ 'isyesterday(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of yesterday, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isyesterday(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isthisweek' type: 'function' subtype: 'date and time' syntax: [ 'isthisweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isthisweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isnextweek' type: 'function' subtype: 'date and time' syntax: [ 'isnextweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the week after the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isnextweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'islastweek' type: 'function' subtype: 'date and time' syntax: [ 'islastweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the week prior to the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = islastweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isthismonth' type: 'function' subtype: 'date and time' syntax: [ 'isthismonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isthismonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isnextmonth' type: 'function' subtype: 'date and time' syntax: [ 'isnextmonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the month after the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isnextmonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth'] } { name: 'islastmonth' type: 'function' subtype: 'date and time' syntax: [ 'islastmonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the month prior to the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = islastmonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:isnextmonth'] } { name: 'bucket' type: 'function' syntax: [ 'bucket(:expr, :buckets)' ] description: [ 'Assigns buckets to :expr based on the 2nd argument, and returns the bucket for each value. Buckets can be numerical or time-based. The start of the bucket will be returned.' 'Numerical buckets are determined by dividing the set of real numbers into equivalent ranges of a given width. Numbers are then located in the buckets according to their value. For example, bucketing by 5 will yield buckets starting at 0, 5, 10, 15, etc. Numerical buckets can be fractions or decimals.' 'Time-based buckets are determined by dividing the time line into equivalent ranges of a given interval. The :buckets argument must be given as a Period, created by the period() function. For example, bucketing by a period of 5 minutes will yield buckets starting at 12:00, 12:05, 12:10, etc. Buckets are always aligned on the hour.' ] examples: [ { q: 'input mock | buckets = bucket(col1, 2)' } { description: 'Bucket by every 4th number and calculate an average per bucket' q: 'input mock name="chick-weight"\n| timebucket = bucket(Time, 4)\n| stats avgWeight = avg(weight) by timebucket\n| sort timebucket' } { description: 'Bucket by 5 minute periods' q: 'input mock n=20\n| t = minusMinutes(now(), col1)\n| tbuckets = bucket(t, period(5, "minutes"))' } ], related: ['function:period'] } { name: 'apply' type: 'function' subtype: 'functional' syntax: [ 'apply(:function, :args, ...)' ] description: [ 'Invokes a first-order :function with any number of arguments. Commonly used to execute functions stored in variables.' 'Using the def statement will avoid the need to call apply(), as the function will be mapped to a user-defined function name.' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @cube = (n) -> n*n*n, @cube9 = apply(@cube, 9)' } { q: 'input mock name="thurstone"\n| set @differenceFromAvg = (n, avg) -> abs(n - avg)\n| set @avgX = avg(x), @avgY = avg(y)\n| diffX = apply(@differenceFromAvg, x, @avgX)\n| diffY = apply(@differenceFromAvg, y, @avgY)' } ] related: ['symbol:->:function'] } { name: 'map' type: 'function' subtype: 'functional' syntax: [ 'map(:function, :list)' ] returns: 'list' description: [ 'Applies a first-order :function to each item in :list, and returns a list of the return values.' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @x = map(n -> n / 100, [10, 20, 30, 40, 50])' } { description: 'Using a function in a variable' q: 'set @percent = n -> n / 100,\n@x = map(@percent, [10, 20, 30, 40, 50])' } { description: 'Generating a dataset using map() and range()' q: 'project map((x) -> {`x`: x, `square`: x^2, `cube`: x^3, `fourth-power`: x^4}, range(1,10))' } ] related: ['symbol:->:function', 'function:mapcat', 'function:mapvalues', 'function:filter'] } { name: 'mapcat' type: 'function' subtype: 'functional' syntax: [ 'mapcat(:function, :list)' ] returns: 'list' description: [ 'Applies a first-order :function to each item in :list, and applies concat() over the return values.' 'Typically :function should return a list, otherwise it works identically to map().' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @x = mapcat(n -> [n, n^2], [10, 20, 30, 40, 50])' } { description: 'Using a function in a variable' q: 'set @percent = n -> n / 100,\n@x = mapcat(@percent, [10, 20, 30, 40, 50])' } { description: 'Generating a set of ranges using mapcat() and range()' q: 'project mapcat((x) -> range(x, x + 5), [0, 10, 20, 30])' } ] related: ['symbol:->:function', 'function:map'] } { name: 'mapvalues' type: 'function' subtype: 'functional' syntax: [ 'mapvalues(:function, :map)' ] returns: 'map' description: [ 'Applies a first-order :function to the value of each key in :map, and returns a new map containing the keys and their return values.' 'Throws an exception if the first argument is not a function.' ] examples: [ { description: 'Increment each value in the map' q: 'set @map = mapvalues(n -> n+1, { x: 1, y: 2, z: 3 })' } { description: 'Using a function in a variable' q: 'set @inc = n -> n+1,\n@map = mapvalues(@inc, { x: 1, y: 2, z: 3 })' } ] related: ['symbol:->:function', 'function:map'] } { name: 'filter' type: 'function' subtype: 'functional' syntax: [ 'filter(:function, :list)' ] returns: 'list' description: [ 'Returns a list of items in :list for which the first-order :function returns true.' 'Throws an exception if the first argument is not a function.' ] examples: [ { description: 'Filtering for even numbers' q: 'set @x = filter(n -> n mod 2 == 0, range(1,20))' } { description: 'Using a function in a variable' q: 'set @isEven = n -> n mod 2 == 0,\n @x = filter(@isEven, range(1,20))' } ] related: ['symbol:->:function', 'function:map'] } { name: 'exec' type: 'function' subtype: 'execution' syntax: [ 'exec(:query)' 'exec(:query, { dataset: ":dataset-name" })' 'exec(:query, { variable: ":variable-name" })' 'exec(:query, { context: true })' ] returns: 'any' description: [ 'Executes a Parsec query contained in :query, and returns the resulting context object. Any parsing, execution, or type errors will return a context with errors, rather than throwing an exception.' 'A map of :options can be provided to return a specific part of the result, rather than the entire context. Either a single dataset or a single variable can be named in the :options, causing that dataset or variable value to be returned. If the dataset or variable is not found, null is returned. Caution: if an error occurs, the dataset or variable may not exist (depending on when the error occurs), so null may also be returned.' 'By default, uses a new isolated query context. However if the context option is set to true, the current parent context will be used to execute :query, allowing access to variables and datasets. Note this is read-only access; the parent context cannot be modified from within exec().' 'Returns null if :query is null.' ] examples: [ { q: 'set @x = exec("input mock")' } { description: 'Using options to select only the default dataset' q: 'set @dataset = exec("input mock", { dataset: "0" })' } { description: 'Using options to select a specific named dataset' q: 'set @dataset = exec("input mock | output name=\'mock\'; input mock name=\'chick-weight\'", { dataset: "mock" })' } { description: 'Using options to return only the value of a specific variable' q: 'set @avg = exec("input mock | set @avg=avg(col1+col2)", { variable: "@avg" })' } { description: 'Looking at the performance of a query ran with exec()' q: 'set @performance = get(exec("input mock"), "performance")' } { description: 'Using a shared context to access variables' q: 'set @price = 49.95,\n @tax = 9.2%,\n @total = exec("set @total = round(@price * (1 + @tax), 2)", { variable: "@total", context: true })' } ] } { name: 'mock' type: 'input' syntax: [ 'input mock' 'input mock n=:number' 'input mock name=:name' 'input mock name=:name incanterHome=:path' ] description: [ 'The mock input type is for testing and experimental purposes. By default, it returns a fixed dataset of 5 rows and 4 columns. If "n" is provided, the mock dataset will contain n-number of rows, and an additional column.' 'There are also specific test datasets included, which can be loaded using the "name" option. The available named datasets are: "iris", "cars", "survey", "us-arrests", "flow-meter", "co2", "chick-weight", "plant-growth", "pontius", "filip", "longely", "chwirut", "thurstone", "austres", "hair-eye-color", "airline-passengers", "math-prog", "iran-election".' 'By default, test datasets are loaded from GitHub. In order to load them from the local machine, download the Incanter source code (https://github.com/incanter/incanter), and provide the root directory as incanterHome.' ] examples: [ { description: 'Loading mock data' q: 'input mock' } { description: 'Loading lots of mock data' q: 'input mock n=100' } { description: 'Loading a named mock dataset' q: 'input mock name="chick-weight"' } { description: 'Loading a named dataset from disk (requires additional download)' q: 'input mock name="chick-weight" incanterHome="~/Downloads/incanter-master"' } ] related: ['statement:input'] } { name: 'datastore' type: 'input' syntax: [ 'input datastore name=:name' ] description: [ 'The datastore input type retrieves and loads datasets from the datastore in the current execution context. Datasets may have been written previously to the datastore using the temp or output statements.' ] examples: [ { description: 'Storing and loading a dataset' q: 'input mock | output name="ds1"; input datastore name="ds1"' } { description: 'Storing and loading a temporary dataset' q: 'input mock | temp ds2; input datastore name="ds2"' } ] related: ['statement:input'] } { name: 'jdbc' type: 'input' syntax: [ 'input jdbc uri=":uri" query=":query"' 'input jdbc uri=":uri" [user | username]=":username" password=":<PASSWORD>" query=":query"' 'input jdbc uri=":uri" [user | username]=":username" password=":<PASSWORD>" query=":query" operation=":operation"' ] description: [ 'The jdbc input type connects to various databases using the JDBC api and executes a query. The results of the query will be returned as the current dataset.' 'The default JDBC operation is "query", which is used for selecting data. The operation option can be used to provide another operation to run—currently, only "execute" is implemented. INSERT/UPDATE/DELETE/EXECUTE queries can all be run through the "execute" operation.' 'Caution: The implementation of the URI may vary across JDBC drivers, e.g. some require the username and password in the URI, whereas others as separate options. This is determined by the specific JDBC driver and its implementation, not Parsec. Please check the documentation for the JDBC driver you are using, or check the examples below. There may be multiple valid ways to configure some drivers.' 'The following JDBC drivers are bundled with Parsec: AWS Redshift, DB2, Hive2, HSQLDB, MySQL, PostgreSQL, Presto, Qubole, SQL Server, SQL Server (jTDS), Teradata.' ] examples: [ { description: 'Querying MySQL' q: 'input jdbc uri="jdbc:mysql://my-mysql-server:3306/database?user=username&password=<PASSWORD>"\nquery="..."' } { description: 'Inserting data into MySQL' q: 'input jdbc uri="jdbc:mysql://my-mysql-server:3306/database?user=username&password=<PASSWORD>" operation="execute"\nquery="INSERT INTO ... VALUES (...)"' } { description: 'Querying SQL Server' q: 'input jdbc uri="jdbc:sqlserver://my-sql-server:1433;databaseName=database;username=username;password=<PASSWORD>"\n query="..."' } { description: 'Querying Hive (Hiveserver2)' q: 'input jdbc uri="jdbc:hive2://my-hive-server:10000/default?mapred.job.queue.name=queuename" username="username" password="<PASSWORD>"\n query="show tables"' } { description: 'Querying Teradata' q: 'input jdbc uri="jdbc:teradata://my-teradata-server/database=database,user=user,password=<PASSWORD>"\n query="..."' } { description: 'Querying DB2' q: 'input jdbc uri="jdbc:db2://my-db2-server:50001/database:user=username;password=<PASSWORD>;"\n query="..."' } { description: 'Querying Oracle' q: 'input jdbc uri="jdbc:oracle:thin:username/password@//my-oracle-server:1566/database"\n query="..."' } { description: 'Querying PostgreSQL' q: 'input jdbc uri="jdbc:postgresql://my-postgres-server/database?user=username&password=<PASSWORD>"\n query="..."' } ] related: ['statement:input'] } { name: 'graphite' type: 'input' syntax: [ 'input graphite uri=":uri" targets=":target"' 'input graphite uri=":uri" targets=[":target", ":target"]' 'input graphite uri=":uri" targets=[":target", ":target"] from="-24h" until="-10min"' ] description: [ 'The graphite input type retrieves data from Graphite, a time-series database. One or more target metrics can be retrieved; any valid Graphite targets can be used, including functions and wildcards.' 'The :uri option should be set to the Graphite server UI or render API.' ] examples: [ { q: 'input graphite uri="http://my-graphite-server" targets="carbon.agents.*.metricsReceived" from="-4h"' } { description: 'Unpivoting metrics into a row' q: 'input graphite uri="http://my-graphite-server" targets="carbon.agents.*.*" from="-2h"\n| unpivot value per metric by _time\n| filter value != null' } ] related: ['statement:input'] } { name: 'http' type: 'input' syntax: [ 'input http uri=":uri"' 'input http uri=":uri" user=":user" password="<PASSWORD>*****"' 'input http uri=":uri" method=":method" body=":body"' 'input http uri=":uri" parser=":parser"' 'input http uri=":uri" parser=":parser" jsonpath=":jsonpath"' ] description: [ 'The http input type retrieves data from web servers using the HTTP/HTTPS networking protocol. It defaults to an HTTP GET without authentication, but can be changed to any HTTP method.' 'Optional authentication is available using the user/password options. Preemptive authentication can also be enabled, which sends the authentication in the initial request instead of waiting for a 401 response. This may be required by some web services.' 'Without the :parser option, a single row will be output, containing information about the request and response. If a parser is specified, the body of the file will be parsed and projected as the new data set. The JSON parser has an option jsonpath option, allowing a subsection of the JSON document to be projected.' 'Output columns are: "body", "headers", "status", "msg", "protocol", "content-type"' 'Available options: user, password, method, body, parser, headers, query, timeout, connection-timeout, request-timeout, compression-enabled, and follow-redirects.' ] examples: [ { description: 'Loading a web page' q: 'input http uri="http://www.expedia.com"' } { description: 'Authenticating with username and password' q: 'input http uri="http://my-web-server/path"\n user="readonly" password="<PASSWORD>"' } { description: 'Preemptive authentication (sending credentials with initial request)' q: 'input http uri="http://my-web-server/path"\n auth={ user: "readonly", password: "<PASSWORD>", preemptive: true }' } { description: 'Posting data' q: 'input http uri="http://my-web-server/path"\n method="post" body="{ \'key\': 123456 }"\n headers={ "Content-Type": "application/json" }' } { description: 'Providing custom headers' q: 'input http uri="http://my-web-server/path"\n headers={ "Accept": "application/json, text/plain, */*",\n "Accept-Encoding": "en-US,en;q=0.5" }' } { description: 'Parsing an XML file' q: 'input http uri="http://news.ycombinator.com/rss"\n| project parsexml(first(body), { xpath: "/rss/channel/item" })' } { description: 'Parsing a JSON file with JsonPath' q: 'input http uri="http://pastebin.com/raw/wzmy7TMZ" parser="json" jsonpath="$.values[*]"' } ] related: ['statement:input', 'function:parsexml', 'function:parsecsv', 'function:parsejson', 'function:jsonpath'] } { name: 'influxdb' type: 'input' syntax: [ 'input influxdb uri=":uri" db=":db" query=":query"' 'input influxdb uri=":uri" db=":db" query=":query" user=":user" password=":<PASSWORD>"' ] description: [ 'The influxdb input type retrieves data from InfluxDB, a time-series database. Supports InfluxDB 0.9 and higher.' 'The :uri option should be set to the Query API endpoint on an InfluxDB server; by default is is on port 8086. The URI of the Admin UI will not work.' 'An error will be thrown if multiple queries are sent in one input statement.' ] examples: [ { q: 'input influxdb uri="http://my-influxdb-server:8086/query"\n db="NOAA_water_database"\n query="SELECT * FROM h2o_feet"' } ] related: ['statement:input'] } { name: 'mongodb' type: 'input' syntax: [ 'input mongodb uri=":uri" query=":query"' ] description: [ 'The mongodb input type retrieves data from MongoDB, a NoSQL document database.' 'The :uri option should follow the standard connection string format, documented here: https://docs.mongodb.com/manual/reference/connection-string/.' 'The :query option accepts a limited subset of the Mongo Shell functionality.' ] examples: [ { q: 'input mongodb uri="mongodb://localhost:27017/testdb" query="show collections"' } { q: 'input mongodb uri="mongodb://localhost:27017/testdb" query="db.testcollection.find({type: \'orders\'}.sort({name: 1})"' } ] related: ['statement:input'] } { name: 's3' type: 'input' syntax: [ 'input s3 accessKeyId=":key-id" secretAccessKey=":secret"' 'input s3 accessKeyId=":key-id" secretAccessKey=":secret" token=":token"' 'input s3 uri="s3://:uri" accessKeyId=":key-id" secretAccessKey=":secret" token=":token" operation=":operation" maxKeys=:max-keys delimiter=:delimiter gzip=:gzip-enabled zip=:zip-enabled' 'input s3 uri="s3://:uri" accessKeyId=":key-id" secretAccessKey=":secret" token=":token" operation=":operation" maxKeys=:max-keys delimiter=:delimiter parser=":parser"' ] description: [ 'The s3 input type retrieves data from Amazon S3. It is designed to either retrieve information about objects stored in S3, or retrieve the contents of those objects.' 'The following operations are supported: "list-buckets", "list-objects", "list-objects-from", "get-objects", "get-objects-from", "get-object". The operation can be specified manually, or auto-detected based on the arguments.' 'Authentication requires AWS credentials of either accessKeyId/secretAccessKey, or accessKeyId/secretAccessKey/token.' '"list-objects" and "get-objects" have a default limit of 10 objects, which can be configured via the maxKeys option' '"list-objects-from" and "get-objects-from" use a marker to retrieve objects only after the given prefix or object. Partial object names are supported.' 'Zip or gzip-compressed objects can be decompressed by setting gzip=true, or zip=true. If neither is set, the object is assumed to be uncompressed' ] examples: [ { description: 'Listing all S3 buckets available for the given credentials' q: 'input s3 accessKeyId="***" secretAccessKey="****"' } { description: 'Listing all S3 objects in the given bucket' q: 'input s3 uri="s3://:bucket" accessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Listing S3 objects in the given bucket with a given prefix (prefix must end in /)' q: 'input s3 uri="s3://:bucket/:prefix/" accessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting the next level of the object hierarchy by using a delimiter.' q: 'input s3 uri="s3://:bucket/:prefix/" accessKeyId=":key-id" secretAccessKey=":secret-key" delimiter="/"' } { description: 'Getting an S3 object' q: 'input s3 uri="s3://:bucket/:prefix/:object.json"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting an S3 object and parsing its contents' q: 'input s3 uri="s3://:bucket/:prefix/:object.json" parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting multiple S3 objects and parsing their contents into a combined dataset' q: 'input s3 uri="s3://:bucket/:prefix/" operation="get-objects" parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Limiting the number of objects returned' q: 'input s3 uri="s3://:bucket/:prefix/" operation="list-objects" maxKeys=100\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting a single S3 object and parsing its contents' q: 'input s3 uri="s3://:bucket/:prefix/:object.json" gzip=true parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } ] related: ['statement:input'] } { name: 'smb' type: 'input' syntax: [ 'input smb uri="smb://:hostname/:path"' 'input smb uri="smb://:hostname/:path" user=":user" password="<PASSWORD>*****"' 'input smb uri="smb://:user:******@:hostname/:path"' 'input smb uri="smb://:hostname/:path" parser=":parser"' ] description: [ 'The smb input type retrieves data using the SMB/CIFS networking protocol. It can either retrieve directory listings or file contents.' 'Optional NTLM authentication is supported using the user/password options, or by embedding them in the :uri (slightly slower).' 'Without the :parser option, a single row will be output, containing metadata about the directory or file. If a parser is specified, the body of the file will be parsed and projected as the new data set (directories cannot be parsed).' 'Metadata columns are: "name", "path", "isfile", "body", "attributes", "createdTime", "lastmodifiedTime", "length", "files"' ] examples: [ { description: 'Retrieving a directory listing' q: 'input smb uri="smb://my-samba-server/my-share"\n user="readonly" password="<PASSWORD>"' } { description: 'Retrieving file metadata' q: 'input smb uri="smb://my-samba-server/my-share/file.txt"\n user="readonly" password="<PASSWORD>"' } { description: 'Parsing a JSON file' q: 'input smb uri="smb://my-samba-server/my-share/file.txt"\n user="readonly" password="<PASSWORD>" parser="json"' } ] related: ['statement:input'] } ] _.each documentation.tokens, (token) -> token.key = token.type + ':' + token.name token.typeKey = 'type:' + token.type token.subtypeKey = 'subtype:' + token.subtype if token.altName? token.key += ':' + token.altName if !token.description? console.log 'Token without description: ' + token.key if !token.examples? console.log 'Token without examples: ' + token.key return functions = _.sortBy _.filter(documentation.tokens, { type: 'function' }), 'subtype' groups = _.groupBy functions, 'subtype' _.each groups, (functions, name) -> console.log '# ' + name + ' functions' console.log _.sortBy(_.map(functions, 'name')).join('|') return documentation
true
# Documentation for Parsec Parsec.Services.factory 'documentationService', -> documentation = tokens: [ { name: ';' altName: 'query separator' type: 'symbol' syntax: ['query1; query2', 'query1; query2; query3 ...'] description: [ 'The query separator is used to separate two distinct Parsec queries. The queries will be executed sequentially with a shared context.' ] examples: [ { q: 'input mock; input mock' } ] } { name: '/* */' altName: 'comment block' type: 'symbol' syntax: ['/* ... */'] description: [ 'Comments in Parsec follow the general C style /* ... */ block comment form and are ignored by the parser.' 'Nested comment blocks are supported provided they are balanced.' ] examples: [ { q: '/* My query */ input mock' } { q: 'input mock | /* filter col1 == 1 | */ sort col1 desc' } ] } { name: '//' altName: 'line comment' type: 'symbol' syntax: ['// ...'] description: [ 'Line comments in Parsec follow the general C style // comment form and are ignored by the parser.' 'Line comments must either end in a newline character, or the end of the query.' ] examples: [ { q: '// My query \ninput mock' } { q: 'input mock\n//| filter col1 == 1\n| sort col1 desc' } ] } { name: '()' altName: 'parentheses' type: 'symbol' syntax: ['(expression)'] description: [ 'Parentheses can be used to explicitly specify order the order of evaluation. An expression wrapped in parentheses evaluates to the value of the expression.' 'Parentheses are also used in a function call to contain the arguments to the function.' 'Nested parentheses are supported.' ] examples: [ { q: 'input mock | x = col1 + col2 * col3, y = (col1 + col2) * col3 | select x, y' } { description: 'As a function call' q: 'input mock | x = (col2 * col4) / 2, y = round(x)' } { q: 'input mock | x = sqrt(sin(col1) - cos(col2))' } ] } { name: '*' altName: 'asterisk' type: 'symbol' syntax: ['*'] description: [ 'The asterisk (*) symbol can be used as a wildcard in limited functions. The most notable use case is in the count(*) function to indicate a count of all rows.' 'It is identical in appearance to the multiplication operator.' ] examples: [ { q: 'input mock | stats numRows = count(*)' } ] } { name: '->' altName: 'function' type: 'symbol' syntax: [ ':arg, :arg, .. -> :expression' '(:arg, :arg, ..) -> :expression' ] description: [ 'The function (->) symbol is used to define first-order functions. Any number of arguments can precede it, followed by an expression in terms of those arguments.' 'Functions created with this symbol can be mapped to user-defined functions using the def statement, or they can be stored in variables or passed directly to functions like map().' 'The apply() function can be used to invoke a function, if it isn\'t mapped to a function name using def.' ] examples: [ { q: 'set @cube = (n) -> n*n*n, @cube9 = apply(@cube, 9)' } { q: 'set @isOdd = (n) -> gcd(n,2) != 2\n| input mock | isCol1Odd = apply(@isOdd, col1)' } ] related: ['statement:def', 'function:apply'] } { name: 'null' type: 'literal' syntax: ['null'] description: [ 'The keyword "null" represents the absence of value.' 'Generally, operators and functions applied to null value tend to return null.' ] examples: [ { q: 'set @x = null' } ] } { name: 'true' type: 'literal' syntax: ['true'] description: [ 'The keyword "true" represents the boolean truth value. It can be used in equality/inequality expressions, or assigned to columns or variables.' 'Non-zero numbers are considered true from a boolean perspective.' ] examples: [ { q: 'set @truth = true' } { description: 'Non-zero numbers are considered true from a boolean perspective' q: 'set @truth = (1 == true)' } ] related: ['literal:false'] } { name: 'false' type: 'literal' syntax: ['false'] description: [ 'The keyword "false" represents the boolean falsehood value It can be used in equality/inequality expressions, or assigned to columns or variables.' 'Zero numbers are considered false from a boolean perspective.' ] examples: [ { q: 'set @truth = false' } { description: 'Zero numbers are considered false from a boolean perspective' q: 'set @truth = (0 == false)' } ] related: ['literal:true'] } { name: '"number"' type: 'literal' syntax: [ 'Regex: /[-+]?(0(\.\d*)?|([1-9]\d*\.?\d*)|(\.\d+))([Ee][+-]?\d+)?/' 'Regex: /[-+]?(0(\.\d*)?|([1-9]\d*\.?\d*)|(\.\d+))([Ee][+-]?\d+)?[%]/' ] returns: 'number' description: [ 'Internally, Parsec supports the full range of JVM primitive numbers, as well as BigInteger, BigDecimal, and Ratios.' 'A number that ends with a percent sign indicates a percentage. The numerical value of the number will be divided by 100.' ] examples: [ { description: 'Integer' q: 'set @x = 100' } { description: 'Floating-point (double) number' q: 'set @y = 3.141592' } { description: 'Scientific-notation' q: 'set @a = 1.234e50, @b = 1.234e-10' } { description: 'Percents' q: 'set @a = 50%, @b = 12 * @a' } ] } { name: '"identifier"' type: 'literal' syntax: [ 'Regex: /[a-zA-Z_][a-zA-Z0-9_]*/' 'Regex: /`[^`]+`/' ] description: [ 'Identifiers are alpha-numeric strings used to reference columns in the current dataset.' 'There are two possible forms for identifiers: the primary form must start with a letter or underscore, and may only contain letters, numbers, or underscores. The alternate form uses two backtick (`) characters to enclose any string of characters, including spaces or special characters (except backticks).' 'Identifiers are case-sensitive.' ] examples: [ { description: 'Primary form' q: 'input mock | col6 = col5' } { description: 'Backtick form allows spaces and special characters' q: 'input mock | stats `avg $` = mean(col1 * col2)' } ] } { name: '"variable"' type: 'literal' syntax: ['Regex: /@[a-zA-Z0-9_]+[\']?/'] description: [ 'Variables are alpha-numeric strings prefixed with an at symbol (@). A trailing single-quote character is allowed, representing the prime symbol.' 'Unlike identifiers, variables are not associated with rows in the current dataset. Variables are stored in the context and available throughout the evaluation of a query (once they have been set.' ] examples: [ { description: 'Setting a variable' q: 'set @fruit = "banana"' } { description: 'Storing a calculated value in a variable' q: 'input mock | set @x=mean(col1) | y = col1 - @x' } { description: 'Prime variables' q: 'input mock | set @x = mean(col1), @x\' = @x^2 | stats x=@x, y=@x\'' } ] related: ['statement:set'] } { name: '"string"' type: 'literal' syntax: [ "Regex: /\'(?:.*?([^\\]|\\\\))?\'/s" 'Regex: /\"(?:.*?([^\\]|\\\\))?\"/s' 'Regex: /\'{3}(?:.*?([^\\]|\\\\))?\'{3}/s' ] returns: 'string' description: [ 'Strings can be created by wrapping text in single or double-quote characters. The quote character can be escaped inside a string using \\" or \\\'.' 'Strings can also be created using a triple single-quote, which has the benefit of allowing single and double quote characters to be used unescaped. Naturally, a triple single quote can be escaped inside a string using \\\'\'\'.' 'Standard escape characters can be used inside a string, e.g.: \\n, \\r, \\t, \\\\, etc.' ] examples: [ { description: 'Single-quoted string' q: 'set @msg = \'hello world\'' } { description: 'Double-quoted string' q: 'set @msg = "hello world"' } { description: 'Double-quoted string with escaped characters inside' q: 'set @msg = "\\"I can\'t imagine\\", said the Princess."' } { description: 'Triple-quoted string' q: 'set @query = \'\'\'Parsec query:\\t \'set @msg = "hello world"\'.\'\'\'' } ] } { name: '"list"' type: 'literal' syntax: ['[expr1, expr2, ... ]'] description: ['Lists can be created using the tolist() function or with a list literal: [expr1, expr2, ...].'] examples: [ { description: 'Creating a list with hard-coded values' q: 'set @list = [1, 2, 3]' } { description: 'Creating a list using expressions for each value' q: 'input mock | x = [col1, col2, col3 + col4]' } ] related: ['function:tolist'] } { name: '"map"' type: 'literal' syntax: ['{ key1: expr1, key2: expr2, ... }'] description: ['Maps can be created using the tomap() function or with a map literal: {key1: expr1, key2: expr2, ...}.'] examples: [ { description: 'Creating a map with hard-coded values' q: 'set @map = { a: 1, b: 2 }' } { description: 'Creating a map with strings for keys' q: 'set @map = { "a": 1, "b": 2 }' } { description: 'Creating a map using expressions for each value' q: 'input mock | x = { col1: col1, col2: col2 }' } { description: 'Aggregating into a map' q: 'input mock | stats x = { min: min(col1), max: max(col1) }' } ] related: ['function:tomap'] } { name: '-' altName: 'negation' type: 'operator' subtype: 'arithmetic' syntax: ['-:expression'] returns: 'number' description: [ 'The negation operator toggles the sign of a number: making positive numbers negtive and negative numbers positive.' 'Returns null if the expression is null' 'Since numbers can be parsed with a negative sign, this operator will only be used when preceding a non-numerical expression in the query, e.g. "-x" or "-cos(y)".' ] examples: [ { description: 'Negating a column' q: 'input mock | x = -col1' } ] } { name: '+' altName: 'addition' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 + :expression2'] returns: 'number' description: [ 'The addition operator adds one number to another, or concatenates two strings. If one operand is a string, the other will be coerced into a string, and concatenated.' 'Returns null if either expression is null.' ] examples: [ { description: 'Adding numbers' q: 'input mock | x = col1 + col2' } { description: 'Concatenating strings' q: 'input mock | x = "hello" + " " + "world"' } ] } { name: '-' altName: 'subtraction' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 - :expression2'] returns: 'number' description: [ 'The subtraction operator subtracts one number from another, or creates an interval between two DateTimes.' 'Returns null if either expression is null.' ] examples: [ { description: 'Subtracting numbers' q: 'input mock | x = col1 - col2' } { description: 'Subtracting DateTimes to create an interval' q: 'input mock | x = inminutes(now() - today())' } ] } { name: '*' altName: 'multiplication' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 * :expression2'] returns: 'number' description: [ 'The multiplication operator multiplies two numbers together.' 'Returns null if either expression is null.' 'Multiplying by any non-zero number by infinity gives infinity, while the result of zero times infinity is NaN.' ] examples: [ { description: 'Multiplying numbers' q: 'input mock | x = col1 * col2' } { description: 'Multiplying by infinity' q: 'input mock | x = col1 * infinity()' } ] } { name: '/' altName: 'division' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 / :expression2'] returns: 'number' description: [ 'The division operator divides the value of one number by another. If the value is not an integer, it will be stored as a ratio or floating-point number.' 'Returns null if either expression is null.' 'Dividing a positive number by zero yields infinity, and dividing a negative number by zero yields -infinity. If both numeric expressions are zero, the result is NaN.' ] examples: [ { description: 'Dividing numbers' q: 'input mock | x = col1 / col2' } { description: 'Dividing by zero gives infinity' q: 'input mock | x = col1 / 0, isInfinity = isinfinite(x)' } ] } { name: 'mod' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 mod :expression2'] returns: 'number' description: [ 'The modulus operator finds the amount by which a dividend exceeds the largest integer multiple of the divisor that is not greater than that number. For positive numbers, this is equivalent to the remainder after division of one number by another.' 'Returns null if either expression is null.' 'By definition, 0 mod N yields 0, and N mod 0 yields NaN.' ] examples: [ { q: 'input mock | x = col2 mod col1' } { description: 'Modulus by zero is NaN' q: 'input mock | x = col1 mod 0, isNaN = isnan(x)' } ] } { name: '^' altName: 'exponent' type: 'operator' subtype: 'arithmetic' syntax: [':expression1 ^ :expression2'] returns: 'number' description: [ 'The exponent operator raises a number to the power of another number.' 'Returns null if either expression is null.' 'By definition, N^0 yields 1.' ] examples: [ { q: 'input mock | x = col1 ^ col2' } ] } { name: 'and' type: 'operator' subtype: 'logical' syntax: [':expression1 and :expression2', ':expression1 && :expression2'] returns: 'boolean' description: [ 'The logical and operator compares the value of two expressions and returns true if both values are true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true and true)' } { q: 'input mock | x = (true && false)' } { q: 'input mock | x = isnumber(col1) and col1 > 3' } { q: 'input mock | x = col1 > 1 and null' } ] } { name: 'or' type: 'operator' subtype: 'logical' syntax: [':expression1 or :expression2', ':expression1 || :expression2'] returns: 'boolean' description: [ 'The logical or operator compares the value of two expressions and returns true if at least one value is true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true or false)' } { q: 'input mock | x = (false || false)' } { q: 'input mock | x = col3 == 3 or col1 > 3' } { q: 'input mock | x = col1 > 1 or null' } ] } { name: 'not' type: 'operator' subtype: 'logical' syntax: ['not :expression', '!:expression'] returns: 'boolean' description: [ 'The logical negation operator returns true if the boolean value of :expression is false, else it returns false.' 'Returns null if the expression is null.' ] examples: [ { q: 'input mock | x = not true' } { q: 'input mock | x = !false' } { q: 'input mock | x = !null' } ] } { name: 'xor' type: 'operator' subtype: 'logical' syntax: [':expression1 xor :expression2', ':expression1 ^^ :expression2'] returns: 'boolean' description: [ 'The logical xor operator compares the value of two expressions and returns true if exactly one value is true, else false.' 'Returns null if either expression is null.' ] examples: [ { q: 'input mock | x = (true xor false)' } { q: 'input mock | x = (false ^^ false)' } { q: 'input mock | x = true xor null' } ] } { name: '==' altName: 'equals' type: 'operator' subtype: 'equality' syntax: [':expression1 == :expression2'] returns: 'boolean' description: [ 'The equality operator compares the value of two expressions and returns true if they are equal, else false.' ] examples: [ { q: 'input mock | x = (col1 == col2)' } { q: 'input mock | filter col1 == 1 ' } ] } { name: '!=' altName: 'unequals' type: 'operator' subtype: 'equality' syntax: [':expression1 != :expression2'] returns: 'boolean' description: [ 'The inequality operator compares the value of two expressions and returns true if they are unequal, else false.' ] examples: [ { q: 'input mock | x = (col1 != col2)' } { q: 'input mock | filter col1 != 1 ' } ] } { name: '>' altName: 'greater than' type: 'operator' subtype: 'equality' syntax: [':expression1 > :expression2'] returns: 'boolean' description: [ 'The greater-than operator returns true if :expression1 is strictly greater than :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 > col2)' } { q: 'input mock | filter col1 > 1 ' } ] } { name: '<' altName: 'less than' type: 'operator' subtype: 'equality' syntax: [':expression1 < :expression2'] returns: 'boolean' description: [ 'The less-than operator returns true if :expression1 is strictly less than :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 < col2)' } { q: 'input mock | filter col1 < 1 ' } ] } { name: '>=' altName: 'greater or equal' type: 'operator' subtype: 'equality' syntax: [':expression1 >= :expression2'] returns: 'boolean' description: [ 'The greater than or equal operator returns true if :expression1 is greater than or equal to :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 >= col2)' } { q: 'input mock | filter col1 >= 1 ' } ] } { name: '<=' altName: 'less or equal' type: 'operator' subtype: 'equality' syntax: [':expression1 <= :expression2'] returns: 'boolean' description: [ 'The less than or equal operator returns true if :expression1 is less than or equal to :expression2, else false.' ] examples: [ { q: 'input mock | x = (col1 <= col2)' } { q: 'input mock | filter col1 <= 1 ' } ] } { name: 'input' type: 'statement' description: ['The input statement loads a dataset from various possible sources. Different input sources are available, like mock, jdbc, and http. Each source has various options for configuring it. If a dataset is already in the pipeline, it will be replaced.'] examples: [ { description: 'Loading mock data from the built-in mock input' q: 'input mock' } { description: 'Several named datasets are included in the mock input' q: 'input mock name="chick-weight"' } ] related: ['input:mock', 'input:datastore', 'input:graphite', 'input:http', 'input:influxdb', 'input:jdbc', 'input:mongodb', 'input:smb', 'input:s3'] } { name: 'output' type: 'statement' syntax: [ 'output name=":name" :options' 'output ignore' ] description: [ 'Outputs the current dataset. This is useful when executing multiple queries at once, in order to return multiple named datasets in the result. Any query which does not end in either an output or temp statement will have an implicit output added. To prevent this, use "output ignore".' 'If the option "temporary=true" is added, the dataset will be stored in the datastore but not returned with the final query results. This is useful for intermediate datasets.' 'If no name is provided, an automatic name will be generated using the index of the dataset in the data store.' 'By default, the dataset is output to the datastore, in the execution context. There is a "type" option to change the default destination.' 'Available output types: "datastore" (default), "ignore".' ] examples: [ { description: 'Returning two named datasets' q: 'input mock | output name="ds1";\ninput mock | output name="ds2"' } { description: 'Creating a temporary dataset' q: 'input mock | output name="ds1" temporary=true;\ninput mock | output name="ds2"' } { description: 'Ignoring the current dataset' q: 'input mock | output ignore' } { description: 'Explicit options' q: 'input mock | output name="results" temporary=false type="datastore" auto=false' } ] related: ['statement:temp'] } { name: 'temp' type: 'statement' syntax: ['temp :name'] description: [ 'The temp statement stores the current dataset in the datastore as a temporary dataset. This means the dataset will be accessible to the rest of the queries, but will not be output as a result dataset.' 'The temp statement is a shortcut for "output name=\'name\' temporary=true".' ] examples: [ { q: 'input mock | temp ds1; input datastore name="ds1"' } ] related: ['statement:output'] } { name: 'head' type: 'statement' syntax: [ 'head' 'head :number' ] description: [ 'Filters the current dataset to the first row or first :number of rows.' ] examples: [ { description: 'Just the first row' q: 'input mock | head' } { description: 'First twenty rows' q: 'input mock name="PI:NAME:<NAME>END_PIurstone" | head 20' } ] related: ['statement:tail'] } { name: 'tail' type: 'statement' syntax: [ 'tail' 'tail :number' ] description: [ 'Filters the current dataset to the last row or last :number of rows.' ] examples: [ { description: 'Just the tail row' q: 'input mock | tail' } { description: 'Last twenty rows' q: 'input mock name="thurstone" | tail 20' } ] related: ['statement:head'] } { name: 'select' type: 'statement' syntax: [ 'select :identifier [, :identifier, ...]' ] description: [ 'Selects the specified columns in each row and removes all other columns.' ] examples: [ { description: 'Creating and selecting a new column' q: 'input mock | sum = col1 + col2 | select sum' } { description: 'Selecting several columns' q: 'input mock name="survey" | select age, income, male' } ] related: ['statement:unselect'] } { name: 'unselect' type: 'statement' syntax: [ 'unselect :identifier [, :identifier, ...]' ] description: [ 'Removes the specified columns in each row, leaving the remaining columns.' ] examples: [ { description: 'Unselecting a specific column' q: 'input mock | unselect col3' } { description: 'Unselecting several columns' q: 'input mock name="survey" | unselect n, intercept, outmig, inmig | head 20' } ] related: ['statement:select'] } { name: 'filter' type: 'statement' syntax: [ 'filter :expression' ] description: [ 'Filters rows in the current dataset by a predicate. Rows for which the predicate evaluates to true will be kept in the dataset.' 'This is the inverse of the remove statement.' ] examples: [ { description: 'Simple predicate' q: 'input mock name="chick-weight" | filter Chick == 1' } { description: 'Predicate with multiple conditions' q: 'input mock name="chick-weight" | filter Chick == 1 and Time == 0' } ] related: ['statement:remove'] } { name: 'remove' type: 'statement' syntax: [ 'remove :expression' ] description: [ 'Removes rows in the current dataset by a predicate. Rows for which the predicate evaluates to true will be removed from the dataset.' 'This is the inverse of the filter statement.' ] examples: [ { description: 'Simple predicate' q: 'input mock name="chick-weight" | remove Chick == 1' } { description: 'Predicate with multiple conditions' q: 'input mock name="chick-weight" | remove Chick > 1 or Time > 0' } ] related: ['statement:filter'] } { name: 'reverse' type: 'statement' syntax: [ 'reverse' ] description: [ 'Reverses the order of the current dataset. That is, sorts the rows by the current index, descending.' ] examples: [ { q: 'input mock name="iran-election" | reverse' } ] } { name: 'union' type: 'statement' syntax: [ 'union :query' 'union (all|distinct) :query' 'union (all|distinct) (:query)' ] description: [ 'Combines the rows of the current dataset with those from another sub-query. If the sub-query is longer than a single input statement, it should be wrapped in parentheses to differentiate from the parent query.' 'The argument ALL or DISTINCT determines which rows are included in the dataset. DISTINCT returns only unique rows, whereas ALL includes all rows from both datasets, even if they are identical. The default behavior is DISTINCT.' 'Rows from the first dataset will preceed those from the sub-query.' ] examples: [ { description: 'Performs a distinct union by default' q: 'input mock | union input mock' } { description: 'Optionally unions all rows' q: 'input mock | union all input mock' } { description: 'Wrap multi-statement sub-queries in parentheses' q: 'input mock | union (input mock | col1 = col2 + col3)' } ] } { name: 'distinct' type: 'statement' syntax: [ 'distinct' ] description: [ 'Filters the current dataset to the set of unique rows. A row is unique if there is no other row in the dataset with the same columns and values.' 'Rows in the resulting dataset will remain in the same order as in the original dataset.' ] examples: [ { q: 'input mock | select col3 | distinct' } { q: 'input mock | union all input mock | distinct' } ] } { name: 'rownumber' type: 'statement' syntax: [ 'rownumber' 'rownumber :identifier' ] description: [ 'Assigns the current row number in the dataset to a column. If a column identifier is not provided, the default value of "_index" will be used.' 'The rank() function implements similar functionality as a function, but has greater overhead and is only preferable when being used in an expression.' ] examples: [ { q: 'input mock | rownumber' } { q: 'input mock | rownumber rowNumber' } { q: 'input mock name="chick-weight" | rownumber rank1 | rank2 = rank() | equal = rank1 == rank2 | stats count = count(*) by equal' } ] related: ['function:rank'] } { name: 'sort' type: 'statement' syntax: [ 'sort :identifier' 'sort :identifier (asc|desc)' 'sort :identifier (asc|desc) [, :identifier (asc|desc), ...]' ] description: [ 'Sorts the current dataset by one or more columns. Each column can be sorted either in ascending (default) or descending order' ] examples: [ { q: 'input mock | sort col1' } { q: 'input mock | sort col1 asc' } { q: 'input mock | sort col1 asc, col2 desc' } ] } { name: 'def' type: 'statement' syntax: [ 'def :function-name = (:arg, :arg, ..) -> :expression, ...' ] description: [ 'Defines one or more user-defined functions and saves into the current query context. Functions can take any number of arguments and return a single value.' 'Def can be used at any point in the query, even before input. user-defined functions must be defined before they are invoked, but can be used recursively or by other functions.' 'It is not possible to override built-in Parsec functions, but user-defined functions can be redefined multiple times.' ] examples: [ { description: 'Calculate the distance between two points' q: 'def distance = (p1, p2) -> \n sqrt((index(p2, 0) - index(p1, 0))^2 + (index(p2, 1) - index(p1, 1))^2)\n| set @d = distance([0,0],[1,1])' } { description: 'Calculate the range of a list' q: 'def range2 = (list) -> lmax(list) - lmin(list)\n| set @range = range2([8, 11, 5, 14, 25])' } { description: 'Calculate the factorial of a number using recursion' q: 'def factorial = (n) -> if(n == 1, 1, n*factorial(n-1))\n| set @f9 = factorial(9)' } { description: 'Calculate the number of permutations of n things, taken r at a time' q: 'def factorial = (n) -> if(n == 1, 1, n*factorial(n-1)), permutations = (n, r) -> factorial(n) / factorial(n - r)\n| set @p = permutations(5, 2)' } ] related: ['symbol:->:function'] } { name: 'set' type: 'statement' syntax: [ 'set @var1 = :expression, [@var2 = :expression, ...]' 'set @var1 = :expression, [@var2 = :expression, ...] where :predicate' ] description: [ 'Sets one or more variables in the context. As variables are not row-based, the expression used cannot reference individual rows in the data set. However, it can use aggregate functions over the data set. An optional predicate argument can be used to filter rows before the aggregation.' 'Set can be used at any point in the query, even before input' 'Variables are assigned from left to right, so later variables can reference previously assigned variables.' 'Existing variables will be overridden.' ] examples: [ { description: 'Set a constant variable' q: 'set @plank = 6.626070040e-34' } { description: 'Set several dependent variables' q: 'set @inches = 66, @centimeters_per_inch = 2.54, @centimeters = @inches * @centimeters_per_inch' } { description: 'Calculate an average and use later in the query' q: 'input mock | set @avg = avg(col1) | filter col1 > @avg' } ] related: ['literal:"variable"'] } { name: 'rename' type: 'statement' syntax: [ 'rename :column=:oldcolumn, ...' 'rename :column=:oldcolumn, ... where :predicate' ] description: [ 'Renames one or more columns in the dataset.' 'If a predicate is specified, the rename will apply only to rows satisfying the predicate.' ] examples: [ { q: 'input mock | rename day = col1, sales = col2, bookings = col3, numberOfNights = col4' } { description: 'With predicate' q: 'input mock | rename col5 = col1 where col1 < 2' } ] } { name: 'assignment' type: 'statement' syntax: [ ':column=:expr, ...' ':column=:expr, ... where :predicate' ] description: [ 'Assigns one or more columns to each row in the dataset, by evaluating an expression for each row. Assignments are made from left to right, so it is possible to reference previously assigned columns in the same assignemnt statement.' 'If a predicate is specified, the assignments will apply only to rows satisfying the predicate.' ] examples: [ { q: 'input mock | ratio = col1 / col2' } { description: 'With predicate' q: 'input mock | col1 = col1 + col2 where col1 < 3' } { description: 'With multiple assignments' q: 'input mock | ratio = col1 / col2, col5 = col3 * ratio' } ] } { name: 'stats' type: 'statement' syntax: [ 'stats :expression, ... ' 'stats :expression, ... by :expression, ...' ] description: [ 'Calculates one or more aggregate expressions across the dataset, optionally grouped by one or more expressions. The resulting dataset will have a single row for each unique value(s) of the grouping expressions.' 'Grouping expressions will be evaluated for each row, and the values used to divide the datasets into subsets. Each grouping expression will become a column in the resulting dataset, containing the values for that subset. If no grouping expressions are provided, the aggregations will run across the entire dataset.' ] examples: [ { q: 'input mock | stats count=count(*) by col2' } { q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick' } { description: 'Expressions can be used to group by' q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick, bucket(Time, 4)' } { q: 'input mock name="chick-weight" | stats avgWeight = avg(weight) by Chick, Time = bucket(Time, 4)' } ] } { name: 'sleep' type: 'statement' syntax: [ 'sleep' 'sleep :expression' ] description: [ 'Delays execution of the query for a given number of milliseconds. Defaults to 1000 milliseconds if no argument is given.' ] examples: [ { q: 'input mock | sleep 5000' } ] } { name: 'sample' type: 'statement' syntax: [ 'sample :expr' ] description: [ 'Returns a sample of a given size from the current dataset. The sample size can be either smaller or larger than the current dataset.' ] examples: [ { description: 'Selecting a sample' q: 'input mock n=100 | sample 10' } { description: 'Generating a larger sample from a smaller dataset' q: 'input mock n=10 | sample 100' } ] } { name: 'benchmark' type: 'statement' syntax: [ 'benchmark :expr [:options]' 'bench :expr [:options]' ] description: [ 'Benchmarks a query and returns a single row of the results. The query will be run multiple times and includes a warm-up period for the JIT compiler and forced GC before and after testing.' 'Various options are available to customize the benchmark, but defaults will be used if not provided. The values used will be returned as a map in the "options" column.' ] examples: [ { description: 'Benchmarking a query with default options' q: 'benchmark "input mock"' } { description: 'Providing a sample size' q: 'bench "input mock | head 1" samples=20' } { description: 'Projecting the performance results for each sample' q: 'benchmark "input mock" | project first(performance)' } { description: 'Projecting the text summary of the benchmark' q: 'benchmark "set @x = random()" | project split(first(summary), "\n")' } ] } { name: 'pivot' type: 'statement' description: [ 'Increases the number of columns in the current dataset by "pivoting" values of one or more columns into additional columns. For example, unique values in a column "type" can be converted into separate columns, with the values attributable to each type as their contents.' ] syntax: [ 'pivot :value [, :value ...] per :expression [, :expression ...] by :group-by [, :group-by ...]' 'pivot :identifier=:value [, identifier=:value ...] per :expression [, :expression ...] by :group-by [, :group-by ...]' ] related: ['statement:unpivot'] } { name: 'unpivot' type: 'statement' syntax: ['unpivot :value per :column by :group-by [, :group-by ...]'] description: [ 'Reduces the number of columns in the current dataset by "unpivoting" them into rows of a single column. This is the inverse operation of the pivot statement.' ] examples: [ { q: 'input http uri="http://pastebin.com/raw.php?i=YGN7gWWG" parser="json" | unpivot CrimesCommitted per Type by Year, Population' } ] related: ['statement:pivot'] } { name: 'project' type: 'statement' syntax: ['project :expression'] description: [ 'Replaces the current dataset with the result of an expression. The expression must be either a list or a single map which will be wrapped in a list automatically.' 'Projecting a list of maps replaces the entire dataset verbatim. If the list does not contain maps, each value will be stored in a new column called "value".' 'Can be useful when parsing data from a string.' ] examples: [ { description: 'With a list of maps' q: 'input mock | project [{x:1, y:1},{x:2, y:2}]' } { description: 'With a list of numbers' q: 'input mock | project [4, 8, 15, 16, 23, 42] | stats avg = avg(value)' } { description: 'From a variable' q: 'input mock | x = [{x:1, y:1},{x:2, y:2}] | project first(x)' } { description: 'With a single map' q: 'input mock | project {a: 1, b: 2, c: 3}' } { description: 'With a JSON string' q: 'input mock | x = \'[{"x":1, "y":1},{"x":2, "y":2}]\' | project parsejson(first(x))' } { description: 'With a CSV string' q: 'input http uri="http://pastebin.com/raw.php?i=s6xmiNzx" | project parsecsv(first(body), { strict: true, delimiter: "," })' } ] } { name: 'join' type: 'statement' syntax: [ '[inner] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'left [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'right [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'full [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]' 'cross join :dataset-or-query' ] description: [ 'Joins the current dataset with another dataset. The join statement takes the current dataset as the left dataset, and either accepts the name of a dataset in the context or an inline query in parentheses.' 'Join types available: Inner, Left Outer (Left), Right Outer (Right), Full Outer (Full), and Cross Join. If no join type is specified, inner join will be assumed.' 'The joined dataset is the output of this statement. Columns from joined rows will be merged, with preference given to the value in the Left dataset.' ] examples: [ { description: 'Inner join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }] | inner join types on typeId == types.id' } { description: 'Left outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 3 }] | left outer join types on typeId == types.id' } { description: 'Right outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 1 }] | right outer join types on typeId == types.id' } { description: 'Full outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 4 }] | full outer join types on typeId == types.id' } { description: 'Cross join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x" }, { name: "y" }] | cross join types' } ] related: ['statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'inner join' type: 'statement' syntax: ['[inner] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Inner join is a type of join which requires each row in the joined datasets to satisfy a join predicate.' ] examples: [ { description: 'Inner join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }] | inner join types on typeId == types.id' } ] related: ['statement:join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'left outer join' type: 'statement' syntax: ['left [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Left Outer join is a type of join which always includes all rows of the left-hand dataset, even if they do not satisfy the join predicate.' ] examples: [ { description: 'Left outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 3 }] | left outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:right outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'right outer join' type: 'statement' syntax: ['right [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Right Outer join is a type of join which always includes all rows of the right-hand dataset, even if they do not satisfy the join predicate.' ] examples: [ { description: 'Right outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 1 }] | right outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:full outer join', 'statement:cross join'] } { name: 'full outer join' type: 'statement' syntax: ['full [outer] join [:left-alias], :dataset-or-query on :expression [, :expression, ...]'] description: [ 'Full Outer join is a type of join which combines the effects of both left and right outer join. All rows from both left and right datasets will be included in the result.' ] examples: [ { description: 'Full outer join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }, { id: 3, type: "c" }] | temp types; project [{ name: "x", typeId: 1 }, { name: "y", typeId: 2 }, { name: "z", typeId: 4 }] | full outer join types on typeId == types.id' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:cross join'] } { name: 'cross join' type: 'statement' syntax: ['cross join [:left-alias], :dataset-or-query'] description: [ 'Cross join is a type of join which returns the cartesian product of rows from both datasets.' ] examples: [ { description: 'Cross join' q: 'project [{ id: 1, type: "a" }, { id: 2, type: "b" }] | temp types; project [{ name: "x" }, { name: "y" }] | cross join types' } ] related: ['statement:join', 'statement:inner join', 'statement:left outer join', 'statement:right outer join', 'statement:full outer join'] } { name: 'avg' type: 'function' subtype: 'aggregation' description: [ 'avg() is an alias for mean().' ] aliases: ['function:mean'] } { name: 'count' type: 'function' subtype: 'aggregation' syntax: [ 'count(*)' 'count(:expression)' 'count(:expression, :predicate)' ] returns: 'number' description: [ 'Counts the number of rows where :expression is non-null. An optional predicate argument can be used to filter rows before the aggregation.' 'count(*) is equivalent to count(1); it counts every row.' ] examples: [ { q: 'input mock | stats count = count(*)' } { q: 'input mock | col1 = null where col2 == 2 | stats count = count(col1)' } { q: 'input mock | stats count = count(*, col2 == 2)' } ] related: ['function:distinctcount'] } { name: 'cumulativeavg' type: 'function' subtype: 'aggregation' description: [ 'cumulativeavg() is an alias for cumulativemean().' ] aliases: ['function:cumulativemean'] } { name: 'cumulativemean' type: 'function' subtype: 'aggregation' syntax: [ 'cumulativemean(:expression)' 'cumulativemean(:expression, :predicate)' ] returns: 'list' description: [ 'Returns a list of cumulative means for the current dataset. For example, the first value in the list is the value of the first row; the second value is the mean of the first two rows, the third is the mean of the first three rows, etc.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats c1 = cumulativemean(col1), c2 = cumulativemean(col2)' } ] related: ['function:mean', 'function:geometricmean'] aliases: ['function:cumulativeavg'] } { name: 'distinctcount' type: 'function' subtype: 'aggregation' syntax: [ 'distinctcount(:expression)' 'distinctcount(:expression, :predicate)' ] returns: 'number' description: [ 'Counts the number of rows for which :expression is distinct and non-null. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats col1DistinctCount = distinctcount(col1), col2DistinctCount = distinctcount(col2)' } { q: 'input mock | stats count = count(*, col2 == 2)' } ] related: ['function:count'] } { name: 'geometricmean' type: 'function' subtype: 'aggregation' syntax: [ 'geometricmean(:expression)' 'geometricmean(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the geometric mean of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats geometricmean = geometricmean(col1)' } { q: 'input mock | stats geometricmean = geometricmean(col1 + col2, col3 == 3)' } ] related: ['function:mean', 'function:cumulativemean'] } { name: 'max' type: 'function' subtype: 'aggregation' syntax: [ 'max(:expression)' 'max(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the maximum value of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats max = max(col1)' } { q: 'input mock name="chick-weight" | stats maxWeight = max(weight, Chick == 1)' } ] related: ['function:min'] } { name: 'mean' type: 'function' subtype: 'aggregation' syntax: [ 'mean(:expression)' 'mean(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the arithmetic mean of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats mean = mean(col1)' } { q: 'input mock | stats mean = mean(col1 + col2, col3 == 3)' } ] related: ['function:geometricmean', 'function:cumulativemean'] aliases: ['function:avg'] } { name: 'median' type: 'function' subtype: 'aggregation' syntax: [ 'median(:expression)' 'median(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the median value of :expression, calculated across all rows. If there is no middle value, the median is the mean of the two middle values.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats median = median(col1)' } { q: 'input mock name="chick-weight" | stats medianWeight = median(weight, Chick == 1)' } { q: 'input mock name="airline-passengers" | stats mean = mean(passengers), median = median(passengers)' } ] } { name: 'mode' type: 'function' subtype: 'aggregation' syntax: [ 'mode(:expression)' 'mode(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the mode of :expression, calculated across all rows. If there are multiple modes, one of them will be returned.' 'An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats mode = mode(col2)' } { q: 'input mock name="hair-eye-color" | stats mode = mode(hair) by gender' } { q: 'input mock name="survey" | stats medianAge = median(age), modeAge = mode(age)' } ] } { name: 'min' type: 'function' subtype: 'aggregation' syntax: [ 'min(:expression)' 'min(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the minimum value of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats min = min(col1)' } { q: 'input mock name="chick-weight" | stats minWeight = min(weight, Chick == 1)' } ] related: ['function:max'] } { name: 'pluck' type: 'function' subtype: 'aggregation' syntax: ['pluck(expression)'] returns: 'list' description: ['Evaluates an expression against each row in the data set, and returns a list composed of the resulting values. The list maintains the same order as the rows in the data set.'] examples: [ { description: 'Plucking a column' q: 'input mock | stats values = pluck(col1)' } { description: 'Plucking a calculated expression' q: 'input mock | stats values = pluck(col1 + col2)' } ] } { name: 'stddev_pop' type: 'function' subtype: 'aggregation' description: [ 'stddev_pop() is an alias for stddevp().' ] aliases: ['function:stddevp'] } { name: 'stddev_samp' type: 'function' subtype: 'aggregation' description: [ 'stddev_samp() is an alias for stddev().' ] aliases: ['function:stddev'] } { name: 'stddevp' type: 'function' subtype: 'aggregation' syntax: [ 'stddevp(:expression)' 'stddevp(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the population standard deviation of :expression, calculated across all rows in the data set (excluding nulls). An optional predicate argument can be used to filter rows before the aggregation.' 'If the data set is not the complete population, use stddev() instead to calculate the sample standard deviation.' ] examples: [ { description: 'Standard deviation of a column' q: 'input mock | stats sigma = stddevp(col1)' } { description: 'Standard deviation of a calculated value' q: 'input mock | stats sigma = stddevp(col1 + col2)' } ] related: ['function:stddev'] aliases: ['function:stddev_pop'] } { name: 'stddev' type: 'function' subtype: 'aggregation' syntax: [ 'stddev(:expression)' 'stddev(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the sample standard deviation of :expression, calculated across all rows in the data set (excluding nulls). An optional predicate argument can be used to filter rows before the aggregation.' 'If the data set is the complete population, use stddevp() instead to calculate the population standard deviation.' ] examples: [ { description: 'Standard deviation of a column' q: 'input mock | stats sigma = stddev(col1)' } { description: 'Standard deviation of a calculated value' q: 'input mock | stats sigma = stddev(col1 + col2)' } ] related: ['function:stddevp'] aliases: ['function:stddev_samp'] } { name: 'sum' type: 'function' subtype: 'aggregation' syntax: [ 'sum(:expression)' 'sum(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the sum of :expression, calculated across all rows. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats total = sum(col1)' } { q: 'input mock name="airline-passengers" | stats pTotal = sum(passengers), p1960 = sum(passengers, year == 1960)' } ] } { name: 'every' type: 'function' subtype: 'aggregation' syntax: [ 'every(:expression)' 'every(:expression, :predicate)' ] returns: 'boolean' description: [ 'Returns true if :expression is true for all rows in the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats test = every(col1 > 0)' } { q: 'input mock name="chick-weight" | stats hasWeight = every(weight > 0, Chick == 1)' } ] related: ['function:some'] } { name: 'first' type: 'function' subtype: 'aggregation' syntax: [ 'first(:expression)' 'first(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the first non-null value of :expression in the dataset, closest to the top of the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats first = first(col1)' } { q: 'input mock name="chick-weight" | stats firstWeight = min(weight, Chick == 1)' } ] related: ['function:last'] } { name: 'last' type: 'function' subtype: 'aggregation' syntax: [ 'last(:expression)' 'last(:expression, :predicate)' ] returns: 'number' description: [ 'Returns the last non-null value of :expression in the dataset, closest to the bottom of the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats last = last(col1)' } { q: 'input mock name="chick-weight" | stats lastWeight = last(weight, Chick == 1)' } ] related: ['function:first'] } { name: 'percentile' type: 'function' subtype: 'aggregation' syntax: [ 'percentile(:expression, :percentage)' 'percentile(:expression, :percentage, :predicate)' ] returns: 'number' description: [ 'Calculates the percentile of an :expression and a given :percentage. Specifically, it returns the value below which :percentage of values in the dataset are less than the value. The percentage can be a number or calculated value.' 'Uses the linear interpolation method, so the returned value may not be in the original dataset. Excludes nils from the calculation and returns nil if there are no non-nil values.' ] examples: [ { q: 'input mock name="chick-weight" | stats p95 = percentile(weight, 95) by PI:NAME:<NAME>END_PIick' } ] } { name: 'some' type: 'function' subtype: 'aggregation' syntax: [ 'some(:expression)' 'some(:expression, :predicate)' ] returns: 'boolean' description: [ 'Returns true if :expression is true for some rows in the dataset. An optional predicate argument can be used to filter rows before the aggregation.' ] examples: [ { q: 'input mock | stats test = some(col1 > 0)' } { q: 'input mock name="chick-weight" | stats hasWeight = some(weight > 0, Chick == 1)' } ] related: ['function:some'] } { name: 'isexist' type: 'function' subtype: 'is-functions' syntax: ['isexist(:column)'] returns: 'boolean' description: [ 'Returns true if its argument exists as a column the current row, else false. It does not check the value of the column, just its existance. As a result, isexist() on a column with a null value will return true.' ] examples: [ { q: 'input mock | col6 = 1 where col2 == 2 | exists = isexist(col6)' } ] } { name: 'isnull' type: 'function' subtype: 'is-functions' syntax: ['isnull(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is null, else false.' ] examples: [ { q: 'set @test = isnull(null)' } ] } { name: 'isnan' type: 'function' subtype: 'is-functions' syntax: ['isnan(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is NaN, else false.' ] examples: [ { q: 'set @test = isnan(0 * infinity())' } ] related: ['function:nan'] } { name: 'isinfinite' type: 'function' subtype: 'is-functions' syntax: ['isinfinite(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is infinite, else false.' ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'isfinite' type: 'function' subtype: 'is-functions' syntax: ['isfinite(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is finite, else false.' ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'isempty' type: 'function' subtype: 'is-functions' syntax: ['isempty(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is "empty", else false.' 'Lists are empty if they have no elements; maps are empty if they have no keys; strings are empty if they have zero length or contain only whitespace. Zero and null are both considered empty.' ] examples: [ { q: 'set @nonempty = isempty("hello"), @empty = isempty(" \n")' } { q: 'set @nonempty = isempty({a: 1}), @empty = isempty(tomap())' } { q: 'set @nonempty = isempty([1, 2, 3]), @empty = isempty([])' } ] } { name: 'isdate' type: 'function' subtype: 'type' syntax: ['isdate(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a DateTime, else false.' 'isdate(null) returns false.' ] examples: [ { q: 'set @test = isdate(now())' } { description: 'Numbers are not DateTimes' q: 'set @test = isdate(101)' } ] } { name: 'isboolean' type: 'function' subtype: 'type' syntax: ['isboolean(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a boolean.' 'isboolean(null) returns false.' ] examples: [ { q: 'set @test = isboolean(true)' } { description: 'Numbers are not booleans' q: 'set @test = isboolean(false)' } { description: 'Equality operators always return booleans' q: 'set @test = isboolean(100 > 0)' } ] } { name: 'isnumber' type: 'function' subtype: 'type' syntax: ['isnumber(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a number. This includes integers, doubles, ratios, etc.' 'isnumber(null) returns false.' ] examples: [ { q: 'set @test = isnumber(0)' } { description: 'Booleans are not numbers' q: 'set @test = isnumber(false)' } { description: 'Numerical strings are not numbers' q: 'set @test = isnumber("3.14")' } ] } { name: 'isinteger' type: 'function' subtype: 'type' syntax: ['isinteger(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is an integer.' 'isinteger(null) returns false.' ] examples: [ { q: 'set @test = isinteger(100)' } { description: 'Floating-point numbers are not integers' q: 'set @test = isinteger(1.5)' } { description: 'Since these numbers can be represented accurately as ratios, their addition yields an integer.' q: 'set @test = isinteger(1.5 + 0.5)' } ] } { name: 'isratio' type: 'function' subtype: 'type' syntax: ['isratio(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a ratio. Parsec will automatically store the result of computations in ratio form if possible, e.g. if two integers are divided.' 'isratio(null) returns false.' ] examples: [ { q: 'set @test = isratio(1/2)' } { description: 'Booleans are not ratios' q: 'set @test = isratio(false)' } { description: 'Numerical strings are not ratios' q: 'set @test = isratio("1/3")' } ] } { name: 'isdouble' type: 'function' subtype: 'type' syntax: ['isdouble(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a double.' 'isdouble(null) returns false.' ] examples: [ { q: 'set @test = isdouble(pi())' } { description: 'Forcing a conversion to double' q: 'input mock | x = todouble(col1), @y = isdouble(x)' } { description: 'Parsec stores exact ratios when possible, which are not considered doubles' q: 'set @test = isdouble(1 / 2)' } ] } { name: 'isstring' type: 'function' subtype: 'type' syntax: ['isstring(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a string.' 'isstring(null) returns false.' ] examples: [ { q: 'set @test = isstring("hello world")' } ] } { name: 'islist' type: 'function' subtype: 'type' syntax: ['islist(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a list.' 'islist(null) returns false.' ] examples: [ { q: 'set @test = islist([1, 2, 3])' } ] } { name: 'ismap' type: 'function' subtype: 'type' syntax: ['ismap(:expression)'] returns: 'boolean' description: [ 'Returns true if its argument is a map.' 'ismap(null) returns false.' ] examples: [ { q: 'set @test = ismap({ a: 1, y: 2, z: 3})' } ] } { name: 'type' type: 'function' subtype: 'type' syntax: ['istype(:expression)'] returns: 'string' description: [ 'Evaluates :expression and returns its data type name as a string.' ] examples: [ { q: 'input mock | x = type(col1)' } { q: 'input mock | x = tostring(col1), y = type(x)' } { q: 'input mock | stats x = pluck(col1) | y = type(x)' } { q: 'input mock | x=type(null)' } ] } { name: 'toboolean' type: 'function' subtype: 'conversion' syntax: ['toboolean(:expression)'] returns: 'boolean' description: [ 'Attempts to convert :expression to a boolean value, returning null if the conversion is not possible.' 'If :expression is a boolean, it is returned as-is.' 'If :expression is a number, yields true for any non-zero number, else false.' 'If :expression is a string, a case-insensitive "true" or "false" will be converted to true and false respectively, with all other values returning null.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a number' q: 'set @true = toboolean(1),\n @false = toboolean(0)' } { description: 'Converting a string' q: 'set @test = toboolean("TRUE")' } ] related: ['function:isboolean'] } { name: 'tostring' type: 'function' subtype: 'conversion' syntax: [ 'tostring(:expression)' 'tostring(:expression, :format)' ] returns: 'string' description: [ 'Attempts to convert :expression to a string type, returning null if the conversion is not possible.' 'If :expression is a string, it is returned as-is.' 'If :expression is a boolean, "true" or "false" is returned.' 'If :expression is a number, yields a string containing the numeric representation of the number.' 'If :expression is a map or list, yields a string containing the JSON representation of :expression.' 'If :expression is a date, yields an ISO 8601-format string representing the date, unless a format code is provided as the second argument. Joda-Time formatting code are accepted, see here: http://www.joda.org/joda-time/key_format.html' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a number' q: 'set @test = tostring(1) // returns "1"' } { description: 'Converting a boolean' q: 'set @test = tostring(true) // returns "true"' } { description: 'Converting a map' q: 'set @test = tostring({ "id": 123, "name": "PI:NAME:<NAME>END_PI" }) // returns {"id":123,"name":"PI:NAME:<NAME>END_PI"}' } { description: 'Converting a list' q: 'set @test = tostring([1, 2, 3]) // returns "[1,2,3]"' } { description: 'Converting a date into ISO 8601 format' q: 'set @year = tostring(now())' } { description: 'Converting a date with a format' q: 'set @year = tostring(now(), "YYYY")' } ] related: ['function:isboolean'] } { name: 'tonumber' type: 'function' subtype: 'conversion' syntax: ['tonumber(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a numerical type, returning null if the conversion is not possible. This function can return integers, doubles, ratios, etc.' 'If :expression is a number, it is returned as-is.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an integer, double, or ratio. If the parsed value can be represented as a ratio, it will be stored internally as such.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting an integer string' q: 'set @test = tonumber("1") // returns 1' } { description: 'Converting a double string' q: 'set @test = tonumber("3.14") // returns 3.14' } { description: 'Converting a ratio' q: 'set @test = tonumber("1/5") // returns 0.2' } { description: 'Converting a date' q: 'set @test = tonumber(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isnumber', 'function:tointeger', 'function:todouble'] } { name: 'tointeger' type: 'function' subtype: 'conversion' syntax: ['tointeger(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a long integer, returning null if the conversion is not possible.' 'If :expression is an integer, it is returned as-is.' 'If :expression is a non-integer number, it will be rounded down to the nearest integer.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an integer.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting a double' q: 'set @test = tointeger(3.14) // returns 3' } { description: 'Converting an integer string' q: 'set @test = tointeger("1") // returns 1' } { description: 'Converting a ratio' q: 'set @test = tointeger("22/3") // returns 7' } { description: 'Converting a date' q: 'set @test = tointeger(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isinteger', 'function:tonumber', 'function:todouble'] } { name: 'todouble' type: 'function' subtype: 'conversion' syntax: ['todouble(:expression)'] returns: 'number' description: [ 'Attempts to convert :expression to a double, returning null if the conversion is not possible.' 'If :expression is an double, it is returned as-is.' 'If :expression is an number, it will be coerced into a double type internally.' 'If :expression is a date, yields the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse it as an double.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting an integer' q: 'set @test = todouble(1) // returns 1' } { description: 'Converting a double string' q: 'set @test = todouble("3.14") // returns 3.14' } { description: 'Converting a ratio string' q: 'set @test = todouble("22/3") // returns 7.333333333333333' } { description: 'Converting a date' q: 'set @test = todouble(todate("2016-04-25T00:02:05.000Z")) // returns 1461542525000' } ] related: ['function:isdouble', 'function:tonumber', 'function:tointeger'] } { name: 'todate' type: 'function' subtype: 'conversion' syntax: [ 'todate(:expression)' 'todate(:expression, :format)' ] returns: 'number' description: [ 'Attempts to convert :expression to a date, returning null if the conversion is not possible.' 'If :expression is an date, it is returned as-is.' 'If :expression is a number, it will be coerced to a long and interpreted as the number of milliseconds since the epoch (1970-01-01).' 'If :expression is a string, attempts to parse using various standard formats. A format argument can optionally be provided to specify the correct format.' 'All other data types (including null) return null.' ] examples: [ { description: 'Converting epoch milliseconds' q: 'set @test = todate(1461543510000)' } { description: 'Converting an ISO-8601 date' q: 'set @test = todate("2016-04-25T00:02:05.000Z")' } { description: 'Converting a date with a format code' q: 'set @test = todate("1985-10-31", "yyyy-MM-dd")' } ] related: ['function:isdate'] } { name: 'tolist' type: 'function' subtype: 'conversion' syntax: ['tolist(:expression [, :expression ...])'] returns: 'map' description: ['Creates a list from a series of arguments.'] examples: [ { q: 'input mock | x = tolist(1, 2, 3, 4)' } { q: 'input mock | x = tolist("red", "yellow", "green")' } { description: 'Creating a list from expressions' q: 'input mock | x = tolist(meanmean(col1), meanmean(col2), meanmean(col3))' } ] related: ['literal:"list"', 'function:islist'] } { name: 'tomap' type: 'function' subtype: 'conversion' syntax: ['tomap(:key, :expression [, :key, :expression ...])'] returns: 'map' description: ['Creates a map from a series of key/value pair arguments: tomap(key1, expr1, key2, expr2, ...).'] examples: [ { q: 'input mock | x = tomap("x", 1, "y", 2)' } { description: 'Creating a map from expressions' q: 'input mock | x = tomap("meanmean", mean(col1), "max", max(col1))' } ] related: ['literal:"map"', 'function:ismap'] } { name: 'e' type: 'function' subtype: 'constant' syntax: ['e()'] returns: 'number' description: ['Returns the constant Euler\'s number.'] examples: [ { q: 'input mock | pi = e()' } ] related: ['function:ln'] } { name: 'pi' type: 'function' subtype: 'constant' syntax: ['pi()'] returns: 'number' description: ['Returns the constant Pi.'] examples: [ { q: 'input mock | pi = pi()' } ] } { name: 'nan' type: 'function' subtype: 'constant' syntax: ['nan()'] returns: 'number' description: ['Returns the not-a-number (NaN) numerical value.'] examples: [ { q: 'input mock | x = nan(), isnotanumber = isnan(x)' } ] related: ['function:isnan'] } { name: 'infinity' type: 'function' subtype: 'constant' syntax: ['infinity()'] returns: 'number' description: ['Returns the positive infinite numerical value.'] examples: [ { q: 'input mock | x = infinity(), isInf = isinfinite(x)' } ] related: ['function:isfinite', 'function:isinfinite', 'function:neginfinity'] } { name: 'neginfinity' type: 'function' subtype: 'constant' syntax: ['neginfinity()'] description: ['Returns the negative infinite numerical value.'] examples: [ { q: 'input mock | x = neginfinity(), isInf = isinfinite(x)' } ] related: ['function:isfinite', 'function:isinfinite', 'function:infinity'] } { name: 'floor' type: 'function' subtype: 'math' syntax: ['floor(:number)'] description: [ 'Returns the greatest integer less than or equal to :number.' ] examples: [ { description: 'Floor of an double' q: 'input mock name="thurstone" | z = y / x, floor = floor(z)' } { description: 'Floor of an integer' q: 'set @floor = floor(42)' } ] related: ['function:ceil', 'function:round'] } { name: 'ceil' type: 'function' subtype: 'math' syntax: ['ceil(:number)'] description: [ 'Returns the least integer greater than or equal to :number.' ] examples: [ { description: 'Ceiling of an double' q: 'input mock name="thurstone" | z = y / x, ceil = ceil(z)' } { description: 'Ceiling of an integer' q: 'set @ceil = ceil(42)' } ] related: ['function:floor', 'function:round'] } { name: 'abs' type: 'function' subtype: 'math' syntax: ['abs(:number)'] description: [ 'Returns the absolute value of :number.' ] examples: [ { description: 'Absolute value of a positive number' q: 'set @abs = abs(10)' } { description: 'Absolute value of a negative number' q: 'set @abs = abs(-99)' } ] } { name: 'sign' type: 'function' subtype: 'math' syntax: ['sign(:number)'] description: [ 'Returns 1 if :number is greater than zero, -1 if :number is less than zero, and 0 if :number is zero.' 'Returns NaN if :number is NaN.' ] examples: [ { description: 'Sign of a positive number' q: 'set @sign = sign(10)' } { description: 'Sign of a negative number' q: 'set @sign = sign(-99)' } { description: 'Sign of zero' q: 'set @sign = sign(0)' } ] } { name: 'sqrt' type: 'function' subtype: 'math' syntax: ['sqrt(:number)'] description: [ 'Returns the square root of :number.' ] examples: [ { q: 'input mock name="thurstone" | sqrt = sqrt(x + y)' } { description: 'Square root of a perfect square' q: 'set @square = sqrt(64)' } ] related: ['function:pow'] } { name: 'pow' type: 'function' subtype: 'math' syntax: ['pow(:base, :power)'] description: [ 'Returns :base raised to the power of :power.' ] examples: [ { q: 'input mock name="thurstone" | cube = pow(x + y, 3)' } { description: 'Square root of a square' q: 'set @square = sqrt(pow(8, 2))' } ] related: ['function:sqrt'] } { name: 'round' type: 'function' subtype: 'math' syntax: ['round(:number)', 'round(:number, :places)'] description: [ 'Rounds a number to a given number of decimal places.' 'If the 2nd argument is omitted, the number is rounded to an integer (0 decimal places).' ] examples: [ { description: 'Rounding to an integer' q: 'input mock name="thurstone" | stats p90 = percentile(x, 90), r = round(p90)' } { description: 'Rounding to five decimal places' q: 'input mock name="thurstone" | stats z = mean(x / y), r = round(z, 5)' } ] related: ['function:ceil', 'function:floor'] } { name: 'within' type: 'function' subtype: 'math' syntax: ['within(:number, :test, :tolerance)'] description: [ 'Returns true if the difference between :number and :test is less than or equal to :tolerance. That is, it evaluates whether the value of :number is in the range of :test +/- :tolerance (inclusive).' ] examples: [ { q: 'input mock | x = within(col1, col3, 1)' } { description: 'Comparing maximum Chick weights to the average' q: 'input mock name="chick-weight" | stats mean=mean(weight), max=max(weight), stdev = stddev(weight) by Chick | withinOneSigma = within(mean, max, stdev)' } ] related: ['function:within%'] } { name: 'within%' type: 'function' subtype: 'math' syntax: ['within%(:number, :test, :percent)'] description: [ 'Similar to within(), but uses :percent to calculate the tolerance from :test. Returns true if the difference between :number and :test is less than or equal to (:percent * :test).' 'The :percent argument is expected as a decimal or percentage literal: "0.1" or "10%". A value of "10" is interpreted as 1000%, not 10%.' ] examples: [ { q: 'input mock | select col1, col4 | x = within%(col1, col4, 50%)' } { description: 'Comparing maximum Chick weights to the average' q: 'input mock name="chick-weight" | stats avg=avg(weight), max=max(weight) by Chick | test = within%(max, avg, 50%)' } ] related: ['function:within'] } { name: 'greatest' type: 'function' subtype: 'math' syntax: ['greatest(:number, :number, ...)'] description: [ 'Returns the argument with the greatest numerical value, regardless of order.' 'greatest(null) returns null, and non-numerical arguments will cause an exception. If a single argument is provided, it will be returned regardless of its type.' ] examples: [ { q: 'input mock | greatest = greatest(col1, col2, col3)' } ] related: ['function:least'] } { name: 'least' type: 'function' subtype: 'math' syntax: ['least(:number, :number, ...)'] description: [ 'Returns the argument with the smallest numerical value, regardless of order.' 'least(null) returns null, and non-numerical arguments will cause an exception. If a single argument is provided, it will be returned regardless of its type.' ] examples: [ { q: 'input mock | least = least(col1, col2, col3)' } ] related: ['function:greatest'] } { name: 'gcd' type: 'function' subtype: 'math' syntax: ['gcd(:integer, :integer)'] description: [ 'Returns the greatest common divisor of two integers.' 'Returns null if either :integer is null, or if non-integer arguments are passed.' ] examples: [ { q: 'set @gcd = gcd(12, 18)' } ] related: ['function:lcm'] } { name: 'lcm' type: 'function' subtype: 'math' syntax: ['lcm(:integer, :integer)'] description: [ 'Returns the least common multiple of two integers.' 'Returns null if either :integer is null, or if non-integer arguments are passed.' ] examples: [ { q: 'set @lcm = lcm(12, 18)' } ] related: ['function:gcd'] } { name: 'ln' type: 'function' subtype: 'math' syntax: ['ln(:number)'] description: [ 'Returns the natural logarithm (base e) for :number' 'Returns null for non-numerical arguments. If :number is NaN or less than zero, returns NaN. If :number is positive infinity, then returns positive infinity. If :number is positive zero or negative zero, then returns negative infinity.' ] examples: [ { q: 'set @ln = ln(5)' } ] related: ['function:e', 'function:log'] } { name: 'log' type: 'function' subtype: 'math' syntax: ['log(:number)'] description: [ 'Returns the base 10 logarithm for :number' 'Returns null for non-numerical arguments. If :number is NaN or less than zero, returns NaN. If :number is positive infinity, then returns positive infinity. If :number is positive zero or negative zero, then returns negative infinity.' ] examples: [ { q: 'set @log = log(5)' } ] related: ['function:ln'] } { name: 'degrees' type: 'function' subtype: 'trigonometric' syntax: ['degrees(:angle)'] description: [ 'Converts an :angle in radians to degrees.' ] examples: [ { q: 'set @degrees = degrees(pi() / 2)' } ] related: ['function:radians'] } { name: 'radians' type: 'function' subtype: 'trigonometric' syntax: ['radians(:angle)'] description: [ 'Converts an :angle in degrees to radians.' ] examples: [ { q: 'set @radians = radians(45)' } ] related: ['function:degrees'] } { name: 'sin' type: 'function' subtype: 'trigonometric' syntax: ['sin(:number)'] description: [ 'Returns the trigonometric sine of an angle in radians.' 'If :number is NaN or infinity, returns NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @sin = sin(3.1415)' } ] related: ['function:cos', 'function:tan', 'function:asin', 'function:sinh'] } { name: 'cos' type: 'function' subtype: 'trigonometric' syntax: ['cos(:number)'] description: [ 'Returns the trigonometric cosine of an angle in radians.' 'If :number is NaN or infinity, returns NaN.' ] examples: [ { q: 'set @cos = cos(3.1415)' } ] related: ['function:sin', 'function:tan', 'function:acos', 'function:cosh'] } { name: 'tan' type: 'function' subtype: 'trigonometric' syntax: ['tan(:number)'] description: [ 'Returns the trigonometric tangent of an angle in radians.' 'If :number is NaN or infinity, returns NaN. If :number is zero, then the result is a zero with the same sign as :number.' ] examples: [ { q: 'set @tan = tan(3.1415)' } ] related: ['function:sin', 'function:cos', 'function:atan', 'function:atan2', 'function:tanh'] } { name: 'sinh' type: 'function' subtype: 'trigonometric' syntax: ['sinh(:number)'] description: [ 'Returns the hyperbolic sine of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is infinite, then the result is an infinity with the same sign as :number. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @sinh = sinh(3.1415)' } ] related: ['function:sin', 'function:cosh', 'function:tanh', 'function:asin'] } { name: 'cosh' type: 'function' subtype: 'trigonometric' syntax: ['cosh(:number)'] description: [ 'Returns the hyperbolic cosine of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is infinite, then the result then the result is positive infinity. If :number is zero, then the result is 1.' ] examples: [ { q: 'set @cosh = cosh(3.1415)' } ] related: ['function:cos', 'function:sinh', 'function:tanh', 'function:acos'] } { name: 'tanh' type: 'function' subtype: 'trigonometric' syntax: ['tanh(:number)'] description: [ 'Returns the hyperbolic tangent of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is zero, then the result is zero. If :number is positive infinity, then the result is 1. If :number is negative infinity, then the result is -1.0.' ] examples: [ { q: 'set @tanh = tanh(3.1415)' } ] related: ['function:sinh', 'function:cosh', 'function:tan', 'function:atan'] } { name: 'asin' type: 'function' subtype: 'trigonometric' syntax: ['asin(:number)'] description: [ 'Returns the arc sine of an angle in radians.' 'If :number is NaN or its absolute value is greater than 1, then the result is NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @asin = asin(0.5)' } ] related: ['function:sin', 'function:sinh', 'function:acos', 'function:atan'] } { name: 'acos' type: 'function' subtype: 'trigonometric' syntax: ['acos(:number)'] description: [ 'Returns the arc cosine of an angle in radians.' 'If :number is NaN or its absolute value is greater than 1, then the result is NaN.' ] examples: [ { q: 'set @acos = acos(0.5)' } ] related: ['function:cos', 'function:cosh', 'function:asin', 'function:atan'] } { name: 'atan' type: 'function' subtype: 'trigonometric' syntax: ['atan(:number)'] description: [ 'Returns the arc tangent of an angle in radians.' 'If :number is NaN, then the result is NaN. If :number is zero, then the result is zero.' ] examples: [ { q: 'set @atan = atan(0.5)' } ] related: ['function:tan', 'function:tanh', 'function:asin', 'function:acos'] } { name: 'atan2' type: 'function' subtype: 'trigonometric' syntax: ['atan2(:y, :x)'] description: [ 'Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).' ] examples: [ { q: 'set @atan2 = atan2(1, 1)' } ] related: ['function:tan', 'function:tanh', 'function:tan', 'function:atan'] } { name: 'pdfuniform' type: 'function' subtype: 'probability' syntax: [ 'pdfuniform(:number)' 'pdfuniform(:number, :min, :max)' 'pdfuniform(:list)' 'pdfuniform(:list, :min, :max)' ] description: [ 'Returns the continuous uniform distribution function of the given :number or :list, with default values of min=0, max=1.' 'If a :list is provided, the result will be a list with pdfuniform() applied to each element.' ] examples: [ { q: 'set @pdf = pdfuniform(0.5), @pdf2 = pdfuniform(0.5, 0, 5)' } { description: 'Applying pdfuniform() to a list' q: 'project range(0, 10) | P = pdfnormal(value, 0, 10)' } ] related: ['function:cdfuniform', 'function:pdfnormal', 'function:pdfpoisson'] } { name: 'pdfnormal' type: 'function' subtype: 'probability' syntax: [ 'pdfnormal(:number)' 'pdfnormal(:number, :mean, :sd)' 'pdfnormal(:list)' 'pdfnormal(:list, :mean, :sd)' ] description: [ 'Returns the continuous Normal cumulative distribution function of the given :number or :list, with default values of mean=0, sd=1.' 'If a :list is provided, the result will be a list with pdfnormal() applied to each element.' ] examples: [ { q: 'set @pdf = pdfnormal(0.5), @pdf2 = pdfnormal(0.5, 0, 5)' } { description: 'Applying pdfnormal() to a list' q: 'project range(0, 10) | P = pdfnormal(value, 0, 10)' } ] related: ['function:cdfnormal', 'function:pdfuniform', 'function:pdfpoisson'] } { name: 'pdfpoisson' type: 'function' subtype: 'probability' syntax: [ 'pdfpoisson(:number)' 'pdfpoisson(:number, :lambda)' 'pdfpoisson(:list)' 'pdfpoisson(:list, :lambda)' ] description: [ 'Returns the continuous Poisson cumulative distribution function of the given :number or :list, with default value of lambda=1.' 'If a :list is provided, the result will be a list with pdfpoisson() applied to each element.' ] examples: [ { q: 'set @pdf = pdfpoisson(0.5), @pdf2 = pdfpoisson(0.5, 5)' } { description: 'Applying pdfpoisson() to a list' q: 'project range(0, 10) | P = pdfpoisson(value, 2)' } ] related: ['function:cdfpoisson', 'function:pdfuniform', 'function:pdfnormal'] } { name: 'cdfuniform' type: 'function' subtype: 'probability' syntax: [ 'cdfuniform(:number)' 'cdfuniform(:number, :min, :max)' 'cdfuniform(:list)' 'cdfuniform(:list, :min, :max)' ] description: [ 'Returns the Uniform cumulative distribution function of the given :number or :list, with default values of min=0, max=1.' 'If a :list is provided, the result will be a list with cdfuniform() applied to each element.' ] examples: [ { q: 'set @cdf = cdfuniform(0.5), @cdf2 = cdfuniform(0.5, 0, 5)' } { description: 'If plant weights are equally probable, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfuniform(weight, min(weight), max(weight))' } { description: 'Same as above, but with lists' q: 'input mock name="plant-growth" \n| set @weights = pluck(weight)\n| set @P = cdfuniform(@weights, listmin(@weights), listmax(@weights));' } ] related: ['function:pdfuniform', 'function:cdfnormal', 'function:cdfpoisson'] } { name: 'cdfnormal' type: 'function' subtype: 'probability' syntax: [ 'cdfnormal(:number)' 'cdfnormal(:number, :mean, :sd)' 'cdfnormal(:list)' 'cdfnormal(:list, :mean, :sd)' ] description: [ 'Returns the Normal cumulative distribution function of the given :number or :list, with default values of mean=0, sd=1.' 'If a :list is provided, the result will be a list with cdfnormal() applied to each element.' ] examples: [ { q: 'set @cdf = cdfnormal(0.5), @cdf2 = cdfnormal(0.5, 0, 5)' } { description: 'If plant weights have a normal distribution, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfnormal(weight, mean(weight), stddev(weight))' } { description: 'Same as above, but with lists' q: 'input mock name="plant-growth" \n| set @weights = pluck(weight)\n| set @P = cdfnormal(@weights, listmean(@weights), liststddev(@weights));' } ] related: ['function:pdfnormal', 'function:cdfuniform', 'function:cdfpoisson'] } { name: 'cdfpoisson' type: 'function' subtype: 'probability' syntax: [ 'cdfpoisson(:number)' 'cdfpoisson(:number, :lambda)' 'cdfpoisson(:list)' 'cdfpoisson(:list, :lambda)' ] description: [ 'Returns the Poisson cumulative distribution function of the given :number or :list, with default value of lambda=1.' 'If a :list is provided, the result will be a list with cdfpoisson() applied to each element.' ] examples: [ { q: 'set @cdf = cdfpoisson(3), @cdf2 = cdfpoisson(3, 4)' } { description: 'If plant weights have a normal distribution, calculate the probability for each plant that another plant weighs less than or equal to it.' q: 'input mock name="plant-growth" | P = cdfpoisson(weight, mean(weight), stddev(weight))' } { description: 'Applying cdfpoisson() to a list' q: 'set @l = cdfpoisson([1,2,3,4,5,6,7], 2)' } ] related: ['function:pdfpoisson', 'function:cdfuniform', 'function:cdfnormal'] } { name: 'len' type: 'function' subtype: 'string' description: [ 'len() is an alias for length().' ] aliases: ['function:length'] } { name: 'substring' type: 'function' subtype: 'string' syntax: [ 'substring(:string, :start)' 'substring(:string, :start, :end)' ] description: [ 'Returns a substring of the given :string, beginning with the character at the :start index, and extending either to the end of the string, or to the character before the :end index.' 'The :start and :end indices are inclusive and exclusive, respectively. If the :end index is beyond the end of :string, the substring will extend to the end of the :string.' 'Returns null if :string is either null or not a string.' 'Do not confuse this function with substr(), which takes a :start index and a number of characters.' ] examples: [ { description: 'With start but no end' q: 'set @sub = substring("Parsec is cool!", 10)' } { description: 'With a start and end' q: 'set @sub = substring("Parsec is cool!", 10, 14)' } { description: 'Using indexof()' q: 'set @s = "Hello World", @sub = substring(@s, indexof(@s, "o"), indexof(@s, "r"))' } ] related: ['function:substr'] } { name: 'substr' type: 'function' subtype: 'string' syntax: [ 'substr(:string, :start)' 'substr(:string, :start, :length)' ] description: [ 'Returns a substring of the given :string, beginning with the character at the :start index, and extending either to the end of the string, or to the next :length number of characters.' 'The :start index is inclusive. If the :length extends beyond the end of :string, the substring will extend to the end of the :string.' 'Returns null if :string is either null or not a string.' 'Do not confuse this function with substring(), which takes a :start index and an :end index.' ] examples: [ { description: 'With start but no length' q: 'set @sub = substr("Parsec is cool!", 10)' } { description: 'With a start and length' q: 'set @sub = substr("Parsec is cool!", 10, 4)' } { description: 'Using indexof()' q: 'set @s = "Hello World", @sub = substr(@s, indexof(@s, "W"))' } ] related: ['function:substring', 'function:indexof'] } { name: 'indexof' type: 'function' subtype: 'string' syntax: [ 'indexof(:string, :value)' ] description: [ 'Returns the first index of :value in :string, if it exists. If :value is not found, it will return null.' 'If :value is not a string, it will be converted to a string automatically. This allows indexof() to find numbers in a string, for example.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @index = indexof("Parsec", "s")' } { q: 'set @s = "Hello World", @sub = substr(@s, indexof(@s, "W"))' } ] related: ['function:lastindexof'] } { name: 'lastindexof' type: 'function' subtype: 'string' syntax: [ 'lastindexof(:string, :value)' ] description: [ 'Returns the last index of :value in :string, if it exists. If :value is not found, it will return null.' 'If :value is not a string, it will be converted to a string automatically. This allows lastindexof() to find numbers in a string, for example.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @index = lastindexof("123,445,660.0", ",")' } { q: 'set @s = "Hello World", @sub = substr(@s, lastindexof(@s, "o"))' } ] related: ['function:indexof'] } { name: 'trim' type: 'function' subtype: 'string' syntax: ['trim(:string)'] returns: 'string' description: [ 'The trim() function removes whitespace from both ends of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = trim(" parsec\t ")' } ] related: ['function:ltrim', 'function:rtrim'] } { name: 'ltrim' type: 'function' subtype: 'string' syntax: ['ltrim(:string)'] returns: 'string' description: [ 'The ltrim() function removes whitespace from the left end of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = ltrim(" parsec")' } ] related: ['function:trim', 'function:rtrim'] } { name: 'rtrim' type: 'function' subtype: 'string' syntax: ['rtrim(:string)'] returns: 'string' description: [ 'The rtrim() function removes whitespace from the right end of a string.' 'This function follows the Java whitespace definition: https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = rtrim("parsec ")' } ] related: ['function:trim', 'function:ltrim'] } { name: 'uppercase' type: 'function' subtype: 'string' syntax: ['uppercase(:string)'] returns: 'string' description: [ 'The uppercase() function returns its argument converted to uppercase.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = uppercase("parsec")' } ] related: ['function:lowercase'] } { name: 'lowercase' type: 'function' subtype: 'string' syntax: ['lowercase(:string)'] returns: 'string' description: [ 'The lowercase() function returns its argument converted to lowercase.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @x = lowercase("parsec")' } ] related: ['function:uppercase'] } { name: 'replace' type: 'function' subtype: 'string' syntax: ['replace(:string, :search, :replacement)'] returns: 'string' description: [ 'Replaces the first instance of :search in :string with :replacement.' 'If either :search or :replacement are not strings, they will be converted to strings automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @string = replace("aaabbbbccc", "a", "x")' } ] related: ['function:replaceall'] } { name: 'replaceall' type: 'function' subtype: 'string' syntax: ['replaceall(:string, :search, :replacement)'] returns: 'string' description: [ 'Replaces all instance of :search in :string with :replacement.' 'If either :search or :replacement are not strings, they will be converted to strings automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @string = replaceall("aaabbbbccc", "a", "x")' } ] related: ['function:replace'] } { name: 'startswith' type: 'function' subtype: 'string' syntax: ['startswith(:string, :search)'] returns: 'string' description: [ 'Returns true if :string begins with :search, else false.' 'If :search is not a string, it will be converted to a string automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @test = startswith("parsec", "p")' } ] related: ['function:endswith'] } { name: 'endswith' type: 'function' subtype: 'string' syntax: ['endswith(:string, :search)'] returns: 'string' description: [ 'Returns true if :string ends with :search, else false.' 'If :search is not a string, it will be converted to a string automatically.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'set @test = endswith("parsec", "c")' } ] related: ['function:startswith'] } { name: 'join' type: 'function' subtype: 'string' syntax: [ 'join(:list)' 'join(:list, :separator)' ] returns: 'string' description: [ 'Returns a string of all elements in :list, concatenated together with an optional :separator between them.' 'Returns null if :list is either null or not a list.' ] examples: [ { q: 'set @string = join(["a", "b", "c"], ", ")' } { q: 'input mock | set @col1 = join(pluck(col1), "-")' } ] } { name: 'split' type: 'function' subtype: 'string' syntax: ['split(:string, :delimiter)'] returns: 'list' description: [ 'Splits a string into tokens using a delimiter and returns a list of the tokens. A regex can be given as :delimiter.' ] examples: [ { q: 'input mock | x = split("1,2,3", ",")' } { description: 'Using regex to match delimiters' q: 'set @phone = pop(split("(425)555-1234", "[^\d]"))' } ] } { name: 'urlencode' type: 'function' subtype: 'string' syntax: ['urlencode(:string)'] returns: 'string' description: [ 'Translates a string into application/x-www-form-urlencoded format.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = urlencode("x=1&y=2")' } ] related: ['function:urldecode'] } { name: 'urldecode' type: 'function' subtype: 'string' syntax: ['urldecode(:string)'] returns: 'string' description: [ 'Decodes a string encoded in the application/x-www-form-urlencoded format.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = urldecode("x%3D1%26y%3D2")' } ] related: ['function:urlencode'] } { name: 'base64encode' type: 'function' subtype: 'string' syntax: ['base64encode(:string)'] returns: 'string' description: [ 'Encodes a string into a base64 string representation.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = base64encode("hello world"), y = base64decode(x)' } ] related: ['function:base64decode'] } { name: 'base64decode' type: 'function' subtype: 'string' syntax: ['base64decode(:string)'] returns: 'string' description: [ 'Decodes a string from a base64-encoded string.' 'Returns null if :string is either null or not a string.' ] examples: [ { q: 'input mock | x = base64encode("hello world"), y = base64decode(x)' } ] related: ['function:base64encode'] } { name: 'parsejson' type: 'function' subtype: 'parsing' syntax: [ 'parsejson(:string)' ] description: [ 'Parses a JSON string and returns the result. Any valid JSON data type may be returned, including lists, maps, strings, numbers, and booleans.' ] examples: [ { description: 'Parsing a string' q: 'input mock | x = parsejson(\'"my-json"\')' } { description: 'Parsing a list' q: 'input mock | list = parsejson("[" + col1 + "," + col2 + "," + col3 + "]")' } { description: 'Projecting a JSON list of maps as a new data set' q: 'project parsejson(\'[{ "x": 1, "y": 2 }, {"x": 3, "y": 4 }]\')' } ] related: ['function:jsonpath', 'function:parsecsv', 'function:parsexml'] } { name: 'parsecsv' type: 'function' subtype: 'parsing' syntax: [ 'parsecsv(:string)' 'parsecsv(:string, { delimiter: string, quote: string, eol: string })' ] description: [ 'Parses a CSV string and returns the result (list of maps).' ] examples: [ { description: 'Parsing CSV with default options' q: 'set @text="a,b,c\n1,2,3\n4,5,6\n7,8,9", @parsed = parsecsv(@text)' } { description: 'Using a custom end-of-line and delimiter' q: 'set @text="col1~col2~col3|1~2~3|4~5~6|7~8~9", @parsed = parsecsv(@text, { eol: "|", delimiter: "~" })' } { description: 'Parsing data without a header row' q: 'set @text="1,2,3\n4,5,6\n7,8,9", @parsed = parsecsv(@text, { headers: false })' } { description: 'Parsing a TSV string (tab-separated values)' q: 'set @text="col1\tcol2\tcol3|1\t2\t3|4\t5\t6|7\t8\t9", @parsed = parsecsv(@text, { eol: "|", delimiter: "\t" })' } ] related: ['function:parsejson', 'function:parsexml'] } { name: 'parsexml' type: 'function' subtype: 'parsing' syntax: [ 'parsexml(:string)' 'parsexml(:string, :xpath)' 'parsexml(:string, { xpath: string, raw: boolean, flatten: boolean })' ] description: [ 'Parses an XML string and returns the result (list of maps).' ] examples: [ { description: 'Without an XPath expression, parsing starts at the root element' q: 'input mock | xml = "<root>" + col1 + "</root>", parsed = parsexml(xml)' } { description: 'Attributes are parsed into columns' q: 'input mock | xml = \'<root q="xyz" s="abc">\' + col1 + \'</root>\', parsed = parsexml(xml)' } { description: 'By default, child elements are flattened.' q: 'input mock | xml = "<root><col1>" + col1 + "</col1><col2>" + col2 + "</col2></root>", parsed = parsexml(xml, "/root")' } { description: 'Repeated elements are parsed into multiple rows' q: 'input mock | xml = "<root><val>" + col1 + "</val><val>" + col2 + "</val></root>", parsed = parsexml(xml, "/root/val")' } { description: 'Hacker News' q: 'input http uri="http://news.ycombinator.com/rss" | project parsexml(first(body), "/rss/channel/item")' } ] related: ['function:parsecsv', 'function:parsejson'] } { name: 'jsonpath' type: 'function' subtype: 'parsing' syntax: [ 'jsonpath(:map-or-list, :string)' ] description: [ 'Applies a JsonPath expression to a map or list and returns the result. Any valid JSON data type may be returned, including lists, maps, strings, numbers, and booleans.' 'This function cannot be used on JSON strings. Use parsejson() beforehand to convert the strings into objects.' 'The http input type has a built-in option for using jsonpath().' 'JsonPath reference: http://goessner.net/articles/JsonPath/. For specific implementation reference, see: https://github.com/gga/json-path' ] examples: [ { description: 'Select a field' q: 'set @results = jsonpath({ numbers: [1, 2, 3] }, "$.numbers")' } { description: 'Select a field of all children' q: 'set @obj = { messages: [{from: "PI:EMAIL:<EMAIL>END_PI"}, {from: "PI:EMAIL:<EMAIL>END_PI"}, {from: "PI:EMAIL:<EMAIL>END_PI"}] },\n @results = jsonpath(@obj, "$.messages[*].from")' } ] related: ['input:http', 'function:parsejson'] } { name: 'if' type: 'function' subtype: 'conditional' syntax: [ 'if(:predicate, :when-true)' 'if(:predicate, :when-true, :when-false)' ] description: [ 'Evaluates :predicate and, if true, returns :when-true. Else returns :when-false.' 'If the :when-false clause is omitted, null will be returned' ] examples: [ { q: 'input mock | x = if(col1 < 3, "less than three", "greater than three")' } ] } { name: 'case' type: 'function' subtype: 'conditional' syntax: [ 'case(:predicate1, :result1 [, :predicate2, :result2 ...])' ] description: [ 'Evalutes a series of test expression & result pairs from left to right. The first test expression that evaluates to true will cause its corresponding result expression to be returned. If no test expression evaluates to true, the function will return null.' 'If an odd number of arguments are provided, the last will be treated as an "else" clause, and returned in absense of any other successful test' ] examples: [ { description: 'With two test expressions' q: 'input mock | x = case(col3 == 3, "apples", col3 == 5, "oranges")' } { description: 'With an "else" clause' q: 'input mock | x = case(col1 == 1, "one", col1 == 2, "two", "else")' } { description: 'With a single test expression' q: 'input mock | greaterThanThree = case(col1 >= 3, true)' } ] } { name: 'coalesce' type: 'function' subtype: 'conditional' syntax: [ 'coalesce(:expression1 [, :expression2, ...])' ] description: [ 'Returns the first non-null expression in the argument list.' 'If all expressions are null, coalesce() returns null.' ] examples: [ { q: 'input mock | x = coalesce(null, null, 1)' } ] } { name: 'reverse' type: 'function' subtype: 'list' syntax: [ 'reverse(:string)' 'reverse(:list)' ] returns: 'string | list' description: [ 'Returns the characters in a string, or items in a list. Returns null for all other arguments.' ] examples: [ { description: 'Reversing a string' q: 'set @reversed = reverse("Parsec")' } { description: 'Reversing a list' q: 'set @reversed = reverse([1, 2, 3, 4])' } ] } { name: 'listmean' type: 'function' subtype: 'list' syntax: [ 'listmean(:list)' ] returns: 'number' description: [ 'Returns the arithmetic mean of the list elements in :list.' 'Throws an error if any of the list elements are non-numerical.' ] examples: [ { q: 'set @listmean = listmean([1, 2, 3, 4])' } ] aliases: ['function:lmean'] } { name: 'listmax' type: 'function' subtype: 'list' syntax: [ 'listmax(:list)' ] returns: 'number' description: [ 'Returns the element in :list with the maximal value of all elements.' 'Throws an error if any of the list elements are non-numerical, unless :list has only a single element, in which case that element is returned.' ] examples: [ { q: 'set @listmax = listmax([2, 10, 4, 8, 5])' } ] aliases: ['function:lmax'] } { name: 'listmin' type: 'function' subtype: 'list' syntax: [ 'listmin(:list)' ] returns: 'number' description: [ 'Returns the element in :list with the minimal value of all elements.' 'Throws an error if any of the list elements are non-numerical, unless :list has only a single element, in which case that element is returned.' ] examples: [ { q: 'set @listmin = listmin([2, 10, 4, 8, 5])' } ] aliases: ['function:lmin'] } { name: 'lmean' type: 'function' subtype: 'list' description: [ 'lmean() is an alias for listmean().' ] aliases: ['function:listmean'] } { name: 'lmax' type: 'function' subtype: 'list' description: [ 'lmax() is an alias for listmax().' ] aliases: ['function:listmax'] } { name: 'lmin' type: 'function' subtype: 'list' description: [ 'lmin() is an alias for listmin().' ] aliases: ['function:listmin'] } { name: 'liststddev' type: 'function' subtype: 'list' syntax: [ 'liststddev(:list)' ] returns: 'number' description: [ 'Returns the sample standard deviation of :list.' 'If the list is the complete population, use liststddevp() instead to calculate the population standard deviation.' ] examples: [ { q: 'set @liststddev = liststddev([2, 10, 4, 8, 5])' } ] related: ['function:liststddevp'] } { name: 'liststddevp' type: 'function' subtype: 'list' syntax: [ 'liststddevp(:list)' ] returns: 'number' description: [ 'Returns the population standard deviation of :list.' 'If the list is not the complete population, use liststddev() instead to calculate the sample standard deviation.' ] examples: [ { q: 'set @liststddevp = liststddevp([2, 10, 4, 8, 5])' } ] related: ['function:liststddev'] } { name: 'length' type: 'function' subtype: 'list' syntax: [ 'length(:string)' 'length(:list)' ] returns: 'number' description: [ 'Returns the number of characters in a string, or items in a list. Returns null for all other arguments.' ] examples: [ { description: 'Length of a string' q: 'set @length = length("Parsec")' } { description: 'Length of a list' q: 'set @length = length([1, 2, 3, 4])' } ] aliases: ['function:len'] } { name: 'peek' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'peek(:list)' ] description: [ 'Returns the first item in a list. To retrieve the last item of the list, use peeklast().' 'peek() on an empty list returns null.' ] examples: [ { q: 'set @first = peek([1,2,3])' } ] related: ['function:peeklast', 'function:pop', 'function:push'] } { name: 'peeklast' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'peeklast(:list)' ] description: [ 'Returns the last item in a list. To retrieve the first item of the list, use peek().' 'peeklast() on an empty list returns null.' ] examples: [ { q: 'set @last = peeklast([1,2,3])' } ] related: ['function:peek', 'function:pop', 'function:push'] } { name: 'pop' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'pop(:list)' ] description: [ 'Returns a list without the first item. To retrieve the first value of the list, use peek().' 'pop() on an empty list throws an error.' ] examples: [ { q: 'set @list = pop([1,2,3])' } ] related: ['function:peek', 'function:push'] } { name: 'push' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'push(:list, :value)' 'push(:list, :value, :value, ...)' ] description: [ 'Appends one or more values to the end of a list and returns the updated list.' ] examples: [ { description: 'One value' q: 'set @list = push([1, 2, 3], 4)' } { description: 'Two values' q: 'set @list = push([1, 2, 3], 4, 5)' } ] related: ['function:pop', 'function:concat'] } { name: 'concat' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'concat(:list, :list)' 'concat(:list, :list, :list, ...)' 'concat(:list, :value)' ] description: [ 'Concatenates one or more lists or values together, from left to right.' 'Non-list arguments will be converted into lists and concatenated.' ] examples: [ { description: 'Two lists' q: 'set @list = concat([1, 2, 3], [4, 5, 6])' } { description: 'Three lists' q: 'set @list = concat([1, 2, 3], [4, 5, 6], [7, 8, 9])' } { description: 'Lists and non-lists' q: 'set @list = concat([1, 2, 3], 4, 5, [6, 7])' } ] related: ['function:push'] } { name: 'contains' type: 'function' subtype: 'list' returns: 'boolean' syntax: ['contains(:list, :expr)', 'contains(:string, :expr)'] description: [ 'Returns true if :expr is contained as a member of :list, else false.' 'If :string is given instead of :list, it returns true if :expr is a substring of :string, else false. If necessary, :expr will be automatically converted to a string to perform the comparison.' ] examples: [ { q: 'input mock | set @list = [1, 2, 5] | test = contains(@list, col1)' } { q: 'input mock | str = "hello world", hasWorld = contains(str, "world")' } ] } { name: 'distinct' type: 'function' subtype: 'list' returns: 'list' syntax: ['distinct(:list)'] description: [ 'Returns a list of the elements of :list with duplicates removed.' 'distinct(null) returns null; same for any non-list argument.' ] examples: [ { q: 'input mock | set @list = [1, 1, 2, 3, 2, 3] | test = distinct(@list)' } ] } { name: 'flatten' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'flatten(:list)' ] description: [ 'Flattens a list of lists one level deep.' ] examples: [ { description: 'Two lists' q: 'set @list = flatten([[1, 2, 3], [4, 5, 6]])' } { description: 'Three lists' q: 'set @list = flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]])' } { description: 'Lists and non-lists' q: 'set @list = flatten([0, [1, 2, 3], 4, 5, [6, 7]])' } { description: 'Deeply-nested data' q: 'set @list = flatten([[["red", "blue"], ["apple", "orange"]], [["WA", "CA"], ["Seattle", "San Franscisco"]]])' } ] related: ['function:flattendeep'] } { name: 'flattendeep' type: 'function' subtype: 'list' returns: 'list' syntax: [ 'flattendeep(:list)' ] description: [ 'Flattens a list of lists recursively.' ] examples: [ { description: 'Two lists' q: 'set @list = flattendeep([[1, 2, 3], [4, 5, 6]])' } { description: 'Lists and non-lists' q: 'set @list = flattendeep([0, [1, 2, 3], 4, 5, [6, 7]])' } { description: 'Deeply-nested data' q: 'set @list = flattendeep([[["WA", "OR", "AK"], ["CA", "AZ"]], [["IN", "IL"], ["GA", "TX"]]])' } ] related: ['function:flatten'] } { name: 'index' type: 'function' subtype: 'list' returns: 'any' syntax: [ 'index(:list, :index)' ] description: [ 'Returns the element of :list at the given 0-based :index.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), values = values(map), second = index(values, 1)' } ] } { name: 'range' type: 'function' subtype: 'list' syntax: [ 'range(start,end,step)' ] returns: 'list' description: [ 'Returns a list of numbers from start to end, by step. If only one argument is provided (end), start defaults to 0. If two arguments are provided (start,end), step defaults to 1. If step=0 it will remain the default of 1.' ] examples: [ { q: 'input mock | range = range(10)' } { q: 'input mock | range = range(-10, 10)' } { q: 'input mock | range = range(-10, 10, 2)' } ] } { name: 'get' type: 'function' subtype: 'map' syntax: [ 'get(:map, :key)' 'get(:map, :key, :default)' 'get(:map, [:key, ...])' 'get(:map, [:key, ...], :default)' ] returns: 'any' description: [ 'Retrieves the value for :key in :map. If a list of :keys is given, it will traverse nested maps by applying get() in a recursive fashion.' 'Returns null if :key is not found, or optionally :default if provided.' ] examples: [ { q: 'set @headers = {Accepts: "application/json"}, @accepts = get(@headers, "Accepts")' } { description: 'With a default value' q: 'set @headers = {Accepts: "application/json"}, @accepts = get(@headers, "Accepts")' } ] related: ['function:set', 'function:delete', 'function:merge'] } { name: 'set' type: 'function' subtype: 'map' syntax: [ 'set(:map, :key, :value)' 'set(:map, [:key, ...], :value)' ] returns: 'map' description: [ 'Sets the :value for :key in :map, and returns the modified map.' 'If a list of :keys is given, it will traverse nested maps for each :key, and set the value of the last :key to :value. Any missing keys will be initialized with empty maps. If a key exists but is not a map, an exception will be thrown.' ] examples: [ { q: 'set @headers = {},\n @headers = set(@headers, "Accept", "text/plain")\n @headers = set(@headers, "Content-Type", "application/xml")' } { description: 'Setting nested keys' q: 'set @req = {},\n @req = set(@req, ["headers", "Accept"], "text/plain")\n @req = set(@req, ["headers", "Content-Type"], "application/xml")' } ] related: ['function:get', 'function:delete', 'function:merge'] } { name: 'delete' type: 'function' subtype: 'map' syntax: [ 'delete(:map, :key)' 'delete(:map, [:key, ...])' ] returns: 'map' description: [ 'Deletes the value for :key in :map, and returns the modified map.' 'If a list of :keys is given, it will traverse nested maps and for each :key, and delete the last :key. Any maps which were made empty will be removed.' ] examples: [ { q: 'set @headers = {"Accept": "application/json", "Content-Type": "application/json"},\n @updated = delete(@headers, "Accept")' } { description: 'Deleting a nested key' q: 'set @req = {headers: {"Accept": "application/json", "Content-Type": "application/json"}},\n @updated = delete(@req, ["headers", "Accept"])' } ] related: ['function:get', 'function:set', 'function:merge'] } { name: 'merge' type: 'function' subtype: 'map' syntax: [ 'merge(:map, ...)' ] returns: 'map' description: [ 'Returns a map created by merging the keys of each argument :map together, with subsequent maps overwriting keys of previous maps.' 'Any number of maps can be merged together. Any non-map arguments will be ignored.' ] examples: [ { q: 'set @headers = merge({"Content-Type": "application/json", "Accept-Language": "en-US,en;q=0.8"}, {"Content-Length": 100})' } ] related: ['function:get', 'function:set', 'function:delete', 'function:merge'] } { name: 'keys' type: 'function' subtype: 'map' syntax: [ 'keys(:map)' ] returns: 'list' description: [ 'Returns a list of the keys in :map.' 'keys(null) returns null.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), keys = keys(map)' } ] related: ['function:values'] } { name: 'values' type: 'function' subtype: 'map' syntax: [ 'values(:map)' ] returns: 'list' description: [ 'Returns a list of the values in :map.' 'values(null) returns null.' ] examples: [ { q: 'input mock | map = tomap("foo", "bar", "fooz", "baz"), values = values(map)' } ] related: ['function:keys'] } { name: 'adler32' type: 'function' subtype: 'digest' returns: 'string' syntax: ['adler32(:string)'] description: ['Computes the Adler-32 checksum of :string'] examples: [ { q: 'set @digest = adler32("hello world")' } ] related: ['function:sha256', 'function:sha1', 'function:sha512'] } { name: 'crc32' type: 'function' subtype: 'digest' returns: 'string' syntax: ['crc32(:string)'] description: ['Computes the CRC-32 cyclic redundancy check of :string'] examples: [ { q: 'set @digest = crc32("hello world")' } ] related: ['function:adler32', 'function:md5'] } { name: 'gost' type: 'function' subtype: 'digest' returns: 'string' syntax: ['gost(:string)'] description: ['Computes the GOST R 34.11-94 hash of :string'] examples: [ { q: 'set @digest = gost("hello world")' } ] related: ['function:hmac_gost', 'function:ripemd128', 'function:sha1'] } { name: 'hmac_gost' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_gost(:string, :secret)'] description: ['Computes the HMAC of :string using the GOST R 34.11-94 hash and :secret'] examples: [ { q: 'set @digest = hmac_gost("hello world", "secret")' } ] related: ['function:gost', 'function:ripemd128'] } { name: 'md5' type: 'function' subtype: 'digest' returns: 'string' syntax: ['md5(:string)'] description: ['Computes the MD5 hash of :string'] examples: [ { q: 'set @digest = md5("hello world")' } ] related: ['function:hmac_md5', 'function:sha256', 'function:sha1', 'function:sha512'] } { name: 'hmac_md5' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_md5(:string, :secret)'] description: ['Computes the HMAC of :string using the MD5 hash and :secret'] examples: [ { q: 'set @digest = hmac_md5("hello world", "secret")' } ] related: ['function:md5', 'function:sha256', 'function:sha1', 'function:sha512'] } { name: 'ripemd128' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd128(:string)'] description: ['Computes the RIPEMD-128 hash of :string'] examples: [ { q: 'set @digest = ripemd128("hello world")' } ] related: ['function:hmac_ripemd128', 'function:gost', 'function:ripemd256', 'function:ripemd320', 'function:sha1'] } { name: 'hmac_ripemd128' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd128(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-128 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd128("hello world", "secret")' } ] related: ['function:ripemd128', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'ripemd256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd256(:string)'] description: ['Computes the RIPEMD-256 hash of :string'] examples: [ { q: 'set @digest = ripemd256("hello world")' } ] related: ['function:hmac_ripemd256', 'function:gost', 'function:ripemd128', 'function:ripemd320', 'function:sha256'] } { name: 'hmac_ripemd256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd256(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd256("hello world", "secret")' } ] related: ['function:ripemd256', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'ripemd320' type: 'function' subtype: 'digest' returns: 'string' syntax: ['ripemd320(:string)'] description: ['Computes the RIPEMD-320 hash of :string'] examples: [ { q: 'set @digest = ripemd320("hello world")' } ] related: ['function:hmac_ripemd320', 'function:gost', 'function:ripemd128', 'function:ripemd256', 'function:sha384'] } { name: 'hmac_ripemd320' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_ripemd320(:string, :secret)'] description: ['Computes the HMAC of :string using the RIPEMD-320 hash and :secret'] examples: [ { q: 'set @digest = hmac_ripemd320("hello world", "secret")' } ] related: ['function:ripemd256', 'function:hmac_gost', 'function:hmac_ripemd128'] } { name: 'sha1' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha1(:string)'] description: ['Computes the SHA-1 hash of :string'] examples: [ { q: 'set @digest = sha1("hello world")' } ] related: ['function:hmac_sha1', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'hmac_sha1' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha1(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-1 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha1("hello world", "secret")' } ] related: ['function:sha1', 'function:sha512', 'function:md5'] } { name: 'sha3_224' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_224(:string)'] description: ['Computes the SHA-3-224 hash of :string'] examples: [ { q: 'set @digest = sha3_224("hello world")' } ] related: ['function:hmac_sha3_224', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_224' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_224(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-224 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_224("hello world", "secret")' } ] related: ['function:sha3_224', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_256(:string)'] description: ['Computes the SHA-3-256 hash of :string'] examples: [ { q: 'set @digest = sha3_256("hello world")' } ] related: ['function:hmac_sha3_256', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_256(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_256("hello world", "secret")' } ] related: ['function:sha3_256', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_384' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_384(:string)'] description: ['Computes the SHA-3-384 hash of :string'] examples: [ { q: 'set @digest = sha3_384("hello world")' } ] related: ['function:hmac_sha3_384', 'function:sha1', 'function:sha384', 'function:md5'] } { name: 'hmac_sha3_384' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_384(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-384 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_384("hello world", "secret")' } ] related: ['function:sha3_384', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha3_512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha3_512(:string)'] description: ['Computes the SHA-3-224 hash of :string'] examples: [ { q: 'set @digest = sha3_512("hello world")' } ] related: ['function:hmac_sha3_512', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha3_512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha3_512(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-3-512 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha3_512("hello world", "secret")' } ] related: ['function:sha3_512', 'function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'sha256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha256(:string)'] description: ['Computes the SHA-256 hash of :string'] examples: [ { q: 'set @digest = sha256("hello world")' } ] related: ['function:hmac_sha256', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'hmac_sha256' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha256(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-256 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha256("hello world", "secret")' } ] related: ['function:sha256', 'function:sha1', 'function:sha512', 'function:md5'] } { name: 'sha512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['sha512(:string)'] description: ['Computes the SHA-512 hash of :string'] examples: [ { q: 'set @digest = sha512("hello world")' } ] related: ['function:hmac_sha512', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_sha512' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_sha512(:string, :secret)'] description: ['Computes the HMAC of :string using the SHA-512 hash and :secret'] examples: [ { q: 'set @digest = hmac_sha512("hello world", "secret")' } ] related: ['function:sha512', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'siphash' type: 'function' subtype: 'digest' returns: 'string' syntax: ['siphash(:string, :secret)'] description: [ 'Computes the HMAC of :string using the SipHash-2-4 hash and a 128-bit :secret.' ':secret must be 128-bits, e.g. a 16-character string.' ] examples: [ { q: 'set @digest = siphash("hello world", "abcdefghijklmnop")' } ] related: ['function:siphash48', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'siphash48' type: 'function' subtype: 'digest' returns: 'string' syntax: ['siphash48(:string, :secret)'] description: [ 'Computes the HMAC of :string using the SipHash-4-8 hash and a 128-bit :secret.' ':secret must be 128-bits, e.g. a 16-character string.' ] examples: [ { q: 'set @digest = siphash48("hello world", "abcdefghijklmnop")' } ] related: ['function:siphash', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'tiger' type: 'function' subtype: 'digest' returns: 'string' syntax: ['tiger(:string)'] description: ['Computes the Tiger-192 hash of :string'] examples: [ { q: 'set @digest = tiger("hello world")' } ] related: ['function:hmac_tiger', 'function:sha1', 'function:sha256', 'function:md5'] } { name: 'hmac_tiger' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_tiger(:string, :secret)'] description: ['Computes the HMAC of :string using the Tiger-192 hash and :secret'] examples: [ { q: 'set @digest = hmac_tiger("hello world", "secret")' } ] related: ['function:tiger', 'function:sha1', 'function:hmac_sha1', 'function:md5'] } { name: 'whirlpool' type: 'function' subtype: 'digest' returns: 'string' syntax: ['whirlpool(:string)'] description: ['Computes the Whirlpool hash of :string'] examples: [ { q: 'set @digest = whirlpool("hello world")' } ] related: ['function:hmac_whirlpool', 'function:tiger', 'function:sha256', 'function:md5'] } { name: 'hmac_whirlpool' type: 'function' subtype: 'digest' returns: 'string' syntax: ['hmac_whirlpool(:string, :secret)'] description: ['Computes the HMAC of :string using the Whirlpool hash and :secret'] examples: [ { q: 'set @digest = hmac_whirlpool("hello world", "secret")' } ] related: ['function:whirlpool', 'function:hmac_tiger', 'function:hmac_sha1', 'function:md5'] } { name: 'random' type: 'function' subtype: 'math' syntax: [ 'random()' 'random(:upperBound)' 'random(:lowerBound, :upperBound)' ] returns: 'double' description: [ 'Returns a random number between 0 inclusive and 1 exclusive, when no arguments are provided.' 'When called with a single argument, returns a random number between 0 inclusive and :upperBound, exclusive.' 'When called with two arguments, returns a random number between :lowerBound inclusive and :upperBound, exclusive.' ] examples: [ { description: 'Random number between 0 and 1 (exclusive)' q: 'set @rand = random()' } { description: 'Random number between 0 and 10 (exclusive)' q: 'set @rand = floor(random(10))' } { description: 'Random number between 1 and 10 (exclusive)' q: 'set @rand = floor(random(1,10))' } ] } { name: 'rank' type: 'function' syntax: [ 'rank()' ] description: [ 'Returns the current row number in the dataset. The rownumber statement is faster for the general case, but as a function this may be more versatile.' 'Can be used in the assignment statement, stats statement, and pivot statement. Cannot be used in a group-by expression.' ] examples: [ { q: 'input mock | x = rank()' } { q: 'input mock | name = "row " + (rank() + 1)' } { q: 'input mock name="chick-weight" | stats avgWeight = mean(weight), rank=rank() by Chick' } ] related: ['statement:rownumber'] } { name: 'hostname' type: 'function' syntax: [ 'hostname()' ] description: [ 'Returns the current hostname of the Parsec server.' ] examples: [ { q: 'set @hostname = hostname()' } ] related: ['function:ip'] } { name: 'ip' type: 'function' syntax: [ 'ip()' ] description: [ 'Returns the current IP address of the Parsec server.' ] examples: [ { q: 'set @ip = ip()' } ] related: ['function:hostname'] } { name: 'runtime' type: 'function' syntax: [ 'runtime()' ] description: [ 'Returns information about Parsec\'s JVM runtime.' ] examples: [ { q: 'set @runtime = runtime()' } { q: 'project [runtime()]' } ] related: ['function:os'] } { name: 'os' type: 'function' syntax: [ 'os()' ] description: [ 'Returns operating-system level information.' ] examples: [ { q: 'set @os = os()' } { q: 'project [os()]' } ] related: ['function:runtime'] } { name: 'now' type: 'function' subtype: 'date and time' syntax: [ 'now()' ] description: [ 'Returns the current date/time in the time zone of the server.' ] examples: [ { q: 'set @now = now()' } ] related: ['function:nowutc', 'function:today', 'function:yesterday', 'function:tomorrow'] } { name: 'nowutc' type: 'function' subtype: 'date and time' syntax: [ 'nowutc()' ] description: [ 'Returns the current date/time in the UTC time zone.' ] examples: [ { q: 'set @nowutc = nowutc()' } ] related: ['function:nowutc', 'function:todayutc', 'function:yesterdayutc', 'function:tomorrowutc'] } { name: 'today' type: 'function' subtype: 'date and time' syntax: [ 'today()' ] description: [ 'Returns the date/time of midnight of the current day, in the time zone of the server.' ] examples: [ { q: 'set @today = today()' } ] related: ['function:todayutc', 'function:now', 'function:yesterday', 'function:tomorrow'] } { name: 'todayutc' type: 'function' subtype: 'date and time' syntax: [ 'todayutc()' ] description: [ 'Returns the date/time of midnight of the current day, in the UTC time zone.' ] examples: [ { q: 'set @todayutc = todayutc()' } ] related: ['function:today', 'function:nowutc', 'function:yesterdayutc', 'function:tomorrowutc'] } { name: 'yesterday' type: 'function' subtype: 'date and time' syntax: [ 'yesterday()' ] description: [ 'Returns the date/time of midnight yesterday, in the time zone of the server.' ] examples: [ { q: 'set @yesterday = yesterday()' } ] related: ['function:yesterdayutc', 'function:now', 'function:today', 'function:tomorrow'] } { name: 'yesterdayutc' type: 'function' subtype: 'date and time' syntax: [ 'yesterdayutc()' ] description: [ 'Returns the date/time of midnight yesterday, in the UTC time zone.' ] examples: [ { q: 'set @yesterdayutc = yesterdayutc()' } ] related: ['function:yesterday', 'function:todayutc', 'function:nowutc', 'function:tomorrowutc'] } { name: 'tomorrow' type: 'function' subtype: 'date and time' syntax: [ 'tomorrow()' ] description: [ 'Returns the date/time of midnight tomorrow, in the time zone of the server.' ] examples: [ { q: 'set @tomorrow = tomorrow()' } ] related: ['function:todayutc', 'function:now', 'function:yesterday', 'function:tomorrow'] } { name: 'tomorrowutc' type: 'function' subtype: 'date and time' syntax: [ 'tomorrowutc()' ] description: [ 'Returns the date/time of midnight tomorrow, in the UTC time zone.' ] examples: [ { q: 'set @tomorrowutc = tomorrowutc()' } ] related: ['function:tomorrow', 'function:nowutc', 'function:yesterdayutc', 'function:todayutc'] } { name: 'tolocaltime' type: 'function' subtype: 'date and time' syntax: [ 'tolocaltime(:datetime)' ] description: [ 'Converts a date/time to the local time zone of the server.' ] examples: [ { q: 'set @nowutc = nowutc(), @nowlocal = tolocaltime(@nowutc)' } ] related: ['function:toutctime', 'function:totimezone'] } { name: 'toutctime' type: 'function' subtype: 'date and time' syntax: [ 'toutctime(:datetime)' ] description: [ 'Converts a date/time to the UTC time zone.' ] examples: [ { q: 'set @now = now(), @nowutc = toutctime(@now)' } ] related: ['function:tolocaltime', 'function:totimezone'] } { name: 'totimezone' type: 'function' subtype: 'date and time' syntax: [ 'totimezone(:datetime, :timezone)' ] description: [ 'Converts a date/time to another time zone. :timezone must be a long-form time zone, e.g. "America/Matamoros".' 'A list of all valid time zones can be retrieved using timezones().' ] examples: [ { q: 'set @southpole = totimezone(now(), "Antarctica/South_Pole"), @str = tostring(@southpole)' } ] related: ['function:tolocaltime', 'function:totimezone', 'function:timezones'] } { name: 'timezones' type: 'function' subtype: 'date and time' syntax: ['timezones()'] description: [ 'Returns a list of all available time zones, for use with totimezone()' ] examples: [ { q: 'set @tz = timezones()' } { description: 'Project as dataset' q: 'project timezones()' } ] related: ['function:totimezone'] } { name: 'toepoch' type: 'function' subtype: 'date and time' syntax: ['toepoch(:datetime)'] returns: 'number' description: [ 'Converts :datetime into the number of seconds after the Unix epoch.' ] examples: [ q: 'set @timestamp = toepoch(now())' ] related: ['function:toepochmillis'] } { name: 'toepochmillis' type: 'function' subtype: 'date and time' syntax: ['toepochmillis(:datetime)'] returns: 'number' description: [ 'Converts :datetime into the number of milliseconds after the Unix epoch.' ] examples: [ q: 'set @timestamp = toepochmillis(now())' ] related: ['function:toepoch'] } { name: 'startofminute' type: 'function' subtype: 'date and time' syntax: ['startofminute(:datetime)'] returns: 'datetime' description: [ 'Returns :datetime with the number of seconds and milliseconds zeroed.' ] examples: [ q: 'set @time = startofminute(now())' ] related: ['function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofhour' type: 'function' subtype: 'date and time' syntax: ['startofhour(:datetime)'] returns: 'datetime' description: [ 'Returns :datetime with the number of minutes, seconds, and milliseconds zeroed.' ] examples: [ q: 'set @time = startofhour(now())' ] related: ['function:startofminute', 'function:startofday', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofday' type: 'function' subtype: 'date and time' syntax: ['startofday(:datetime)'] returns: 'datetime' description: [ 'Returns midnight on the same day as :datetime.' ] examples: [ q: 'set @time = startofday(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofweek', 'function:startofmonth', 'function:startofyear'] } { name: 'startofweek' type: 'function' subtype: 'date and time' syntax: ['startofweek(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the week, in the same week as :datetime.' ] examples: [ q: 'set @time = startofweek(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofmonth', 'function:startofyear'] } { name: 'startofmonth' type: 'function' subtype: 'date and time' syntax: ['startofmonth(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the month, in the same month as :datetime.' ] examples: [ q: 'set @time = startofmonth(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofyear'] } { name: 'startofyear' type: 'function' subtype: 'date and time' syntax: ['startofyear(:datetime)'] returns: 'datetime' description: [ 'Returns midnight of the first day of the year, in the same year as :datetime.' ] examples: [ q: 'set @time = startofyear(now())' ] related: ['function:startofminute', 'function:startofhour', 'function:startofday', 'function:startofweek', 'function:startofmonth'] } { name: 'millisecond' type: 'function' subtype: 'date and time' syntax: ['millisecond(:datetime)'] returns: 'number' description: [ 'Returns the millisecond of second component of the given :datetime.' ] examples: [ q: 'set @millis = millisecond(now())' ] related: ['function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'millisecondofday' type: 'function' subtype: 'date and time' syntax: ['millisecondofday(:datetime)'] returns: 'number' description: [ 'Returns the number of milliseconds elapsed since midnight in :datetime.' ] examples: [ q: 'set @millis = millisecondofday(now())' ] related: ['function:millisecond', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'second' type: 'function' subtype: 'date and time' syntax: ['second(:datetime)'] returns: 'number' description: [ 'Returns the second of minute component of the given :datetime.' ] examples: [ q: 'set @seconds = second(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'secondofday' type: 'function' subtype: 'date and time' syntax: ['secondofday(:datetime)'] returns: 'number' description: [ 'Returns the number of seconds elapsed since midnight in :datetime.' ] examples: [ q: 'set @seconds = secondofday(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'minute' type: 'function' subtype: 'date and time' syntax: ['minute(:datetime)'] returns: 'number' description: [ 'Returns the minute of hour component of the given :datetime.' ] examples: [ q: 'set @minutes = minute(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'minuteofday' type: 'function' subtype: 'date and time' syntax: ['minuteofday(:datetime)'] returns: 'number' description: [ 'Returns the number of minutes elapsed since midnight in :datetime.' ] examples: [ q: 'set @minutes = minuteofday(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'hour' type: 'function' subtype: 'date and time' syntax: ['hour(:datetime)'] returns: 'number' description: [ 'Returns the hour of day component of the given :datetime.' ] examples: [ q: 'set @hours = hour(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'day' type: 'function' subtype: 'date and time' syntax: ['day(:datetime)'] returns: 'number' description: [ 'Returns the day of month component of the given :datetime.' ] examples: [ q: 'set @day = day(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'dayofweek' type: 'function' subtype: 'date and time' syntax: ['dayofweek(:datetime)'] returns: 'number' description: [ 'Returns the day of week component of the given date/time, where Monday is 1 and Sunday is 7.' ] examples: [ q: 'set @day = dayofweek(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'dayofyear' type: 'function' subtype: 'date and time' syntax: ['dayofyear(:datetime)'] returns: 'number' description: [ 'Returns the number of days elapsed since the beginning of the year, including the current day of :datetime.' ] examples: [ q: 'set @days = dayofyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:weekyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'weekyear' type: 'function' subtype: 'date and time' syntax: ['weekyear(:datetime)'] returns: 'number' description: [ 'Returns the week year for a given date. In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year. The weekyear allows you to query the effective year for that day.' 'The weekyear is used by the function weekofweekyear().' ] examples: [ q: 'set @weekyear = weekyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekofweekyear', 'function:month', 'function:year'] } { name: 'weekofweekyear' type: 'function' subtype: 'date and time' syntax: ['weekofweekyear(:datetime)'] returns: 'number' description: [ 'Given a date, returns the number of weeks elapsed since the beginning of the weekyear. In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year.' 'The function weekyear() gives the current weekyear for a given date.' ] examples: [ q: 'set @weeks = weekofweekyear(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:month', 'function:year'] } { name: 'month' type: 'function' subtype: 'date and time' syntax: ['month(:datetime)'] returns: 'number' description: [ 'Returns the month component of the given :datetime.' ] examples: [ q: 'set @months = month(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:year'] } { name: 'year' type: 'function' subtype: 'date and time' syntax: ['year(:datetime)'] returns: 'number' description: [ 'Returns the year of the given :datetime.' ] examples: [ q: 'set @years = year(now())' ] related: ['function:millisecond', 'function:millisecondofday', 'function:second', 'function:secondofday', 'function:minute', 'function:minuteofday', 'function:hour', 'function:day', 'function:dayofweek', 'function:dayofyear', 'function:weekyear', 'function:weekofweekyear', 'function:month'] } { name: 'adddays' type: 'function' subtype: 'date and time' } { name: 'addhours' type: 'function' subtype: 'date and time' } { name: 'addmilliseconds' type: 'function' subtype: 'date and time' } { name: 'addminutes' type: 'function' subtype: 'date and time' } { name: 'addmonths' type: 'function' subtype: 'date and time' } { name: 'addseconds' type: 'function' subtype: 'date and time' } { name: 'addweeks' type: 'function' subtype: 'date and time' } { name: 'addyears' type: 'function' subtype: 'date and time' } { name: 'minusdays' type: 'function' subtype: 'date and time' } { name: 'minushours' type: 'function' subtype: 'date and time' } { name: 'minusmilliseconds' type: 'function' subtype: 'date and time' } { name: 'minusminutes' type: 'function' subtype: 'date and time' } { name: 'minusmonths' type: 'function' subtype: 'date and time' } { name: 'minusseconds' type: 'function' subtype: 'date and time' } { name: 'minusweeks' type: 'function' subtype: 'date and time' } { name: 'minusyears' type: 'function' subtype: 'date and time' } { name: 'interval' type: 'function' subtype: 'date and time' } { name: 'inmillis' type: 'function' subtype: 'date and time' } { name: 'inseconds' type: 'function' subtype: 'date and time' } { name: 'inminutes' type: 'function' subtype: 'date and time' } { name: 'inhours' type: 'function' subtype: 'date and time' } { name: 'indays' type: 'function' subtype: 'date and time' } { name: 'inweeks' type: 'function' subtype: 'date and time' } { name: 'inmonths' type: 'function' subtype: 'date and time' } { name: 'inyears' type: 'function' subtype: 'date and time' } { name: 'period' type: 'function' subtype: 'date and time' syntax: [ 'period(:value, :name)' ] description: [ 'Creates a time period representing some number (:value) of a particular time unit (:name).' 'The following units are supported: milliseconds, seconds, minutes, hours, days, weeks, months, years. Both singular/plural forms, as well as some short forms (min, sec) are accepted.' 'The bucket() function uses periods to group data.' ] examples: [ { q: 'set @fivemin = period(5, "minutes")' } { q: 'input mock | mins = period(col1, "minutes")' } { q: 'input mock | onehour = period(1, "hours")' } ], related: ['function:bucket'] } { name: 'earliest' type: 'function' subtype: 'date and time' syntax: [ 'earliest(:datetime, :datetime)' ] description: [ 'Given two dates, returns the date which occurs first chronologically.' ] examples: [ { q: 'set @firstOccurrence = earliest(todate("2015-04-20"), todate("2016-06-01"))' } { q: 'set @earliest = earliest(1462009645000, 1461999645000)' } ] related: ['function:latest'] } { name: 'latest' type: 'function' subtype: 'date and time' syntax: [ 'latest(:datetime, :datetime)' ] description: [ 'Given two dates, returns the date which occurs last chronologically.' ] examples: [ { q: 'set @lastOccurrence = latest(todate("2015-04-20"), todate("2016-06-01"))' } { q: 'set @latest = latest(1462009645000, 1461999645000)' } ] related: ['function:earliest'] } { name: 'isbetween' type: 'function' subtype: 'date and time' syntax: [ 'isbetween(:datetime, :start, :end)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after :start and before or at :end. In other words, the function returns true if :datetime is within the inclusive interval between :start and :end.' ] examples: [ { q: 'set @test = isbetween(now(), minusminutes(now(), 1), addminutes(now(), 1))' } ] } { name: 'istoday' type: 'function' subtype: 'date and time' syntax: [ 'istoday(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current day, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = istoday(now())' } ] related: ['function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'istomorrow' type: 'function' subtype: 'date and time' syntax: [ 'istomorrow(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of tomorrow, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = istomorrow(now())' } ] related: ['function:istoday', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isyesterday' type: 'function' subtype: 'date and time' syntax: [ 'isyesterday(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of yesterday, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isyesterday(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isthisweek' type: 'function' subtype: 'date and time' syntax: [ 'isthisweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isthisweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isnextweek' type: 'function' subtype: 'date and time' syntax: [ 'isnextweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the week after the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isnextweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'islastweek' type: 'function' subtype: 'date and time' syntax: [ 'islastweek(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the week prior to the current week, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = islastweek(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isthismonth' type: 'function' subtype: 'date and time' syntax: [ 'isthismonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isthismonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:islastmonth', 'function:isnextmonth'] } { name: 'isnextmonth' type: 'function' subtype: 'date and time' syntax: [ 'isnextmonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the month after the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = isnextmonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:islastmonth'] } { name: 'islastmonth' type: 'function' subtype: 'date and time' syntax: [ 'islastmonth(:datetime)' ] returns: 'boolean' description: [ 'Returns true if :datetime occurs at or after the start of the month prior to the current month, and before the end.' 'The result is relative to the timezone of :datetime. Use tolocaltime() or totimezone() to adjust if needed.' ] examples: [ { q: 'set @test = islastmonth(now())' } ] related: ['function:istoday', 'function:istomorrow', 'function:isyesterday', 'function:isthisweek', 'function:islastweek', 'function:isnextweek', 'function:isthismonth', 'function:isnextmonth'] } { name: 'bucket' type: 'function' syntax: [ 'bucket(:expr, :buckets)' ] description: [ 'Assigns buckets to :expr based on the 2nd argument, and returns the bucket for each value. Buckets can be numerical or time-based. The start of the bucket will be returned.' 'Numerical buckets are determined by dividing the set of real numbers into equivalent ranges of a given width. Numbers are then located in the buckets according to their value. For example, bucketing by 5 will yield buckets starting at 0, 5, 10, 15, etc. Numerical buckets can be fractions or decimals.' 'Time-based buckets are determined by dividing the time line into equivalent ranges of a given interval. The :buckets argument must be given as a Period, created by the period() function. For example, bucketing by a period of 5 minutes will yield buckets starting at 12:00, 12:05, 12:10, etc. Buckets are always aligned on the hour.' ] examples: [ { q: 'input mock | buckets = bucket(col1, 2)' } { description: 'Bucket by every 4th number and calculate an average per bucket' q: 'input mock name="chick-weight"\n| timebucket = bucket(Time, 4)\n| stats avgWeight = avg(weight) by timebucket\n| sort timebucket' } { description: 'Bucket by 5 minute periods' q: 'input mock n=20\n| t = minusMinutes(now(), col1)\n| tbuckets = bucket(t, period(5, "minutes"))' } ], related: ['function:period'] } { name: 'apply' type: 'function' subtype: 'functional' syntax: [ 'apply(:function, :args, ...)' ] description: [ 'Invokes a first-order :function with any number of arguments. Commonly used to execute functions stored in variables.' 'Using the def statement will avoid the need to call apply(), as the function will be mapped to a user-defined function name.' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @cube = (n) -> n*n*n, @cube9 = apply(@cube, 9)' } { q: 'input mock name="thurstone"\n| set @differenceFromAvg = (n, avg) -> abs(n - avg)\n| set @avgX = avg(x), @avgY = avg(y)\n| diffX = apply(@differenceFromAvg, x, @avgX)\n| diffY = apply(@differenceFromAvg, y, @avgY)' } ] related: ['symbol:->:function'] } { name: 'map' type: 'function' subtype: 'functional' syntax: [ 'map(:function, :list)' ] returns: 'list' description: [ 'Applies a first-order :function to each item in :list, and returns a list of the return values.' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @x = map(n -> n / 100, [10, 20, 30, 40, 50])' } { description: 'Using a function in a variable' q: 'set @percent = n -> n / 100,\n@x = map(@percent, [10, 20, 30, 40, 50])' } { description: 'Generating a dataset using map() and range()' q: 'project map((x) -> {`x`: x, `square`: x^2, `cube`: x^3, `fourth-power`: x^4}, range(1,10))' } ] related: ['symbol:->:function', 'function:mapcat', 'function:mapvalues', 'function:filter'] } { name: 'mapcat' type: 'function' subtype: 'functional' syntax: [ 'mapcat(:function, :list)' ] returns: 'list' description: [ 'Applies a first-order :function to each item in :list, and applies concat() over the return values.' 'Typically :function should return a list, otherwise it works identically to map().' 'Throws an exception if the first argument is not a function.' ] examples: [ { q: 'set @x = mapcat(n -> [n, n^2], [10, 20, 30, 40, 50])' } { description: 'Using a function in a variable' q: 'set @percent = n -> n / 100,\n@x = mapcat(@percent, [10, 20, 30, 40, 50])' } { description: 'Generating a set of ranges using mapcat() and range()' q: 'project mapcat((x) -> range(x, x + 5), [0, 10, 20, 30])' } ] related: ['symbol:->:function', 'function:map'] } { name: 'mapvalues' type: 'function' subtype: 'functional' syntax: [ 'mapvalues(:function, :map)' ] returns: 'map' description: [ 'Applies a first-order :function to the value of each key in :map, and returns a new map containing the keys and their return values.' 'Throws an exception if the first argument is not a function.' ] examples: [ { description: 'Increment each value in the map' q: 'set @map = mapvalues(n -> n+1, { x: 1, y: 2, z: 3 })' } { description: 'Using a function in a variable' q: 'set @inc = n -> n+1,\n@map = mapvalues(@inc, { x: 1, y: 2, z: 3 })' } ] related: ['symbol:->:function', 'function:map'] } { name: 'filter' type: 'function' subtype: 'functional' syntax: [ 'filter(:function, :list)' ] returns: 'list' description: [ 'Returns a list of items in :list for which the first-order :function returns true.' 'Throws an exception if the first argument is not a function.' ] examples: [ { description: 'Filtering for even numbers' q: 'set @x = filter(n -> n mod 2 == 0, range(1,20))' } { description: 'Using a function in a variable' q: 'set @isEven = n -> n mod 2 == 0,\n @x = filter(@isEven, range(1,20))' } ] related: ['symbol:->:function', 'function:map'] } { name: 'exec' type: 'function' subtype: 'execution' syntax: [ 'exec(:query)' 'exec(:query, { dataset: ":dataset-name" })' 'exec(:query, { variable: ":variable-name" })' 'exec(:query, { context: true })' ] returns: 'any' description: [ 'Executes a Parsec query contained in :query, and returns the resulting context object. Any parsing, execution, or type errors will return a context with errors, rather than throwing an exception.' 'A map of :options can be provided to return a specific part of the result, rather than the entire context. Either a single dataset or a single variable can be named in the :options, causing that dataset or variable value to be returned. If the dataset or variable is not found, null is returned. Caution: if an error occurs, the dataset or variable may not exist (depending on when the error occurs), so null may also be returned.' 'By default, uses a new isolated query context. However if the context option is set to true, the current parent context will be used to execute :query, allowing access to variables and datasets. Note this is read-only access; the parent context cannot be modified from within exec().' 'Returns null if :query is null.' ] examples: [ { q: 'set @x = exec("input mock")' } { description: 'Using options to select only the default dataset' q: 'set @dataset = exec("input mock", { dataset: "0" })' } { description: 'Using options to select a specific named dataset' q: 'set @dataset = exec("input mock | output name=\'mock\'; input mock name=\'chick-weight\'", { dataset: "mock" })' } { description: 'Using options to return only the value of a specific variable' q: 'set @avg = exec("input mock | set @avg=avg(col1+col2)", { variable: "@avg" })' } { description: 'Looking at the performance of a query ran with exec()' q: 'set @performance = get(exec("input mock"), "performance")' } { description: 'Using a shared context to access variables' q: 'set @price = 49.95,\n @tax = 9.2%,\n @total = exec("set @total = round(@price * (1 + @tax), 2)", { variable: "@total", context: true })' } ] } { name: 'mock' type: 'input' syntax: [ 'input mock' 'input mock n=:number' 'input mock name=:name' 'input mock name=:name incanterHome=:path' ] description: [ 'The mock input type is for testing and experimental purposes. By default, it returns a fixed dataset of 5 rows and 4 columns. If "n" is provided, the mock dataset will contain n-number of rows, and an additional column.' 'There are also specific test datasets included, which can be loaded using the "name" option. The available named datasets are: "iris", "cars", "survey", "us-arrests", "flow-meter", "co2", "chick-weight", "plant-growth", "pontius", "filip", "longely", "chwirut", "thurstone", "austres", "hair-eye-color", "airline-passengers", "math-prog", "iran-election".' 'By default, test datasets are loaded from GitHub. In order to load them from the local machine, download the Incanter source code (https://github.com/incanter/incanter), and provide the root directory as incanterHome.' ] examples: [ { description: 'Loading mock data' q: 'input mock' } { description: 'Loading lots of mock data' q: 'input mock n=100' } { description: 'Loading a named mock dataset' q: 'input mock name="chick-weight"' } { description: 'Loading a named dataset from disk (requires additional download)' q: 'input mock name="chick-weight" incanterHome="~/Downloads/incanter-master"' } ] related: ['statement:input'] } { name: 'datastore' type: 'input' syntax: [ 'input datastore name=:name' ] description: [ 'The datastore input type retrieves and loads datasets from the datastore in the current execution context. Datasets may have been written previously to the datastore using the temp or output statements.' ] examples: [ { description: 'Storing and loading a dataset' q: 'input mock | output name="ds1"; input datastore name="ds1"' } { description: 'Storing and loading a temporary dataset' q: 'input mock | temp ds2; input datastore name="ds2"' } ] related: ['statement:input'] } { name: 'jdbc' type: 'input' syntax: [ 'input jdbc uri=":uri" query=":query"' 'input jdbc uri=":uri" [user | username]=":username" password=":PI:PASSWORD:<PASSWORD>END_PI" query=":query"' 'input jdbc uri=":uri" [user | username]=":username" password=":PI:PASSWORD:<PASSWORD>END_PI" query=":query" operation=":operation"' ] description: [ 'The jdbc input type connects to various databases using the JDBC api and executes a query. The results of the query will be returned as the current dataset.' 'The default JDBC operation is "query", which is used for selecting data. The operation option can be used to provide another operation to run—currently, only "execute" is implemented. INSERT/UPDATE/DELETE/EXECUTE queries can all be run through the "execute" operation.' 'Caution: The implementation of the URI may vary across JDBC drivers, e.g. some require the username and password in the URI, whereas others as separate options. This is determined by the specific JDBC driver and its implementation, not Parsec. Please check the documentation for the JDBC driver you are using, or check the examples below. There may be multiple valid ways to configure some drivers.' 'The following JDBC drivers are bundled with Parsec: AWS Redshift, DB2, Hive2, HSQLDB, MySQL, PostgreSQL, Presto, Qubole, SQL Server, SQL Server (jTDS), Teradata.' ] examples: [ { description: 'Querying MySQL' q: 'input jdbc uri="jdbc:mysql://my-mysql-server:3306/database?user=username&password=PI:PASSWORD:<PASSWORD>END_PI"\nquery="..."' } { description: 'Inserting data into MySQL' q: 'input jdbc uri="jdbc:mysql://my-mysql-server:3306/database?user=username&password=PI:PASSWORD:<PASSWORD>END_PI" operation="execute"\nquery="INSERT INTO ... VALUES (...)"' } { description: 'Querying SQL Server' q: 'input jdbc uri="jdbc:sqlserver://my-sql-server:1433;databaseName=database;username=username;password=PI:PASSWORD:<PASSWORD>END_PI"\n query="..."' } { description: 'Querying Hive (Hiveserver2)' q: 'input jdbc uri="jdbc:hive2://my-hive-server:10000/default?mapred.job.queue.name=queuename" username="username" password="PI:PASSWORD:<PASSWORD>END_PI"\n query="show tables"' } { description: 'Querying Teradata' q: 'input jdbc uri="jdbc:teradata://my-teradata-server/database=database,user=user,password=PI:PASSWORD:<PASSWORD>END_PI"\n query="..."' } { description: 'Querying DB2' q: 'input jdbc uri="jdbc:db2://my-db2-server:50001/database:user=username;password=PI:PASSWORD:<PASSWORD>END_PI;"\n query="..."' } { description: 'Querying Oracle' q: 'input jdbc uri="jdbc:oracle:thin:username/password@//my-oracle-server:1566/database"\n query="..."' } { description: 'Querying PostgreSQL' q: 'input jdbc uri="jdbc:postgresql://my-postgres-server/database?user=username&password=PI:PASSWORD:<PASSWORD>END_PI"\n query="..."' } ] related: ['statement:input'] } { name: 'graphite' type: 'input' syntax: [ 'input graphite uri=":uri" targets=":target"' 'input graphite uri=":uri" targets=[":target", ":target"]' 'input graphite uri=":uri" targets=[":target", ":target"] from="-24h" until="-10min"' ] description: [ 'The graphite input type retrieves data from Graphite, a time-series database. One or more target metrics can be retrieved; any valid Graphite targets can be used, including functions and wildcards.' 'The :uri option should be set to the Graphite server UI or render API.' ] examples: [ { q: 'input graphite uri="http://my-graphite-server" targets="carbon.agents.*.metricsReceived" from="-4h"' } { description: 'Unpivoting metrics into a row' q: 'input graphite uri="http://my-graphite-server" targets="carbon.agents.*.*" from="-2h"\n| unpivot value per metric by _time\n| filter value != null' } ] related: ['statement:input'] } { name: 'http' type: 'input' syntax: [ 'input http uri=":uri"' 'input http uri=":uri" user=":user" password="PI:PASSWORD:<PASSWORD>END_PI*****"' 'input http uri=":uri" method=":method" body=":body"' 'input http uri=":uri" parser=":parser"' 'input http uri=":uri" parser=":parser" jsonpath=":jsonpath"' ] description: [ 'The http input type retrieves data from web servers using the HTTP/HTTPS networking protocol. It defaults to an HTTP GET without authentication, but can be changed to any HTTP method.' 'Optional authentication is available using the user/password options. Preemptive authentication can also be enabled, which sends the authentication in the initial request instead of waiting for a 401 response. This may be required by some web services.' 'Without the :parser option, a single row will be output, containing information about the request and response. If a parser is specified, the body of the file will be parsed and projected as the new data set. The JSON parser has an option jsonpath option, allowing a subsection of the JSON document to be projected.' 'Output columns are: "body", "headers", "status", "msg", "protocol", "content-type"' 'Available options: user, password, method, body, parser, headers, query, timeout, connection-timeout, request-timeout, compression-enabled, and follow-redirects.' ] examples: [ { description: 'Loading a web page' q: 'input http uri="http://www.expedia.com"' } { description: 'Authenticating with username and password' q: 'input http uri="http://my-web-server/path"\n user="readonly" password="PI:PASSWORD:<PASSWORD>END_PI"' } { description: 'Preemptive authentication (sending credentials with initial request)' q: 'input http uri="http://my-web-server/path"\n auth={ user: "readonly", password: "PI:PASSWORD:<PASSWORD>END_PI", preemptive: true }' } { description: 'Posting data' q: 'input http uri="http://my-web-server/path"\n method="post" body="{ \'key\': 123456 }"\n headers={ "Content-Type": "application/json" }' } { description: 'Providing custom headers' q: 'input http uri="http://my-web-server/path"\n headers={ "Accept": "application/json, text/plain, */*",\n "Accept-Encoding": "en-US,en;q=0.5" }' } { description: 'Parsing an XML file' q: 'input http uri="http://news.ycombinator.com/rss"\n| project parsexml(first(body), { xpath: "/rss/channel/item" })' } { description: 'Parsing a JSON file with JsonPath' q: 'input http uri="http://pastebin.com/raw/wzmy7TMZ" parser="json" jsonpath="$.values[*]"' } ] related: ['statement:input', 'function:parsexml', 'function:parsecsv', 'function:parsejson', 'function:jsonpath'] } { name: 'influxdb' type: 'input' syntax: [ 'input influxdb uri=":uri" db=":db" query=":query"' 'input influxdb uri=":uri" db=":db" query=":query" user=":user" password=":PI:PASSWORD:<PASSWORD>END_PI"' ] description: [ 'The influxdb input type retrieves data from InfluxDB, a time-series database. Supports InfluxDB 0.9 and higher.' 'The :uri option should be set to the Query API endpoint on an InfluxDB server; by default is is on port 8086. The URI of the Admin UI will not work.' 'An error will be thrown if multiple queries are sent in one input statement.' ] examples: [ { q: 'input influxdb uri="http://my-influxdb-server:8086/query"\n db="NOAA_water_database"\n query="SELECT * FROM h2o_feet"' } ] related: ['statement:input'] } { name: 'mongodb' type: 'input' syntax: [ 'input mongodb uri=":uri" query=":query"' ] description: [ 'The mongodb input type retrieves data from MongoDB, a NoSQL document database.' 'The :uri option should follow the standard connection string format, documented here: https://docs.mongodb.com/manual/reference/connection-string/.' 'The :query option accepts a limited subset of the Mongo Shell functionality.' ] examples: [ { q: 'input mongodb uri="mongodb://localhost:27017/testdb" query="show collections"' } { q: 'input mongodb uri="mongodb://localhost:27017/testdb" query="db.testcollection.find({type: \'orders\'}.sort({name: 1})"' } ] related: ['statement:input'] } { name: 's3' type: 'input' syntax: [ 'input s3 accessKeyId=":key-id" secretAccessKey=":secret"' 'input s3 accessKeyId=":key-id" secretAccessKey=":secret" token=":token"' 'input s3 uri="s3://:uri" accessKeyId=":key-id" secretAccessKey=":secret" token=":token" operation=":operation" maxKeys=:max-keys delimiter=:delimiter gzip=:gzip-enabled zip=:zip-enabled' 'input s3 uri="s3://:uri" accessKeyId=":key-id" secretAccessKey=":secret" token=":token" operation=":operation" maxKeys=:max-keys delimiter=:delimiter parser=":parser"' ] description: [ 'The s3 input type retrieves data from Amazon S3. It is designed to either retrieve information about objects stored in S3, or retrieve the contents of those objects.' 'The following operations are supported: "list-buckets", "list-objects", "list-objects-from", "get-objects", "get-objects-from", "get-object". The operation can be specified manually, or auto-detected based on the arguments.' 'Authentication requires AWS credentials of either accessKeyId/secretAccessKey, or accessKeyId/secretAccessKey/token.' '"list-objects" and "get-objects" have a default limit of 10 objects, which can be configured via the maxKeys option' '"list-objects-from" and "get-objects-from" use a marker to retrieve objects only after the given prefix or object. Partial object names are supported.' 'Zip or gzip-compressed objects can be decompressed by setting gzip=true, or zip=true. If neither is set, the object is assumed to be uncompressed' ] examples: [ { description: 'Listing all S3 buckets available for the given credentials' q: 'input s3 accessKeyId="***" secretAccessKey="****"' } { description: 'Listing all S3 objects in the given bucket' q: 'input s3 uri="s3://:bucket" accessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Listing S3 objects in the given bucket with a given prefix (prefix must end in /)' q: 'input s3 uri="s3://:bucket/:prefix/" accessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting the next level of the object hierarchy by using a delimiter.' q: 'input s3 uri="s3://:bucket/:prefix/" accessKeyId=":key-id" secretAccessKey=":secret-key" delimiter="/"' } { description: 'Getting an S3 object' q: 'input s3 uri="s3://:bucket/:prefix/:object.json"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting an S3 object and parsing its contents' q: 'input s3 uri="s3://:bucket/:prefix/:object.json" parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting multiple S3 objects and parsing their contents into a combined dataset' q: 'input s3 uri="s3://:bucket/:prefix/" operation="get-objects" parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Limiting the number of objects returned' q: 'input s3 uri="s3://:bucket/:prefix/" operation="list-objects" maxKeys=100\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } { description: 'Getting a single S3 object and parsing its contents' q: 'input s3 uri="s3://:bucket/:prefix/:object.json" gzip=true parser="jsonlines"\naccessKeyId=":key-id" secretAccessKey=":secret-key"' } ] related: ['statement:input'] } { name: 'smb' type: 'input' syntax: [ 'input smb uri="smb://:hostname/:path"' 'input smb uri="smb://:hostname/:path" user=":user" password="PI:PASSWORD:<PASSWORD>END_PI*****"' 'input smb uri="smb://:user:******@:hostname/:path"' 'input smb uri="smb://:hostname/:path" parser=":parser"' ] description: [ 'The smb input type retrieves data using the SMB/CIFS networking protocol. It can either retrieve directory listings or file contents.' 'Optional NTLM authentication is supported using the user/password options, or by embedding them in the :uri (slightly slower).' 'Without the :parser option, a single row will be output, containing metadata about the directory or file. If a parser is specified, the body of the file will be parsed and projected as the new data set (directories cannot be parsed).' 'Metadata columns are: "name", "path", "isfile", "body", "attributes", "createdTime", "lastmodifiedTime", "length", "files"' ] examples: [ { description: 'Retrieving a directory listing' q: 'input smb uri="smb://my-samba-server/my-share"\n user="readonly" password="PI:PASSWORD:<PASSWORD>END_PI"' } { description: 'Retrieving file metadata' q: 'input smb uri="smb://my-samba-server/my-share/file.txt"\n user="readonly" password="PI:PASSWORD:<PASSWORD>END_PI"' } { description: 'Parsing a JSON file' q: 'input smb uri="smb://my-samba-server/my-share/file.txt"\n user="readonly" password="PI:PASSWORD:<PASSWORD>END_PI" parser="json"' } ] related: ['statement:input'] } ] _.each documentation.tokens, (token) -> token.key = token.type + ':' + token.name token.typeKey = 'type:' + token.type token.subtypeKey = 'subtype:' + token.subtype if token.altName? token.key += ':' + token.altName if !token.description? console.log 'Token without description: ' + token.key if !token.examples? console.log 'Token without examples: ' + token.key return functions = _.sortBy _.filter(documentation.tokens, { type: 'function' }), 'subtype' groups = _.groupBy functions, 'subtype' _.each groups, (functions, name) -> console.log '# ' + name + ' functions' console.log _.sortBy(_.map(functions, 'name')).join('|') return documentation
[ { "context": "t-form\").serializeObject()\n form[\"reset-token\"] = window.location.hash.substring(1)\n apiCall \"POST\", \"/api/user/confirm_", "end": 547, "score": 0.5321102142333984, "start": 527, "tag": "PASSWORD", "value": "window.location.hash" }, { "context": "e\", {team_name: @state.team_name, team_password: @state.team_password}\n .done (resp) ->\n switch resp.status", "end": 2277, "score": 0.7053563594818115, "start": 2258, "tag": "PASSWORD", "value": "state.team_password" }, { "context": "n\", {team_name: @state.team_name, team_password: @state.team_password}\n .done (resp) ->\n switch resp.status\n ", "end": 2589, "score": 0.7675348520278931, "start": 2570, "tag": "PASSWORD", "value": "state.team_password" } ]
picoCTF-web/web/coffee/account.coffee
NNHSSE201819/picoCTF
0
updatePassword = (e) -> e.preventDefault() apiCall "POST", "/api/user/update_password", $("#password-update-form").serializeObject() .done (data) -> switch data['status'] when 1 ga('send', 'event', 'Authentication', 'UpdatePassword', 'Success') when 0 ga('send', 'event', 'Authentication', 'UpdatePassword', 'Failure::' + data.message) apiNotify data, "/account" resetPassword = (e) -> e.preventDefault() form = $("#password-reset-form").serializeObject() form["reset-token"] = window.location.hash.substring(1) apiCall "POST", "/api/user/confirm_password_reset", form .done (data) -> ga('send', 'event', 'Authentication', 'ResetPassword', 'Success') apiNotify data, "/" disableAccount = (e) -> e.preventDefault() confirmDialog("This will disable your account, drop you from your team, and prevent you from playing!", "Disable Account Confirmation", "Disable Account", "Cancel", () -> form = $("#disable-account-form").serializeObject() apiCall "POST", "/api/user/disable_account", form .done (data) -> ga('send', 'event', 'Authentication', 'DisableAccount', 'Success') apiNotify data, "/") Input = ReactBootstrap.Input Row = ReactBootstrap.Row Col = ReactBootstrap.Col Button = ReactBootstrap.Button Panel = ReactBootstrap.Panel Glyphicon = ReactBootstrap.Glyphicon ButtonInput = ReactBootstrap.ButtonInput ButtonGroup = ReactBootstrap.ButtonGroup update = React.addons.update # Should figure out how we want to share components. TeamManagementForm = React.createClass mixins: [React.addons.LinkedStateMixin] getInitialState: -> user: {} team: {} team_name: "" team_password: "" componentWillMount: -> apiCall "GET", "/api/user/status" .done ((api) -> @setState update @state, user: $set: api.data ).bind this apiCall "GET", "/api/team" .done ((api) -> @setState update @state, team: $set: api.data ).bind this onTeamRegistration: (e) -> e.preventDefault() if (!@state.team_name || !@state.team_password) apiNotify({status: 0, message: "Invalid team name or password."}) else apiCall "POST", "/api/team/create", {team_name: @state.team_name, team_password: @state.team_password} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 document.location.href = "/profile" onTeamJoin: (e) -> e.preventDefault() apiCall "POST", "/api/team/join", {team_name: @state.team_name, team_password: @state.team_password} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 document.location.href = "/profile" onTeamPasswordChange: (e) -> e.preventDefault() if @state.team_password != @state.confirm_team_password apiNotify {status: 0, message: "Passwords do not match."} else newpass = @state.team_password newpass_confirm = @state.confirm_team_password confirmDialog("This will change the password needed to join your team.", "Team Password Change Confirmation", "Confirm", "Cancel", () -> apiCall "POST", "/api/team/update_password", {"new-password": newpass, "new-password-confirmation": newpass_confirm} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 apiNotify resp, "/account" ) listMembers: () -> for member in @state.team["members"] <li>{member.username}</li> render: -> if @state.team.max_team_size > 1 and not @state.user.teacher towerGlyph = <Glyphicon glyph="tower"/> lockGlyph = <Glyphicon glyph="lock"/> teamCreated = (@state.user and @state.user.username != @state.user.team_name) if teamCreated <Panel header="Team Management"> <p><strong>Team Name:</strong> {@state.team.team_name}</p> <p><strong>Members</strong> ({@state.team.members.length}/{@state.team.max_team_size}):</p> <ul> {@listMembers()} </ul> <hr/> <form onSubmit={@onTeamPasswordChange}> <Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="New Team Password" required/> <Input type="password" valueLink={@linkState "confirm_team_password"} addonBefore={lockGlyph} label="Confirm New Team Password" required/> <Col md={6}> <Button type="submit">Change Team Password</Button> </Col> </form> </Panel> else <Panel header="Team Management"> <p>To avoid confusion on the scoreboard, you may not create a team that shares the same name as an existing user.</p> <form onSubmit={@onTeamJoin}> <Input type="text" valueLink={@linkState "team_name"} addonBefore={towerGlyph} label="Team Name" required/> <Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="Team Password" required/> <Col md={6}> <span> <Button type="submit">Join Team</Button> <Button onClick={@onTeamRegistration}>Register Team</Button> </span> </Col> </form> </Panel> else <div/> $ -> $("#password-update-form").on "submit", updatePassword $("#password-reset-form").on "submit", resetPassword $("#disable-account-form").on "submit", disableAccount React.render <TeamManagementForm/>, document.getElementById("team-management")
6739
updatePassword = (e) -> e.preventDefault() apiCall "POST", "/api/user/update_password", $("#password-update-form").serializeObject() .done (data) -> switch data['status'] when 1 ga('send', 'event', 'Authentication', 'UpdatePassword', 'Success') when 0 ga('send', 'event', 'Authentication', 'UpdatePassword', 'Failure::' + data.message) apiNotify data, "/account" resetPassword = (e) -> e.preventDefault() form = $("#password-reset-form").serializeObject() form["reset-token"] = <PASSWORD>.substring(1) apiCall "POST", "/api/user/confirm_password_reset", form .done (data) -> ga('send', 'event', 'Authentication', 'ResetPassword', 'Success') apiNotify data, "/" disableAccount = (e) -> e.preventDefault() confirmDialog("This will disable your account, drop you from your team, and prevent you from playing!", "Disable Account Confirmation", "Disable Account", "Cancel", () -> form = $("#disable-account-form").serializeObject() apiCall "POST", "/api/user/disable_account", form .done (data) -> ga('send', 'event', 'Authentication', 'DisableAccount', 'Success') apiNotify data, "/") Input = ReactBootstrap.Input Row = ReactBootstrap.Row Col = ReactBootstrap.Col Button = ReactBootstrap.Button Panel = ReactBootstrap.Panel Glyphicon = ReactBootstrap.Glyphicon ButtonInput = ReactBootstrap.ButtonInput ButtonGroup = ReactBootstrap.ButtonGroup update = React.addons.update # Should figure out how we want to share components. TeamManagementForm = React.createClass mixins: [React.addons.LinkedStateMixin] getInitialState: -> user: {} team: {} team_name: "" team_password: "" componentWillMount: -> apiCall "GET", "/api/user/status" .done ((api) -> @setState update @state, user: $set: api.data ).bind this apiCall "GET", "/api/team" .done ((api) -> @setState update @state, team: $set: api.data ).bind this onTeamRegistration: (e) -> e.preventDefault() if (!@state.team_name || !@state.team_password) apiNotify({status: 0, message: "Invalid team name or password."}) else apiCall "POST", "/api/team/create", {team_name: @state.team_name, team_password: @<PASSWORD>} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 document.location.href = "/profile" onTeamJoin: (e) -> e.preventDefault() apiCall "POST", "/api/team/join", {team_name: @state.team_name, team_password: @<PASSWORD>} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 document.location.href = "/profile" onTeamPasswordChange: (e) -> e.preventDefault() if @state.team_password != @state.confirm_team_password apiNotify {status: 0, message: "Passwords do not match."} else newpass = @state.team_password newpass_confirm = @state.confirm_team_password confirmDialog("This will change the password needed to join your team.", "Team Password Change Confirmation", "Confirm", "Cancel", () -> apiCall "POST", "/api/team/update_password", {"new-password": newpass, "new-password-confirmation": newpass_confirm} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 apiNotify resp, "/account" ) listMembers: () -> for member in @state.team["members"] <li>{member.username}</li> render: -> if @state.team.max_team_size > 1 and not @state.user.teacher towerGlyph = <Glyphicon glyph="tower"/> lockGlyph = <Glyphicon glyph="lock"/> teamCreated = (@state.user and @state.user.username != @state.user.team_name) if teamCreated <Panel header="Team Management"> <p><strong>Team Name:</strong> {@state.team.team_name}</p> <p><strong>Members</strong> ({@state.team.members.length}/{@state.team.max_team_size}):</p> <ul> {@listMembers()} </ul> <hr/> <form onSubmit={@onTeamPasswordChange}> <Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="New Team Password" required/> <Input type="password" valueLink={@linkState "confirm_team_password"} addonBefore={lockGlyph} label="Confirm New Team Password" required/> <Col md={6}> <Button type="submit">Change Team Password</Button> </Col> </form> </Panel> else <Panel header="Team Management"> <p>To avoid confusion on the scoreboard, you may not create a team that shares the same name as an existing user.</p> <form onSubmit={@onTeamJoin}> <Input type="text" valueLink={@linkState "team_name"} addonBefore={towerGlyph} label="Team Name" required/> <Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="Team Password" required/> <Col md={6}> <span> <Button type="submit">Join Team</Button> <Button onClick={@onTeamRegistration}>Register Team</Button> </span> </Col> </form> </Panel> else <div/> $ -> $("#password-update-form").on "submit", updatePassword $("#password-reset-form").on "submit", resetPassword $("#disable-account-form").on "submit", disableAccount React.render <TeamManagementForm/>, document.getElementById("team-management")
true
updatePassword = (e) -> e.preventDefault() apiCall "POST", "/api/user/update_password", $("#password-update-form").serializeObject() .done (data) -> switch data['status'] when 1 ga('send', 'event', 'Authentication', 'UpdatePassword', 'Success') when 0 ga('send', 'event', 'Authentication', 'UpdatePassword', 'Failure::' + data.message) apiNotify data, "/account" resetPassword = (e) -> e.preventDefault() form = $("#password-reset-form").serializeObject() form["reset-token"] = PI:PASSWORD:<PASSWORD>END_PI.substring(1) apiCall "POST", "/api/user/confirm_password_reset", form .done (data) -> ga('send', 'event', 'Authentication', 'ResetPassword', 'Success') apiNotify data, "/" disableAccount = (e) -> e.preventDefault() confirmDialog("This will disable your account, drop you from your team, and prevent you from playing!", "Disable Account Confirmation", "Disable Account", "Cancel", () -> form = $("#disable-account-form").serializeObject() apiCall "POST", "/api/user/disable_account", form .done (data) -> ga('send', 'event', 'Authentication', 'DisableAccount', 'Success') apiNotify data, "/") Input = ReactBootstrap.Input Row = ReactBootstrap.Row Col = ReactBootstrap.Col Button = ReactBootstrap.Button Panel = ReactBootstrap.Panel Glyphicon = ReactBootstrap.Glyphicon ButtonInput = ReactBootstrap.ButtonInput ButtonGroup = ReactBootstrap.ButtonGroup update = React.addons.update # Should figure out how we want to share components. TeamManagementForm = React.createClass mixins: [React.addons.LinkedStateMixin] getInitialState: -> user: {} team: {} team_name: "" team_password: "" componentWillMount: -> apiCall "GET", "/api/user/status" .done ((api) -> @setState update @state, user: $set: api.data ).bind this apiCall "GET", "/api/team" .done ((api) -> @setState update @state, team: $set: api.data ).bind this onTeamRegistration: (e) -> e.preventDefault() if (!@state.team_name || !@state.team_password) apiNotify({status: 0, message: "Invalid team name or password."}) else apiCall "POST", "/api/team/create", {team_name: @state.team_name, team_password: @PI:PASSWORD:<PASSWORD>END_PI} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 document.location.href = "/profile" onTeamJoin: (e) -> e.preventDefault() apiCall "POST", "/api/team/join", {team_name: @state.team_name, team_password: @PI:PASSWORD:<PASSWORD>END_PI} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 document.location.href = "/profile" onTeamPasswordChange: (e) -> e.preventDefault() if @state.team_password != @state.confirm_team_password apiNotify {status: 0, message: "Passwords do not match."} else newpass = @state.team_password newpass_confirm = @state.confirm_team_password confirmDialog("This will change the password needed to join your team.", "Team Password Change Confirmation", "Confirm", "Cancel", () -> apiCall "POST", "/api/team/update_password", {"new-password": newpass, "new-password-confirmation": newpass_confirm} .done (resp) -> switch resp.status when 0 apiNotify resp when 1 apiNotify resp, "/account" ) listMembers: () -> for member in @state.team["members"] <li>{member.username}</li> render: -> if @state.team.max_team_size > 1 and not @state.user.teacher towerGlyph = <Glyphicon glyph="tower"/> lockGlyph = <Glyphicon glyph="lock"/> teamCreated = (@state.user and @state.user.username != @state.user.team_name) if teamCreated <Panel header="Team Management"> <p><strong>Team Name:</strong> {@state.team.team_name}</p> <p><strong>Members</strong> ({@state.team.members.length}/{@state.team.max_team_size}):</p> <ul> {@listMembers()} </ul> <hr/> <form onSubmit={@onTeamPasswordChange}> <Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="New Team Password" required/> <Input type="password" valueLink={@linkState "confirm_team_password"} addonBefore={lockGlyph} label="Confirm New Team Password" required/> <Col md={6}> <Button type="submit">Change Team Password</Button> </Col> </form> </Panel> else <Panel header="Team Management"> <p>To avoid confusion on the scoreboard, you may not create a team that shares the same name as an existing user.</p> <form onSubmit={@onTeamJoin}> <Input type="text" valueLink={@linkState "team_name"} addonBefore={towerGlyph} label="Team Name" required/> <Input type="password" valueLink={@linkState "team_password"} addonBefore={lockGlyph} label="Team Password" required/> <Col md={6}> <span> <Button type="submit">Join Team</Button> <Button onClick={@onTeamRegistration}>Register Team</Button> </span> </Col> </form> </Panel> else <div/> $ -> $("#password-update-form").on "submit", updatePassword $("#password-reset-form").on "submit", resetPassword $("#disable-account-form").on "submit", disableAccount React.render <TeamManagementForm/>, document.getElementById("team-management")
[ { "context": "\"#login-username\")\n @$login_password = $(\"#login-password\")\n\n @$login_username.val(localStorage.getI", "end": 15083, "score": 0.9465584754943848, "start": 15069, "tag": "PASSWORD", "value": "login-password" }, { "context": " @$login_username.val(localStorage.getItem(\"username\"))\n @$login_password.val(localStorage.getI", "end": 15146, "score": 0.7648071050643921, "start": 15138, "tag": "USERNAME", "value": "username" }, { "context": " @$login_password.val(localStorage.getItem(\"password\"))\n\n @$login_button.click =>\n @", "end": 15209, "score": 0.7806908488273621, "start": 15201, "tag": "PASSWORD", "value": "password" }, { "context": "username)\n localStorage.setItem(\"password\", password)\n # send auth info\n editor.con.ws.s", "end": 15594, "score": 0.9874219298362732, "start": 15586, "tag": "PASSWORD", "value": "password" }, { "context": " username: username\n password: password\n\n show: ->\n @$login_box.show()\n\n log", "end": 15721, "score": 0.9891329407691956, "start": 15713, "tag": "PASSWORD", "value": "password" }, { "context": " @$holder.width(@width)\n @$pad.width(@width-a)\n @$ghost.width(@width-a)\n @$high", "end": 28471, "score": 0.6675716042518616, "start": 28465, "tag": "USERNAME", "value": "@width" } ]
client/front.coffee
treeform/asterisk
1
# nice short cut print = (args...) -> console.log(args...) String::contains = (s) -> @indexOf(s) != -1 afterTimeout = (ms, fn) -> setTimeout(fn, ms) afterInterval = (ms, fn) -> setInterval(fn, ms) requestAnimFrame = window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or ((cb) -> window.setTimeout(cb, 1000 / 60)) # keyboard system KEY_MAP = 8: "backspace" 9: "tab" 13: "enter" 27: "esc" 32: "space" 37: "left" 38: "up" 39: "right" 40: "down" keybord_key = (e) -> k = [] if e.metaKey if navigator.platform.match("Mac") k.push("ctrl") else k.push("meta") if e.ctrlKey if navigator.platform.match("Mac") k.push("meta") else k.push("ctrl") if e.altKey k.push("alt") if e.shiftKey k.push("shift") if e.which of KEY_MAP k.push(KEY_MAP[e.which]) else k.push(String.fromCharCode(e.which).toLowerCase()) return k.join("-") common_str = (strs) -> return "" if strs.length == 0 return strs[0] if strs.length == 1 first = strs[0] common = "" fail = false for c,i in first for str in strs if str[i] != c fail = true break break if fail common += c return common gcd = (a, b) -> while b [a, b] = [b, a % b] return a guess_indent = (text) -> indents = {} for line in text.split("\n") indent = line.match(/^\s*/)[0].length continue if indent == 0 if indent of indents indents[indent] += 1 else indents[indent] = 1 indents = ([k*1,v] for k,v of indents) indents = indents.sort (a,b) -> b[1] - a[1] indents = (i[0] for i in indents) if indents.length == 1 return indents[0] if indents.length == 0 return 4 indent = gcd(indents[0], indents[1]) return indent window.specs = # plain spec highlights strings and quotes and thats it plain: NAME: "plain" FILE_TYPES: [] CASESEN_SITIVE: true MULTILINE_STR: true DELIMITERS: " (){}[]<>+-*/%=\"'~!@#&$^&|\\?:;,." ESCAPECHAR: "\\" QUOTATION_MARK1: "\"" BLOCK_COMMENT: ["",""] PAIRS1: "()" PAIRS2: "[]" PAIRS3: "{}" KEY1: [] KEY2: [] KEY3: [] html_safe = (text) -> text.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') #" .replace(/'/g, '&#x27;') #' .replace(/\//g,'&#x2F;'); # its very simple and stupid class Tokenizer constructor: -> @token_cache = {} @spec = specs.plain guess_spec: (filename) -> @spec = specs.plain m = filename.match("\.([^\.]*)$") if not m ext = "txt" else ext = m.pop() for name, spec of specs for t in spec.FILE_TYPES if ext == t @spec = spec @token_cache = {} return tokenize: (@line, @mode) -> key = @mode + "|" + @line if @token_cache[key] return @token_cache[key] return @token_cache[key] = @tokenize_line() colorize_line: -> line = @line spec = @spec colored = [] norm = 0 i = 0 mode = in_mode = @mode[1] next_char = -> c = line[i] i += 1 return c prev_char = -> return line[i-1] or " " match = (str) -> if not str return substr = line[i...i + str.length] if substr == str i += str.length return substr else return false keywords = -> for k in [0..6] if spec["KEY"+k]? for key_word in spec["KEY"+k] text = line[i...i + key_word.length] end = line[i+key_word.length] if text == key_word and (end in spec.DELIMITERS or not end) add_str("key"+k, match(key_word)) return true return false add_str = (mode, str) -> if not str return last = colored[colored.length-1] if not last or last[0] != mode colored.push([mode, str]) else last[1] += str while i < line.length switch mode when "plain" if c = match(spec.ESCAPECHAR) add_str(mode, c) add_str(mode, next_char()) else if c = match(spec.QUOTATION_MARK1) or c = match(spec.QUOTATION_MARK2) or c = match(spec.QUOTATION_MARK3) or c = match(spec.QUOTATION_MARK4) mode = c add_str("string", c) else if spec.BLOCK_COMMENT and c = match(spec.BLOCK_COMMENT[0]) add_str("comment", c) mode = "block_comment" else if c = match(spec.LINE_COMMENT) add_str("comment", line[(i-spec.LINE_COMMENT.length)...]) i = line.length else if prev_char() in spec.DELIMITERS if not keywords() add_str("text", next_char()) else add_str("text", next_char()) when spec.QUOTATION_MARK1, spec.QUOTATION_MARK2, spec.QUOTATION_MARK3, spec.QUOTATION_MARK4 if c = match(spec.ESCAPECHAR) add_str("string", c) add_str("string", next_char()) else if c = match(mode) add_str("string", c) mode = "plain" else add_str("string", next_char()) when "block_comment" if c = match(spec.ESCAPECHAR) add_str("comment", c) add_str("comment", next_char()) else if c = match(spec.BLOCK_COMMENT[1]) add_str("comment", c) mode = "plain" else add_str("comment", next_char()) return [colored, [in_mode, mode]] tokenize_line: -> [colored, mode] = @colorize_line() out = [] for [cls, words] in colored out.push("<span class='#{cls}'>#{html_safe(words)}</span>") #for c in words # out.push("<span class='#{cls}'>#{html_safe(w)}</span>") #out.push(@line) out.push("\n") #print "line", [colored, mode, out.join("")] return [colored, mode, out.join("")] # command line diolog class Command constructor: -> @$box = $("#command-box") @$input = $("#command-input") @$input.keyup (e) => if keybord_key(e) == "enter" @enter() envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> command = @$input.val() js = CoffeeScript.compile(command) eval(js) esc() # goto any line diolog class GotoLine constructor: -> @$box = $("#goto-box") @$input = $("#goto-input") @$input.keyup (e) => if keybord_key(e) == "enter" @enter() envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> esc() line = parseInt(@$input.val()) if line > 0 editor.goto_line(line - 1) class Replacer styleChange: -> [text, [start, end], s] = editor.get_text_state() word = text[start...end] startsUpper = word[0].toUpperCase() == word[0] onlyLower = word.toLowerCase() == word onlyUpper = word.toUpperCase() == word hasUnderScore = word[0...word.length - 1].contains("_") ### styles: 1 SuperWidgetThing 2 superWidgetThing 3 super_widget_thing 4 SUPER_WIDGET_THING ### if onlyUpper style = 4 else if hasUnderScore if onlyLower style = 3 else style = 4 else if startsUpper style = 1 else style = 2 sort: -> [text, [start, end], scroll] = editor.get_text_state() area = text[start...end] lines = area.split("\n") lines.sort() area = lines.join("\n") text = text[0...start] + area + text[end...] editor.set_text_state([text, [start, end], scroll]) # open file and the file autocomplete class OpenFile constructor: -> @$box = $("#open-box") @$input = $("#open-input") @$sug = $("#open-sugest") @$input.keyup @keyup @directory = localStorage.getItem("directory") or "." @$sug.on "click", ".sug", (e) -> filename = $(e.currentTarget).text() esc() editor.open(filename) keyup: (e) => key = keybord_key(e) if key == "enter" @enter() else if key == "up" or key == "down" chosen = @$sug.find(".sug-highlight") if chosen.size() == 0 chosen = @$sug.children().last() else if key == "up" next = chosen.prev() else next = chosen.next() if next.size() > 0 chosen.removeClass("sug-highlight") next.addClass("sug-highlight") chosen = next chosen.addClass("sug-highlight") @$input.val(chosen.text()) else editor.con.ws.safeSend "suggest", query: @$input.val() directory: @directory envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> esc() filename = @$input.val() editor.open(filename) open_push: (res) -> editor.opened(res.filename, res.data) @add_common(res.filename) open_suggest_push: (res) -> @$sug.children().remove() search = @$input.val() for file in res.files file = file.replace(search,"<b>#{search}</b>") @$sug.append("<div class='sug'>#{file}<div>") # add in common files for file in @get_common() if file.indexOf(search) != -1 file = file.replace(search,"<b>#{search}</b>") @$sug.append("<div class='sug sug-common'>#{file}<div>") add_common: (file) -> common = @get_common() for f, n in common if f == file common.splice(n,1) break common.unshift(file) common = common[..10] common = localStorage.setItem("common", JSON.stringify(common)) get_common: -> common = localStorage.getItem("common") if common? return JSON.parse(common) return [] # command line diolog class SearchBox constructor: -> @$box = $("#search-box") @$search = $("#search-input") @$search.keyup (e) => if keybord_key(e) == "enter" @search() else if keybord_key(e) == "down" @search() else if keybord_key(e) == "up" @search(false) @$search.focus() @$replace = $("#replace-input") @$replace.keyup (e) => if keybord_key(e) == "enter" @replace() @search() else if keybord_key(e) == "down" @search() else if keybord_key(e) == "up" @search(false) @$replace.focus() envoke: => esc() @$box.show() @$search.focus() @$search[0].selectionStart = 0 @$search[0].selectionEnd = @$search.val().length search: (down=true)-> query = @$search.val() [text, [at, end], scroll] = editor.get_text_state() if down bottom = text[at+1...] pos = bottom.indexOf(query) if pos != -1 at = at + pos + 1 else pos = text.indexOf(query) if pos != -1 at = pos else return else top = text[...at] pos = top.lastIndexOf(query) if pos != -1 at = pos else pos = text.lastIndexOf(query) if pos != -1 at = pos else return editor.$pad[0].selectionStart = at editor.$pad[0].selectionEnd = at + query.length editor.update() editor.scroll_pos(at) replace: -> [text, [start, end], scroll] = editor.get_text_state() query = @$search.val() if text[start...end] == query replace = @$replace.val() text = text[...start] + replace + text[end...] editor.set_text_state([text, [start, start + replace.length], scroll]) class UndoStack constructor: -> @clear() clear: => @undos = [] @redos = [] undo: => if @undos.length > 0 text = @undos.pop() # dont allow to pop 1st undo if @undos.length == 0 @undos.push(text) @redos.push(editor.get_text_state()) editor.set_text_state(text) redo: => if @redos.length > 1 text = @redos.pop() @undos.push(editor.get_text_state()) editor.set_text_state(text) snapshot: => text = editor.get_text_state() old_text = @undos[@undos.length-1] @redos = [] if !old_text? or old_text[0] != text[0] @undos.push(text) window.logout = -> localStorage.setItem("username", "") localStorage.setItem("password", "") location.reload() class Auth constructor: -> @$login_box = $("#login-box") @$login_button = $("#login-button") @$login_username = $("#login-username") @$login_password = $("#login-password") @$login_username.val(localStorage.getItem("username")) @$login_password.val(localStorage.getItem("password")) @$login_button.click => @login() return false think: -> if @$login_username.val() @login() else @show() login: -> username = @$login_username.val() password = @$login_password.val() localStorage.setItem("username", username) localStorage.setItem("password", password) # send auth info editor.con.ws.safeSend "auth", username: username password: password show: -> @$login_box.show() loggedin: -> @$login_box.hide() if editor.fresh and window.location.pathname[0...5] == "/edit" editor.open(window.location.pathname[6..]) esc() class Connection constructor: -> @lastPong = Date.now() afterInterval 1000, => lastPongTime = Date.now() - @lastPong if lastPongTime > 10 * 1000 or @ws.readyState == 3 print "no pongs, trying to reconnect", lastPongTime @ws.close() @reconnect() else @ws.safeSend("ping", {}) @reconnect() reconnect: -> @lastPong = Date.now() host = window.document.location.host.replace(/:.*/, '') @ws = new WebSocket 'ws://' + location.hostname + ":" + 1977 @ws.safeSend = (msg, kargs) => if @ws.readyState == WebSocket.OPEN @ws.send JSON.stringify msg: msg kargs: kargs else @connectionError() @ws.onopen = (data) -> print "connected with", data.iden editor.auth.think() @ws.onerror = (data) => @connectionError() #editor.auth.think() @ws.onmessage = (e) => packet = JSON.parse(e.data) msg = packet.msg kargs = packet.kargs if msg != "pong" print "got message", msg, kargs switch msg when 'pong' @lastPong = Date.now() when 'open-push' editor.open_cmd.open_push(kargs) when 'loggedin' editor.auth.loggedin(kargs) when 'suggest-push' editor.open_cmd.open_suggest_push(kargs) when 'error-push' if kargs.message == "invalid username or password" editor.auth.show() if kargs.message == "not logged in" editor.auth.login() editor.$errorbox.show() editor.$errorbox.html(kargs.message) when 'marks-push' editor.add_marks(kargs) connectionError: -> editor.$errorbox.show() editor.$errorbox.html("not connected") window.esc = -> editor.$errorbox.hide() editor.focus() window.cd = (directory) -> editor.open_cmd.directory = directory localStorage.setItem("directory", directory) # the main editor class class Editor # create a new editor constructor: -> @fresh = true window.editor = @ @con = new Connection() @filename = "untiled" @tab_width = 2 # grab common elements @$doc = $(document) @$win = $(window) @$holder = $(".holder") @$marks = $(".marks") @$pad = $(".pad") @$ghost = $(".ghost") @$highlight = $(".highlight") @$errorbox = $("#error-box") @$errorbox.hide() # grab careat @$caret_line = $("#caret-line") @$caret_text = $("#caret-text") @$caret_char = $("#caret-char") @$caret_tail = $("#caret-tail") @auth = new Auth() keydown = (e) => @update() key = keybord_key(e) if key.length != 1 and key.indexOf("-") == -1 # for all non character keys non meta @undo.snapshot() @con.ws.safeSend("keypress", key) if e.which == 13 and document.activeElement == @$pad[0] # some times browsers scrolls on enter # just started happening on Feb 11 2017 # to prevent this manually insert new line e.stopPropagation() e.preventDefault() @insert_text("\n") if e.metaKey and e.which == 86 and document.activeElement == @$pad[0] # some times browsers scrolls on paste # just started happening on Mar 15 2017 # fix scoll after paste topScroll = document.activeElement.scrollTop afterTimeout 1, -> document.activeElement.scrollTop = topScroll if @keymap[key]? @keymap[key]() e.stopPropagation() e.preventDefault() return null return true window.addEventListener("keydown", keydown, false) @$doc.keyup (e) => @update() e.preventDefault() return true @$doc.keypress (e) => @update() return true @$doc.mousedown => @undo.snapshot() @mousedown=true @update() @$doc.mousemove => if @mousedown @update() @$doc.mouseup => @mousedown = false @update() @$win.resize(@update) @$doc.click(@update) @$doc.on "mouseenter", ".mark", (e) -> $(".mark-text").hide() $(e.target).find(".mark-text").show() # keeps all the highlight state @lines = [] @tokenizer = new Tokenizer() # does not update if not changed @old_text = "" @old_caret = [0,0] @cmd = new Command() @goto_cmd = new GotoLine() @open_cmd = new OpenFile() @search_cmd = new SearchBox() @undo = new UndoStack() @replacer = new Replacer() @keymap = 'esc': esc 'tab': @tab 'shift-tab': @deindent 'ctrl-esc': @cmd.envoke 'ctrl-i': @cmd.envoke 'ctrl-g': @goto_cmd.envoke 'ctrl-o': @open_cmd.envoke 'ctrl-l': @open_cmd.envoke 'ctrl-s': @save 'ctrl-f': @search_cmd.envoke 'ctrl-z': @undo.undo 'ctrl-shift-z': @undo.redo 'ctrl-e': @replacer.styleChange 'ctrl-y': @replacer.sort @focus() # loop that redoes the work when needed @requset_update = true @workloop() # open current file open: (filename) => @con.ws.safeSend "open", filename: filename # opened opened: (filename, textdata) -> @fresh = false if @filename != filename @undo.clear() else savedSelection = [ @$pad[0].selectionEnd @$pad[0].selectionStart ] @filename = filename @tokenizer.guess_spec(filename) @tab_width = @tokenizer.spec.TAB_INDNET or 4 m = filename.match("\/([^\/]*)$") title = if m then m.pop() else filename $("title").html(title) window.history.pushState({}, "", "/edit/" + filename) @$pad.val(textdata) @undo.snapshot() @clear_makrs() @update() if savedSelection @$pad[0].selectionStart = savedSelection[0] @$pad[0].selectionEnd = savedSelection[1] # save current file save: => text = @$pad.val() # replace tabs by spaces space = (" " for _ in [0...@tab_width]).join("") text = text.replace(/\t/g, space) # strip trailing white space onlines text = text.replace(/[ \r]*\n/g,"\n").replace(/\s*$/, "\n") @con.ws.safeSend "save", filename: @filename data: text # focus the pad focus: => $("div.popup").hide() @$pad.focus() @update() # return the lines selected selected_line_range: -> start = null end = null for line, n in @lines if not start and line[1] <= @old_caret[0] < line[2] start = n if not end and line[1] < @old_caret[1] <= line[2] end = n if not end or end < start end = start return [start, end] # tab was pressed, complex behavior tab: => if $("#search-input").is(":focus") $("#replace-input").focus() return if $("#replace-input").is(":focus") $("#search-input").focus() return if not @$pad.is(":focus") return if @autocomplete() return @indent() return # auto complete right at the current cursor autocomplete: => [text, [start, end], s] = @get_text_state() # if some thing is selected don't auto complete if start != end return false string = text.substr(0, start) at = text[start] string = string.match(/\w+$/) # only when at char is splace and there is a string under curser if (not at or at.match(/\s/)) and string options = {} words = text.split(/\W+/).sort() if words for word in words word_match = word.match("^" + string + "(.+)") if word_match and word_match[1] != "" options[word_match[1]] = true add = common_str(k for k of options) if add.length > 0 @insert_text(add) return true return false # insert text into the selected range insert_text: (add) => [text, [start, end], s] = @get_text_state() if start == 0 text = add + text[end..] else text = text[..start-1] + add + text[end..] start += add.length end += add.length @set_text_state([text, [start, end], s]) # indent selected range indent: => [start, end] = @selected_line_range() if start == end real = @$pad[0].selectionStart just_tab = true lines = (l[3] for l in @lines) tab_str = "" for n in [0...@tab_width] tab_str += " " for n in [start..end] lines[n] = tab_str + lines[n] text = (l for l in lines).join("\n") @set_text(text) if just_tab @$pad[0].selectionStart = real + @tab_width @$pad[0].selectionEnd = @$pad[0].selectionStart else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @lines[end][2] + @tab_width * (end-start+1) # deindent selected range deindent: => [start, end] = @selected_line_range() if start == end real = @$pad[0].selectionStart just_tab = true lines = (l[3] for l in @lines) old_length = 0 for n in [start..end] old_length += lines[n].length + 1 for t in [0...@tab_width] if lines[n][0] == " " lines[n] = lines[n][1..] text = (l for l in lines).join("\n") @set_text(text) new_length = 0 for n in [start..end] new_length += lines[n].length + 1 if just_tab if real - @tab_width > @lines[start][1] @$pad[0].selectionStart = real - @tab_width else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @$pad[0].selectionStart else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @$pad[0].selectionStart + new_length # set the text of the pad to a value set_text: (text) -> @$pad.val(text) @update() # return the text of the pad get_text: () -> return @$pad.val() # set the state of the text set_text_state: (text_state) -> @$pad.val(text_state[0]) @$pad[0].selectionEnd = text_state[1][0] @$pad[0].selectionStart = text_state[1][1] if text_state[2] != 0 @$holder.stop(true).animate(scrollTop: text_state[2]) @update() # gets the state of the text get_text_state: () -> start = @$pad[0].selectionStart end = @$pad[0].selectionEnd if start > end [start, end] = [end, start] text_state = [ @$pad.val(), [start, end], @$holder.scrollTop(), ] return text_state # request for an update to be made update: => @requset_update = true # redraw the ghost buffer real_update: -> if performance? and performance.now? now = performance.now() # adjust hight and width of things @height = @$win.height() @width = @$win.width() - 10 # 10 for scrollbar @$holder.height(@height) a = 4 @$holder.width(@width) @$pad.width(@width-a) @$ghost.width(@width-a) @$highlight.width(@width-a) @$caret_line.width(@width-a) @$marks.width(@width-a) # get the current text @text = text = @$pad.val() or "" set_line = (i, html) => $("#line#{i}").html(html) # for debugging refresh performance #$("#line#{i}").stop().css("opacity", 0) #$("#line#{i}").animate({opacity: 1}, 300); add_line = (i, html) => @$ghost.append("<span id='line#{i}'>#{html}</span>") rm_line = (i) => $("#line#{i}").remove() # high light if it has changed if @old_text != text @old_text = text lines = text.split("\n") start = 0 for line, i in lines if i > 0 prev_mode = @lines[i-1][4] else prev_mode = ["plain", "plain"] end = start + line.length + 1 if @lines[i]? oldline = @lines[i] oldline[1] = start oldline[2] = end if oldline[3] != line or prev_mode[1] != oldline[4][0] [colored, mode, html] = @tokenizer.tokenize(line, prev_mode) oldline[3] = line oldline[4] = mode set_line(i, html) else [colored, mode, html] = @tokenizer.tokenize(line, prev_mode) @lines.push([i, start, end, line, mode]) add_line(i, html) start = end while lines.length < @lines.length l = @lines.pop() rm_line(l[0]) # update caret if it has changed caret at = @$pad[0].selectionStart end = @$pad[0].selectionEnd if @old_caret != [at, end] @old_caret = [at, end] if at == end for line in @lines if line[1] <= at < line[2] if at != line[1] caret_text = text[line[1]..at-1] else caret_text = "" top = $("#line"+line[0]).position().top + 100 @$caret_text.html(html_safe(caret_text)) @$caret_char.html("&nbsp;") @$caret_line.css("top", top) @$caret_tail.html(html_safe(text[at+1...text.indexOf("\n", at)])) else if at > end [at, end] = [end, at] for line in @lines if line[1] <= at < line[2] if at != line[1] caret_text = text[line[1]..at-1] else caret_text = "" top = $("#line"+line[0]).position().top + 100 @$caret_text.html(html_safe(caret_text)) @$caret_line.css("top", top) @$caret_char.html(html_safe(text[at..end-1])) @$caret_tail.html(html_safe(text[end..text.indexOf("\n", end)])) @full_height = @$ghost.height() @$pad.height(@full_height+100) # scroll to a char position scroll_pos: (offset) -> line = 0 for c in @text[0...offset] if c == "\n" line += 1 @scroll_line(line) # go to a line number goto_line: (line_num) -> line = @lines[line_num] ? @lines[@lines.length - 1] @$pad[0].selectionStart = line[1] @$pad[0].selectionEnd = line[1] @scroll_line(line[0]) # animate a scroll to a line number scroll_line: (line_num) -> line = @lines[line_num] ? @lines[@lines.length - 1] y = @get_line_y(line[0]) y -= @$win.height()/2 @$holder.stop(true).animate(scrollTop: y) # get line's y cordiante for scrolling get_line_y: (line_num) -> top = $("#line"+line_num).position().top + 100 return top # adds the makrs about lint stuff to the editor # this is used to show errors or git lines add_marks: (marks) -> if marks.filename == @filename $layer = $("#marks-"+marks.layer) $layer.html("") for mark in marks.marks continue if not mark $line = $("#line"+(mark.line-1)) p = $line.position() return if not p if mark.tag == "change" $layer.append("<div class='mark change' style='top:#{p.top}px;'>*</div>") else $layer.append("<div class='mark' style='top:#{p.top}px;'>#{mark.tag}:#{mark.text}</div>") clear_makrs: (layer) -> $(".marks").html("") # loop that does the work for rendering when update is requested workloop: => if @requset_update @real_update() @requset_update = false requestAnimFrame(@workloop) $ -> window.editor = new Editor()
52287
# nice short cut print = (args...) -> console.log(args...) String::contains = (s) -> @indexOf(s) != -1 afterTimeout = (ms, fn) -> setTimeout(fn, ms) afterInterval = (ms, fn) -> setInterval(fn, ms) requestAnimFrame = window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or ((cb) -> window.setTimeout(cb, 1000 / 60)) # keyboard system KEY_MAP = 8: "backspace" 9: "tab" 13: "enter" 27: "esc" 32: "space" 37: "left" 38: "up" 39: "right" 40: "down" keybord_key = (e) -> k = [] if e.metaKey if navigator.platform.match("Mac") k.push("ctrl") else k.push("meta") if e.ctrlKey if navigator.platform.match("Mac") k.push("meta") else k.push("ctrl") if e.altKey k.push("alt") if e.shiftKey k.push("shift") if e.which of KEY_MAP k.push(KEY_MAP[e.which]) else k.push(String.fromCharCode(e.which).toLowerCase()) return k.join("-") common_str = (strs) -> return "" if strs.length == 0 return strs[0] if strs.length == 1 first = strs[0] common = "" fail = false for c,i in first for str in strs if str[i] != c fail = true break break if fail common += c return common gcd = (a, b) -> while b [a, b] = [b, a % b] return a guess_indent = (text) -> indents = {} for line in text.split("\n") indent = line.match(/^\s*/)[0].length continue if indent == 0 if indent of indents indents[indent] += 1 else indents[indent] = 1 indents = ([k*1,v] for k,v of indents) indents = indents.sort (a,b) -> b[1] - a[1] indents = (i[0] for i in indents) if indents.length == 1 return indents[0] if indents.length == 0 return 4 indent = gcd(indents[0], indents[1]) return indent window.specs = # plain spec highlights strings and quotes and thats it plain: NAME: "plain" FILE_TYPES: [] CASESEN_SITIVE: true MULTILINE_STR: true DELIMITERS: " (){}[]<>+-*/%=\"'~!@#&$^&|\\?:;,." ESCAPECHAR: "\\" QUOTATION_MARK1: "\"" BLOCK_COMMENT: ["",""] PAIRS1: "()" PAIRS2: "[]" PAIRS3: "{}" KEY1: [] KEY2: [] KEY3: [] html_safe = (text) -> text.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') #" .replace(/'/g, '&#x27;') #' .replace(/\//g,'&#x2F;'); # its very simple and stupid class Tokenizer constructor: -> @token_cache = {} @spec = specs.plain guess_spec: (filename) -> @spec = specs.plain m = filename.match("\.([^\.]*)$") if not m ext = "txt" else ext = m.pop() for name, spec of specs for t in spec.FILE_TYPES if ext == t @spec = spec @token_cache = {} return tokenize: (@line, @mode) -> key = @mode + "|" + @line if @token_cache[key] return @token_cache[key] return @token_cache[key] = @tokenize_line() colorize_line: -> line = @line spec = @spec colored = [] norm = 0 i = 0 mode = in_mode = @mode[1] next_char = -> c = line[i] i += 1 return c prev_char = -> return line[i-1] or " " match = (str) -> if not str return substr = line[i...i + str.length] if substr == str i += str.length return substr else return false keywords = -> for k in [0..6] if spec["KEY"+k]? for key_word in spec["KEY"+k] text = line[i...i + key_word.length] end = line[i+key_word.length] if text == key_word and (end in spec.DELIMITERS or not end) add_str("key"+k, match(key_word)) return true return false add_str = (mode, str) -> if not str return last = colored[colored.length-1] if not last or last[0] != mode colored.push([mode, str]) else last[1] += str while i < line.length switch mode when "plain" if c = match(spec.ESCAPECHAR) add_str(mode, c) add_str(mode, next_char()) else if c = match(spec.QUOTATION_MARK1) or c = match(spec.QUOTATION_MARK2) or c = match(spec.QUOTATION_MARK3) or c = match(spec.QUOTATION_MARK4) mode = c add_str("string", c) else if spec.BLOCK_COMMENT and c = match(spec.BLOCK_COMMENT[0]) add_str("comment", c) mode = "block_comment" else if c = match(spec.LINE_COMMENT) add_str("comment", line[(i-spec.LINE_COMMENT.length)...]) i = line.length else if prev_char() in spec.DELIMITERS if not keywords() add_str("text", next_char()) else add_str("text", next_char()) when spec.QUOTATION_MARK1, spec.QUOTATION_MARK2, spec.QUOTATION_MARK3, spec.QUOTATION_MARK4 if c = match(spec.ESCAPECHAR) add_str("string", c) add_str("string", next_char()) else if c = match(mode) add_str("string", c) mode = "plain" else add_str("string", next_char()) when "block_comment" if c = match(spec.ESCAPECHAR) add_str("comment", c) add_str("comment", next_char()) else if c = match(spec.BLOCK_COMMENT[1]) add_str("comment", c) mode = "plain" else add_str("comment", next_char()) return [colored, [in_mode, mode]] tokenize_line: -> [colored, mode] = @colorize_line() out = [] for [cls, words] in colored out.push("<span class='#{cls}'>#{html_safe(words)}</span>") #for c in words # out.push("<span class='#{cls}'>#{html_safe(w)}</span>") #out.push(@line) out.push("\n") #print "line", [colored, mode, out.join("")] return [colored, mode, out.join("")] # command line diolog class Command constructor: -> @$box = $("#command-box") @$input = $("#command-input") @$input.keyup (e) => if keybord_key(e) == "enter" @enter() envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> command = @$input.val() js = CoffeeScript.compile(command) eval(js) esc() # goto any line diolog class GotoLine constructor: -> @$box = $("#goto-box") @$input = $("#goto-input") @$input.keyup (e) => if keybord_key(e) == "enter" @enter() envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> esc() line = parseInt(@$input.val()) if line > 0 editor.goto_line(line - 1) class Replacer styleChange: -> [text, [start, end], s] = editor.get_text_state() word = text[start...end] startsUpper = word[0].toUpperCase() == word[0] onlyLower = word.toLowerCase() == word onlyUpper = word.toUpperCase() == word hasUnderScore = word[0...word.length - 1].contains("_") ### styles: 1 SuperWidgetThing 2 superWidgetThing 3 super_widget_thing 4 SUPER_WIDGET_THING ### if onlyUpper style = 4 else if hasUnderScore if onlyLower style = 3 else style = 4 else if startsUpper style = 1 else style = 2 sort: -> [text, [start, end], scroll] = editor.get_text_state() area = text[start...end] lines = area.split("\n") lines.sort() area = lines.join("\n") text = text[0...start] + area + text[end...] editor.set_text_state([text, [start, end], scroll]) # open file and the file autocomplete class OpenFile constructor: -> @$box = $("#open-box") @$input = $("#open-input") @$sug = $("#open-sugest") @$input.keyup @keyup @directory = localStorage.getItem("directory") or "." @$sug.on "click", ".sug", (e) -> filename = $(e.currentTarget).text() esc() editor.open(filename) keyup: (e) => key = keybord_key(e) if key == "enter" @enter() else if key == "up" or key == "down" chosen = @$sug.find(".sug-highlight") if chosen.size() == 0 chosen = @$sug.children().last() else if key == "up" next = chosen.prev() else next = chosen.next() if next.size() > 0 chosen.removeClass("sug-highlight") next.addClass("sug-highlight") chosen = next chosen.addClass("sug-highlight") @$input.val(chosen.text()) else editor.con.ws.safeSend "suggest", query: @$input.val() directory: @directory envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> esc() filename = @$input.val() editor.open(filename) open_push: (res) -> editor.opened(res.filename, res.data) @add_common(res.filename) open_suggest_push: (res) -> @$sug.children().remove() search = @$input.val() for file in res.files file = file.replace(search,"<b>#{search}</b>") @$sug.append("<div class='sug'>#{file}<div>") # add in common files for file in @get_common() if file.indexOf(search) != -1 file = file.replace(search,"<b>#{search}</b>") @$sug.append("<div class='sug sug-common'>#{file}<div>") add_common: (file) -> common = @get_common() for f, n in common if f == file common.splice(n,1) break common.unshift(file) common = common[..10] common = localStorage.setItem("common", JSON.stringify(common)) get_common: -> common = localStorage.getItem("common") if common? return JSON.parse(common) return [] # command line diolog class SearchBox constructor: -> @$box = $("#search-box") @$search = $("#search-input") @$search.keyup (e) => if keybord_key(e) == "enter" @search() else if keybord_key(e) == "down" @search() else if keybord_key(e) == "up" @search(false) @$search.focus() @$replace = $("#replace-input") @$replace.keyup (e) => if keybord_key(e) == "enter" @replace() @search() else if keybord_key(e) == "down" @search() else if keybord_key(e) == "up" @search(false) @$replace.focus() envoke: => esc() @$box.show() @$search.focus() @$search[0].selectionStart = 0 @$search[0].selectionEnd = @$search.val().length search: (down=true)-> query = @$search.val() [text, [at, end], scroll] = editor.get_text_state() if down bottom = text[at+1...] pos = bottom.indexOf(query) if pos != -1 at = at + pos + 1 else pos = text.indexOf(query) if pos != -1 at = pos else return else top = text[...at] pos = top.lastIndexOf(query) if pos != -1 at = pos else pos = text.lastIndexOf(query) if pos != -1 at = pos else return editor.$pad[0].selectionStart = at editor.$pad[0].selectionEnd = at + query.length editor.update() editor.scroll_pos(at) replace: -> [text, [start, end], scroll] = editor.get_text_state() query = @$search.val() if text[start...end] == query replace = @$replace.val() text = text[...start] + replace + text[end...] editor.set_text_state([text, [start, start + replace.length], scroll]) class UndoStack constructor: -> @clear() clear: => @undos = [] @redos = [] undo: => if @undos.length > 0 text = @undos.pop() # dont allow to pop 1st undo if @undos.length == 0 @undos.push(text) @redos.push(editor.get_text_state()) editor.set_text_state(text) redo: => if @redos.length > 1 text = @redos.pop() @undos.push(editor.get_text_state()) editor.set_text_state(text) snapshot: => text = editor.get_text_state() old_text = @undos[@undos.length-1] @redos = [] if !old_text? or old_text[0] != text[0] @undos.push(text) window.logout = -> localStorage.setItem("username", "") localStorage.setItem("password", "") location.reload() class Auth constructor: -> @$login_box = $("#login-box") @$login_button = $("#login-button") @$login_username = $("#login-username") @$login_password = $("#<PASSWORD>") @$login_username.val(localStorage.getItem("username")) @$login_password.val(localStorage.getItem("<PASSWORD>")) @$login_button.click => @login() return false think: -> if @$login_username.val() @login() else @show() login: -> username = @$login_username.val() password = @$login_password.val() localStorage.setItem("username", username) localStorage.setItem("password", <PASSWORD>) # send auth info editor.con.ws.safeSend "auth", username: username password: <PASSWORD> show: -> @$login_box.show() loggedin: -> @$login_box.hide() if editor.fresh and window.location.pathname[0...5] == "/edit" editor.open(window.location.pathname[6..]) esc() class Connection constructor: -> @lastPong = Date.now() afterInterval 1000, => lastPongTime = Date.now() - @lastPong if lastPongTime > 10 * 1000 or @ws.readyState == 3 print "no pongs, trying to reconnect", lastPongTime @ws.close() @reconnect() else @ws.safeSend("ping", {}) @reconnect() reconnect: -> @lastPong = Date.now() host = window.document.location.host.replace(/:.*/, '') @ws = new WebSocket 'ws://' + location.hostname + ":" + 1977 @ws.safeSend = (msg, kargs) => if @ws.readyState == WebSocket.OPEN @ws.send JSON.stringify msg: msg kargs: kargs else @connectionError() @ws.onopen = (data) -> print "connected with", data.iden editor.auth.think() @ws.onerror = (data) => @connectionError() #editor.auth.think() @ws.onmessage = (e) => packet = JSON.parse(e.data) msg = packet.msg kargs = packet.kargs if msg != "pong" print "got message", msg, kargs switch msg when 'pong' @lastPong = Date.now() when 'open-push' editor.open_cmd.open_push(kargs) when 'loggedin' editor.auth.loggedin(kargs) when 'suggest-push' editor.open_cmd.open_suggest_push(kargs) when 'error-push' if kargs.message == "invalid username or password" editor.auth.show() if kargs.message == "not logged in" editor.auth.login() editor.$errorbox.show() editor.$errorbox.html(kargs.message) when 'marks-push' editor.add_marks(kargs) connectionError: -> editor.$errorbox.show() editor.$errorbox.html("not connected") window.esc = -> editor.$errorbox.hide() editor.focus() window.cd = (directory) -> editor.open_cmd.directory = directory localStorage.setItem("directory", directory) # the main editor class class Editor # create a new editor constructor: -> @fresh = true window.editor = @ @con = new Connection() @filename = "untiled" @tab_width = 2 # grab common elements @$doc = $(document) @$win = $(window) @$holder = $(".holder") @$marks = $(".marks") @$pad = $(".pad") @$ghost = $(".ghost") @$highlight = $(".highlight") @$errorbox = $("#error-box") @$errorbox.hide() # grab careat @$caret_line = $("#caret-line") @$caret_text = $("#caret-text") @$caret_char = $("#caret-char") @$caret_tail = $("#caret-tail") @auth = new Auth() keydown = (e) => @update() key = keybord_key(e) if key.length != 1 and key.indexOf("-") == -1 # for all non character keys non meta @undo.snapshot() @con.ws.safeSend("keypress", key) if e.which == 13 and document.activeElement == @$pad[0] # some times browsers scrolls on enter # just started happening on Feb 11 2017 # to prevent this manually insert new line e.stopPropagation() e.preventDefault() @insert_text("\n") if e.metaKey and e.which == 86 and document.activeElement == @$pad[0] # some times browsers scrolls on paste # just started happening on Mar 15 2017 # fix scoll after paste topScroll = document.activeElement.scrollTop afterTimeout 1, -> document.activeElement.scrollTop = topScroll if @keymap[key]? @keymap[key]() e.stopPropagation() e.preventDefault() return null return true window.addEventListener("keydown", keydown, false) @$doc.keyup (e) => @update() e.preventDefault() return true @$doc.keypress (e) => @update() return true @$doc.mousedown => @undo.snapshot() @mousedown=true @update() @$doc.mousemove => if @mousedown @update() @$doc.mouseup => @mousedown = false @update() @$win.resize(@update) @$doc.click(@update) @$doc.on "mouseenter", ".mark", (e) -> $(".mark-text").hide() $(e.target).find(".mark-text").show() # keeps all the highlight state @lines = [] @tokenizer = new Tokenizer() # does not update if not changed @old_text = "" @old_caret = [0,0] @cmd = new Command() @goto_cmd = new GotoLine() @open_cmd = new OpenFile() @search_cmd = new SearchBox() @undo = new UndoStack() @replacer = new Replacer() @keymap = 'esc': esc 'tab': @tab 'shift-tab': @deindent 'ctrl-esc': @cmd.envoke 'ctrl-i': @cmd.envoke 'ctrl-g': @goto_cmd.envoke 'ctrl-o': @open_cmd.envoke 'ctrl-l': @open_cmd.envoke 'ctrl-s': @save 'ctrl-f': @search_cmd.envoke 'ctrl-z': @undo.undo 'ctrl-shift-z': @undo.redo 'ctrl-e': @replacer.styleChange 'ctrl-y': @replacer.sort @focus() # loop that redoes the work when needed @requset_update = true @workloop() # open current file open: (filename) => @con.ws.safeSend "open", filename: filename # opened opened: (filename, textdata) -> @fresh = false if @filename != filename @undo.clear() else savedSelection = [ @$pad[0].selectionEnd @$pad[0].selectionStart ] @filename = filename @tokenizer.guess_spec(filename) @tab_width = @tokenizer.spec.TAB_INDNET or 4 m = filename.match("\/([^\/]*)$") title = if m then m.pop() else filename $("title").html(title) window.history.pushState({}, "", "/edit/" + filename) @$pad.val(textdata) @undo.snapshot() @clear_makrs() @update() if savedSelection @$pad[0].selectionStart = savedSelection[0] @$pad[0].selectionEnd = savedSelection[1] # save current file save: => text = @$pad.val() # replace tabs by spaces space = (" " for _ in [0...@tab_width]).join("") text = text.replace(/\t/g, space) # strip trailing white space onlines text = text.replace(/[ \r]*\n/g,"\n").replace(/\s*$/, "\n") @con.ws.safeSend "save", filename: @filename data: text # focus the pad focus: => $("div.popup").hide() @$pad.focus() @update() # return the lines selected selected_line_range: -> start = null end = null for line, n in @lines if not start and line[1] <= @old_caret[0] < line[2] start = n if not end and line[1] < @old_caret[1] <= line[2] end = n if not end or end < start end = start return [start, end] # tab was pressed, complex behavior tab: => if $("#search-input").is(":focus") $("#replace-input").focus() return if $("#replace-input").is(":focus") $("#search-input").focus() return if not @$pad.is(":focus") return if @autocomplete() return @indent() return # auto complete right at the current cursor autocomplete: => [text, [start, end], s] = @get_text_state() # if some thing is selected don't auto complete if start != end return false string = text.substr(0, start) at = text[start] string = string.match(/\w+$/) # only when at char is splace and there is a string under curser if (not at or at.match(/\s/)) and string options = {} words = text.split(/\W+/).sort() if words for word in words word_match = word.match("^" + string + "(.+)") if word_match and word_match[1] != "" options[word_match[1]] = true add = common_str(k for k of options) if add.length > 0 @insert_text(add) return true return false # insert text into the selected range insert_text: (add) => [text, [start, end], s] = @get_text_state() if start == 0 text = add + text[end..] else text = text[..start-1] + add + text[end..] start += add.length end += add.length @set_text_state([text, [start, end], s]) # indent selected range indent: => [start, end] = @selected_line_range() if start == end real = @$pad[0].selectionStart just_tab = true lines = (l[3] for l in @lines) tab_str = "" for n in [0...@tab_width] tab_str += " " for n in [start..end] lines[n] = tab_str + lines[n] text = (l for l in lines).join("\n") @set_text(text) if just_tab @$pad[0].selectionStart = real + @tab_width @$pad[0].selectionEnd = @$pad[0].selectionStart else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @lines[end][2] + @tab_width * (end-start+1) # deindent selected range deindent: => [start, end] = @selected_line_range() if start == end real = @$pad[0].selectionStart just_tab = true lines = (l[3] for l in @lines) old_length = 0 for n in [start..end] old_length += lines[n].length + 1 for t in [0...@tab_width] if lines[n][0] == " " lines[n] = lines[n][1..] text = (l for l in lines).join("\n") @set_text(text) new_length = 0 for n in [start..end] new_length += lines[n].length + 1 if just_tab if real - @tab_width > @lines[start][1] @$pad[0].selectionStart = real - @tab_width else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @$pad[0].selectionStart else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @$pad[0].selectionStart + new_length # set the text of the pad to a value set_text: (text) -> @$pad.val(text) @update() # return the text of the pad get_text: () -> return @$pad.val() # set the state of the text set_text_state: (text_state) -> @$pad.val(text_state[0]) @$pad[0].selectionEnd = text_state[1][0] @$pad[0].selectionStart = text_state[1][1] if text_state[2] != 0 @$holder.stop(true).animate(scrollTop: text_state[2]) @update() # gets the state of the text get_text_state: () -> start = @$pad[0].selectionStart end = @$pad[0].selectionEnd if start > end [start, end] = [end, start] text_state = [ @$pad.val(), [start, end], @$holder.scrollTop(), ] return text_state # request for an update to be made update: => @requset_update = true # redraw the ghost buffer real_update: -> if performance? and performance.now? now = performance.now() # adjust hight and width of things @height = @$win.height() @width = @$win.width() - 10 # 10 for scrollbar @$holder.height(@height) a = 4 @$holder.width(@width) @$pad.width(@width-a) @$ghost.width(@width-a) @$highlight.width(@width-a) @$caret_line.width(@width-a) @$marks.width(@width-a) # get the current text @text = text = @$pad.val() or "" set_line = (i, html) => $("#line#{i}").html(html) # for debugging refresh performance #$("#line#{i}").stop().css("opacity", 0) #$("#line#{i}").animate({opacity: 1}, 300); add_line = (i, html) => @$ghost.append("<span id='line#{i}'>#{html}</span>") rm_line = (i) => $("#line#{i}").remove() # high light if it has changed if @old_text != text @old_text = text lines = text.split("\n") start = 0 for line, i in lines if i > 0 prev_mode = @lines[i-1][4] else prev_mode = ["plain", "plain"] end = start + line.length + 1 if @lines[i]? oldline = @lines[i] oldline[1] = start oldline[2] = end if oldline[3] != line or prev_mode[1] != oldline[4][0] [colored, mode, html] = @tokenizer.tokenize(line, prev_mode) oldline[3] = line oldline[4] = mode set_line(i, html) else [colored, mode, html] = @tokenizer.tokenize(line, prev_mode) @lines.push([i, start, end, line, mode]) add_line(i, html) start = end while lines.length < @lines.length l = @lines.pop() rm_line(l[0]) # update caret if it has changed caret at = @$pad[0].selectionStart end = @$pad[0].selectionEnd if @old_caret != [at, end] @old_caret = [at, end] if at == end for line in @lines if line[1] <= at < line[2] if at != line[1] caret_text = text[line[1]..at-1] else caret_text = "" top = $("#line"+line[0]).position().top + 100 @$caret_text.html(html_safe(caret_text)) @$caret_char.html("&nbsp;") @$caret_line.css("top", top) @$caret_tail.html(html_safe(text[at+1...text.indexOf("\n", at)])) else if at > end [at, end] = [end, at] for line in @lines if line[1] <= at < line[2] if at != line[1] caret_text = text[line[1]..at-1] else caret_text = "" top = $("#line"+line[0]).position().top + 100 @$caret_text.html(html_safe(caret_text)) @$caret_line.css("top", top) @$caret_char.html(html_safe(text[at..end-1])) @$caret_tail.html(html_safe(text[end..text.indexOf("\n", end)])) @full_height = @$ghost.height() @$pad.height(@full_height+100) # scroll to a char position scroll_pos: (offset) -> line = 0 for c in @text[0...offset] if c == "\n" line += 1 @scroll_line(line) # go to a line number goto_line: (line_num) -> line = @lines[line_num] ? @lines[@lines.length - 1] @$pad[0].selectionStart = line[1] @$pad[0].selectionEnd = line[1] @scroll_line(line[0]) # animate a scroll to a line number scroll_line: (line_num) -> line = @lines[line_num] ? @lines[@lines.length - 1] y = @get_line_y(line[0]) y -= @$win.height()/2 @$holder.stop(true).animate(scrollTop: y) # get line's y cordiante for scrolling get_line_y: (line_num) -> top = $("#line"+line_num).position().top + 100 return top # adds the makrs about lint stuff to the editor # this is used to show errors or git lines add_marks: (marks) -> if marks.filename == @filename $layer = $("#marks-"+marks.layer) $layer.html("") for mark in marks.marks continue if not mark $line = $("#line"+(mark.line-1)) p = $line.position() return if not p if mark.tag == "change" $layer.append("<div class='mark change' style='top:#{p.top}px;'>*</div>") else $layer.append("<div class='mark' style='top:#{p.top}px;'>#{mark.tag}:#{mark.text}</div>") clear_makrs: (layer) -> $(".marks").html("") # loop that does the work for rendering when update is requested workloop: => if @requset_update @real_update() @requset_update = false requestAnimFrame(@workloop) $ -> window.editor = new Editor()
true
# nice short cut print = (args...) -> console.log(args...) String::contains = (s) -> @indexOf(s) != -1 afterTimeout = (ms, fn) -> setTimeout(fn, ms) afterInterval = (ms, fn) -> setInterval(fn, ms) requestAnimFrame = window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or ((cb) -> window.setTimeout(cb, 1000 / 60)) # keyboard system KEY_MAP = 8: "backspace" 9: "tab" 13: "enter" 27: "esc" 32: "space" 37: "left" 38: "up" 39: "right" 40: "down" keybord_key = (e) -> k = [] if e.metaKey if navigator.platform.match("Mac") k.push("ctrl") else k.push("meta") if e.ctrlKey if navigator.platform.match("Mac") k.push("meta") else k.push("ctrl") if e.altKey k.push("alt") if e.shiftKey k.push("shift") if e.which of KEY_MAP k.push(KEY_MAP[e.which]) else k.push(String.fromCharCode(e.which).toLowerCase()) return k.join("-") common_str = (strs) -> return "" if strs.length == 0 return strs[0] if strs.length == 1 first = strs[0] common = "" fail = false for c,i in first for str in strs if str[i] != c fail = true break break if fail common += c return common gcd = (a, b) -> while b [a, b] = [b, a % b] return a guess_indent = (text) -> indents = {} for line in text.split("\n") indent = line.match(/^\s*/)[0].length continue if indent == 0 if indent of indents indents[indent] += 1 else indents[indent] = 1 indents = ([k*1,v] for k,v of indents) indents = indents.sort (a,b) -> b[1] - a[1] indents = (i[0] for i in indents) if indents.length == 1 return indents[0] if indents.length == 0 return 4 indent = gcd(indents[0], indents[1]) return indent window.specs = # plain spec highlights strings and quotes and thats it plain: NAME: "plain" FILE_TYPES: [] CASESEN_SITIVE: true MULTILINE_STR: true DELIMITERS: " (){}[]<>+-*/%=\"'~!@#&$^&|\\?:;,." ESCAPECHAR: "\\" QUOTATION_MARK1: "\"" BLOCK_COMMENT: ["",""] PAIRS1: "()" PAIRS2: "[]" PAIRS3: "{}" KEY1: [] KEY2: [] KEY3: [] html_safe = (text) -> text.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') #" .replace(/'/g, '&#x27;') #' .replace(/\//g,'&#x2F;'); # its very simple and stupid class Tokenizer constructor: -> @token_cache = {} @spec = specs.plain guess_spec: (filename) -> @spec = specs.plain m = filename.match("\.([^\.]*)$") if not m ext = "txt" else ext = m.pop() for name, spec of specs for t in spec.FILE_TYPES if ext == t @spec = spec @token_cache = {} return tokenize: (@line, @mode) -> key = @mode + "|" + @line if @token_cache[key] return @token_cache[key] return @token_cache[key] = @tokenize_line() colorize_line: -> line = @line spec = @spec colored = [] norm = 0 i = 0 mode = in_mode = @mode[1] next_char = -> c = line[i] i += 1 return c prev_char = -> return line[i-1] or " " match = (str) -> if not str return substr = line[i...i + str.length] if substr == str i += str.length return substr else return false keywords = -> for k in [0..6] if spec["KEY"+k]? for key_word in spec["KEY"+k] text = line[i...i + key_word.length] end = line[i+key_word.length] if text == key_word and (end in spec.DELIMITERS or not end) add_str("key"+k, match(key_word)) return true return false add_str = (mode, str) -> if not str return last = colored[colored.length-1] if not last or last[0] != mode colored.push([mode, str]) else last[1] += str while i < line.length switch mode when "plain" if c = match(spec.ESCAPECHAR) add_str(mode, c) add_str(mode, next_char()) else if c = match(spec.QUOTATION_MARK1) or c = match(spec.QUOTATION_MARK2) or c = match(spec.QUOTATION_MARK3) or c = match(spec.QUOTATION_MARK4) mode = c add_str("string", c) else if spec.BLOCK_COMMENT and c = match(spec.BLOCK_COMMENT[0]) add_str("comment", c) mode = "block_comment" else if c = match(spec.LINE_COMMENT) add_str("comment", line[(i-spec.LINE_COMMENT.length)...]) i = line.length else if prev_char() in spec.DELIMITERS if not keywords() add_str("text", next_char()) else add_str("text", next_char()) when spec.QUOTATION_MARK1, spec.QUOTATION_MARK2, spec.QUOTATION_MARK3, spec.QUOTATION_MARK4 if c = match(spec.ESCAPECHAR) add_str("string", c) add_str("string", next_char()) else if c = match(mode) add_str("string", c) mode = "plain" else add_str("string", next_char()) when "block_comment" if c = match(spec.ESCAPECHAR) add_str("comment", c) add_str("comment", next_char()) else if c = match(spec.BLOCK_COMMENT[1]) add_str("comment", c) mode = "plain" else add_str("comment", next_char()) return [colored, [in_mode, mode]] tokenize_line: -> [colored, mode] = @colorize_line() out = [] for [cls, words] in colored out.push("<span class='#{cls}'>#{html_safe(words)}</span>") #for c in words # out.push("<span class='#{cls}'>#{html_safe(w)}</span>") #out.push(@line) out.push("\n") #print "line", [colored, mode, out.join("")] return [colored, mode, out.join("")] # command line diolog class Command constructor: -> @$box = $("#command-box") @$input = $("#command-input") @$input.keyup (e) => if keybord_key(e) == "enter" @enter() envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> command = @$input.val() js = CoffeeScript.compile(command) eval(js) esc() # goto any line diolog class GotoLine constructor: -> @$box = $("#goto-box") @$input = $("#goto-input") @$input.keyup (e) => if keybord_key(e) == "enter" @enter() envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> esc() line = parseInt(@$input.val()) if line > 0 editor.goto_line(line - 1) class Replacer styleChange: -> [text, [start, end], s] = editor.get_text_state() word = text[start...end] startsUpper = word[0].toUpperCase() == word[0] onlyLower = word.toLowerCase() == word onlyUpper = word.toUpperCase() == word hasUnderScore = word[0...word.length - 1].contains("_") ### styles: 1 SuperWidgetThing 2 superWidgetThing 3 super_widget_thing 4 SUPER_WIDGET_THING ### if onlyUpper style = 4 else if hasUnderScore if onlyLower style = 3 else style = 4 else if startsUpper style = 1 else style = 2 sort: -> [text, [start, end], scroll] = editor.get_text_state() area = text[start...end] lines = area.split("\n") lines.sort() area = lines.join("\n") text = text[0...start] + area + text[end...] editor.set_text_state([text, [start, end], scroll]) # open file and the file autocomplete class OpenFile constructor: -> @$box = $("#open-box") @$input = $("#open-input") @$sug = $("#open-sugest") @$input.keyup @keyup @directory = localStorage.getItem("directory") or "." @$sug.on "click", ".sug", (e) -> filename = $(e.currentTarget).text() esc() editor.open(filename) keyup: (e) => key = keybord_key(e) if key == "enter" @enter() else if key == "up" or key == "down" chosen = @$sug.find(".sug-highlight") if chosen.size() == 0 chosen = @$sug.children().last() else if key == "up" next = chosen.prev() else next = chosen.next() if next.size() > 0 chosen.removeClass("sug-highlight") next.addClass("sug-highlight") chosen = next chosen.addClass("sug-highlight") @$input.val(chosen.text()) else editor.con.ws.safeSend "suggest", query: @$input.val() directory: @directory envoke: => esc() @$box.show() @$input.focus() @$input[0].selectionStart = 0 @$input[0].selectionEnd = @$input.val().length enter: -> esc() filename = @$input.val() editor.open(filename) open_push: (res) -> editor.opened(res.filename, res.data) @add_common(res.filename) open_suggest_push: (res) -> @$sug.children().remove() search = @$input.val() for file in res.files file = file.replace(search,"<b>#{search}</b>") @$sug.append("<div class='sug'>#{file}<div>") # add in common files for file in @get_common() if file.indexOf(search) != -1 file = file.replace(search,"<b>#{search}</b>") @$sug.append("<div class='sug sug-common'>#{file}<div>") add_common: (file) -> common = @get_common() for f, n in common if f == file common.splice(n,1) break common.unshift(file) common = common[..10] common = localStorage.setItem("common", JSON.stringify(common)) get_common: -> common = localStorage.getItem("common") if common? return JSON.parse(common) return [] # command line diolog class SearchBox constructor: -> @$box = $("#search-box") @$search = $("#search-input") @$search.keyup (e) => if keybord_key(e) == "enter" @search() else if keybord_key(e) == "down" @search() else if keybord_key(e) == "up" @search(false) @$search.focus() @$replace = $("#replace-input") @$replace.keyup (e) => if keybord_key(e) == "enter" @replace() @search() else if keybord_key(e) == "down" @search() else if keybord_key(e) == "up" @search(false) @$replace.focus() envoke: => esc() @$box.show() @$search.focus() @$search[0].selectionStart = 0 @$search[0].selectionEnd = @$search.val().length search: (down=true)-> query = @$search.val() [text, [at, end], scroll] = editor.get_text_state() if down bottom = text[at+1...] pos = bottom.indexOf(query) if pos != -1 at = at + pos + 1 else pos = text.indexOf(query) if pos != -1 at = pos else return else top = text[...at] pos = top.lastIndexOf(query) if pos != -1 at = pos else pos = text.lastIndexOf(query) if pos != -1 at = pos else return editor.$pad[0].selectionStart = at editor.$pad[0].selectionEnd = at + query.length editor.update() editor.scroll_pos(at) replace: -> [text, [start, end], scroll] = editor.get_text_state() query = @$search.val() if text[start...end] == query replace = @$replace.val() text = text[...start] + replace + text[end...] editor.set_text_state([text, [start, start + replace.length], scroll]) class UndoStack constructor: -> @clear() clear: => @undos = [] @redos = [] undo: => if @undos.length > 0 text = @undos.pop() # dont allow to pop 1st undo if @undos.length == 0 @undos.push(text) @redos.push(editor.get_text_state()) editor.set_text_state(text) redo: => if @redos.length > 1 text = @redos.pop() @undos.push(editor.get_text_state()) editor.set_text_state(text) snapshot: => text = editor.get_text_state() old_text = @undos[@undos.length-1] @redos = [] if !old_text? or old_text[0] != text[0] @undos.push(text) window.logout = -> localStorage.setItem("username", "") localStorage.setItem("password", "") location.reload() class Auth constructor: -> @$login_box = $("#login-box") @$login_button = $("#login-button") @$login_username = $("#login-username") @$login_password = $("#PI:PASSWORD:<PASSWORD>END_PI") @$login_username.val(localStorage.getItem("username")) @$login_password.val(localStorage.getItem("PI:PASSWORD:<PASSWORD>END_PI")) @$login_button.click => @login() return false think: -> if @$login_username.val() @login() else @show() login: -> username = @$login_username.val() password = @$login_password.val() localStorage.setItem("username", username) localStorage.setItem("password", PI:PASSWORD:<PASSWORD>END_PI) # send auth info editor.con.ws.safeSend "auth", username: username password: PI:PASSWORD:<PASSWORD>END_PI show: -> @$login_box.show() loggedin: -> @$login_box.hide() if editor.fresh and window.location.pathname[0...5] == "/edit" editor.open(window.location.pathname[6..]) esc() class Connection constructor: -> @lastPong = Date.now() afterInterval 1000, => lastPongTime = Date.now() - @lastPong if lastPongTime > 10 * 1000 or @ws.readyState == 3 print "no pongs, trying to reconnect", lastPongTime @ws.close() @reconnect() else @ws.safeSend("ping", {}) @reconnect() reconnect: -> @lastPong = Date.now() host = window.document.location.host.replace(/:.*/, '') @ws = new WebSocket 'ws://' + location.hostname + ":" + 1977 @ws.safeSend = (msg, kargs) => if @ws.readyState == WebSocket.OPEN @ws.send JSON.stringify msg: msg kargs: kargs else @connectionError() @ws.onopen = (data) -> print "connected with", data.iden editor.auth.think() @ws.onerror = (data) => @connectionError() #editor.auth.think() @ws.onmessage = (e) => packet = JSON.parse(e.data) msg = packet.msg kargs = packet.kargs if msg != "pong" print "got message", msg, kargs switch msg when 'pong' @lastPong = Date.now() when 'open-push' editor.open_cmd.open_push(kargs) when 'loggedin' editor.auth.loggedin(kargs) when 'suggest-push' editor.open_cmd.open_suggest_push(kargs) when 'error-push' if kargs.message == "invalid username or password" editor.auth.show() if kargs.message == "not logged in" editor.auth.login() editor.$errorbox.show() editor.$errorbox.html(kargs.message) when 'marks-push' editor.add_marks(kargs) connectionError: -> editor.$errorbox.show() editor.$errorbox.html("not connected") window.esc = -> editor.$errorbox.hide() editor.focus() window.cd = (directory) -> editor.open_cmd.directory = directory localStorage.setItem("directory", directory) # the main editor class class Editor # create a new editor constructor: -> @fresh = true window.editor = @ @con = new Connection() @filename = "untiled" @tab_width = 2 # grab common elements @$doc = $(document) @$win = $(window) @$holder = $(".holder") @$marks = $(".marks") @$pad = $(".pad") @$ghost = $(".ghost") @$highlight = $(".highlight") @$errorbox = $("#error-box") @$errorbox.hide() # grab careat @$caret_line = $("#caret-line") @$caret_text = $("#caret-text") @$caret_char = $("#caret-char") @$caret_tail = $("#caret-tail") @auth = new Auth() keydown = (e) => @update() key = keybord_key(e) if key.length != 1 and key.indexOf("-") == -1 # for all non character keys non meta @undo.snapshot() @con.ws.safeSend("keypress", key) if e.which == 13 and document.activeElement == @$pad[0] # some times browsers scrolls on enter # just started happening on Feb 11 2017 # to prevent this manually insert new line e.stopPropagation() e.preventDefault() @insert_text("\n") if e.metaKey and e.which == 86 and document.activeElement == @$pad[0] # some times browsers scrolls on paste # just started happening on Mar 15 2017 # fix scoll after paste topScroll = document.activeElement.scrollTop afterTimeout 1, -> document.activeElement.scrollTop = topScroll if @keymap[key]? @keymap[key]() e.stopPropagation() e.preventDefault() return null return true window.addEventListener("keydown", keydown, false) @$doc.keyup (e) => @update() e.preventDefault() return true @$doc.keypress (e) => @update() return true @$doc.mousedown => @undo.snapshot() @mousedown=true @update() @$doc.mousemove => if @mousedown @update() @$doc.mouseup => @mousedown = false @update() @$win.resize(@update) @$doc.click(@update) @$doc.on "mouseenter", ".mark", (e) -> $(".mark-text").hide() $(e.target).find(".mark-text").show() # keeps all the highlight state @lines = [] @tokenizer = new Tokenizer() # does not update if not changed @old_text = "" @old_caret = [0,0] @cmd = new Command() @goto_cmd = new GotoLine() @open_cmd = new OpenFile() @search_cmd = new SearchBox() @undo = new UndoStack() @replacer = new Replacer() @keymap = 'esc': esc 'tab': @tab 'shift-tab': @deindent 'ctrl-esc': @cmd.envoke 'ctrl-i': @cmd.envoke 'ctrl-g': @goto_cmd.envoke 'ctrl-o': @open_cmd.envoke 'ctrl-l': @open_cmd.envoke 'ctrl-s': @save 'ctrl-f': @search_cmd.envoke 'ctrl-z': @undo.undo 'ctrl-shift-z': @undo.redo 'ctrl-e': @replacer.styleChange 'ctrl-y': @replacer.sort @focus() # loop that redoes the work when needed @requset_update = true @workloop() # open current file open: (filename) => @con.ws.safeSend "open", filename: filename # opened opened: (filename, textdata) -> @fresh = false if @filename != filename @undo.clear() else savedSelection = [ @$pad[0].selectionEnd @$pad[0].selectionStart ] @filename = filename @tokenizer.guess_spec(filename) @tab_width = @tokenizer.spec.TAB_INDNET or 4 m = filename.match("\/([^\/]*)$") title = if m then m.pop() else filename $("title").html(title) window.history.pushState({}, "", "/edit/" + filename) @$pad.val(textdata) @undo.snapshot() @clear_makrs() @update() if savedSelection @$pad[0].selectionStart = savedSelection[0] @$pad[0].selectionEnd = savedSelection[1] # save current file save: => text = @$pad.val() # replace tabs by spaces space = (" " for _ in [0...@tab_width]).join("") text = text.replace(/\t/g, space) # strip trailing white space onlines text = text.replace(/[ \r]*\n/g,"\n").replace(/\s*$/, "\n") @con.ws.safeSend "save", filename: @filename data: text # focus the pad focus: => $("div.popup").hide() @$pad.focus() @update() # return the lines selected selected_line_range: -> start = null end = null for line, n in @lines if not start and line[1] <= @old_caret[0] < line[2] start = n if not end and line[1] < @old_caret[1] <= line[2] end = n if not end or end < start end = start return [start, end] # tab was pressed, complex behavior tab: => if $("#search-input").is(":focus") $("#replace-input").focus() return if $("#replace-input").is(":focus") $("#search-input").focus() return if not @$pad.is(":focus") return if @autocomplete() return @indent() return # auto complete right at the current cursor autocomplete: => [text, [start, end], s] = @get_text_state() # if some thing is selected don't auto complete if start != end return false string = text.substr(0, start) at = text[start] string = string.match(/\w+$/) # only when at char is splace and there is a string under curser if (not at or at.match(/\s/)) and string options = {} words = text.split(/\W+/).sort() if words for word in words word_match = word.match("^" + string + "(.+)") if word_match and word_match[1] != "" options[word_match[1]] = true add = common_str(k for k of options) if add.length > 0 @insert_text(add) return true return false # insert text into the selected range insert_text: (add) => [text, [start, end], s] = @get_text_state() if start == 0 text = add + text[end..] else text = text[..start-1] + add + text[end..] start += add.length end += add.length @set_text_state([text, [start, end], s]) # indent selected range indent: => [start, end] = @selected_line_range() if start == end real = @$pad[0].selectionStart just_tab = true lines = (l[3] for l in @lines) tab_str = "" for n in [0...@tab_width] tab_str += " " for n in [start..end] lines[n] = tab_str + lines[n] text = (l for l in lines).join("\n") @set_text(text) if just_tab @$pad[0].selectionStart = real + @tab_width @$pad[0].selectionEnd = @$pad[0].selectionStart else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @lines[end][2] + @tab_width * (end-start+1) # deindent selected range deindent: => [start, end] = @selected_line_range() if start == end real = @$pad[0].selectionStart just_tab = true lines = (l[3] for l in @lines) old_length = 0 for n in [start..end] old_length += lines[n].length + 1 for t in [0...@tab_width] if lines[n][0] == " " lines[n] = lines[n][1..] text = (l for l in lines).join("\n") @set_text(text) new_length = 0 for n in [start..end] new_length += lines[n].length + 1 if just_tab if real - @tab_width > @lines[start][1] @$pad[0].selectionStart = real - @tab_width else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @$pad[0].selectionStart else @$pad[0].selectionStart = @lines[start][1] @$pad[0].selectionEnd = @$pad[0].selectionStart + new_length # set the text of the pad to a value set_text: (text) -> @$pad.val(text) @update() # return the text of the pad get_text: () -> return @$pad.val() # set the state of the text set_text_state: (text_state) -> @$pad.val(text_state[0]) @$pad[0].selectionEnd = text_state[1][0] @$pad[0].selectionStart = text_state[1][1] if text_state[2] != 0 @$holder.stop(true).animate(scrollTop: text_state[2]) @update() # gets the state of the text get_text_state: () -> start = @$pad[0].selectionStart end = @$pad[0].selectionEnd if start > end [start, end] = [end, start] text_state = [ @$pad.val(), [start, end], @$holder.scrollTop(), ] return text_state # request for an update to be made update: => @requset_update = true # redraw the ghost buffer real_update: -> if performance? and performance.now? now = performance.now() # adjust hight and width of things @height = @$win.height() @width = @$win.width() - 10 # 10 for scrollbar @$holder.height(@height) a = 4 @$holder.width(@width) @$pad.width(@width-a) @$ghost.width(@width-a) @$highlight.width(@width-a) @$caret_line.width(@width-a) @$marks.width(@width-a) # get the current text @text = text = @$pad.val() or "" set_line = (i, html) => $("#line#{i}").html(html) # for debugging refresh performance #$("#line#{i}").stop().css("opacity", 0) #$("#line#{i}").animate({opacity: 1}, 300); add_line = (i, html) => @$ghost.append("<span id='line#{i}'>#{html}</span>") rm_line = (i) => $("#line#{i}").remove() # high light if it has changed if @old_text != text @old_text = text lines = text.split("\n") start = 0 for line, i in lines if i > 0 prev_mode = @lines[i-1][4] else prev_mode = ["plain", "plain"] end = start + line.length + 1 if @lines[i]? oldline = @lines[i] oldline[1] = start oldline[2] = end if oldline[3] != line or prev_mode[1] != oldline[4][0] [colored, mode, html] = @tokenizer.tokenize(line, prev_mode) oldline[3] = line oldline[4] = mode set_line(i, html) else [colored, mode, html] = @tokenizer.tokenize(line, prev_mode) @lines.push([i, start, end, line, mode]) add_line(i, html) start = end while lines.length < @lines.length l = @lines.pop() rm_line(l[0]) # update caret if it has changed caret at = @$pad[0].selectionStart end = @$pad[0].selectionEnd if @old_caret != [at, end] @old_caret = [at, end] if at == end for line in @lines if line[1] <= at < line[2] if at != line[1] caret_text = text[line[1]..at-1] else caret_text = "" top = $("#line"+line[0]).position().top + 100 @$caret_text.html(html_safe(caret_text)) @$caret_char.html("&nbsp;") @$caret_line.css("top", top) @$caret_tail.html(html_safe(text[at+1...text.indexOf("\n", at)])) else if at > end [at, end] = [end, at] for line in @lines if line[1] <= at < line[2] if at != line[1] caret_text = text[line[1]..at-1] else caret_text = "" top = $("#line"+line[0]).position().top + 100 @$caret_text.html(html_safe(caret_text)) @$caret_line.css("top", top) @$caret_char.html(html_safe(text[at..end-1])) @$caret_tail.html(html_safe(text[end..text.indexOf("\n", end)])) @full_height = @$ghost.height() @$pad.height(@full_height+100) # scroll to a char position scroll_pos: (offset) -> line = 0 for c in @text[0...offset] if c == "\n" line += 1 @scroll_line(line) # go to a line number goto_line: (line_num) -> line = @lines[line_num] ? @lines[@lines.length - 1] @$pad[0].selectionStart = line[1] @$pad[0].selectionEnd = line[1] @scroll_line(line[0]) # animate a scroll to a line number scroll_line: (line_num) -> line = @lines[line_num] ? @lines[@lines.length - 1] y = @get_line_y(line[0]) y -= @$win.height()/2 @$holder.stop(true).animate(scrollTop: y) # get line's y cordiante for scrolling get_line_y: (line_num) -> top = $("#line"+line_num).position().top + 100 return top # adds the makrs about lint stuff to the editor # this is used to show errors or git lines add_marks: (marks) -> if marks.filename == @filename $layer = $("#marks-"+marks.layer) $layer.html("") for mark in marks.marks continue if not mark $line = $("#line"+(mark.line-1)) p = $line.position() return if not p if mark.tag == "change" $layer.append("<div class='mark change' style='top:#{p.top}px;'>*</div>") else $layer.append("<div class='mark' style='top:#{p.top}px;'>#{mark.tag}:#{mark.text}</div>") clear_makrs: (layer) -> $(".marks").html("") # loop that does the work for rendering when update is requested workloop: => if @requset_update @real_update() @requset_update = false requestAnimFrame(@workloop) $ -> window.editor = new Editor()
[ { "context": "# Copyright (c) 2014-2015 Riceball LEE, MIT License\ndeprecate = require('dep", "end": 38, "score": 0.9997366666793823, "start": 26, "tag": "NAME", "value": "Riceball LEE" } ]
src/custom-factory.coffee
snowyu/custom-factory.js
2
# Copyright (c) 2014-2015 Riceball LEE, MIT License deprecate = require('depd')('custom-factory') inherits = require('inherits-ex/lib/inherits') isInheritedFrom = require('inherits-ex/lib/isInheritedFrom') createObject = require('inherits-ex/lib/createObject') getPrototypeOf = require('inherits-ex/lib/getPrototypeOf') extend = require('./extend') isFunction = (v)-> 'function' is typeof v isString = (v)-> 'string' is typeof v isObject = (v)-> v? and 'object' is typeof v getObjectKeys = Object.keys getParentClass = (ctor)-> ctor.super_ || getPrototypeOf(ctor) exports = module.exports = (Factory, aOptions)-> if isObject aOptions flatOnly = aOptions.flatOnly baseNameOnly = aOptions.baseNameOnly if aOptions.baseNameOnly? baseNameOnly ?= 1 # the Static(Class) Methods for Factory: extend Factory, ROOT_NAME: Factory.name getClassList: (ctor)-> result = while ctor and ctor isnt Factory item = ctor ctor = getParentClass ctor item getClassNameList: getClassNameList = (ctor)-> result = while ctor and ctor isnt Factory item = ctor::name ctor = getParentClass ctor item path: (aClass, aRootName)-> '/' + @pathArray(aClass, aRootName).join '/' pathArray: (aClass, aRootName) -> result = aClass::name return result.split('/').filter(Boolean) if result and result[0] is '/' aRootName = Factory.ROOT_NAME unless aRootName? result = getClassNameList(aClass) result.push aRootName if aRootName if Factory.formatName isnt formatName result = (Factory.formatName(i) for i in result) result.reverse() _objects: registeredObjects = {} _aliases: aliases = {} formatName: formatName = (aName)->aName getNameFrom: (aClass)-> if isFunction aClass #Factory.getNameFromClass(aClass) aClass::name else Factory.formatName aClass getNameFromClass: (aClass, aParentClass, aBaseNameOnly)-> result = aClass.name len = result.length throw new InvalidArgumentError( 'can not getNameFromClass: the ' + vFactoryName+'(constructor) has no name error.' ) unless len aBaseNameOnly = baseNameOnly unless aBaseNameOnly? ### vFactoryName = Factory.name if vFactoryName and vFactoryName.length and result.substring(len-vFactoryName.length) is vFactoryName result = result.substring(0, len-vFactoryName.length) ### if aBaseNameOnly # then remove Parent Name if any aParentClass = getParentClass(aClass) unless aParentClass names = getClassNameList aParentClass names.push Factory.name if names.length for vFactoryName in names.reverse() if vFactoryName and vFactoryName.length and result.substring(len-vFactoryName.length) is vFactoryName result = result.substring(0, len-vFactoryName.length) len = result.length break unless --aBaseNameOnly Factory.formatName result _get: getInstance = (aName, aOptions)-> result = registeredObjects[aName] if result is undefined # Is it a alias? aName = Factory.getRealNameFromAlias aName if aName result = registeredObjects[aName] return if result is undefined if result instanceof Factory # do not initialize if no aOptions result.initialize aOptions if aOptions? else result = if isObject result then extend(result, aOptions) else if aOptions? then aOptions else result cls = Factory[aName] if cls result = createObject cls, undefined, result registeredObjects[aName] = result else result = undefined return result get: (aName, aOptions)-> getInstance(aName, aOptions) extendClass: extendClass = (aParentClass) -> extend aParentClass, forEachClass: (cb)-> if isFunction cb for k in getObjectKeys aParentClass v = aParentClass[k] if isInheritedFrom v, Factory break if cb(v, k) == 'brk' aParentClass forEach: (aOptions, cb)-> if isFunction aOptions cb = aOptions aOptions = null if isFunction cb aParentClass.forEachClass (v,k)-> cb(Factory.get(k, aOptions), k) aParentClass register: _register = (aClass, aOptions)-> if isString aOptions vName = aOptions else if aOptions vName = aOptions.name vDisplayName = aOptions.displayName vCreateOnDemand = aOptions.createOnDemand if not vName if aOptions && aOptions.baseNameOnly vBaseNameOnly = aOptions.baseNameOnly else vBaseNameOnly = baseNameOnly vName = Factory.getNameFromClass(aClass, aParentClass, vBaseNameOnly) else vName = Factory.formatName vName result = not registeredObjects.hasOwnProperty(vName) throw new TypeError( 'the ' + vName + ' has already been registered.' ) unless result result = inherits aClass, aParentClass if result extendClass(aClass) unless flatOnly aClass::name = vName aClass::_displayName = vDisplayName if vDisplayName if result aParentClass[vName] = aClass Factory[vName] = aClass unless aParentClass is Factory if vCreateOnDemand isnt false registeredObjects[vName] = if aOptions? then aOptions else null else registeredObjects[vName] = createObject aClass, undefined, aOptions result _register: _register unregister: (aName)-> if isString aName aName = Factory.formatName aName vClass = Factory.hasOwnProperty(aName) and Factory[aName] else vClass = aName #aName = Factory.getNameFromClass(aName) result = vClass and isInheritedFrom vClass, aParentClass if result aName = vClass::name #TODO:should I unregister all children? while vClass and (vParentClass = getParentClass(vClass)) and vParentClass isnt Factory vClass = getParentClass vClass delete vClass[aName] delete registeredObjects[aName] delete Factory[aName] for k, v of aliases delete aliases[k] if v is aName !!result registeredClass: (aName)-> aName = Factory.formatName aName result = aParentClass.hasOwnProperty(aName) and aParentClass[aName] return result if result aName = Factory.getRealNameFromAlias aName return aParentClass.hasOwnProperty(aName) and aParentClass[aName] if aName if not flatOnly or aParentClass is Factory extend aParentClass, getRealNameFromAlias: (alias)-> aliases[alias] displayName: (aClass, aValue)-> if isString aClass aValue = aClass aClass = aParentClass if isString aValue if isFunction aClass if !aValue vClassName = Factory.getNameFrom(aClass) for k,v of aliases if v is vClassName aValue = k break if aValue aClass::_displayName = aValue else delete aClass::_displayName else throw new TypeError 'set displayName: Invalid Class' return aClass = aParentClass unless aClass # if isString aClass # aClass = Factory.registeredClass aClass if isFunction aClass result = aClass::_displayName if aClass::hasOwnProperty '_displayName' result ?= aClass::name else throw new TypeError 'get displayName: Invalid Class' result alias: alias = (aClass, aAliases...)-> if aAliases.length # aClass could be a class or class name. vClass = aClass aClass = Factory.getNameFrom(aClass) aAliases = aAliases.map Factory.formatName vClass = Factory.registeredClass(aClass) if !isFunction vClass if vClass and not vClass::hasOwnProperty '_displayName' vClass::_displayName = aAliases[0] for alias in aAliases aliases[alias] = aClass return aClass = aParentClass unless aClass aClass = Factory.getNameFrom(aClass) result = [] for k,v of aliases result.push k if v is aClass result aliases: alias create: (aName, aOptions)-> result = aParentClass.registeredClass aName if result is undefined and aParentClass isnt Factory # search the root factory result = Factory.registeredClass aName if result then createObject result, aOptions Factory.extendClass Factory Factory::_objects = registeredObjects Factory::_aliases = aliases deprecate.property Factory, '_objects', 'use Factory::_objects instead' deprecate.property Factory, '_aliases', 'use Factory::_aliases instead' Factory.register = (aClass, aParentClass, aOptions)-> if aParentClass if not isFunction aParentClass or not isInheritedFrom aParentClass, Factory aOptions = aParentClass aParentClass = aOptions.parent aParentClass = Factory if flatOnly or not aParentClass else if flatOnly throw new TypeError " It's a flat factory, register to the parent class is not allowed" else aParentClass = Factory if aParentClass is Factory Factory._register aClass, aOptions else aParentClass.register aClass, aOptions if aOptions and isFunction aOptions.fnGet vNewGetInstance = aOptions.fnGet getInstance = ((inherited)-> that = super: inherited self: this return -> vNewGetInstance.apply(that, arguments) )(Factory._get) Factory.get = getInstance class CustomFactory constructor: (aName, aOptions)-> if aName instanceof Factory # do not initialize if no aOptions aName.initialize aOptions if aOptions? return aName if aName if isObject aName aOptions = aName aName = aOptions.name else if not isString aName aOptions = aName aName = undefined if not (this instanceof Factory) if not aName # arguments.callee is forbidden if strict mode enabled. try vCaller = arguments.callee.caller if vCaller and isInheritedFrom vCaller, Factory aName = vCaller vCaller = vCaller.caller #get farest hierarchical registered class while isInheritedFrom vCaller, aName aName = vCaller vCaller = vCaller.caller #aName = Factory.getNameFromClass(aName) if aName aName = aName::name if aName return unless aName else aName = Factory.formatName aName return Factory.get aName, aOptions else @initialize(aOptions) #@_create: createInstance = (aName, aOptions)-> initialize: (aOptions)-> toString: -> #@name.toLowerCase() @name getFactoryItem: (aName, aOptions)->Factory.get.call(@, aName, aOptions) aliases: -> @Class.aliases.apply @, arguments displayName: (aClass, aValue)-> @Class.displayName.call @, aClass, aValue if not flatOnly @::register= (aClass, aOptions)-> @Class.register.call @, aClass, aOptions @::unregister= (aName)-> @Class.unregister.call @, aName @::registered= (aName)-> Factory(aName) @::registeredClass= (aName)-> aName = Factory.formatName aName result = @Class.hasOwnProperty(aName) and @Class[aName] return result if result aName = Factory.getRealNameFromAlias.call @, aName return @Class.hasOwnProperty(aName) and @Class[aName] if aName return @::path = (aRootName)-> '/' + @pathArray(aRootName).join '/' @::pathArray = (aRootName) ->Factory.pathArray(@Class, aRootName) inherits Factory, CustomFactory
145094
# Copyright (c) 2014-2015 <NAME>, MIT License deprecate = require('depd')('custom-factory') inherits = require('inherits-ex/lib/inherits') isInheritedFrom = require('inherits-ex/lib/isInheritedFrom') createObject = require('inherits-ex/lib/createObject') getPrototypeOf = require('inherits-ex/lib/getPrototypeOf') extend = require('./extend') isFunction = (v)-> 'function' is typeof v isString = (v)-> 'string' is typeof v isObject = (v)-> v? and 'object' is typeof v getObjectKeys = Object.keys getParentClass = (ctor)-> ctor.super_ || getPrototypeOf(ctor) exports = module.exports = (Factory, aOptions)-> if isObject aOptions flatOnly = aOptions.flatOnly baseNameOnly = aOptions.baseNameOnly if aOptions.baseNameOnly? baseNameOnly ?= 1 # the Static(Class) Methods for Factory: extend Factory, ROOT_NAME: Factory.name getClassList: (ctor)-> result = while ctor and ctor isnt Factory item = ctor ctor = getParentClass ctor item getClassNameList: getClassNameList = (ctor)-> result = while ctor and ctor isnt Factory item = ctor::name ctor = getParentClass ctor item path: (aClass, aRootName)-> '/' + @pathArray(aClass, aRootName).join '/' pathArray: (aClass, aRootName) -> result = aClass::name return result.split('/').filter(Boolean) if result and result[0] is '/' aRootName = Factory.ROOT_NAME unless aRootName? result = getClassNameList(aClass) result.push aRootName if aRootName if Factory.formatName isnt formatName result = (Factory.formatName(i) for i in result) result.reverse() _objects: registeredObjects = {} _aliases: aliases = {} formatName: formatName = (aName)->aName getNameFrom: (aClass)-> if isFunction aClass #Factory.getNameFromClass(aClass) aClass::name else Factory.formatName aClass getNameFromClass: (aClass, aParentClass, aBaseNameOnly)-> result = aClass.name len = result.length throw new InvalidArgumentError( 'can not getNameFromClass: the ' + vFactoryName+'(constructor) has no name error.' ) unless len aBaseNameOnly = baseNameOnly unless aBaseNameOnly? ### vFactoryName = Factory.name if vFactoryName and vFactoryName.length and result.substring(len-vFactoryName.length) is vFactoryName result = result.substring(0, len-vFactoryName.length) ### if aBaseNameOnly # then remove Parent Name if any aParentClass = getParentClass(aClass) unless aParentClass names = getClassNameList aParentClass names.push Factory.name if names.length for vFactoryName in names.reverse() if vFactoryName and vFactoryName.length and result.substring(len-vFactoryName.length) is vFactoryName result = result.substring(0, len-vFactoryName.length) len = result.length break unless --aBaseNameOnly Factory.formatName result _get: getInstance = (aName, aOptions)-> result = registeredObjects[aName] if result is undefined # Is it a alias? aName = Factory.getRealNameFromAlias aName if aName result = registeredObjects[aName] return if result is undefined if result instanceof Factory # do not initialize if no aOptions result.initialize aOptions if aOptions? else result = if isObject result then extend(result, aOptions) else if aOptions? then aOptions else result cls = Factory[aName] if cls result = createObject cls, undefined, result registeredObjects[aName] = result else result = undefined return result get: (aName, aOptions)-> getInstance(aName, aOptions) extendClass: extendClass = (aParentClass) -> extend aParentClass, forEachClass: (cb)-> if isFunction cb for k in getObjectKeys aParentClass v = aParentClass[k] if isInheritedFrom v, Factory break if cb(v, k) == 'brk' aParentClass forEach: (aOptions, cb)-> if isFunction aOptions cb = aOptions aOptions = null if isFunction cb aParentClass.forEachClass (v,k)-> cb(Factory.get(k, aOptions), k) aParentClass register: _register = (aClass, aOptions)-> if isString aOptions vName = aOptions else if aOptions vName = aOptions.name vDisplayName = aOptions.displayName vCreateOnDemand = aOptions.createOnDemand if not vName if aOptions && aOptions.baseNameOnly vBaseNameOnly = aOptions.baseNameOnly else vBaseNameOnly = baseNameOnly vName = Factory.getNameFromClass(aClass, aParentClass, vBaseNameOnly) else vName = Factory.formatName vName result = not registeredObjects.hasOwnProperty(vName) throw new TypeError( 'the ' + vName + ' has already been registered.' ) unless result result = inherits aClass, aParentClass if result extendClass(aClass) unless flatOnly aClass::name = vName aClass::_displayName = vDisplayName if vDisplayName if result aParentClass[vName] = aClass Factory[vName] = aClass unless aParentClass is Factory if vCreateOnDemand isnt false registeredObjects[vName] = if aOptions? then aOptions else null else registeredObjects[vName] = createObject aClass, undefined, aOptions result _register: _register unregister: (aName)-> if isString aName aName = Factory.formatName aName vClass = Factory.hasOwnProperty(aName) and Factory[aName] else vClass = aName #aName = Factory.getNameFromClass(aName) result = vClass and isInheritedFrom vClass, aParentClass if result aName = vClass::name #TODO:should I unregister all children? while vClass and (vParentClass = getParentClass(vClass)) and vParentClass isnt Factory vClass = getParentClass vClass delete vClass[aName] delete registeredObjects[aName] delete Factory[aName] for k, v of aliases delete aliases[k] if v is aName !!result registeredClass: (aName)-> aName = Factory.formatName aName result = aParentClass.hasOwnProperty(aName) and aParentClass[aName] return result if result aName = Factory.getRealNameFromAlias aName return aParentClass.hasOwnProperty(aName) and aParentClass[aName] if aName if not flatOnly or aParentClass is Factory extend aParentClass, getRealNameFromAlias: (alias)-> aliases[alias] displayName: (aClass, aValue)-> if isString aClass aValue = aClass aClass = aParentClass if isString aValue if isFunction aClass if !aValue vClassName = Factory.getNameFrom(aClass) for k,v of aliases if v is vClassName aValue = k break if aValue aClass::_displayName = aValue else delete aClass::_displayName else throw new TypeError 'set displayName: Invalid Class' return aClass = aParentClass unless aClass # if isString aClass # aClass = Factory.registeredClass aClass if isFunction aClass result = aClass::_displayName if aClass::hasOwnProperty '_displayName' result ?= aClass::name else throw new TypeError 'get displayName: Invalid Class' result alias: alias = (aClass, aAliases...)-> if aAliases.length # aClass could be a class or class name. vClass = aClass aClass = Factory.getNameFrom(aClass) aAliases = aAliases.map Factory.formatName vClass = Factory.registeredClass(aClass) if !isFunction vClass if vClass and not vClass::hasOwnProperty '_displayName' vClass::_displayName = aAliases[0] for alias in aAliases aliases[alias] = aClass return aClass = aParentClass unless aClass aClass = Factory.getNameFrom(aClass) result = [] for k,v of aliases result.push k if v is aClass result aliases: alias create: (aName, aOptions)-> result = aParentClass.registeredClass aName if result is undefined and aParentClass isnt Factory # search the root factory result = Factory.registeredClass aName if result then createObject result, aOptions Factory.extendClass Factory Factory::_objects = registeredObjects Factory::_aliases = aliases deprecate.property Factory, '_objects', 'use Factory::_objects instead' deprecate.property Factory, '_aliases', 'use Factory::_aliases instead' Factory.register = (aClass, aParentClass, aOptions)-> if aParentClass if not isFunction aParentClass or not isInheritedFrom aParentClass, Factory aOptions = aParentClass aParentClass = aOptions.parent aParentClass = Factory if flatOnly or not aParentClass else if flatOnly throw new TypeError " It's a flat factory, register to the parent class is not allowed" else aParentClass = Factory if aParentClass is Factory Factory._register aClass, aOptions else aParentClass.register aClass, aOptions if aOptions and isFunction aOptions.fnGet vNewGetInstance = aOptions.fnGet getInstance = ((inherited)-> that = super: inherited self: this return -> vNewGetInstance.apply(that, arguments) )(Factory._get) Factory.get = getInstance class CustomFactory constructor: (aName, aOptions)-> if aName instanceof Factory # do not initialize if no aOptions aName.initialize aOptions if aOptions? return aName if aName if isObject aName aOptions = aName aName = aOptions.name else if not isString aName aOptions = aName aName = undefined if not (this instanceof Factory) if not aName # arguments.callee is forbidden if strict mode enabled. try vCaller = arguments.callee.caller if vCaller and isInheritedFrom vCaller, Factory aName = vCaller vCaller = vCaller.caller #get farest hierarchical registered class while isInheritedFrom vCaller, aName aName = vCaller vCaller = vCaller.caller #aName = Factory.getNameFromClass(aName) if aName aName = aName::name if aName return unless aName else aName = Factory.formatName aName return Factory.get aName, aOptions else @initialize(aOptions) #@_create: createInstance = (aName, aOptions)-> initialize: (aOptions)-> toString: -> #@name.toLowerCase() @name getFactoryItem: (aName, aOptions)->Factory.get.call(@, aName, aOptions) aliases: -> @Class.aliases.apply @, arguments displayName: (aClass, aValue)-> @Class.displayName.call @, aClass, aValue if not flatOnly @::register= (aClass, aOptions)-> @Class.register.call @, aClass, aOptions @::unregister= (aName)-> @Class.unregister.call @, aName @::registered= (aName)-> Factory(aName) @::registeredClass= (aName)-> aName = Factory.formatName aName result = @Class.hasOwnProperty(aName) and @Class[aName] return result if result aName = Factory.getRealNameFromAlias.call @, aName return @Class.hasOwnProperty(aName) and @Class[aName] if aName return @::path = (aRootName)-> '/' + @pathArray(aRootName).join '/' @::pathArray = (aRootName) ->Factory.pathArray(@Class, aRootName) inherits Factory, CustomFactory
true
# Copyright (c) 2014-2015 PI:NAME:<NAME>END_PI, MIT License deprecate = require('depd')('custom-factory') inherits = require('inherits-ex/lib/inherits') isInheritedFrom = require('inherits-ex/lib/isInheritedFrom') createObject = require('inherits-ex/lib/createObject') getPrototypeOf = require('inherits-ex/lib/getPrototypeOf') extend = require('./extend') isFunction = (v)-> 'function' is typeof v isString = (v)-> 'string' is typeof v isObject = (v)-> v? and 'object' is typeof v getObjectKeys = Object.keys getParentClass = (ctor)-> ctor.super_ || getPrototypeOf(ctor) exports = module.exports = (Factory, aOptions)-> if isObject aOptions flatOnly = aOptions.flatOnly baseNameOnly = aOptions.baseNameOnly if aOptions.baseNameOnly? baseNameOnly ?= 1 # the Static(Class) Methods for Factory: extend Factory, ROOT_NAME: Factory.name getClassList: (ctor)-> result = while ctor and ctor isnt Factory item = ctor ctor = getParentClass ctor item getClassNameList: getClassNameList = (ctor)-> result = while ctor and ctor isnt Factory item = ctor::name ctor = getParentClass ctor item path: (aClass, aRootName)-> '/' + @pathArray(aClass, aRootName).join '/' pathArray: (aClass, aRootName) -> result = aClass::name return result.split('/').filter(Boolean) if result and result[0] is '/' aRootName = Factory.ROOT_NAME unless aRootName? result = getClassNameList(aClass) result.push aRootName if aRootName if Factory.formatName isnt formatName result = (Factory.formatName(i) for i in result) result.reverse() _objects: registeredObjects = {} _aliases: aliases = {} formatName: formatName = (aName)->aName getNameFrom: (aClass)-> if isFunction aClass #Factory.getNameFromClass(aClass) aClass::name else Factory.formatName aClass getNameFromClass: (aClass, aParentClass, aBaseNameOnly)-> result = aClass.name len = result.length throw new InvalidArgumentError( 'can not getNameFromClass: the ' + vFactoryName+'(constructor) has no name error.' ) unless len aBaseNameOnly = baseNameOnly unless aBaseNameOnly? ### vFactoryName = Factory.name if vFactoryName and vFactoryName.length and result.substring(len-vFactoryName.length) is vFactoryName result = result.substring(0, len-vFactoryName.length) ### if aBaseNameOnly # then remove Parent Name if any aParentClass = getParentClass(aClass) unless aParentClass names = getClassNameList aParentClass names.push Factory.name if names.length for vFactoryName in names.reverse() if vFactoryName and vFactoryName.length and result.substring(len-vFactoryName.length) is vFactoryName result = result.substring(0, len-vFactoryName.length) len = result.length break unless --aBaseNameOnly Factory.formatName result _get: getInstance = (aName, aOptions)-> result = registeredObjects[aName] if result is undefined # Is it a alias? aName = Factory.getRealNameFromAlias aName if aName result = registeredObjects[aName] return if result is undefined if result instanceof Factory # do not initialize if no aOptions result.initialize aOptions if aOptions? else result = if isObject result then extend(result, aOptions) else if aOptions? then aOptions else result cls = Factory[aName] if cls result = createObject cls, undefined, result registeredObjects[aName] = result else result = undefined return result get: (aName, aOptions)-> getInstance(aName, aOptions) extendClass: extendClass = (aParentClass) -> extend aParentClass, forEachClass: (cb)-> if isFunction cb for k in getObjectKeys aParentClass v = aParentClass[k] if isInheritedFrom v, Factory break if cb(v, k) == 'brk' aParentClass forEach: (aOptions, cb)-> if isFunction aOptions cb = aOptions aOptions = null if isFunction cb aParentClass.forEachClass (v,k)-> cb(Factory.get(k, aOptions), k) aParentClass register: _register = (aClass, aOptions)-> if isString aOptions vName = aOptions else if aOptions vName = aOptions.name vDisplayName = aOptions.displayName vCreateOnDemand = aOptions.createOnDemand if not vName if aOptions && aOptions.baseNameOnly vBaseNameOnly = aOptions.baseNameOnly else vBaseNameOnly = baseNameOnly vName = Factory.getNameFromClass(aClass, aParentClass, vBaseNameOnly) else vName = Factory.formatName vName result = not registeredObjects.hasOwnProperty(vName) throw new TypeError( 'the ' + vName + ' has already been registered.' ) unless result result = inherits aClass, aParentClass if result extendClass(aClass) unless flatOnly aClass::name = vName aClass::_displayName = vDisplayName if vDisplayName if result aParentClass[vName] = aClass Factory[vName] = aClass unless aParentClass is Factory if vCreateOnDemand isnt false registeredObjects[vName] = if aOptions? then aOptions else null else registeredObjects[vName] = createObject aClass, undefined, aOptions result _register: _register unregister: (aName)-> if isString aName aName = Factory.formatName aName vClass = Factory.hasOwnProperty(aName) and Factory[aName] else vClass = aName #aName = Factory.getNameFromClass(aName) result = vClass and isInheritedFrom vClass, aParentClass if result aName = vClass::name #TODO:should I unregister all children? while vClass and (vParentClass = getParentClass(vClass)) and vParentClass isnt Factory vClass = getParentClass vClass delete vClass[aName] delete registeredObjects[aName] delete Factory[aName] for k, v of aliases delete aliases[k] if v is aName !!result registeredClass: (aName)-> aName = Factory.formatName aName result = aParentClass.hasOwnProperty(aName) and aParentClass[aName] return result if result aName = Factory.getRealNameFromAlias aName return aParentClass.hasOwnProperty(aName) and aParentClass[aName] if aName if not flatOnly or aParentClass is Factory extend aParentClass, getRealNameFromAlias: (alias)-> aliases[alias] displayName: (aClass, aValue)-> if isString aClass aValue = aClass aClass = aParentClass if isString aValue if isFunction aClass if !aValue vClassName = Factory.getNameFrom(aClass) for k,v of aliases if v is vClassName aValue = k break if aValue aClass::_displayName = aValue else delete aClass::_displayName else throw new TypeError 'set displayName: Invalid Class' return aClass = aParentClass unless aClass # if isString aClass # aClass = Factory.registeredClass aClass if isFunction aClass result = aClass::_displayName if aClass::hasOwnProperty '_displayName' result ?= aClass::name else throw new TypeError 'get displayName: Invalid Class' result alias: alias = (aClass, aAliases...)-> if aAliases.length # aClass could be a class or class name. vClass = aClass aClass = Factory.getNameFrom(aClass) aAliases = aAliases.map Factory.formatName vClass = Factory.registeredClass(aClass) if !isFunction vClass if vClass and not vClass::hasOwnProperty '_displayName' vClass::_displayName = aAliases[0] for alias in aAliases aliases[alias] = aClass return aClass = aParentClass unless aClass aClass = Factory.getNameFrom(aClass) result = [] for k,v of aliases result.push k if v is aClass result aliases: alias create: (aName, aOptions)-> result = aParentClass.registeredClass aName if result is undefined and aParentClass isnt Factory # search the root factory result = Factory.registeredClass aName if result then createObject result, aOptions Factory.extendClass Factory Factory::_objects = registeredObjects Factory::_aliases = aliases deprecate.property Factory, '_objects', 'use Factory::_objects instead' deprecate.property Factory, '_aliases', 'use Factory::_aliases instead' Factory.register = (aClass, aParentClass, aOptions)-> if aParentClass if not isFunction aParentClass or not isInheritedFrom aParentClass, Factory aOptions = aParentClass aParentClass = aOptions.parent aParentClass = Factory if flatOnly or not aParentClass else if flatOnly throw new TypeError " It's a flat factory, register to the parent class is not allowed" else aParentClass = Factory if aParentClass is Factory Factory._register aClass, aOptions else aParentClass.register aClass, aOptions if aOptions and isFunction aOptions.fnGet vNewGetInstance = aOptions.fnGet getInstance = ((inherited)-> that = super: inherited self: this return -> vNewGetInstance.apply(that, arguments) )(Factory._get) Factory.get = getInstance class CustomFactory constructor: (aName, aOptions)-> if aName instanceof Factory # do not initialize if no aOptions aName.initialize aOptions if aOptions? return aName if aName if isObject aName aOptions = aName aName = aOptions.name else if not isString aName aOptions = aName aName = undefined if not (this instanceof Factory) if not aName # arguments.callee is forbidden if strict mode enabled. try vCaller = arguments.callee.caller if vCaller and isInheritedFrom vCaller, Factory aName = vCaller vCaller = vCaller.caller #get farest hierarchical registered class while isInheritedFrom vCaller, aName aName = vCaller vCaller = vCaller.caller #aName = Factory.getNameFromClass(aName) if aName aName = aName::name if aName return unless aName else aName = Factory.formatName aName return Factory.get aName, aOptions else @initialize(aOptions) #@_create: createInstance = (aName, aOptions)-> initialize: (aOptions)-> toString: -> #@name.toLowerCase() @name getFactoryItem: (aName, aOptions)->Factory.get.call(@, aName, aOptions) aliases: -> @Class.aliases.apply @, arguments displayName: (aClass, aValue)-> @Class.displayName.call @, aClass, aValue if not flatOnly @::register= (aClass, aOptions)-> @Class.register.call @, aClass, aOptions @::unregister= (aName)-> @Class.unregister.call @, aName @::registered= (aName)-> Factory(aName) @::registeredClass= (aName)-> aName = Factory.formatName aName result = @Class.hasOwnProperty(aName) and @Class[aName] return result if result aName = Factory.getRealNameFromAlias.call @, aName return @Class.hasOwnProperty(aName) and @Class[aName] if aName return @::path = (aRootName)-> '/' + @pathArray(aRootName).join '/' @::pathArray = (aRootName) ->Factory.pathArray(@Class, aRootName) inherits Factory, CustomFactory
[ { "context": "Each ->\n project = new Project\n name:\"testProject\"\n bomExporter = new BomExporter()\n ", "end": 264, "score": 0.7396036982536316, "start": 260, "tag": "NAME", "value": "test" }, { "context": "rt fails',-> \n project.addFile\n name:\"testFileName\"\n errorCallback = jasmine.createSpy(", "end": 905, "score": 0.5748266577720642, "start": 901, "tag": "NAME", "value": "test" }, { "context": "ails',-> \n project.addFile\n name:\"testFileName\"\n blobUrl = bomExporter.export(proje", "end": 1315, "score": 0.5290057063102722, "start": 1311, "tag": "NAME", "value": "test" } ]
src/test/spec/exporters/bomExporter/bomExporter.spec.coffee
kaosat-dev/CoffeeSCad
110
define (require)-> BomExporter = require "exporters/bomExporter/bomExporter" Project = require "core/projects/project" describe "BomExporter", -> project = null bomExporter = null beforeEach -> project = new Project name:"testProject" bomExporter = new BomExporter() it 'can export a project to bom (blobUrl)',-> project.addFile name:"testProject.coffee" content:""" class TestPart extends Part constructor:(options) -> super options @union(new Cylinder(h:300, r:20,$fn:3)) testPart = new TestPart() assembly.add(testPart) """ project.compile() blobUrl = bomExporter.export(project.rootAssembly) expect(blobUrl).not.toBe(null) it 'triggers an bomExport:error event when export fails',-> project.addFile name:"testFileName" errorCallback = jasmine.createSpy('-error event callback-') bomExporter.vent.on("bomExport:error", errorCallback) bomExporter.export(project) errorArgs = errorCallback.mostRecentCall.args expect(errorArgs).toBeDefined() expect(errorArgs[0].message).toBe(" ") it 'fail gracefully when export fails',-> project.addFile name:"testFileName" blobUrl = bomExporter.export(project.rootAssembly) expect(blobUrl).toBe("data:text/json;charset=utf-8,undefined")
88963
define (require)-> BomExporter = require "exporters/bomExporter/bomExporter" Project = require "core/projects/project" describe "BomExporter", -> project = null bomExporter = null beforeEach -> project = new Project name:"<NAME>Project" bomExporter = new BomExporter() it 'can export a project to bom (blobUrl)',-> project.addFile name:"testProject.coffee" content:""" class TestPart extends Part constructor:(options) -> super options @union(new Cylinder(h:300, r:20,$fn:3)) testPart = new TestPart() assembly.add(testPart) """ project.compile() blobUrl = bomExporter.export(project.rootAssembly) expect(blobUrl).not.toBe(null) it 'triggers an bomExport:error event when export fails',-> project.addFile name:"<NAME>FileName" errorCallback = jasmine.createSpy('-error event callback-') bomExporter.vent.on("bomExport:error", errorCallback) bomExporter.export(project) errorArgs = errorCallback.mostRecentCall.args expect(errorArgs).toBeDefined() expect(errorArgs[0].message).toBe(" ") it 'fail gracefully when export fails',-> project.addFile name:"<NAME>FileName" blobUrl = bomExporter.export(project.rootAssembly) expect(blobUrl).toBe("data:text/json;charset=utf-8,undefined")
true
define (require)-> BomExporter = require "exporters/bomExporter/bomExporter" Project = require "core/projects/project" describe "BomExporter", -> project = null bomExporter = null beforeEach -> project = new Project name:"PI:NAME:<NAME>END_PIProject" bomExporter = new BomExporter() it 'can export a project to bom (blobUrl)',-> project.addFile name:"testProject.coffee" content:""" class TestPart extends Part constructor:(options) -> super options @union(new Cylinder(h:300, r:20,$fn:3)) testPart = new TestPart() assembly.add(testPart) """ project.compile() blobUrl = bomExporter.export(project.rootAssembly) expect(blobUrl).not.toBe(null) it 'triggers an bomExport:error event when export fails',-> project.addFile name:"PI:NAME:<NAME>END_PIFileName" errorCallback = jasmine.createSpy('-error event callback-') bomExporter.vent.on("bomExport:error", errorCallback) bomExporter.export(project) errorArgs = errorCallback.mostRecentCall.args expect(errorArgs).toBeDefined() expect(errorArgs[0].message).toBe(" ") it 'fail gracefully when export fails',-> project.addFile name:"PI:NAME:<NAME>END_PIFileName" blobUrl = bomExporter.export(project.rootAssembly) expect(blobUrl).toBe("data:text/json;charset=utf-8,undefined")
[ { "context": "lt=\"First slide\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIH", "end": 649, "score": 0.7412447929382324, "start": 647, "tag": "KEY", "value": "N2" }, { "context": "First slide\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZH", "end": 653, "score": 0.592375636100769, "start": 651, "tag": "KEY", "value": "B4" }, { "context": " slide\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI", "end": 658, "score": 0.6818731427192688, "start": 656, "tag": "KEY", "value": "uc" }, { "context": "ide\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzc3NyI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojN2E3YTdhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+Rmlyc3Qgc2xpZGU8L3RleHQ+PC9zdmc+\">\n <div class=\"container\">\n ", "end": 1037, "score": 0.9303613305091858, "start": 659, "tag": "KEY", "value": "0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzc3NyI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojN2E3YTdhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+Rmlyc3Qgc2xpZGU8L3RleHQ+" }, { "context": "WxpbmU6Y2VudHJhbCI+Rmlyc3Qgc2xpZGU8L3RleHQ+PC9zdmc+\">\n <div class=\"container\">\n ", "end": 1044, "score": 0.6688042879104614, "start": 1044, "tag": "KEY", "value": "" }, { "context": "alt=\"Second slide\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzY2NiI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojNmE2YTZhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+U2Vjb25kIHNsaWRlPC90ZXh0Pjwvc3ZnPg==\">\n <div class=\"container\">\n ", "end": 2115, "score": 0.9709130525588989, "start": 1710, "tag": "KEY", "value": "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzY2NiI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojNmE2YTZhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+U2Vjb25kIHNsaWRlPC90ZXh0Pjwvc3ZnPg==\"" }, { "context": "\" src=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiI", "end": 2775, "score": 0.519017219543457, "start": 2773, "tag": "KEY", "value": "HR" }, { "context": ";base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aW", "end": 2804, "score": 0.595669686794281, "start": 2798, "tag": "KEY", "value": "AwMC9z" }, { "context": "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD", "end": 2808, "score": 0.5101791024208069, "start": 2806, "tag": "KEY", "value": "ci" }, { "context": "ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOT", "end": 2812, "score": 0.6377774477005005, "start": 2810, "tag": "KEY", "value": "dp" }, { "context": "4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzU1NSI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojNWE1YTVhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+VGhpcmQgc2xpZGU8L3RleHQ+PC9zdmc+\">\n <div class=\"container\">\n ", "end": 3156, "score": 0.9090583324432373, "start": 2813, "tag": "KEY", "value": "HRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzU1NSI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojNWE1YTVhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+VGhpcmQgc2xpZGU8L3RleHQ+PC9zdmc+" } ]
snippets/carousel.cson
OBomber/At-bs3-snippet
0
'.text.html': 'Carousel': 'prefix': 'bs3-carousel' 'body': """ <div id="${1:carousel-id}" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#${1:carousel-id}" data-slide-to="0" class=""></li> <li data-target="#${1:carousel-id}" data-slide-to="1" class=""></li> <li data-target="#${1:carousel-id}" data-slide-to="2" class="active"></li> </ol> <div class="carousel-inner"> <div class="item"> <img data-src="holder.js/900x500/auto/#777:#7a7a7a/text:First slide" alt="First slide" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzc3NyI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojN2E3YTdhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+Rmlyc3Qgc2xpZGU8L3RleHQ+PC9zdmc+"> <div class="container"> <div class="carousel-caption"> <h1>Example headline.</h1> <p>Note: If you're viewing this page via a <code>file://</code> URL, the "next" and "previous" Glyphicon buttons on the left and right might not load/display properly due to web browser security rules.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p> </div> </div> </div> <div class="item"> <img data-src="holder.js/900x500/auto/#666:#6a6a6a/text:Second slide" alt="Second slide" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzY2NiI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojNmE2YTZhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+U2Vjb25kIHNsaWRlPC90ZXh0Pjwvc3ZnPg=="> <div class="container"> <div class="carousel-caption"> <h1>Another example headline.</h1> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p> </div> </div> </div> <div class="item active"> <img data-src="holder.js/900x500/auto/#555:#5a5a5a/text:Third slide" alt="Third slide" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MDAiIGhlaWdodD0iNTAwIj48cmVjdCB3aWR0aD0iOTAwIiBoZWlnaHQ9IjUwMCIgZmlsbD0iIzU1NSI+PC9yZWN0Pjx0ZXh0IHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ1MCIgeT0iMjUwIiBzdHlsZT0iZmlsbDojNWE1YTVhO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjU2cHg7Zm9udC1mYW1pbHk6QXJpYWwsSGVsdmV0aWNhLHNhbnMtc2VyaWY7ZG9taW5hbnQtYmFzZWxpbmU6Y2VudHJhbCI+VGhpcmQgc2xpZGU8L3RleHQ+PC9zdmc+"> <div class="container"> <div class="carousel-caption"> <h1>One more for good measure.</h1> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Browse gallery</a></p> </div> </div> </div> </div> <a class="left carousel-control" href="#${1:carousel-id}" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a> <a class="right carousel-control" href="#${1:carousel-id}" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a> </div> """
7586
'.text.html': 'Carousel': 'prefix': 'bs3-carousel' 'body': """ <div id="${1:carousel-id}" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#${1:carousel-id}" data-slide-to="0" class=""></li> <li data-target="#${1:carousel-id}" data-slide-to="1" class=""></li> <li data-target="#${1:carousel-id}" data-slide-to="2" class="active"></li> </ol> <div class="carousel-inner"> <div class="item"> <img data-src="holder.js/900x500/auto/#777:#7a7a7a/text:First slide" alt="First slide" src="data:image/svg+xml;base64,PH<KEY>Zy<KEY>bWx<KEY>z<KEY>PC9zdmc<KEY>+"> <div class="container"> <div class="carousel-caption"> <h1>Example headline.</h1> <p>Note: If you're viewing this page via a <code>file://</code> URL, the "next" and "previous" Glyphicon buttons on the left and right might not load/display properly due to web browser security rules.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p> </div> </div> </div> <div class="item"> <img data-src="holder.js/900x500/auto/#666:#6a6a6a/text:Second slide" alt="Second slide" src="data:image/svg+xml;base64,<KEY>> <div class="container"> <div class="carousel-caption"> <h1>Another example headline.</h1> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p> </div> </div> </div> <div class="item active"> <img data-src="holder.js/900x500/auto/#555:#5a5a5a/text:Third slide" alt="Third slide" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0ia<KEY>0cDovL3d3dy53My5vcmcvMj<KEY>dm<KEY>IH<KEY>Z<KEY>"> <div class="container"> <div class="carousel-caption"> <h1>One more for good measure.</h1> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Browse gallery</a></p> </div> </div> </div> </div> <a class="left carousel-control" href="#${1:carousel-id}" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a> <a class="right carousel-control" href="#${1:carousel-id}" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a> </div> """
true
'.text.html': 'Carousel': 'prefix': 'bs3-carousel' 'body': """ <div id="${1:carousel-id}" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#${1:carousel-id}" data-slide-to="0" class=""></li> <li data-target="#${1:carousel-id}" data-slide-to="1" class=""></li> <li data-target="#${1:carousel-id}" data-slide-to="2" class="active"></li> </ol> <div class="carousel-inner"> <div class="item"> <img data-src="holder.js/900x500/auto/#777:#7a7a7a/text:First slide" alt="First slide" src="data:image/svg+xml;base64,PHPI:KEY:<KEY>END_PIZyPI:KEY:<KEY>END_PIbWxPI:KEY:<KEY>END_PIzPI:KEY:<KEY>END_PIPC9zdmcPI:KEY:<KEY>END_PI+"> <div class="container"> <div class="carousel-caption"> <h1>Example headline.</h1> <p>Note: If you're viewing this page via a <code>file://</code> URL, the "next" and "previous" Glyphicon buttons on the left and right might not load/display properly due to web browser security rules.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p> </div> </div> </div> <div class="item"> <img data-src="holder.js/900x500/auto/#666:#6a6a6a/text:Second slide" alt="Second slide" src="data:image/svg+xml;base64,PI:KEY:<KEY>END_PI> <div class="container"> <div class="carousel-caption"> <h1>Another example headline.</h1> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p> </div> </div> </div> <div class="item active"> <img data-src="holder.js/900x500/auto/#555:#5a5a5a/text:Third slide" alt="Third slide" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaPI:KEY:<KEY>END_PI0cDovL3d3dy53My5vcmcvMjPI:KEY:<KEY>END_PIdmPI:KEY:<KEY>END_PIIHPI:KEY:<KEY>END_PIZPI:KEY:<KEY>END_PI"> <div class="container"> <div class="carousel-caption"> <h1>One more for good measure.</h1> <p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p> <p><a class="btn btn-lg btn-primary" href="#" role="button">Browse gallery</a></p> </div> </div> </div> </div> <a class="left carousel-control" href="#${1:carousel-id}" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a> <a class="right carousel-control" href="#${1:carousel-id}" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a> </div> """
[ { "context": "older : 'What is your name?'\n value : 'Fatih Acet'\n name : 'name'\n\n input = new spar", "end": 294, "score": 0.9997430443763733, "start": 284, "tag": "NAME", "value": "Fatih Acet" } ]
src/tests/components/inputs/test_input.coffee
dashersw/spark
1
goog = goog or goog = require: -> goog.require 'spark.components.Input' goog.require 'spark.components.Field' describe 'spark.components.Input', -> input = null options = null beforeEach -> options = placeholder : 'What is your name?' value : 'Fatih Acet' name : 'name' input = new spark.components.Input options it 'should extends spark.components.Field', -> expect(input instanceof spark.components.Field).toBeTruthy() it 'should set placeholder if passed in options', -> expect(input.getElement().placeholder).toBe options.placeholder it 'should have default options', -> input = new spark.components.Input null, null expect(input.getOptions().type).toBe 'text' it 'should set and update placeholder', -> newPlaceholder = 'name please?' input.setPlaceholder newPlaceholder expect(input.getElement().placeholder).toBe newPlaceholder it 'should clear placeholder', -> input.clearPlaceholder() expect(input.getElement().placeholder).toBe '' it 'should has focus class when focussed', -> input.focus() expect(input.hasClass('focus')).toBeTruthy()
104985
goog = goog or goog = require: -> goog.require 'spark.components.Input' goog.require 'spark.components.Field' describe 'spark.components.Input', -> input = null options = null beforeEach -> options = placeholder : 'What is your name?' value : '<NAME>' name : 'name' input = new spark.components.Input options it 'should extends spark.components.Field', -> expect(input instanceof spark.components.Field).toBeTruthy() it 'should set placeholder if passed in options', -> expect(input.getElement().placeholder).toBe options.placeholder it 'should have default options', -> input = new spark.components.Input null, null expect(input.getOptions().type).toBe 'text' it 'should set and update placeholder', -> newPlaceholder = 'name please?' input.setPlaceholder newPlaceholder expect(input.getElement().placeholder).toBe newPlaceholder it 'should clear placeholder', -> input.clearPlaceholder() expect(input.getElement().placeholder).toBe '' it 'should has focus class when focussed', -> input.focus() expect(input.hasClass('focus')).toBeTruthy()
true
goog = goog or goog = require: -> goog.require 'spark.components.Input' goog.require 'spark.components.Field' describe 'spark.components.Input', -> input = null options = null beforeEach -> options = placeholder : 'What is your name?' value : 'PI:NAME:<NAME>END_PI' name : 'name' input = new spark.components.Input options it 'should extends spark.components.Field', -> expect(input instanceof spark.components.Field).toBeTruthy() it 'should set placeholder if passed in options', -> expect(input.getElement().placeholder).toBe options.placeholder it 'should have default options', -> input = new spark.components.Input null, null expect(input.getOptions().type).toBe 'text' it 'should set and update placeholder', -> newPlaceholder = 'name please?' input.setPlaceholder newPlaceholder expect(input.getElement().placeholder).toBe newPlaceholder it 'should clear placeholder', -> input.clearPlaceholder() expect(input.getElement().placeholder).toBe '' it 'should has focus class when focussed', -> input.focus() expect(input.hasClass('focus')).toBeTruthy()
[ { "context": "./lib/author').Author\n\nauthor = new Author name: \"Name\", email: \"Email\"\n\nassert.equal true, author.doc.", "end": 99, "score": 0.9862586855888367, "start": 95, "tag": "NAME", "value": "Name" }, { "context": ".doc.hash?, \"A hash exists\"\n\nauthor.set_password \"secret\"\n\nassert.equal true, author.authenticates('secre", "end": 248, "score": 0.9994333386421204, "start": 242, "tag": "PASSWORD", "value": "secret" } ]
test/author_test.coffee
nko/emergent-heroes
2
assert = require 'assert' Author = require('../lib/author').Author author = new Author name: "Name", email: "Email" assert.equal true, author.doc.salt?, "No salt" assert.equal false, author.doc.hash?, "A hash exists" author.set_password "secret" assert.equal true, author.authenticates('secret'), "Valid password doesn't match" assert.equal false, author.authenticates('foo'), "Invalid password matches"
83961
assert = require 'assert' Author = require('../lib/author').Author author = new Author name: "<NAME>", email: "Email" assert.equal true, author.doc.salt?, "No salt" assert.equal false, author.doc.hash?, "A hash exists" author.set_password "<PASSWORD>" assert.equal true, author.authenticates('secret'), "Valid password doesn't match" assert.equal false, author.authenticates('foo'), "Invalid password matches"
true
assert = require 'assert' Author = require('../lib/author').Author author = new Author name: "PI:NAME:<NAME>END_PI", email: "Email" assert.equal true, author.doc.salt?, "No salt" assert.equal false, author.doc.hash?, "A hash exists" author.set_password "PI:PASSWORD:<PASSWORD>END_PI" assert.equal true, author.authenticates('secret'), "Valid password doesn't match" assert.equal false, author.authenticates('foo'), "Invalid password matches"
[ { "context": "g'\n },{\n id: 'st-petersburg'\n name: 'St. Petersburg'\n extra_key: 'something'\n }]\n\n @aggreg", "end": 861, "score": 0.6726847290992737, "start": 847, "tag": "NAME", "value": "St. Petersburg" }, { "context": "ation 4' },\n { id: 'st-petersburg', name: 'St. Petersburg' }]\n @facet.countItems.should.eq", "end": 1582, "score": 0.5533505082130432, "start": 1580, "tag": "NAME", "value": "St" }, { "context": "nt: 0 }\n { id: 'st-petersburg', name: 'St. Petersburg', count: 0 }\n ]\n done()\n\n @agg", "end": 2557, "score": 0.5662195086479187, "start": 2547, "tag": "NAME", "value": "Petersburg" }, { "context": " { id: 'st-petersburg', name: 'St. Petersburg', count: 0 }\n ]\n done()", "end": 3844, "score": 0.514832615852356, "start": 3841, "tag": "NAME", "value": "ers" } ]
src/desktop/apps/galleries_institutions/components/filter_facet/test/partner_filter_facet.coffee
kanaabe/force
1
Backbone = require 'backbone' _ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' PartnerFilterFacet = rewire '../partner_filter_facet.coffee' describe 'PartnerFilterFacet', -> aggreationsUpdate = location: { total: 10, countItems: [ { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-5', name: 'Location 5', count: 2 }]} beforeEach -> @defaultItems = [{ id: 'location-1' name: 'Location 1' extra_key: 'something' },{ id: 'location-2' name: 'Location 2' extra_key: 'something' },{ id: 'location-3' name: 'Location 3' extra_key: 'something' },{ id: 'location-4' name: 'Location 4' extra_key: 'something' },{ id: 'st-petersburg' name: 'St. Petersburg' extra_key: 'something' }] @aggregations = new Backbone.Model @facet = new PartnerFilterFacet allItems: @defaultItems facetName: 'location' displayName: 'Locations' aggregations: @aggregations synonyms: [ ['st', 'saint'] ] describe '#initialize', -> it 'creates the item for all suggestions', -> @facet.allItemsSuggestion.name.should.equal 'All Locations' it 'stores the defaultItems', -> @facet.allItems.should.deepEqual [ { id: 'location-1', name: 'Location 1' }, { id: 'location-2', name: 'Location 2' }, { id: 'location-3', name: 'Location 3' }, { id: 'location-4', name: 'Location 4' }, { id: 'st-petersburg', name: 'St. Petersburg' }] @facet.countItems.should.equal @facet.allItems @aggregations.set 'location', 'some value' describe '#updateSuggestions', -> afterEach -> @aggregations.off 'change:location' it 'updates `allItemSuggestion` count', (done) -> @aggregations.on 'change:location', (aggregations, changed) => @facet.allItemsSuggestion.should.deepEqual { name: 'All Locations', count: 10 } done() @aggregations.set aggreationsUpdate it 'updates countItems, excluding results not in `allItems`', (done) -> @aggregations.on 'change:location', (aggregations, changed) => @facet.countItems.should.deepEqual [ { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } { id: 'location-4', name: 'Location 4', count: 0 } { id: 'st-petersburg', name: 'St. Petersburg', count: 0 } ] done() @aggregations.set aggreationsUpdate describe '#matcher', -> beforeEach -> @aggregations.set aggreationsUpdate describe 'empty query', -> describe 'with empty state item ids supplied', -> it 'returns `allItemsSuggestion` and limits results to those specified', (done) -> @facet.emptyStateItemIDs = ['location-2', 'location-3'] @facet.matcher '', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } ] done() describe 'without empty state item ids supplied', -> it 'returns `allItemsSuggestion` and all countItems', (done) -> @facet.matcher '', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } { id: 'location-4', name: 'Location 4', count: 0 } { id: 'st-petersburg', name: 'St. Petersburg', count: 0 } ] done() describe 'with query', -> it 'matches name substrings', (done) -> @facet.matcher '2', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-2', name: 'Location 2', count: 3 } ] done() it 'matches strings with non-word characters around whitespaces', (done) -> @facet.matcher 'St P', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'st-petersburg', name: 'St. Petersburg', count: 0 } ] done() describe '#isMatched', -> it 'does not match random substrings', -> @facet.isMatched('ste', 'St. Petersburg').should.not.be.ok() it 'matches strings case insensitively', -> @facet.isMatched('st. petersburg', 'St. Petersburg').should.be.ok() it 'matches strings with hyphens', -> @facet.isMatched('Winchester-o', 'Winchester-on-the-Severn').should.be.ok() @facet.isMatched('Winchester-on-', 'Winchester-on-the-Severn').should.be.ok() it 'allows missing special characters around white spaces', -> @facet.isMatched('st petersburg', 'St. Petersburg').should.be.ok() @facet.isMatched('st petersburg', 'St -Petersburg').should.be.ok() @facet.isMatched('st petersburg', 'St- -Petersburg').should.be.ok() it 'allows additinal whitespaces', -> @facet.isMatched(' st petersburg ', 'St. Petersburg').should.be.ok() it 'ignores diacritics', -> @facet.isMatched('zur', 'Zürich').should.be.ok() it 'replaces synonyms', -> @facet.isMatched('st ives', 'Saint Ives').should.be.ok() describe '#async_matcher', -> beforeEach -> # stub methods for FetchFilterPartner @fetch = sinon.stub() @fetch.returns then: sinon.stub() @fetchFilterPartnersStub = sinon.stub() @fetchFilterPartnersStub.returns { fetch: @fetch } PartnerFilterFacet.__set__ 'FetchFilterPartners', @fetchFilterPartnersStub @aggregations.set aggreationsUpdate describe 'empty query', -> it 'returns empty list', -> @facet.emptyStateItemIDs = ['location-2', 'location-3'] @facet.async_matcher '', (matches) => matches.should.eql [] @fetch.called.should.not.be.ok() describe 'with query', -> it 'does not call fetch', -> @facet.async_matcher 'test', (matches) => @fetch.calledOnce.should.be.ok()
157757
Backbone = require 'backbone' _ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' PartnerFilterFacet = rewire '../partner_filter_facet.coffee' describe 'PartnerFilterFacet', -> aggreationsUpdate = location: { total: 10, countItems: [ { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-5', name: 'Location 5', count: 2 }]} beforeEach -> @defaultItems = [{ id: 'location-1' name: 'Location 1' extra_key: 'something' },{ id: 'location-2' name: 'Location 2' extra_key: 'something' },{ id: 'location-3' name: 'Location 3' extra_key: 'something' },{ id: 'location-4' name: 'Location 4' extra_key: 'something' },{ id: 'st-petersburg' name: '<NAME>' extra_key: 'something' }] @aggregations = new Backbone.Model @facet = new PartnerFilterFacet allItems: @defaultItems facetName: 'location' displayName: 'Locations' aggregations: @aggregations synonyms: [ ['st', 'saint'] ] describe '#initialize', -> it 'creates the item for all suggestions', -> @facet.allItemsSuggestion.name.should.equal 'All Locations' it 'stores the defaultItems', -> @facet.allItems.should.deepEqual [ { id: 'location-1', name: 'Location 1' }, { id: 'location-2', name: 'Location 2' }, { id: 'location-3', name: 'Location 3' }, { id: 'location-4', name: 'Location 4' }, { id: 'st-petersburg', name: '<NAME>. Petersburg' }] @facet.countItems.should.equal @facet.allItems @aggregations.set 'location', 'some value' describe '#updateSuggestions', -> afterEach -> @aggregations.off 'change:location' it 'updates `allItemSuggestion` count', (done) -> @aggregations.on 'change:location', (aggregations, changed) => @facet.allItemsSuggestion.should.deepEqual { name: 'All Locations', count: 10 } done() @aggregations.set aggreationsUpdate it 'updates countItems, excluding results not in `allItems`', (done) -> @aggregations.on 'change:location', (aggregations, changed) => @facet.countItems.should.deepEqual [ { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } { id: 'location-4', name: 'Location 4', count: 0 } { id: 'st-petersburg', name: 'St. <NAME>', count: 0 } ] done() @aggregations.set aggreationsUpdate describe '#matcher', -> beforeEach -> @aggregations.set aggreationsUpdate describe 'empty query', -> describe 'with empty state item ids supplied', -> it 'returns `allItemsSuggestion` and limits results to those specified', (done) -> @facet.emptyStateItemIDs = ['location-2', 'location-3'] @facet.matcher '', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } ] done() describe 'without empty state item ids supplied', -> it 'returns `allItemsSuggestion` and all countItems', (done) -> @facet.matcher '', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } { id: 'location-4', name: 'Location 4', count: 0 } { id: 'st-petersburg', name: 'St. Pet<NAME>burg', count: 0 } ] done() describe 'with query', -> it 'matches name substrings', (done) -> @facet.matcher '2', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-2', name: 'Location 2', count: 3 } ] done() it 'matches strings with non-word characters around whitespaces', (done) -> @facet.matcher 'St P', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'st-petersburg', name: 'St. Petersburg', count: 0 } ] done() describe '#isMatched', -> it 'does not match random substrings', -> @facet.isMatched('ste', 'St. Petersburg').should.not.be.ok() it 'matches strings case insensitively', -> @facet.isMatched('st. petersburg', 'St. Petersburg').should.be.ok() it 'matches strings with hyphens', -> @facet.isMatched('Winchester-o', 'Winchester-on-the-Severn').should.be.ok() @facet.isMatched('Winchester-on-', 'Winchester-on-the-Severn').should.be.ok() it 'allows missing special characters around white spaces', -> @facet.isMatched('st petersburg', 'St. Petersburg').should.be.ok() @facet.isMatched('st petersburg', 'St -Petersburg').should.be.ok() @facet.isMatched('st petersburg', 'St- -Petersburg').should.be.ok() it 'allows additinal whitespaces', -> @facet.isMatched(' st petersburg ', 'St. Petersburg').should.be.ok() it 'ignores diacritics', -> @facet.isMatched('zur', 'Zürich').should.be.ok() it 'replaces synonyms', -> @facet.isMatched('st ives', 'Saint Ives').should.be.ok() describe '#async_matcher', -> beforeEach -> # stub methods for FetchFilterPartner @fetch = sinon.stub() @fetch.returns then: sinon.stub() @fetchFilterPartnersStub = sinon.stub() @fetchFilterPartnersStub.returns { fetch: @fetch } PartnerFilterFacet.__set__ 'FetchFilterPartners', @fetchFilterPartnersStub @aggregations.set aggreationsUpdate describe 'empty query', -> it 'returns empty list', -> @facet.emptyStateItemIDs = ['location-2', 'location-3'] @facet.async_matcher '', (matches) => matches.should.eql [] @fetch.called.should.not.be.ok() describe 'with query', -> it 'does not call fetch', -> @facet.async_matcher 'test', (matches) => @fetch.calledOnce.should.be.ok()
true
Backbone = require 'backbone' _ = require 'underscore' sinon = require 'sinon' rewire = require 'rewire' PartnerFilterFacet = rewire '../partner_filter_facet.coffee' describe 'PartnerFilterFacet', -> aggreationsUpdate = location: { total: 10, countItems: [ { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-5', name: 'Location 5', count: 2 }]} beforeEach -> @defaultItems = [{ id: 'location-1' name: 'Location 1' extra_key: 'something' },{ id: 'location-2' name: 'Location 2' extra_key: 'something' },{ id: 'location-3' name: 'Location 3' extra_key: 'something' },{ id: 'location-4' name: 'Location 4' extra_key: 'something' },{ id: 'st-petersburg' name: 'PI:NAME:<NAME>END_PI' extra_key: 'something' }] @aggregations = new Backbone.Model @facet = new PartnerFilterFacet allItems: @defaultItems facetName: 'location' displayName: 'Locations' aggregations: @aggregations synonyms: [ ['st', 'saint'] ] describe '#initialize', -> it 'creates the item for all suggestions', -> @facet.allItemsSuggestion.name.should.equal 'All Locations' it 'stores the defaultItems', -> @facet.allItems.should.deepEqual [ { id: 'location-1', name: 'Location 1' }, { id: 'location-2', name: 'Location 2' }, { id: 'location-3', name: 'Location 3' }, { id: 'location-4', name: 'Location 4' }, { id: 'st-petersburg', name: 'PI:NAME:<NAME>END_PI. Petersburg' }] @facet.countItems.should.equal @facet.allItems @aggregations.set 'location', 'some value' describe '#updateSuggestions', -> afterEach -> @aggregations.off 'change:location' it 'updates `allItemSuggestion` count', (done) -> @aggregations.on 'change:location', (aggregations, changed) => @facet.allItemsSuggestion.should.deepEqual { name: 'All Locations', count: 10 } done() @aggregations.set aggreationsUpdate it 'updates countItems, excluding results not in `allItems`', (done) -> @aggregations.on 'change:location', (aggregations, changed) => @facet.countItems.should.deepEqual [ { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } { id: 'location-4', name: 'Location 4', count: 0 } { id: 'st-petersburg', name: 'St. PI:NAME:<NAME>END_PI', count: 0 } ] done() @aggregations.set aggreationsUpdate describe '#matcher', -> beforeEach -> @aggregations.set aggreationsUpdate describe 'empty query', -> describe 'with empty state item ids supplied', -> it 'returns `allItemsSuggestion` and limits results to those specified', (done) -> @facet.emptyStateItemIDs = ['location-2', 'location-3'] @facet.matcher '', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } ] done() describe 'without empty state item ids supplied', -> it 'returns `allItemsSuggestion` and all countItems', (done) -> @facet.matcher '', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-1', name: 'Location 1', count: 5 } { id: 'location-2', name: 'Location 2', count: 3 } { id: 'location-3', name: 'Location 3', count: 0 } { id: 'location-4', name: 'Location 4', count: 0 } { id: 'st-petersburg', name: 'St. PetPI:NAME:<NAME>END_PIburg', count: 0 } ] done() describe 'with query', -> it 'matches name substrings', (done) -> @facet.matcher '2', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'location-2', name: 'Location 2', count: 3 } ] done() it 'matches strings with non-word characters around whitespaces', (done) -> @facet.matcher 'St P', (matches) => matches.should.deepEqual [ { name: 'All Locations', count: 10 } { id: 'st-petersburg', name: 'St. Petersburg', count: 0 } ] done() describe '#isMatched', -> it 'does not match random substrings', -> @facet.isMatched('ste', 'St. Petersburg').should.not.be.ok() it 'matches strings case insensitively', -> @facet.isMatched('st. petersburg', 'St. Petersburg').should.be.ok() it 'matches strings with hyphens', -> @facet.isMatched('Winchester-o', 'Winchester-on-the-Severn').should.be.ok() @facet.isMatched('Winchester-on-', 'Winchester-on-the-Severn').should.be.ok() it 'allows missing special characters around white spaces', -> @facet.isMatched('st petersburg', 'St. Petersburg').should.be.ok() @facet.isMatched('st petersburg', 'St -Petersburg').should.be.ok() @facet.isMatched('st petersburg', 'St- -Petersburg').should.be.ok() it 'allows additinal whitespaces', -> @facet.isMatched(' st petersburg ', 'St. Petersburg').should.be.ok() it 'ignores diacritics', -> @facet.isMatched('zur', 'Zürich').should.be.ok() it 'replaces synonyms', -> @facet.isMatched('st ives', 'Saint Ives').should.be.ok() describe '#async_matcher', -> beforeEach -> # stub methods for FetchFilterPartner @fetch = sinon.stub() @fetch.returns then: sinon.stub() @fetchFilterPartnersStub = sinon.stub() @fetchFilterPartnersStub.returns { fetch: @fetch } PartnerFilterFacet.__set__ 'FetchFilterPartners', @fetchFilterPartnersStub @aggregations.set aggreationsUpdate describe 'empty query', -> it 'returns empty list', -> @facet.emptyStateItemIDs = ['location-2', 'location-3'] @facet.async_matcher '', (matches) => matches.should.eql [] @fetch.called.should.not.be.ok() describe 'with query', -> it 'does not call fetch', -> @facet.async_matcher 'test', (matches) => @fetch.calledOnce.should.be.ok()
[ { "context": " ->\n service = new AWS.Service(accessKeyId: 'foo', secretAccessKey: 'bar')\n expect(service.co", "end": 1990, "score": 0.8329190611839294, "start": 1987, "tag": "KEY", "value": "foo" }, { "context": "AWS.Service(accessKeyId: 'foo', secretAccessKey: 'bar')\n expect(service.config.credentials.accessK", "end": 2014, "score": 0.9866950511932373, "start": 2011, "tag": "KEY", "value": "bar" } ]
test/service.spec.coffee
ashharrison90/ibm-cos-sdk-js
0
helpers = require('./helpers') AWS = helpers.AWS MockService = helpers.MockService metadata = require('../apis/metadata.json') describe 'AWS.Service', -> config = null; service = null retryableError = (error, result) -> expect(service.retryableError(error)).to.eql(result) beforeEach (done) -> config = new AWS.Config() service = new AWS.Service(config) done() describe 'apiVersions', -> it 'should set apiVersions property', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) expect(CustomService.apiVersions).to.eql(['1999-05-05', '2001-01-01']) describe 'constructor', -> it 'should use AWS.config copy if no config is provided', -> service = new AWS.Service() expect(service.config).not.to.equal(AWS.config) expect(service.config.sslEnabled).to.equal(true) it 'should merge custom options on top of global defaults if config provided', -> service = new AWS.Service(maxRetries: 5) expect(service.config.sslEnabled).to.equal(true) expect(service.config.maxRetries).to.equal(5) it 'merges service-specific configuration from global config', -> AWS.config.update(s3: endpoint: 'localhost') s3 = new AWS.S3 expect(s3.endpoint.host).to.equal('localhost') delete AWS.config.s3 it 'service-specific global config overrides global config', -> region = AWS.config.region AWS.config.update(region: 'us-west-2', s3: region: 'eu-west-1') s3 = new AWS.S3 expect(s3.config.region).to.equal('eu-west-1') AWS.config.region = region delete AWS.config.s3 it 'service-specific local config overrides service-specific global config', -> AWS.config.update(s3: region: 'us-west-2') s3 = new AWS.S3 region: 'eu-west-1' expect(s3.config.region).to.equal('eu-west-1') delete AWS.config.s3 it 'merges credential data into config', -> service = new AWS.Service(accessKeyId: 'foo', secretAccessKey: 'bar') expect(service.config.credentials.accessKeyId).to.equal('foo') expect(service.config.credentials.secretAccessKey).to.equal('bar') it 'should allow AWS.config to be object literal', -> cfg = AWS.config AWS.config = maxRetries: 20 service = new AWS.Service({}) expect(service.config.maxRetries).to.equal(20) expect(service.config.sslEnabled).to.equal(true) AWS.config = cfg it 'tries to construct service with latest API version', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService()).to.throw(errmsg) it 'tries to construct service with exact API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '1999-05-05')).to.throw(errmsg) it 'skips any API versions with a * and uses next (future) service', -> CustomService = AWS.Service.defineService('custom', ['1998-01-01', '1999-05-05*', '2001-01-01']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'skips multiple API versions with a * and uses next (future) service', -> CustomService = AWS.Service.defineService('custom', ['1998-01-01', '1999-05-05*', '1999-07-07*', '2001-01-01']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService(apiVersion: '1999-05-05')).to.throw(errmsg) it 'tries to construct service with fuzzy API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'uses global apiVersion value when constructing versioned services', -> AWS.config.apiVersion = '2002-03-04' CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersion = null it 'uses global apiVersions value when constructing versioned services', -> AWS.config.apiVersions = {custom: '2002-03-04'} CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersions = {} it 'uses service specific apiVersions before apiVersion', -> AWS.config.apiVersions = {custom: '2000-01-01'} AWS.config.apiVersion = '2002-03-04' CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersion = null AWS.config.apiVersions = {} it 'tries to construct service with fuzzy API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'fails if apiVersion matches nothing', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find custom API to satisfy version constraint `1998-01-01'" expect(-> new CustomService(apiVersion: '1998-01-01')).to.throw(errmsg) it 'allows construction of services from one-off apiConfig properties', -> service = new AWS.Service apiConfig: operations: operationName: input: {}, output: {} expect(typeof service.operationName).to.equal('function') expect(service.operationName() instanceof AWS.Request).to.equal(true) it 'interpolates endpoint when reading from configuration', -> service = new MockService(endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('https://mockservice.mock-region.domain.tld') service = new MockService(sslEnabled: false, endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('http://mockservice.mock-region.domain.tld') describe 'will work with', -> allServices = require('../clients/all') for own className, ctor of allServices serviceIdentifier = className.toLowerCase() # check for obsolete versions obsoleteVersions = metadata[serviceIdentifier].versions || [] for version in obsoleteVersions ((ctor, id, v) -> it id + ' version ' + v, -> expect(-> new ctor(apiVersion: v)).not.to.throw() )(ctor, serviceIdentifier, version) describe 'setEndpoint', -> FooService = null beforeEach (done) -> FooService = AWS.util.inherit AWS.Service, api: endpointPrefix: 'fooservice' done() it 'uses specified endpoint if provided', -> service = new FooService() service.setEndpoint('notfooservice.amazonaws.com') expect(service.endpoint.host).to.equal('notfooservice.amazonaws.com') describe 'makeRequest', -> it 'it treats params as an optinal parameter', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() service.makeRequest 'operationName', (err, data) -> expect(data).to.equal('FOOBAR') it 'yields data to the callback', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() req = service.makeRequest 'operation', (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') it 'yields service errors to the callback', -> helpers.mockHttpResponse(500, {}, ['ServiceError']) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err.code).to.equal('ServiceError') expect(err.message).to.equal(null) expect(err.statusCode).to.equal(500) expect(err.retryable).to.equal(true) expect(data).to.equal(null) it 'yields network errors to the callback', -> error = { code: 'NetworkingError' } helpers.mockHttpResponse(error) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.eql(error) expect(data).to.equal(null) it 'does not send the request if a callback function is omitted', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) httpClient = AWS.HttpClient.getInstance() helpers.spyOn(httpClient, 'handleRequest') new MockService().makeRequest('operation') expect(httpClient.handleRequest.calls.length).to.equal(0) it 'allows parameter validation to be disabled in config', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService(paramValidation: false) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') describe 'bound parameters', -> it 'accepts toplevel bound parameters on the service', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) req = service.makeRequest 'getObject' expect(req.params).to.eql(Bucket: 'bucket', Key: 'key') it 'ignores bound parameters not in input members', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) req = service.makeRequest 'listObjects' expect(req.params).to.eql(Bucket: 'bucket') it 'can override bound parameters', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) params = Bucket: 'notBucket' req = service.makeRequest('listObjects', params) expect(params).not.to.equal(req.params) expect(req.params).to.eql(Bucket: 'notBucket') describe 'global events', -> it 'adds AWS.events listeners to requests', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) event = helpers.createSpy() AWS.events.on('complete', event) new MockService().makeRequest('operation').send() expect(event.calls.length).not.to.equal(0) describe 'custom request decorators', -> s3 = new AWS.S3() innerVal = 0 outerVal = 0 innerFn = -> ++innerVal outerFn = -> ++outerVal beforeEach -> innerVal = 0 outerVal = 0 afterEach -> delete s3.customRequestHandler delete AWS.S3.prototype.customRequestHandler it 'will be called when set on a service object', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) s3.customizeRequests(innerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(1) expect(outerVal).to.equal(0) done() it 'will be called when set on a service object prototype', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) AWS.S3.prototype.customizeRequests(outerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(0) expect(outerVal).to.equal(1) done() it 'will be called when set on a service object or prototype', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) AWS.S3.prototype.customizeRequests(outerFn) s3.customizeRequests(innerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(1) expect(outerVal).to.equal(1) done() it 'gives access to the request object', (done) -> innerVal = false outerVal = false innerReqHandler = (req) -> innerVal = req instanceof AWS.Request outerReqHandler = (req) -> outerVal = req instanceof AWS.Request AWS.S3.prototype.customizeRequests(outerReqHandler) s3.customizeRequests(innerReqHandler) s3.makeRequest('listObjects') expect(innerVal).to.equal(true) expect(outerVal).to.equal(true) done() describe 'retryableError', -> it 'should retry on throttle error', -> retryableError({code: 'ProvisionedThroughputExceededException', statusCode:400}, true) retryableError({code: 'ThrottlingException', statusCode:400}, true) retryableError({code: 'Throttling', statusCode:400}, true) retryableError({code: 'RequestLimitExceeded', statusCode:400}, true) retryableError({code: 'RequestThrottled', statusCode:400}, true) it 'should retry on expired credentials error', -> retryableError({code: 'ExpiredTokenException', statusCode:400}, true) it 'should retry on 500 or above regardless of error', -> retryableError({code: 'Error', statusCode:500 }, true) retryableError({code: 'RandomError', statusCode:505 }, true) it 'should not retry when error is < 500 level status code', -> retryableError({code: 'Error', statusCode:200 }, false) retryableError({code: 'Error', statusCode:302 }, false) retryableError({code: 'Error', statusCode:404 }, false) describe 'numRetries', -> it 'should use config max retry value if defined', -> service.config.maxRetries = 30 expect(service.numRetries()).to.equal(30) it 'should use defaultRetries defined on object if undefined on config', -> service.defaultRetryCount = 13 service.config.maxRetries = undefined expect(service.numRetries()).to.equal(13) describe 'defineMethods', -> operations = null serviceConstructor = null beforeEach (done) -> serviceConstructor = () -> AWS.Service.call(this, new AWS.Config()) serviceConstructor.prototype = Object.create(AWS.Service.prototype) serviceConstructor.prototype.api = {} operations = {'foo': {}, 'bar': {}} serviceConstructor.prototype.api.operations = operations done() it 'should add operation methods', -> AWS.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(typeof serviceConstructor.prototype.bar).to.equal('function') it 'should not overwrite methods with generated methods', -> foo = -> serviceConstructor.prototype.foo = foo AWS.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(serviceConstructor.prototype.foo).to.eql(foo) expect(typeof serviceConstructor.prototype.bar).to.equal('function') describe 'should generate a method', -> it 'that makes an authenticated request by default', (done) -> AWS.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') customService.foo(); expect(customService.makeRequest.calls.length).to.equal(1) done() it 'that makes an unauthenticated request when operation authtype is none', (done) -> serviceConstructor.prototype.api.operations.foo.authtype = 'none' AWS.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') helpers.spyOn(customService, 'makeUnauthenticatedRequest') expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(0) customService.foo(); expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) customService.bar(); expect(customService.makeRequest.calls.length).to.equal(1) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) done() describe 'customizeRequests', -> it 'should accept nullable types', -> didError = false try service.customizeRequests(null) service.customizeRequests(undefined) service.customizeRequests() catch err didError = true expect(didError).to.equal(false) expect(!!service.customRequestHandler).to.equal(false) it 'should accept a function', -> didError = false try service.customizeRequests(->) catch err didError = true expect(didError).to.equal(false) expect(typeof service.customRequestHandler).to.equal('function') it 'should throw an error when non-nullable, non-function types are provided', -> didError = false try service.customizeRequests('test') catch err didError = true expect(didError).to.equal(true)
100329
helpers = require('./helpers') AWS = helpers.AWS MockService = helpers.MockService metadata = require('../apis/metadata.json') describe 'AWS.Service', -> config = null; service = null retryableError = (error, result) -> expect(service.retryableError(error)).to.eql(result) beforeEach (done) -> config = new AWS.Config() service = new AWS.Service(config) done() describe 'apiVersions', -> it 'should set apiVersions property', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) expect(CustomService.apiVersions).to.eql(['1999-05-05', '2001-01-01']) describe 'constructor', -> it 'should use AWS.config copy if no config is provided', -> service = new AWS.Service() expect(service.config).not.to.equal(AWS.config) expect(service.config.sslEnabled).to.equal(true) it 'should merge custom options on top of global defaults if config provided', -> service = new AWS.Service(maxRetries: 5) expect(service.config.sslEnabled).to.equal(true) expect(service.config.maxRetries).to.equal(5) it 'merges service-specific configuration from global config', -> AWS.config.update(s3: endpoint: 'localhost') s3 = new AWS.S3 expect(s3.endpoint.host).to.equal('localhost') delete AWS.config.s3 it 'service-specific global config overrides global config', -> region = AWS.config.region AWS.config.update(region: 'us-west-2', s3: region: 'eu-west-1') s3 = new AWS.S3 expect(s3.config.region).to.equal('eu-west-1') AWS.config.region = region delete AWS.config.s3 it 'service-specific local config overrides service-specific global config', -> AWS.config.update(s3: region: 'us-west-2') s3 = new AWS.S3 region: 'eu-west-1' expect(s3.config.region).to.equal('eu-west-1') delete AWS.config.s3 it 'merges credential data into config', -> service = new AWS.Service(accessKeyId: '<KEY>', secretAccessKey: '<KEY>') expect(service.config.credentials.accessKeyId).to.equal('foo') expect(service.config.credentials.secretAccessKey).to.equal('bar') it 'should allow AWS.config to be object literal', -> cfg = AWS.config AWS.config = maxRetries: 20 service = new AWS.Service({}) expect(service.config.maxRetries).to.equal(20) expect(service.config.sslEnabled).to.equal(true) AWS.config = cfg it 'tries to construct service with latest API version', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService()).to.throw(errmsg) it 'tries to construct service with exact API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '1999-05-05')).to.throw(errmsg) it 'skips any API versions with a * and uses next (future) service', -> CustomService = AWS.Service.defineService('custom', ['1998-01-01', '1999-05-05*', '2001-01-01']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'skips multiple API versions with a * and uses next (future) service', -> CustomService = AWS.Service.defineService('custom', ['1998-01-01', '1999-05-05*', '1999-07-07*', '2001-01-01']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService(apiVersion: '1999-05-05')).to.throw(errmsg) it 'tries to construct service with fuzzy API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'uses global apiVersion value when constructing versioned services', -> AWS.config.apiVersion = '2002-03-04' CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersion = null it 'uses global apiVersions value when constructing versioned services', -> AWS.config.apiVersions = {custom: '2002-03-04'} CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersions = {} it 'uses service specific apiVersions before apiVersion', -> AWS.config.apiVersions = {custom: '2000-01-01'} AWS.config.apiVersion = '2002-03-04' CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersion = null AWS.config.apiVersions = {} it 'tries to construct service with fuzzy API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'fails if apiVersion matches nothing', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find custom API to satisfy version constraint `1998-01-01'" expect(-> new CustomService(apiVersion: '1998-01-01')).to.throw(errmsg) it 'allows construction of services from one-off apiConfig properties', -> service = new AWS.Service apiConfig: operations: operationName: input: {}, output: {} expect(typeof service.operationName).to.equal('function') expect(service.operationName() instanceof AWS.Request).to.equal(true) it 'interpolates endpoint when reading from configuration', -> service = new MockService(endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('https://mockservice.mock-region.domain.tld') service = new MockService(sslEnabled: false, endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('http://mockservice.mock-region.domain.tld') describe 'will work with', -> allServices = require('../clients/all') for own className, ctor of allServices serviceIdentifier = className.toLowerCase() # check for obsolete versions obsoleteVersions = metadata[serviceIdentifier].versions || [] for version in obsoleteVersions ((ctor, id, v) -> it id + ' version ' + v, -> expect(-> new ctor(apiVersion: v)).not.to.throw() )(ctor, serviceIdentifier, version) describe 'setEndpoint', -> FooService = null beforeEach (done) -> FooService = AWS.util.inherit AWS.Service, api: endpointPrefix: 'fooservice' done() it 'uses specified endpoint if provided', -> service = new FooService() service.setEndpoint('notfooservice.amazonaws.com') expect(service.endpoint.host).to.equal('notfooservice.amazonaws.com') describe 'makeRequest', -> it 'it treats params as an optinal parameter', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() service.makeRequest 'operationName', (err, data) -> expect(data).to.equal('FOOBAR') it 'yields data to the callback', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() req = service.makeRequest 'operation', (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') it 'yields service errors to the callback', -> helpers.mockHttpResponse(500, {}, ['ServiceError']) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err.code).to.equal('ServiceError') expect(err.message).to.equal(null) expect(err.statusCode).to.equal(500) expect(err.retryable).to.equal(true) expect(data).to.equal(null) it 'yields network errors to the callback', -> error = { code: 'NetworkingError' } helpers.mockHttpResponse(error) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.eql(error) expect(data).to.equal(null) it 'does not send the request if a callback function is omitted', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) httpClient = AWS.HttpClient.getInstance() helpers.spyOn(httpClient, 'handleRequest') new MockService().makeRequest('operation') expect(httpClient.handleRequest.calls.length).to.equal(0) it 'allows parameter validation to be disabled in config', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService(paramValidation: false) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') describe 'bound parameters', -> it 'accepts toplevel bound parameters on the service', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) req = service.makeRequest 'getObject' expect(req.params).to.eql(Bucket: 'bucket', Key: 'key') it 'ignores bound parameters not in input members', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) req = service.makeRequest 'listObjects' expect(req.params).to.eql(Bucket: 'bucket') it 'can override bound parameters', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) params = Bucket: 'notBucket' req = service.makeRequest('listObjects', params) expect(params).not.to.equal(req.params) expect(req.params).to.eql(Bucket: 'notBucket') describe 'global events', -> it 'adds AWS.events listeners to requests', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) event = helpers.createSpy() AWS.events.on('complete', event) new MockService().makeRequest('operation').send() expect(event.calls.length).not.to.equal(0) describe 'custom request decorators', -> s3 = new AWS.S3() innerVal = 0 outerVal = 0 innerFn = -> ++innerVal outerFn = -> ++outerVal beforeEach -> innerVal = 0 outerVal = 0 afterEach -> delete s3.customRequestHandler delete AWS.S3.prototype.customRequestHandler it 'will be called when set on a service object', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) s3.customizeRequests(innerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(1) expect(outerVal).to.equal(0) done() it 'will be called when set on a service object prototype', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) AWS.S3.prototype.customizeRequests(outerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(0) expect(outerVal).to.equal(1) done() it 'will be called when set on a service object or prototype', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) AWS.S3.prototype.customizeRequests(outerFn) s3.customizeRequests(innerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(1) expect(outerVal).to.equal(1) done() it 'gives access to the request object', (done) -> innerVal = false outerVal = false innerReqHandler = (req) -> innerVal = req instanceof AWS.Request outerReqHandler = (req) -> outerVal = req instanceof AWS.Request AWS.S3.prototype.customizeRequests(outerReqHandler) s3.customizeRequests(innerReqHandler) s3.makeRequest('listObjects') expect(innerVal).to.equal(true) expect(outerVal).to.equal(true) done() describe 'retryableError', -> it 'should retry on throttle error', -> retryableError({code: 'ProvisionedThroughputExceededException', statusCode:400}, true) retryableError({code: 'ThrottlingException', statusCode:400}, true) retryableError({code: 'Throttling', statusCode:400}, true) retryableError({code: 'RequestLimitExceeded', statusCode:400}, true) retryableError({code: 'RequestThrottled', statusCode:400}, true) it 'should retry on expired credentials error', -> retryableError({code: 'ExpiredTokenException', statusCode:400}, true) it 'should retry on 500 or above regardless of error', -> retryableError({code: 'Error', statusCode:500 }, true) retryableError({code: 'RandomError', statusCode:505 }, true) it 'should not retry when error is < 500 level status code', -> retryableError({code: 'Error', statusCode:200 }, false) retryableError({code: 'Error', statusCode:302 }, false) retryableError({code: 'Error', statusCode:404 }, false) describe 'numRetries', -> it 'should use config max retry value if defined', -> service.config.maxRetries = 30 expect(service.numRetries()).to.equal(30) it 'should use defaultRetries defined on object if undefined on config', -> service.defaultRetryCount = 13 service.config.maxRetries = undefined expect(service.numRetries()).to.equal(13) describe 'defineMethods', -> operations = null serviceConstructor = null beforeEach (done) -> serviceConstructor = () -> AWS.Service.call(this, new AWS.Config()) serviceConstructor.prototype = Object.create(AWS.Service.prototype) serviceConstructor.prototype.api = {} operations = {'foo': {}, 'bar': {}} serviceConstructor.prototype.api.operations = operations done() it 'should add operation methods', -> AWS.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(typeof serviceConstructor.prototype.bar).to.equal('function') it 'should not overwrite methods with generated methods', -> foo = -> serviceConstructor.prototype.foo = foo AWS.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(serviceConstructor.prototype.foo).to.eql(foo) expect(typeof serviceConstructor.prototype.bar).to.equal('function') describe 'should generate a method', -> it 'that makes an authenticated request by default', (done) -> AWS.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') customService.foo(); expect(customService.makeRequest.calls.length).to.equal(1) done() it 'that makes an unauthenticated request when operation authtype is none', (done) -> serviceConstructor.prototype.api.operations.foo.authtype = 'none' AWS.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') helpers.spyOn(customService, 'makeUnauthenticatedRequest') expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(0) customService.foo(); expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) customService.bar(); expect(customService.makeRequest.calls.length).to.equal(1) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) done() describe 'customizeRequests', -> it 'should accept nullable types', -> didError = false try service.customizeRequests(null) service.customizeRequests(undefined) service.customizeRequests() catch err didError = true expect(didError).to.equal(false) expect(!!service.customRequestHandler).to.equal(false) it 'should accept a function', -> didError = false try service.customizeRequests(->) catch err didError = true expect(didError).to.equal(false) expect(typeof service.customRequestHandler).to.equal('function') it 'should throw an error when non-nullable, non-function types are provided', -> didError = false try service.customizeRequests('test') catch err didError = true expect(didError).to.equal(true)
true
helpers = require('./helpers') AWS = helpers.AWS MockService = helpers.MockService metadata = require('../apis/metadata.json') describe 'AWS.Service', -> config = null; service = null retryableError = (error, result) -> expect(service.retryableError(error)).to.eql(result) beforeEach (done) -> config = new AWS.Config() service = new AWS.Service(config) done() describe 'apiVersions', -> it 'should set apiVersions property', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) expect(CustomService.apiVersions).to.eql(['1999-05-05', '2001-01-01']) describe 'constructor', -> it 'should use AWS.config copy if no config is provided', -> service = new AWS.Service() expect(service.config).not.to.equal(AWS.config) expect(service.config.sslEnabled).to.equal(true) it 'should merge custom options on top of global defaults if config provided', -> service = new AWS.Service(maxRetries: 5) expect(service.config.sslEnabled).to.equal(true) expect(service.config.maxRetries).to.equal(5) it 'merges service-specific configuration from global config', -> AWS.config.update(s3: endpoint: 'localhost') s3 = new AWS.S3 expect(s3.endpoint.host).to.equal('localhost') delete AWS.config.s3 it 'service-specific global config overrides global config', -> region = AWS.config.region AWS.config.update(region: 'us-west-2', s3: region: 'eu-west-1') s3 = new AWS.S3 expect(s3.config.region).to.equal('eu-west-1') AWS.config.region = region delete AWS.config.s3 it 'service-specific local config overrides service-specific global config', -> AWS.config.update(s3: region: 'us-west-2') s3 = new AWS.S3 region: 'eu-west-1' expect(s3.config.region).to.equal('eu-west-1') delete AWS.config.s3 it 'merges credential data into config', -> service = new AWS.Service(accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI') expect(service.config.credentials.accessKeyId).to.equal('foo') expect(service.config.credentials.secretAccessKey).to.equal('bar') it 'should allow AWS.config to be object literal', -> cfg = AWS.config AWS.config = maxRetries: 20 service = new AWS.Service({}) expect(service.config.maxRetries).to.equal(20) expect(service.config.sslEnabled).to.equal(true) AWS.config = cfg it 'tries to construct service with latest API version', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService()).to.throw(errmsg) it 'tries to construct service with exact API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '1999-05-05')).to.throw(errmsg) it 'skips any API versions with a * and uses next (future) service', -> CustomService = AWS.Service.defineService('custom', ['1998-01-01', '1999-05-05*', '2001-01-01']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'skips multiple API versions with a * and uses next (future) service', -> CustomService = AWS.Service.defineService('custom', ['1998-01-01', '1999-05-05*', '1999-07-07*', '2001-01-01']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService(apiVersion: '1999-05-05')).to.throw(errmsg) it 'tries to construct service with fuzzy API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'uses global apiVersion value when constructing versioned services', -> AWS.config.apiVersion = '2002-03-04' CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersion = null it 'uses global apiVersions value when constructing versioned services', -> AWS.config.apiVersions = {custom: '2002-03-04'} CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-2001-01-01" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersions = {} it 'uses service specific apiVersions before apiVersion', -> AWS.config.apiVersions = {custom: '2000-01-01'} AWS.config.apiVersion = '2002-03-04' CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService).to.throw(errmsg) AWS.config.apiVersion = null AWS.config.apiVersions = {} it 'tries to construct service with fuzzy API version match', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find API configuration custom-1999-05-05" expect(-> new CustomService(apiVersion: '2000-01-01')).to.throw(errmsg) it 'fails if apiVersion matches nothing', -> CustomService = AWS.Service.defineService('custom', ['2001-01-01', '1999-05-05']) errmsg = "Could not find custom API to satisfy version constraint `1998-01-01'" expect(-> new CustomService(apiVersion: '1998-01-01')).to.throw(errmsg) it 'allows construction of services from one-off apiConfig properties', -> service = new AWS.Service apiConfig: operations: operationName: input: {}, output: {} expect(typeof service.operationName).to.equal('function') expect(service.operationName() instanceof AWS.Request).to.equal(true) it 'interpolates endpoint when reading from configuration', -> service = new MockService(endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('https://mockservice.mock-region.domain.tld') service = new MockService(sslEnabled: false, endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('http://mockservice.mock-region.domain.tld') describe 'will work with', -> allServices = require('../clients/all') for own className, ctor of allServices serviceIdentifier = className.toLowerCase() # check for obsolete versions obsoleteVersions = metadata[serviceIdentifier].versions || [] for version in obsoleteVersions ((ctor, id, v) -> it id + ' version ' + v, -> expect(-> new ctor(apiVersion: v)).not.to.throw() )(ctor, serviceIdentifier, version) describe 'setEndpoint', -> FooService = null beforeEach (done) -> FooService = AWS.util.inherit AWS.Service, api: endpointPrefix: 'fooservice' done() it 'uses specified endpoint if provided', -> service = new FooService() service.setEndpoint('notfooservice.amazonaws.com') expect(service.endpoint.host).to.equal('notfooservice.amazonaws.com') describe 'makeRequest', -> it 'it treats params as an optinal parameter', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() service.makeRequest 'operationName', (err, data) -> expect(data).to.equal('FOOBAR') it 'yields data to the callback', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() req = service.makeRequest 'operation', (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') it 'yields service errors to the callback', -> helpers.mockHttpResponse(500, {}, ['ServiceError']) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err.code).to.equal('ServiceError') expect(err.message).to.equal(null) expect(err.statusCode).to.equal(500) expect(err.retryable).to.equal(true) expect(data).to.equal(null) it 'yields network errors to the callback', -> error = { code: 'NetworkingError' } helpers.mockHttpResponse(error) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.eql(error) expect(data).to.equal(null) it 'does not send the request if a callback function is omitted', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) httpClient = AWS.HttpClient.getInstance() helpers.spyOn(httpClient, 'handleRequest') new MockService().makeRequest('operation') expect(httpClient.handleRequest.calls.length).to.equal(0) it 'allows parameter validation to be disabled in config', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService(paramValidation: false) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') describe 'bound parameters', -> it 'accepts toplevel bound parameters on the service', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) req = service.makeRequest 'getObject' expect(req.params).to.eql(Bucket: 'bucket', Key: 'key') it 'ignores bound parameters not in input members', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) req = service.makeRequest 'listObjects' expect(req.params).to.eql(Bucket: 'bucket') it 'can override bound parameters', -> service = new AWS.S3(params: {Bucket: 'bucket', Key: 'key'}) params = Bucket: 'notBucket' req = service.makeRequest('listObjects', params) expect(params).not.to.equal(req.params) expect(req.params).to.eql(Bucket: 'notBucket') describe 'global events', -> it 'adds AWS.events listeners to requests', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) event = helpers.createSpy() AWS.events.on('complete', event) new MockService().makeRequest('operation').send() expect(event.calls.length).not.to.equal(0) describe 'custom request decorators', -> s3 = new AWS.S3() innerVal = 0 outerVal = 0 innerFn = -> ++innerVal outerFn = -> ++outerVal beforeEach -> innerVal = 0 outerVal = 0 afterEach -> delete s3.customRequestHandler delete AWS.S3.prototype.customRequestHandler it 'will be called when set on a service object', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) s3.customizeRequests(innerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(1) expect(outerVal).to.equal(0) done() it 'will be called when set on a service object prototype', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) AWS.S3.prototype.customizeRequests(outerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(0) expect(outerVal).to.equal(1) done() it 'will be called when set on a service object or prototype', (done) -> expect(innerVal).to.equal(0) expect(outerVal).to.equal(0) AWS.S3.prototype.customizeRequests(outerFn) s3.customizeRequests(innerFn) s3.makeRequest('listObjects') expect(innerVal).to.equal(1) expect(outerVal).to.equal(1) done() it 'gives access to the request object', (done) -> innerVal = false outerVal = false innerReqHandler = (req) -> innerVal = req instanceof AWS.Request outerReqHandler = (req) -> outerVal = req instanceof AWS.Request AWS.S3.prototype.customizeRequests(outerReqHandler) s3.customizeRequests(innerReqHandler) s3.makeRequest('listObjects') expect(innerVal).to.equal(true) expect(outerVal).to.equal(true) done() describe 'retryableError', -> it 'should retry on throttle error', -> retryableError({code: 'ProvisionedThroughputExceededException', statusCode:400}, true) retryableError({code: 'ThrottlingException', statusCode:400}, true) retryableError({code: 'Throttling', statusCode:400}, true) retryableError({code: 'RequestLimitExceeded', statusCode:400}, true) retryableError({code: 'RequestThrottled', statusCode:400}, true) it 'should retry on expired credentials error', -> retryableError({code: 'ExpiredTokenException', statusCode:400}, true) it 'should retry on 500 or above regardless of error', -> retryableError({code: 'Error', statusCode:500 }, true) retryableError({code: 'RandomError', statusCode:505 }, true) it 'should not retry when error is < 500 level status code', -> retryableError({code: 'Error', statusCode:200 }, false) retryableError({code: 'Error', statusCode:302 }, false) retryableError({code: 'Error', statusCode:404 }, false) describe 'numRetries', -> it 'should use config max retry value if defined', -> service.config.maxRetries = 30 expect(service.numRetries()).to.equal(30) it 'should use defaultRetries defined on object if undefined on config', -> service.defaultRetryCount = 13 service.config.maxRetries = undefined expect(service.numRetries()).to.equal(13) describe 'defineMethods', -> operations = null serviceConstructor = null beforeEach (done) -> serviceConstructor = () -> AWS.Service.call(this, new AWS.Config()) serviceConstructor.prototype = Object.create(AWS.Service.prototype) serviceConstructor.prototype.api = {} operations = {'foo': {}, 'bar': {}} serviceConstructor.prototype.api.operations = operations done() it 'should add operation methods', -> AWS.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(typeof serviceConstructor.prototype.bar).to.equal('function') it 'should not overwrite methods with generated methods', -> foo = -> serviceConstructor.prototype.foo = foo AWS.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(serviceConstructor.prototype.foo).to.eql(foo) expect(typeof serviceConstructor.prototype.bar).to.equal('function') describe 'should generate a method', -> it 'that makes an authenticated request by default', (done) -> AWS.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') customService.foo(); expect(customService.makeRequest.calls.length).to.equal(1) done() it 'that makes an unauthenticated request when operation authtype is none', (done) -> serviceConstructor.prototype.api.operations.foo.authtype = 'none' AWS.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') helpers.spyOn(customService, 'makeUnauthenticatedRequest') expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(0) customService.foo(); expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) customService.bar(); expect(customService.makeRequest.calls.length).to.equal(1) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) done() describe 'customizeRequests', -> it 'should accept nullable types', -> didError = false try service.customizeRequests(null) service.customizeRequests(undefined) service.customizeRequests() catch err didError = true expect(didError).to.equal(false) expect(!!service.customRequestHandler).to.equal(false) it 'should accept a function', -> didError = false try service.customizeRequests(->) catch err didError = true expect(didError).to.equal(false) expect(typeof service.customRequestHandler).to.equal('function') it 'should throw an error when non-nullable, non-function types are provided', -> didError = false try service.customizeRequests('test') catch err didError = true expect(didError).to.equal(true)
[ { "context": "---------------------------------------\n# Authors: Maksym Melnyk <maxim@slatestudio.com>,\n# Alexander Kra", "end": 104, "score": 0.9998645782470703, "start": 91, "tag": "NAME", "value": "Maksym Melnyk" }, { "context": "-----------------------\n# Authors: Maksym Melnyk <maxim@slatestudio.com>,\n# Alexander Kravets <alex@slatestudio.", "end": 127, "score": 0.9999337196350098, "start": 106, "tag": "EMAIL", "value": "maxim@slatestudio.com" }, { "context": " Maksym Melnyk <maxim@slatestudio.com>,\n# Alexander Kravets <alex@slatestudio.com>,\n# Slate Studio (", "end": 158, "score": 0.999869704246521, "start": 141, "tag": "NAME", "value": "Alexander Kravets" }, { "context": "m@slatestudio.com>,\n# Alexander Kravets <alex@slatestudio.com>,\n# Slate Studio (http://www.slatestudio", "end": 180, "score": 0.9999331831932068, "start": 160, "tag": "EMAIL", "value": "alex@slatestudio.com" } ]
app/assets/javascripts/insights.coffee
slate-studio/insights
0
# ----------------------------------------------------------------------------- # Authors: Maksym Melnyk <maxim@slatestudio.com>, # Alexander Kravets <alex@slatestudio.com>, # Slate Studio (http://www.slatestudio.com) # ----------------------------------------------------------------------------- # INSIGHTS DASHBOARD # ----------------------------------------------------------------------------- # Dependencies: #= require_tree ./inputs # ----------------------------------------------------------------------------- class @InsightsDashboard constructor: (config) -> @title = config.title @subtitle = config.subtitle @disableSave = true @objectStore = new ObjectStore({ data: {} }) @formSchema = {} for k, v of config.charts @_add_chart(k, v) ## PRIVATE ================================================================== _add_chart: (name, config) -> @formSchema["#{name}_panel"] = type: "group" groupClass: "group-panel" title: config.title || name.titleize() inputs: {} @formSchema["#{name}_panel"].inputs[name] = type: config.type || "chart-line" query: config.query chartOptions: config.chartOptions
223719
# ----------------------------------------------------------------------------- # Authors: <NAME> <<EMAIL>>, # <NAME> <<EMAIL>>, # Slate Studio (http://www.slatestudio.com) # ----------------------------------------------------------------------------- # INSIGHTS DASHBOARD # ----------------------------------------------------------------------------- # Dependencies: #= require_tree ./inputs # ----------------------------------------------------------------------------- class @InsightsDashboard constructor: (config) -> @title = config.title @subtitle = config.subtitle @disableSave = true @objectStore = new ObjectStore({ data: {} }) @formSchema = {} for k, v of config.charts @_add_chart(k, v) ## PRIVATE ================================================================== _add_chart: (name, config) -> @formSchema["#{name}_panel"] = type: "group" groupClass: "group-panel" title: config.title || name.titleize() inputs: {} @formSchema["#{name}_panel"].inputs[name] = type: config.type || "chart-line" query: config.query chartOptions: config.chartOptions
true
# ----------------------------------------------------------------------------- # Authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, # Slate Studio (http://www.slatestudio.com) # ----------------------------------------------------------------------------- # INSIGHTS DASHBOARD # ----------------------------------------------------------------------------- # Dependencies: #= require_tree ./inputs # ----------------------------------------------------------------------------- class @InsightsDashboard constructor: (config) -> @title = config.title @subtitle = config.subtitle @disableSave = true @objectStore = new ObjectStore({ data: {} }) @formSchema = {} for k, v of config.charts @_add_chart(k, v) ## PRIVATE ================================================================== _add_chart: (name, config) -> @formSchema["#{name}_panel"] = type: "group" groupClass: "group-panel" title: config.title || name.titleize() inputs: {} @formSchema["#{name}_panel"].inputs[name] = type: config.type || "chart-line" query: config.query chartOptions: config.chartOptions
[ { "context": "# Contributed by Jason Huggins\n\nhttp = require 'http'\n\nserver = http.createServe", "end": 30, "score": 0.9998869895935059, "start": 17, "tag": "NAME", "value": "Jason Huggins" } ]
components/coffee-script/examples/web_server.coffee
tubbo/sumatra
33
# Contributed by Jason Huggins http = require 'http' server = http.createServer (req, res) -> res.writeHeader 200, 'Content-Type': 'text/plain' res.write 'Hello, World!' res.end() server.listen 3000 console.log "Server running at http://localhost:3000/"
111843
# Contributed by <NAME> http = require 'http' server = http.createServer (req, res) -> res.writeHeader 200, 'Content-Type': 'text/plain' res.write 'Hello, World!' res.end() server.listen 3000 console.log "Server running at http://localhost:3000/"
true
# Contributed by PI:NAME:<NAME>END_PI http = require 'http' server = http.createServer (req, res) -> res.writeHeader 200, 'Content-Type': 'text/plain' res.write 'Hello, World!' res.end() server.listen 3000 console.log "Server running at http://localhost:3000/"
[ { "context": " {\n type: \"text\"\n name: \"username\"\n key: \"username\"\n id: \"usernam", "end": 289, "score": 0.9995571374893188, "start": 281, "tag": "USERNAME", "value": "username" }, { "context": "\"text\"\n name: \"username\"\n key: \"username\"\n id: \"username\"\n floatingLabel", "end": 315, "score": 0.9983705878257751, "start": 307, "tag": "USERNAME", "value": "username" }, { "context": "sername\"\n key: \"username\"\n id: \"username\"\n floatingLabelText: \"Username\"\n ", "end": 340, "score": 0.9995473027229309, "start": 332, "tag": "USERNAME", "value": "username" }, { "context": " id: \"username\"\n floatingLabelText: \"Username\"\n autofocus: \"\"\n }, {\n t", "end": 380, "score": 0.999186098575592, "start": 372, "tag": "USERNAME", "value": "Username" }, { "context": "sword\"\n name: \"password\"\n key: \"password\"\n id: \"password\"\n floatingLabel", "end": 497, "score": 0.9149821996688843, "start": 489, "tag": "PASSWORD", "value": "password" } ]
src/components/user/login.coffee
dwetterau/life
2
React = require 'react' {FormPage} = require './form_page' Login = React.createClass displayName: 'Login' render: () -> React.createElement FormPage, pageHeader: 'Sign in' action: '/user/login' inputs: [ { type: "text" name: "username" key: "username" id: "username" floatingLabelText: "Username" autofocus: "" }, { type: "password" name: "password" key: "password" id: "password" floatingLabelText: "Password" }, { type: "hidden" name: "redirect" key: "redirect" id: "redirect" value: @props.redirect } ] submitLabel: 'Login' module.exports = {Login}
160549
React = require 'react' {FormPage} = require './form_page' Login = React.createClass displayName: 'Login' render: () -> React.createElement FormPage, pageHeader: 'Sign in' action: '/user/login' inputs: [ { type: "text" name: "username" key: "username" id: "username" floatingLabelText: "Username" autofocus: "" }, { type: "password" name: "password" key: "<PASSWORD>" id: "password" floatingLabelText: "Password" }, { type: "hidden" name: "redirect" key: "redirect" id: "redirect" value: @props.redirect } ] submitLabel: 'Login' module.exports = {Login}
true
React = require 'react' {FormPage} = require './form_page' Login = React.createClass displayName: 'Login' render: () -> React.createElement FormPage, pageHeader: 'Sign in' action: '/user/login' inputs: [ { type: "text" name: "username" key: "username" id: "username" floatingLabelText: "Username" autofocus: "" }, { type: "password" name: "password" key: "PI:PASSWORD:<PASSWORD>END_PI" id: "password" floatingLabelText: "Password" }, { type: "hidden" name: "redirect" key: "redirect" id: "redirect" value: @props.redirect } ] submitLabel: 'Login' module.exports = {Login}
[ { "context": "return model =\n name: 'Bed'\n size: 1\n bodies:\n headrest:\n section_", "end": 27, "score": 0.9755876660346985, "start": 24, "tag": "NAME", "value": "Bed" } ]
utilities/starblast_bed_wars/starblast_bed_final.coffee
JavRedstone/Starblast.io-Modding
5
return model = name: 'Bed' size: 1 bodies: headrest: section_segments: [45, 135, 225, 315] offset: x: 0 y: 0 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 50, 50] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 20, 20, 0] texture: [0] body: section_segments: [45, 135, 225, 315] offset: x: 0 y: 50 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 150, 150] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 20, 20, 0] texture: [63] frame: section_segments: [45, 135, 225, 315] offset: x: 0 y: 0 z: -21 position: x: [0, 0, 0, 0] y: [0, 0, 200, 200] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 10, 10, 0] texture: [6] legsfront: section_segments: [45, 135, 225, 315] offset: x: 63.64 y: 0 z: -42 position: x: [0, 0, 0, 0] y: [0, 0, 15, 15] z: [0, 0, 0, 0] width: [0, 10, 10, 0] height: [0, 20, 20, 0] texture: [6] legsback: section_segments: [45, 135, 225, 315] offset: x: 63.64 y: 185 z: -42 position: x: [0, 0, 0, 0] y: [0, 0, 15, 15] z: [0, 0, 0, 0] width: [0, 10, 10, 0] height: [0, 20, 20, 0] texture: [6]
89274
return model = name: '<NAME>' size: 1 bodies: headrest: section_segments: [45, 135, 225, 315] offset: x: 0 y: 0 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 50, 50] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 20, 20, 0] texture: [0] body: section_segments: [45, 135, 225, 315] offset: x: 0 y: 50 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 150, 150] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 20, 20, 0] texture: [63] frame: section_segments: [45, 135, 225, 315] offset: x: 0 y: 0 z: -21 position: x: [0, 0, 0, 0] y: [0, 0, 200, 200] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 10, 10, 0] texture: [6] legsfront: section_segments: [45, 135, 225, 315] offset: x: 63.64 y: 0 z: -42 position: x: [0, 0, 0, 0] y: [0, 0, 15, 15] z: [0, 0, 0, 0] width: [0, 10, 10, 0] height: [0, 20, 20, 0] texture: [6] legsback: section_segments: [45, 135, 225, 315] offset: x: 63.64 y: 185 z: -42 position: x: [0, 0, 0, 0] y: [0, 0, 15, 15] z: [0, 0, 0, 0] width: [0, 10, 10, 0] height: [0, 20, 20, 0] texture: [6]
true
return model = name: 'PI:NAME:<NAME>END_PI' size: 1 bodies: headrest: section_segments: [45, 135, 225, 315] offset: x: 0 y: 0 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 50, 50] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 20, 20, 0] texture: [0] body: section_segments: [45, 135, 225, 315] offset: x: 0 y: 50 z: 0 position: x: [0, 0, 0, 0] y: [0, 0, 150, 150] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 20, 20, 0] texture: [63] frame: section_segments: [45, 135, 225, 315] offset: x: 0 y: 0 z: -21 position: x: [0, 0, 0, 0] y: [0, 0, 200, 200] z: [0, 0, 0, 0] width: [0, 100, 100, 0] height: [0, 10, 10, 0] texture: [6] legsfront: section_segments: [45, 135, 225, 315] offset: x: 63.64 y: 0 z: -42 position: x: [0, 0, 0, 0] y: [0, 0, 15, 15] z: [0, 0, 0, 0] width: [0, 10, 10, 0] height: [0, 20, 20, 0] texture: [6] legsback: section_segments: [45, 135, 225, 315] offset: x: 63.64 y: 185 z: -42 position: x: [0, 0, 0, 0] y: [0, 0, 15, 15] z: [0, 0, 0, 0] width: [0, 10, 10, 0] height: [0, 20, 20, 0] texture: [6]
[ { "context": "# Zhancheng Qian, February 2018\n\n# Modified from Felix Hageloh 's ", "end": 16, "score": 0.9998870491981506, "start": 2, "tag": "NAME", "value": "Zhancheng Qian" }, { "context": "# Zhancheng Qian, February 2018\n\n# Modified from Felix Hageloh 's Pretty Weather widget\n# Made possible with Dar", "end": 62, "score": 0.9999039769172668, "start": 49, "tag": "NAME", "value": "Felix Hageloh" } ]
weathersummary.widget.coffee
zhanchengqian/weathersummary-widget
0
# Zhancheng Qian, February 2018 # Modified from Felix Hageloh 's Pretty Weather widget # Made possible with DarkSky API (darksky.net/dev) apiKey: '' # put your forcast.io api key inside the quotes here refreshFrequency: 600000 style: """ bottom: 45% left: 10% margin: 0 0 0 -100px font-family: Berlin, Helvetica Neue color: #fff @font-face font-family Weather .temp text-align: center font-size: 30px font-weight: 250 color: rgba(#fff, 0.9) margin-top: 0px max-width: 1000px line-height: 2 .summary text-align: center font-size: 15px font-weight: 400 color: rgba(#fff, 0.9) margin-top: -10px max-width: 1000px line-height: 2 """ command: "echo {}" render: (o) -> """ <div class='temp'></div> <div class='summary'></div> """ afterRender: (domEl) -> geolocation.getCurrentPosition (e) => coords = e.position.coords [lat, lon] = [coords.latitude, coords.longitude] @command = @makeCommand(@apiKey, "#{lat},#{lon}") @refresh() makeCommand: (apiKey, location) -> exclude = "minutely,hourly,alerts,flags" "curl -sS 'https://api.forecast.io/forecast/#{apiKey}/#{location}?units=auto&exclude=#{exclude}'" update: (output, domEl) -> data = JSON.parse(output) today = data.daily?.data[0] return unless today? date = @getDate today.time $(domEl).find('.temp').prop 'textContent', Math.round((today.temperatureMax-30)/2)+" degrees right now" #'°' $(domEl).find('.summary').text @shorten today.summary getDate: (utcTime) -> date = new Date(0) date.setUTCSeconds(utcTime) date shorten: (s) -> if (s.length > 40) s = s.substr(0,39) s + '...' else s
117547
# <NAME>, February 2018 # Modified from <NAME> 's Pretty Weather widget # Made possible with DarkSky API (darksky.net/dev) apiKey: '' # put your forcast.io api key inside the quotes here refreshFrequency: 600000 style: """ bottom: 45% left: 10% margin: 0 0 0 -100px font-family: Berlin, Helvetica Neue color: #fff @font-face font-family Weather .temp text-align: center font-size: 30px font-weight: 250 color: rgba(#fff, 0.9) margin-top: 0px max-width: 1000px line-height: 2 .summary text-align: center font-size: 15px font-weight: 400 color: rgba(#fff, 0.9) margin-top: -10px max-width: 1000px line-height: 2 """ command: "echo {}" render: (o) -> """ <div class='temp'></div> <div class='summary'></div> """ afterRender: (domEl) -> geolocation.getCurrentPosition (e) => coords = e.position.coords [lat, lon] = [coords.latitude, coords.longitude] @command = @makeCommand(@apiKey, "#{lat},#{lon}") @refresh() makeCommand: (apiKey, location) -> exclude = "minutely,hourly,alerts,flags" "curl -sS 'https://api.forecast.io/forecast/#{apiKey}/#{location}?units=auto&exclude=#{exclude}'" update: (output, domEl) -> data = JSON.parse(output) today = data.daily?.data[0] return unless today? date = @getDate today.time $(domEl).find('.temp').prop 'textContent', Math.round((today.temperatureMax-30)/2)+" degrees right now" #'°' $(domEl).find('.summary').text @shorten today.summary getDate: (utcTime) -> date = new Date(0) date.setUTCSeconds(utcTime) date shorten: (s) -> if (s.length > 40) s = s.substr(0,39) s + '...' else s
true
# PI:NAME:<NAME>END_PI, February 2018 # Modified from PI:NAME:<NAME>END_PI 's Pretty Weather widget # Made possible with DarkSky API (darksky.net/dev) apiKey: '' # put your forcast.io api key inside the quotes here refreshFrequency: 600000 style: """ bottom: 45% left: 10% margin: 0 0 0 -100px font-family: Berlin, Helvetica Neue color: #fff @font-face font-family Weather .temp text-align: center font-size: 30px font-weight: 250 color: rgba(#fff, 0.9) margin-top: 0px max-width: 1000px line-height: 2 .summary text-align: center font-size: 15px font-weight: 400 color: rgba(#fff, 0.9) margin-top: -10px max-width: 1000px line-height: 2 """ command: "echo {}" render: (o) -> """ <div class='temp'></div> <div class='summary'></div> """ afterRender: (domEl) -> geolocation.getCurrentPosition (e) => coords = e.position.coords [lat, lon] = [coords.latitude, coords.longitude] @command = @makeCommand(@apiKey, "#{lat},#{lon}") @refresh() makeCommand: (apiKey, location) -> exclude = "minutely,hourly,alerts,flags" "curl -sS 'https://api.forecast.io/forecast/#{apiKey}/#{location}?units=auto&exclude=#{exclude}'" update: (output, domEl) -> data = JSON.parse(output) today = data.daily?.data[0] return unless today? date = @getDate today.time $(domEl).find('.temp').prop 'textContent', Math.round((today.temperatureMax-30)/2)+" degrees right now" #'°' $(domEl).find('.summary').text @shorten today.summary getDate: (utcTime) -> date = new Date(0) date.setUTCSeconds(utcTime) date shorten: (s) -> if (s.length > 40) s = s.substr(0,39) s + '...' else s
[ { "context": "###!\n# JsPlus v0.0.1 (https://github.com/cuidingfeng/jsplus/)\n# Copyright 2015 cuidingfeng, Inc.\n# Lic", "end": 52, "score": 0.999638557434082, "start": 41, "tag": "USERNAME", "value": "cuidingfeng" }, { "context": "ng, Inc.\n# Licensed under MIT (https://github.com/cuidingfeng/jsplus/blob/master/LICENSE)\n# Email: admin@baiket", "end": 149, "score": 0.9996210932731628, "start": 138, "tag": "USERNAME", "value": "cuidingfeng" }, { "context": "m/cuidingfeng/jsplus/blob/master/LICENSE)\n# Email: admin@baiketupu.com\n# Generated by CoffeeScript 1.7.1\n###\n\n'use stric", "end": 206, "score": 0.9999251961708069, "start": 187, "tag": "EMAIL", "value": "admin@baiketupu.com" } ]
main.coffee
cuidingfeng/jsplus
15
###! # JsPlus v0.0.1 (https://github.com/cuidingfeng/jsplus/) # Copyright 2015 cuidingfeng, Inc. # Licensed under MIT (https://github.com/cuidingfeng/jsplus/blob/master/LICENSE) # Email: admin@baiketupu.com # Generated by CoffeeScript 1.7.1 ### 'use strict' ### # JsPlus的定位是一个JavaScript库,目标是提供一系列简化JavaScript操作的基础方法,让开发专注于业务逻辑。 ### #静态对象主体 P = -> #是否开启log P.debug = true #校验字符类型 regs = #数值型 number: /// ^ [+-]? [1-9][0-9]* (\.[0-9]+)? ([eE][+-][1-9][0-9]*)? $ | ^ [+-]? 0? \.[0-9]+ ([eE][+-][1-9][0-9]*)? $ | ^ 0 $ /// #小写字母 lowercase: /^[a-z]$/ #大写字母 uppercase: /^[A-Z]$/ #中文数字 numberCn: /^[零一二三四五六七八九十百千万亿]+$/ #各种字符类型与数字的转换方法 # getnum: 当前类型转为数字 # getstr: 数字转为当前类型 conversion = #数字 number: getnum: (s) -> Number s getstr: (n) -> n #小写字母 lowercase: #小写字母转数字 getnum: (s) -> s.charCodeAt(0) - 97 #数字转小写字母 getstr: (n) -> String.fromCharCode(n + 97) #大写字母 uppercase: getnum: (s) -> s.charCodeAt(0) - 65 getstr: (n) -> String.fromCharCode(n + 65) #中文数字 numberCn: getnum: (s) -> P.cn2num s getstr: (n) -> P.num2cn n #开启debug时,在控制台打印错误信息 log = (str) -> (if window.console? and console.log? then console.log else alert) "JS-Plus:" + str if P.debug #生成包装函数,fn可以为function或格式化字符串 getFnFormat = (fn) -> #如果传入的fn是函数,则原样返回 if typeof fn is 'function' return fn #如果fn不是函数,则返回一个包装函数 else return (index, $1) -> #替换字符串中的$1和$index # $1为数组的当前项值,$index为当前项在数组中的索引 return fn.replace('$1', $1).replace('$index', index) #生成标准化的数组生成规则参数 #返回值格式:[起始值, 递增值, 结束值, 字符类型] getParam = (str = '') -> #分割取参数 ss = str.split ":" #如果参数少于两个,则格式错误,返回未知类型 if ss.length<2 log '数列格式错误,请至少包括一个":",否则原样返回' return [str, 0, null, -1] else #如果有两个参数,则第一个为起始值,第二个为结束值 if ss.length is 2 ss[2] = ss[1] ss[1] = null #如果参数多于两个,则第二个参数为递增值,并且转为数字,第三个参数为结束值 else ss[1] = parseFloat ss[1] #如果递增值不是数字,则将递增值设为0 if not ss[1] log '数列递增字符格式不正确,必须为数字' ss[1] = 0 tp1 = -1 #获取起始值的字符类型 tp1 = getType ss[0] #如果起始值和结束值的字符类型不一致,则把递增值设为0 if tp1 isnt getType ss[2] log '数列起始值和结束值类型不一致' ss[1] = 0 tp1 = -1 #如果字符类型为-1,则为不支持的类型,把递增值设为0 if tp1 is -1 log '数列格式暂时不支持' ss[1] = 0 else #获取将当前字符类型转换为数字的处理函数 fn = conversion[['number', 'lowercase', 'uppercase', 'numberCn'][tp1]].getnum ss[0] = fn ss[0] ss[2] = fn ss[2] #如果没有递增值,当起始值小于结束值时,将递增值设置为 1,否则设置为 -1 if ss[1] is null ss[1] = if ss[0]<ss[2] then 1 else -1 #如果有递增值,但是从起始值通过递增值无法到达结束值时,将递增值设置为 0 else if ss[1] isnt 0 and (if ss[0]<ss[2] then 1 else -1) * ss[1] < 0 log '数列递增数字正负符号不正确,无法从起始值递增到结束值' ss[1] = 0 return [ss[0], ss[1], ss[2], tp1] #获取字符类型 getType = (s) -> return 0 if regs.number.test s #数字 return 1 if regs.lowercase.test s #小写字母 return 2 if regs.uppercase.test s #大写字母 return 3 if regs.numberCn.test s #汉字数字 return -1 #无匹配类型 #获取数字化数组 # @param {param} [起始值, 递增值, 结束值, 字符类型] getNums = (param) -> reArr = [] #如果递增值为 0,或者字符类型不支持,则原样返回存在的起始值和结束值 if param[1] is 0 or param[3] is -1 reArr.push param[0] if param[0]? reArr.push param[2] if param[2]? else i = param[0] #从起始值到结束值,按递增值依次将数字添加到数组 #第一个值为起始值,最后一个值为在递增方向不超过结束值的最近一个值 #循环条件:当前值小于等于结束值,并且递增值为正数;或者当前值大于等于结束值,并且递增值为负数 while i<=param[2] && param[1]>0 || i>=param[2] && param[1]<0 reArr.push i i+=param[1] return reArr #获取原字符化数组 getArr = (nums, tp) -> #如果字符类型可支持 if tp isnt -1 #获取将数字转换为当前字符类型的处理函数 fn = conversion[['number', 'lowercase', 'uppercase', 'numberCn'][tp]].getstr #循环转换 nums[i] = fn num for num, i in nums return nums #用包装函数格式化数组 formatArr = (arr, cb) -> arr[i] = cb(i, li) for li, i in arr return arr ### #======================================== # 静态对象对外提供的方法 # arr: 按指定规则生成一个一维数组 # cn2num: 把中文数字转换为数值 # num2cn: 把自然数转换为中文数字 # assign: 按条件返回值 # inArr: 按条件查找数组 # forArr: 按条件处理数组的每一项 #======================================== ### #按指定规则生成一个一维数组 #第一个参数为生成规则,是必选项 #第二个参数为包装函数,对数组的每个值分别进行处理,是可选项 P.arr = -> #取实参,并转换为数组 arg = Array::slice.call arguments, 0 #数组生成规则 str = arg[0] #如果生成规则无效,则返回空数组 return [] if not str? or typeof str isnt 'string' narr = [] #包装函数 fn = getFnFormat arg[1] or (index, $1) -> return $1 #取到生成规则数组 strs = str.split /\s*,\s*/ for str in strs #标准化生成规则参数 param = getParam str #取到数字化的数组结果 nums = getNums param #取到字符化的数组结果,合并到主队列 narr = narr.concat getArr(nums, param[3]) #返回包装函数格式化后的完整数组 formatArr narr, fn #中文数字转换为数字 # @param {cn}, 中文数字,例如:三十万八千六 # 转换结果:388600 # 适用范围:大于等于 0,小于一亿亿的整数 P.cn2num = (cn) -> #末位不带单位时,补齐单位 #例如三万二,给二补齐单位千 endNum = (s, e) -> if /^[一二三四五六七八九]$/.test s return P.cn2num(s) * e else return P.cn2num s.replace /^零+/g, '' #如果参数不是string类型,则返回 0 if typeof cn isnt 'string' log '中文数字转换参数类型不是String' return 0 #如果参数是空字符串,则返回 0 return 0 if cn is '' #如果参数不匹配中文数字格式规则,则返回 0 if !regs.numberCn.test cn log '中文数字转换格式不正确' return 0 #按亿分割数字 nY = cn.split '亿' #如果包含至少两个‘亿’字,则不支持,返回 0 if nY.length > 2 log '中文数字转换最大支持单位为千万亿' return 0 #如果包含一个亿字,则分别计算亿字前半部分和后半部分 else if nY.length is 2 return P.cn2num( nY[0] ) * 1e8 + endNum( nY[1], 1e7 ) #如果不包含亿,则按万字分割数字 else nW = cn.split '万' #如果包含至少两个‘万’字,则不支持,返回 0 if nW.length > 2 log '中文数字转换格式不正确,不能同时包含两个万字' return 0 #如果包含一个万字,则分别计算万字前半部分和后半部分 else if nW.length is 2 return P.cn2num( nW[0]) * 1e4 + endNum( nW[1], 1e3 ) #如果不包含万,则按千字分割数字 else nQ = cn.split '千' #如果包含至少两个‘千’字,则不支持,返回 0 if nQ.length > 2 log '中文数字转换格式不正确,不能同时包含两个千字' return 0 #如果包含一个千字,则分别计算千字前半部分和后半部分 else if nQ.length is 2 return P.cn2num( nQ[0] ) * 1e3 + endNum( nQ[1], 1e2 ) #如果不包含千,则按百字分割数字 else nB = cn.split '百' #如果包含至少两个‘百’字,则不支持,返回 0 if nB.length > 2 log '中文数字转换格式不正确,不能同时包含两个百字' return 0 #如果包含一个百字,则分别计算百字前半部分和后半部分 else if nB.length is 2 return P.cn2num( nB[0] ) * 1e2 + endNum( nB[1], 1e1 ) #如果不包含百,则按十字分割数字 else nS = cn.split '十' #如果包含至少两个‘十’字,则不支持,返回 0 if nS.length > 2 log '中文数字转换格式不正确,不能同时包含两个十字' return 0 #如果包含一个百字,则分别计算百字前半部分和后半部分 else if nS.length is 2 return P.cn2num( #如果十前面没有量词,默认设置为一,比如:十三,修正为一十三 nS[0] or '一' ) * 1e1 + endNum( nS[1], 1 ) #如果不包含十,则返回个位数对应的数字 else return '一二三四五六七八九'.indexOf( cn ) + 1 #end P.cn2num #自然数转中文数字 # @param {n}, 自然数,例如:388006 # 转换结果:三十万八千零六 # @param {no0}, 逻辑值,转换独立数字 0时,是否返回空字符串,默认为假,返回“零” # 适用范围:大于等于 0,小于一亿亿的整数 P.num2cn = (n, no0) -> #如果 n 不是number类型,则转为String类型原样返回 if typeof n isnt 'number' log '数字换中文参数错误,必须为数字' return n + '' #如果 n 是负数或小数,则转为String类型原样返回 if n < 0 or n % 1 > 0 log '数字换中文只支持自然数' return n + '' if n is 0 return if no0 then '' else '零' #按基数分割数字 # @param {n}, 原数 # @param {s}, 基数 # @return [前半部分, 后半部分, 基数] splitNum = (n, s) -> [n // s, n %% s, s] #分割点 karr = [['亿',1e8],['万',1e4],['千',1e3],['百',1e2],['十',1e1]] #依次尝试分割点 for marr, i in karr #取到当前分割点对应的分割数组 sY = splitNum n, marr[1] #如果分割点存在,及前半部分有值,则分别转换前后部分并连接 if sY[0] > 0 return P.num2cn( sY[0], true ) + #前半部分 marr[0] + #分割点单位 #如果后半部分的值小于基数的下一位数量级,并且后半部分大于 0 ( if sY[1] < sY[2] / 10 and sY[1] > 0 then '零' else '' ) + #后半部分前缀补零 P.num2cn(sY[1], true) #后半部分 #否则,当前是尝试最后一个分割点,且不存在 else if i is _len-1 xGs = '一二三四五六七八九'.split '' xGs.unshift '' #返回个位数对应的数字 return xGs[ sY[1] ] #end P.num2cn #按条件返回值 # @param {vals}, Array,例如:[[1, false], [2, true], 3, [4]] # 返回值:第一个条件为真的值,没有条件相当于条件为真 # 适用场景:按不同条件返回不同值 P.assign = (vals) -> #如果参数不是Array类型,则不支持,返回null if not (vals instanceof Array) log '参数类型错误,期望是Array' return null #循环测试条件 for val in vals #如果当前项不是数组,则相当于条件成立,原样返回当前项 return val if not (val instanceof Array) #如果没有条件,或者条件为真,则返回当前值 return val[0] if val.length is 1 or val.length > 1 and val[1] #无匹配条件,返回null log '无匹配的值' return null #end P.assign # 按条件查找数组 # @param {arr}: Array, 循环处理的数组 # @param {fn}: String or Function, 对每个数组值检测的函数或表达示,返回逻辑值 # @param {reVal}: 是否返回匹配的数组值,默认为false,返回是否匹配。 P.inArr = (arr, fn, reVal) -> #如果arr不是Array类型,则不支持,返回null if not (arr instanceof Array) log '参数类型错误,期望是Array' return null #如果fn不是Function类型,则把fn当作表达示生成一个检测函数 if not (fn instanceof Function) fnstr = fn fn = (index, $1, size) -> #替换表达示中的标记符,$index为当前项的索引值,$1为当前项的值,$size为数组长度 _fnstr = fnstr.replace( "$index", index ).replace( "$1", $1 ).replace( "$size", size ) return ( new Function "return " + _fnstr )() #循环检测数组 for ali, i in arr #如果当前项检测返回真 if fn i, ali, _len #如果reVal为真返回数组当前值,否则返回true return if reVal then ali else true #数组中没有匹配项 return if reVal then undefined else false #end P.inArr # 按条件处理数组的每一项 # @param {arr}: Array, 循环处理的数组 # @param {fn}: String or Function,对每个数组值进行处理的函数或表达示,返回值作为新数组对应位置的值 # @param {old}: 是否修改原数组,默认为false,不修改原数组。 # @return Array: 返回处理后的新数组 P.forArr = (arr, fn, old) -> #如果arr不是Array类型,则不支持,返回null if not (arr instanceof Array) log '参数类型错误,期望是Array' return null newArr = [] #如果fn不是Function类型,则把fn当作表达示生成一个处理函数 if not (fn instanceof Function) fnstr = fn fn = (index, $1, size) -> #替换表达示中的标记符,$index为当前项的索引值,$1为当前项的值,$size为数组长度 _fnstr = fnstr.replace( "$index", index ).replace( "$1", $1 ).replace( "$size", size ) return ( new Function "return " + _fnstr )() #循环处理数组 for ali, i in arr #当前值处理后得到的新值 nVal = fn i, ali, _len #添加到新数组 newArr.push nVal #如果old为真,则修改原数组对应值为新值 arr[i] = nVal if old return newArr #end P.forArr #兼容CMD if "function" is typeof require and "object" is typeof module and module and module.id and "object" is typeof exports and exports module.exports = P #兼容AMD else if "function" is typeof define and define.amd define 'jsplus', [], () -> return P define () -> return P else #将静态对象添加到顶级作用域上 this.P = P
70353
###! # JsPlus v0.0.1 (https://github.com/cuidingfeng/jsplus/) # Copyright 2015 cuidingfeng, Inc. # Licensed under MIT (https://github.com/cuidingfeng/jsplus/blob/master/LICENSE) # Email: <EMAIL> # Generated by CoffeeScript 1.7.1 ### 'use strict' ### # JsPlus的定位是一个JavaScript库,目标是提供一系列简化JavaScript操作的基础方法,让开发专注于业务逻辑。 ### #静态对象主体 P = -> #是否开启log P.debug = true #校验字符类型 regs = #数值型 number: /// ^ [+-]? [1-9][0-9]* (\.[0-9]+)? ([eE][+-][1-9][0-9]*)? $ | ^ [+-]? 0? \.[0-9]+ ([eE][+-][1-9][0-9]*)? $ | ^ 0 $ /// #小写字母 lowercase: /^[a-z]$/ #大写字母 uppercase: /^[A-Z]$/ #中文数字 numberCn: /^[零一二三四五六七八九十百千万亿]+$/ #各种字符类型与数字的转换方法 # getnum: 当前类型转为数字 # getstr: 数字转为当前类型 conversion = #数字 number: getnum: (s) -> Number s getstr: (n) -> n #小写字母 lowercase: #小写字母转数字 getnum: (s) -> s.charCodeAt(0) - 97 #数字转小写字母 getstr: (n) -> String.fromCharCode(n + 97) #大写字母 uppercase: getnum: (s) -> s.charCodeAt(0) - 65 getstr: (n) -> String.fromCharCode(n + 65) #中文数字 numberCn: getnum: (s) -> P.cn2num s getstr: (n) -> P.num2cn n #开启debug时,在控制台打印错误信息 log = (str) -> (if window.console? and console.log? then console.log else alert) "JS-Plus:" + str if P.debug #生成包装函数,fn可以为function或格式化字符串 getFnFormat = (fn) -> #如果传入的fn是函数,则原样返回 if typeof fn is 'function' return fn #如果fn不是函数,则返回一个包装函数 else return (index, $1) -> #替换字符串中的$1和$index # $1为数组的当前项值,$index为当前项在数组中的索引 return fn.replace('$1', $1).replace('$index', index) #生成标准化的数组生成规则参数 #返回值格式:[起始值, 递增值, 结束值, 字符类型] getParam = (str = '') -> #分割取参数 ss = str.split ":" #如果参数少于两个,则格式错误,返回未知类型 if ss.length<2 log '数列格式错误,请至少包括一个":",否则原样返回' return [str, 0, null, -1] else #如果有两个参数,则第一个为起始值,第二个为结束值 if ss.length is 2 ss[2] = ss[1] ss[1] = null #如果参数多于两个,则第二个参数为递增值,并且转为数字,第三个参数为结束值 else ss[1] = parseFloat ss[1] #如果递增值不是数字,则将递增值设为0 if not ss[1] log '数列递增字符格式不正确,必须为数字' ss[1] = 0 tp1 = -1 #获取起始值的字符类型 tp1 = getType ss[0] #如果起始值和结束值的字符类型不一致,则把递增值设为0 if tp1 isnt getType ss[2] log '数列起始值和结束值类型不一致' ss[1] = 0 tp1 = -1 #如果字符类型为-1,则为不支持的类型,把递增值设为0 if tp1 is -1 log '数列格式暂时不支持' ss[1] = 0 else #获取将当前字符类型转换为数字的处理函数 fn = conversion[['number', 'lowercase', 'uppercase', 'numberCn'][tp1]].getnum ss[0] = fn ss[0] ss[2] = fn ss[2] #如果没有递增值,当起始值小于结束值时,将递增值设置为 1,否则设置为 -1 if ss[1] is null ss[1] = if ss[0]<ss[2] then 1 else -1 #如果有递增值,但是从起始值通过递增值无法到达结束值时,将递增值设置为 0 else if ss[1] isnt 0 and (if ss[0]<ss[2] then 1 else -1) * ss[1] < 0 log '数列递增数字正负符号不正确,无法从起始值递增到结束值' ss[1] = 0 return [ss[0], ss[1], ss[2], tp1] #获取字符类型 getType = (s) -> return 0 if regs.number.test s #数字 return 1 if regs.lowercase.test s #小写字母 return 2 if regs.uppercase.test s #大写字母 return 3 if regs.numberCn.test s #汉字数字 return -1 #无匹配类型 #获取数字化数组 # @param {param} [起始值, 递增值, 结束值, 字符类型] getNums = (param) -> reArr = [] #如果递增值为 0,或者字符类型不支持,则原样返回存在的起始值和结束值 if param[1] is 0 or param[3] is -1 reArr.push param[0] if param[0]? reArr.push param[2] if param[2]? else i = param[0] #从起始值到结束值,按递增值依次将数字添加到数组 #第一个值为起始值,最后一个值为在递增方向不超过结束值的最近一个值 #循环条件:当前值小于等于结束值,并且递增值为正数;或者当前值大于等于结束值,并且递增值为负数 while i<=param[2] && param[1]>0 || i>=param[2] && param[1]<0 reArr.push i i+=param[1] return reArr #获取原字符化数组 getArr = (nums, tp) -> #如果字符类型可支持 if tp isnt -1 #获取将数字转换为当前字符类型的处理函数 fn = conversion[['number', 'lowercase', 'uppercase', 'numberCn'][tp]].getstr #循环转换 nums[i] = fn num for num, i in nums return nums #用包装函数格式化数组 formatArr = (arr, cb) -> arr[i] = cb(i, li) for li, i in arr return arr ### #======================================== # 静态对象对外提供的方法 # arr: 按指定规则生成一个一维数组 # cn2num: 把中文数字转换为数值 # num2cn: 把自然数转换为中文数字 # assign: 按条件返回值 # inArr: 按条件查找数组 # forArr: 按条件处理数组的每一项 #======================================== ### #按指定规则生成一个一维数组 #第一个参数为生成规则,是必选项 #第二个参数为包装函数,对数组的每个值分别进行处理,是可选项 P.arr = -> #取实参,并转换为数组 arg = Array::slice.call arguments, 0 #数组生成规则 str = arg[0] #如果生成规则无效,则返回空数组 return [] if not str? or typeof str isnt 'string' narr = [] #包装函数 fn = getFnFormat arg[1] or (index, $1) -> return $1 #取到生成规则数组 strs = str.split /\s*,\s*/ for str in strs #标准化生成规则参数 param = getParam str #取到数字化的数组结果 nums = getNums param #取到字符化的数组结果,合并到主队列 narr = narr.concat getArr(nums, param[3]) #返回包装函数格式化后的完整数组 formatArr narr, fn #中文数字转换为数字 # @param {cn}, 中文数字,例如:三十万八千六 # 转换结果:388600 # 适用范围:大于等于 0,小于一亿亿的整数 P.cn2num = (cn) -> #末位不带单位时,补齐单位 #例如三万二,给二补齐单位千 endNum = (s, e) -> if /^[一二三四五六七八九]$/.test s return P.cn2num(s) * e else return P.cn2num s.replace /^零+/g, '' #如果参数不是string类型,则返回 0 if typeof cn isnt 'string' log '中文数字转换参数类型不是String' return 0 #如果参数是空字符串,则返回 0 return 0 if cn is '' #如果参数不匹配中文数字格式规则,则返回 0 if !regs.numberCn.test cn log '中文数字转换格式不正确' return 0 #按亿分割数字 nY = cn.split '亿' #如果包含至少两个‘亿’字,则不支持,返回 0 if nY.length > 2 log '中文数字转换最大支持单位为千万亿' return 0 #如果包含一个亿字,则分别计算亿字前半部分和后半部分 else if nY.length is 2 return P.cn2num( nY[0] ) * 1e8 + endNum( nY[1], 1e7 ) #如果不包含亿,则按万字分割数字 else nW = cn.split '万' #如果包含至少两个‘万’字,则不支持,返回 0 if nW.length > 2 log '中文数字转换格式不正确,不能同时包含两个万字' return 0 #如果包含一个万字,则分别计算万字前半部分和后半部分 else if nW.length is 2 return P.cn2num( nW[0]) * 1e4 + endNum( nW[1], 1e3 ) #如果不包含万,则按千字分割数字 else nQ = cn.split '千' #如果包含至少两个‘千’字,则不支持,返回 0 if nQ.length > 2 log '中文数字转换格式不正确,不能同时包含两个千字' return 0 #如果包含一个千字,则分别计算千字前半部分和后半部分 else if nQ.length is 2 return P.cn2num( nQ[0] ) * 1e3 + endNum( nQ[1], 1e2 ) #如果不包含千,则按百字分割数字 else nB = cn.split '百' #如果包含至少两个‘百’字,则不支持,返回 0 if nB.length > 2 log '中文数字转换格式不正确,不能同时包含两个百字' return 0 #如果包含一个百字,则分别计算百字前半部分和后半部分 else if nB.length is 2 return P.cn2num( nB[0] ) * 1e2 + endNum( nB[1], 1e1 ) #如果不包含百,则按十字分割数字 else nS = cn.split '十' #如果包含至少两个‘十’字,则不支持,返回 0 if nS.length > 2 log '中文数字转换格式不正确,不能同时包含两个十字' return 0 #如果包含一个百字,则分别计算百字前半部分和后半部分 else if nS.length is 2 return P.cn2num( #如果十前面没有量词,默认设置为一,比如:十三,修正为一十三 nS[0] or '一' ) * 1e1 + endNum( nS[1], 1 ) #如果不包含十,则返回个位数对应的数字 else return '一二三四五六七八九'.indexOf( cn ) + 1 #end P.cn2num #自然数转中文数字 # @param {n}, 自然数,例如:388006 # 转换结果:三十万八千零六 # @param {no0}, 逻辑值,转换独立数字 0时,是否返回空字符串,默认为假,返回“零” # 适用范围:大于等于 0,小于一亿亿的整数 P.num2cn = (n, no0) -> #如果 n 不是number类型,则转为String类型原样返回 if typeof n isnt 'number' log '数字换中文参数错误,必须为数字' return n + '' #如果 n 是负数或小数,则转为String类型原样返回 if n < 0 or n % 1 > 0 log '数字换中文只支持自然数' return n + '' if n is 0 return if no0 then '' else '零' #按基数分割数字 # @param {n}, 原数 # @param {s}, 基数 # @return [前半部分, 后半部分, 基数] splitNum = (n, s) -> [n // s, n %% s, s] #分割点 karr = [['亿',1e8],['万',1e4],['千',1e3],['百',1e2],['十',1e1]] #依次尝试分割点 for marr, i in karr #取到当前分割点对应的分割数组 sY = splitNum n, marr[1] #如果分割点存在,及前半部分有值,则分别转换前后部分并连接 if sY[0] > 0 return P.num2cn( sY[0], true ) + #前半部分 marr[0] + #分割点单位 #如果后半部分的值小于基数的下一位数量级,并且后半部分大于 0 ( if sY[1] < sY[2] / 10 and sY[1] > 0 then '零' else '' ) + #后半部分前缀补零 P.num2cn(sY[1], true) #后半部分 #否则,当前是尝试最后一个分割点,且不存在 else if i is _len-1 xGs = '一二三四五六七八九'.split '' xGs.unshift '' #返回个位数对应的数字 return xGs[ sY[1] ] #end P.num2cn #按条件返回值 # @param {vals}, Array,例如:[[1, false], [2, true], 3, [4]] # 返回值:第一个条件为真的值,没有条件相当于条件为真 # 适用场景:按不同条件返回不同值 P.assign = (vals) -> #如果参数不是Array类型,则不支持,返回null if not (vals instanceof Array) log '参数类型错误,期望是Array' return null #循环测试条件 for val in vals #如果当前项不是数组,则相当于条件成立,原样返回当前项 return val if not (val instanceof Array) #如果没有条件,或者条件为真,则返回当前值 return val[0] if val.length is 1 or val.length > 1 and val[1] #无匹配条件,返回null log '无匹配的值' return null #end P.assign # 按条件查找数组 # @param {arr}: Array, 循环处理的数组 # @param {fn}: String or Function, 对每个数组值检测的函数或表达示,返回逻辑值 # @param {reVal}: 是否返回匹配的数组值,默认为false,返回是否匹配。 P.inArr = (arr, fn, reVal) -> #如果arr不是Array类型,则不支持,返回null if not (arr instanceof Array) log '参数类型错误,期望是Array' return null #如果fn不是Function类型,则把fn当作表达示生成一个检测函数 if not (fn instanceof Function) fnstr = fn fn = (index, $1, size) -> #替换表达示中的标记符,$index为当前项的索引值,$1为当前项的值,$size为数组长度 _fnstr = fnstr.replace( "$index", index ).replace( "$1", $1 ).replace( "$size", size ) return ( new Function "return " + _fnstr )() #循环检测数组 for ali, i in arr #如果当前项检测返回真 if fn i, ali, _len #如果reVal为真返回数组当前值,否则返回true return if reVal then ali else true #数组中没有匹配项 return if reVal then undefined else false #end P.inArr # 按条件处理数组的每一项 # @param {arr}: Array, 循环处理的数组 # @param {fn}: String or Function,对每个数组值进行处理的函数或表达示,返回值作为新数组对应位置的值 # @param {old}: 是否修改原数组,默认为false,不修改原数组。 # @return Array: 返回处理后的新数组 P.forArr = (arr, fn, old) -> #如果arr不是Array类型,则不支持,返回null if not (arr instanceof Array) log '参数类型错误,期望是Array' return null newArr = [] #如果fn不是Function类型,则把fn当作表达示生成一个处理函数 if not (fn instanceof Function) fnstr = fn fn = (index, $1, size) -> #替换表达示中的标记符,$index为当前项的索引值,$1为当前项的值,$size为数组长度 _fnstr = fnstr.replace( "$index", index ).replace( "$1", $1 ).replace( "$size", size ) return ( new Function "return " + _fnstr )() #循环处理数组 for ali, i in arr #当前值处理后得到的新值 nVal = fn i, ali, _len #添加到新数组 newArr.push nVal #如果old为真,则修改原数组对应值为新值 arr[i] = nVal if old return newArr #end P.forArr #兼容CMD if "function" is typeof require and "object" is typeof module and module and module.id and "object" is typeof exports and exports module.exports = P #兼容AMD else if "function" is typeof define and define.amd define 'jsplus', [], () -> return P define () -> return P else #将静态对象添加到顶级作用域上 this.P = P
true
###! # JsPlus v0.0.1 (https://github.com/cuidingfeng/jsplus/) # Copyright 2015 cuidingfeng, Inc. # Licensed under MIT (https://github.com/cuidingfeng/jsplus/blob/master/LICENSE) # Email: PI:EMAIL:<EMAIL>END_PI # Generated by CoffeeScript 1.7.1 ### 'use strict' ### # JsPlus的定位是一个JavaScript库,目标是提供一系列简化JavaScript操作的基础方法,让开发专注于业务逻辑。 ### #静态对象主体 P = -> #是否开启log P.debug = true #校验字符类型 regs = #数值型 number: /// ^ [+-]? [1-9][0-9]* (\.[0-9]+)? ([eE][+-][1-9][0-9]*)? $ | ^ [+-]? 0? \.[0-9]+ ([eE][+-][1-9][0-9]*)? $ | ^ 0 $ /// #小写字母 lowercase: /^[a-z]$/ #大写字母 uppercase: /^[A-Z]$/ #中文数字 numberCn: /^[零一二三四五六七八九十百千万亿]+$/ #各种字符类型与数字的转换方法 # getnum: 当前类型转为数字 # getstr: 数字转为当前类型 conversion = #数字 number: getnum: (s) -> Number s getstr: (n) -> n #小写字母 lowercase: #小写字母转数字 getnum: (s) -> s.charCodeAt(0) - 97 #数字转小写字母 getstr: (n) -> String.fromCharCode(n + 97) #大写字母 uppercase: getnum: (s) -> s.charCodeAt(0) - 65 getstr: (n) -> String.fromCharCode(n + 65) #中文数字 numberCn: getnum: (s) -> P.cn2num s getstr: (n) -> P.num2cn n #开启debug时,在控制台打印错误信息 log = (str) -> (if window.console? and console.log? then console.log else alert) "JS-Plus:" + str if P.debug #生成包装函数,fn可以为function或格式化字符串 getFnFormat = (fn) -> #如果传入的fn是函数,则原样返回 if typeof fn is 'function' return fn #如果fn不是函数,则返回一个包装函数 else return (index, $1) -> #替换字符串中的$1和$index # $1为数组的当前项值,$index为当前项在数组中的索引 return fn.replace('$1', $1).replace('$index', index) #生成标准化的数组生成规则参数 #返回值格式:[起始值, 递增值, 结束值, 字符类型] getParam = (str = '') -> #分割取参数 ss = str.split ":" #如果参数少于两个,则格式错误,返回未知类型 if ss.length<2 log '数列格式错误,请至少包括一个":",否则原样返回' return [str, 0, null, -1] else #如果有两个参数,则第一个为起始值,第二个为结束值 if ss.length is 2 ss[2] = ss[1] ss[1] = null #如果参数多于两个,则第二个参数为递增值,并且转为数字,第三个参数为结束值 else ss[1] = parseFloat ss[1] #如果递增值不是数字,则将递增值设为0 if not ss[1] log '数列递增字符格式不正确,必须为数字' ss[1] = 0 tp1 = -1 #获取起始值的字符类型 tp1 = getType ss[0] #如果起始值和结束值的字符类型不一致,则把递增值设为0 if tp1 isnt getType ss[2] log '数列起始值和结束值类型不一致' ss[1] = 0 tp1 = -1 #如果字符类型为-1,则为不支持的类型,把递增值设为0 if tp1 is -1 log '数列格式暂时不支持' ss[1] = 0 else #获取将当前字符类型转换为数字的处理函数 fn = conversion[['number', 'lowercase', 'uppercase', 'numberCn'][tp1]].getnum ss[0] = fn ss[0] ss[2] = fn ss[2] #如果没有递增值,当起始值小于结束值时,将递增值设置为 1,否则设置为 -1 if ss[1] is null ss[1] = if ss[0]<ss[2] then 1 else -1 #如果有递增值,但是从起始值通过递增值无法到达结束值时,将递增值设置为 0 else if ss[1] isnt 0 and (if ss[0]<ss[2] then 1 else -1) * ss[1] < 0 log '数列递增数字正负符号不正确,无法从起始值递增到结束值' ss[1] = 0 return [ss[0], ss[1], ss[2], tp1] #获取字符类型 getType = (s) -> return 0 if regs.number.test s #数字 return 1 if regs.lowercase.test s #小写字母 return 2 if regs.uppercase.test s #大写字母 return 3 if regs.numberCn.test s #汉字数字 return -1 #无匹配类型 #获取数字化数组 # @param {param} [起始值, 递增值, 结束值, 字符类型] getNums = (param) -> reArr = [] #如果递增值为 0,或者字符类型不支持,则原样返回存在的起始值和结束值 if param[1] is 0 or param[3] is -1 reArr.push param[0] if param[0]? reArr.push param[2] if param[2]? else i = param[0] #从起始值到结束值,按递增值依次将数字添加到数组 #第一个值为起始值,最后一个值为在递增方向不超过结束值的最近一个值 #循环条件:当前值小于等于结束值,并且递增值为正数;或者当前值大于等于结束值,并且递增值为负数 while i<=param[2] && param[1]>0 || i>=param[2] && param[1]<0 reArr.push i i+=param[1] return reArr #获取原字符化数组 getArr = (nums, tp) -> #如果字符类型可支持 if tp isnt -1 #获取将数字转换为当前字符类型的处理函数 fn = conversion[['number', 'lowercase', 'uppercase', 'numberCn'][tp]].getstr #循环转换 nums[i] = fn num for num, i in nums return nums #用包装函数格式化数组 formatArr = (arr, cb) -> arr[i] = cb(i, li) for li, i in arr return arr ### #======================================== # 静态对象对外提供的方法 # arr: 按指定规则生成一个一维数组 # cn2num: 把中文数字转换为数值 # num2cn: 把自然数转换为中文数字 # assign: 按条件返回值 # inArr: 按条件查找数组 # forArr: 按条件处理数组的每一项 #======================================== ### #按指定规则生成一个一维数组 #第一个参数为生成规则,是必选项 #第二个参数为包装函数,对数组的每个值分别进行处理,是可选项 P.arr = -> #取实参,并转换为数组 arg = Array::slice.call arguments, 0 #数组生成规则 str = arg[0] #如果生成规则无效,则返回空数组 return [] if not str? or typeof str isnt 'string' narr = [] #包装函数 fn = getFnFormat arg[1] or (index, $1) -> return $1 #取到生成规则数组 strs = str.split /\s*,\s*/ for str in strs #标准化生成规则参数 param = getParam str #取到数字化的数组结果 nums = getNums param #取到字符化的数组结果,合并到主队列 narr = narr.concat getArr(nums, param[3]) #返回包装函数格式化后的完整数组 formatArr narr, fn #中文数字转换为数字 # @param {cn}, 中文数字,例如:三十万八千六 # 转换结果:388600 # 适用范围:大于等于 0,小于一亿亿的整数 P.cn2num = (cn) -> #末位不带单位时,补齐单位 #例如三万二,给二补齐单位千 endNum = (s, e) -> if /^[一二三四五六七八九]$/.test s return P.cn2num(s) * e else return P.cn2num s.replace /^零+/g, '' #如果参数不是string类型,则返回 0 if typeof cn isnt 'string' log '中文数字转换参数类型不是String' return 0 #如果参数是空字符串,则返回 0 return 0 if cn is '' #如果参数不匹配中文数字格式规则,则返回 0 if !regs.numberCn.test cn log '中文数字转换格式不正确' return 0 #按亿分割数字 nY = cn.split '亿' #如果包含至少两个‘亿’字,则不支持,返回 0 if nY.length > 2 log '中文数字转换最大支持单位为千万亿' return 0 #如果包含一个亿字,则分别计算亿字前半部分和后半部分 else if nY.length is 2 return P.cn2num( nY[0] ) * 1e8 + endNum( nY[1], 1e7 ) #如果不包含亿,则按万字分割数字 else nW = cn.split '万' #如果包含至少两个‘万’字,则不支持,返回 0 if nW.length > 2 log '中文数字转换格式不正确,不能同时包含两个万字' return 0 #如果包含一个万字,则分别计算万字前半部分和后半部分 else if nW.length is 2 return P.cn2num( nW[0]) * 1e4 + endNum( nW[1], 1e3 ) #如果不包含万,则按千字分割数字 else nQ = cn.split '千' #如果包含至少两个‘千’字,则不支持,返回 0 if nQ.length > 2 log '中文数字转换格式不正确,不能同时包含两个千字' return 0 #如果包含一个千字,则分别计算千字前半部分和后半部分 else if nQ.length is 2 return P.cn2num( nQ[0] ) * 1e3 + endNum( nQ[1], 1e2 ) #如果不包含千,则按百字分割数字 else nB = cn.split '百' #如果包含至少两个‘百’字,则不支持,返回 0 if nB.length > 2 log '中文数字转换格式不正确,不能同时包含两个百字' return 0 #如果包含一个百字,则分别计算百字前半部分和后半部分 else if nB.length is 2 return P.cn2num( nB[0] ) * 1e2 + endNum( nB[1], 1e1 ) #如果不包含百,则按十字分割数字 else nS = cn.split '十' #如果包含至少两个‘十’字,则不支持,返回 0 if nS.length > 2 log '中文数字转换格式不正确,不能同时包含两个十字' return 0 #如果包含一个百字,则分别计算百字前半部分和后半部分 else if nS.length is 2 return P.cn2num( #如果十前面没有量词,默认设置为一,比如:十三,修正为一十三 nS[0] or '一' ) * 1e1 + endNum( nS[1], 1 ) #如果不包含十,则返回个位数对应的数字 else return '一二三四五六七八九'.indexOf( cn ) + 1 #end P.cn2num #自然数转中文数字 # @param {n}, 自然数,例如:388006 # 转换结果:三十万八千零六 # @param {no0}, 逻辑值,转换独立数字 0时,是否返回空字符串,默认为假,返回“零” # 适用范围:大于等于 0,小于一亿亿的整数 P.num2cn = (n, no0) -> #如果 n 不是number类型,则转为String类型原样返回 if typeof n isnt 'number' log '数字换中文参数错误,必须为数字' return n + '' #如果 n 是负数或小数,则转为String类型原样返回 if n < 0 or n % 1 > 0 log '数字换中文只支持自然数' return n + '' if n is 0 return if no0 then '' else '零' #按基数分割数字 # @param {n}, 原数 # @param {s}, 基数 # @return [前半部分, 后半部分, 基数] splitNum = (n, s) -> [n // s, n %% s, s] #分割点 karr = [['亿',1e8],['万',1e4],['千',1e3],['百',1e2],['十',1e1]] #依次尝试分割点 for marr, i in karr #取到当前分割点对应的分割数组 sY = splitNum n, marr[1] #如果分割点存在,及前半部分有值,则分别转换前后部分并连接 if sY[0] > 0 return P.num2cn( sY[0], true ) + #前半部分 marr[0] + #分割点单位 #如果后半部分的值小于基数的下一位数量级,并且后半部分大于 0 ( if sY[1] < sY[2] / 10 and sY[1] > 0 then '零' else '' ) + #后半部分前缀补零 P.num2cn(sY[1], true) #后半部分 #否则,当前是尝试最后一个分割点,且不存在 else if i is _len-1 xGs = '一二三四五六七八九'.split '' xGs.unshift '' #返回个位数对应的数字 return xGs[ sY[1] ] #end P.num2cn #按条件返回值 # @param {vals}, Array,例如:[[1, false], [2, true], 3, [4]] # 返回值:第一个条件为真的值,没有条件相当于条件为真 # 适用场景:按不同条件返回不同值 P.assign = (vals) -> #如果参数不是Array类型,则不支持,返回null if not (vals instanceof Array) log '参数类型错误,期望是Array' return null #循环测试条件 for val in vals #如果当前项不是数组,则相当于条件成立,原样返回当前项 return val if not (val instanceof Array) #如果没有条件,或者条件为真,则返回当前值 return val[0] if val.length is 1 or val.length > 1 and val[1] #无匹配条件,返回null log '无匹配的值' return null #end P.assign # 按条件查找数组 # @param {arr}: Array, 循环处理的数组 # @param {fn}: String or Function, 对每个数组值检测的函数或表达示,返回逻辑值 # @param {reVal}: 是否返回匹配的数组值,默认为false,返回是否匹配。 P.inArr = (arr, fn, reVal) -> #如果arr不是Array类型,则不支持,返回null if not (arr instanceof Array) log '参数类型错误,期望是Array' return null #如果fn不是Function类型,则把fn当作表达示生成一个检测函数 if not (fn instanceof Function) fnstr = fn fn = (index, $1, size) -> #替换表达示中的标记符,$index为当前项的索引值,$1为当前项的值,$size为数组长度 _fnstr = fnstr.replace( "$index", index ).replace( "$1", $1 ).replace( "$size", size ) return ( new Function "return " + _fnstr )() #循环检测数组 for ali, i in arr #如果当前项检测返回真 if fn i, ali, _len #如果reVal为真返回数组当前值,否则返回true return if reVal then ali else true #数组中没有匹配项 return if reVal then undefined else false #end P.inArr # 按条件处理数组的每一项 # @param {arr}: Array, 循环处理的数组 # @param {fn}: String or Function,对每个数组值进行处理的函数或表达示,返回值作为新数组对应位置的值 # @param {old}: 是否修改原数组,默认为false,不修改原数组。 # @return Array: 返回处理后的新数组 P.forArr = (arr, fn, old) -> #如果arr不是Array类型,则不支持,返回null if not (arr instanceof Array) log '参数类型错误,期望是Array' return null newArr = [] #如果fn不是Function类型,则把fn当作表达示生成一个处理函数 if not (fn instanceof Function) fnstr = fn fn = (index, $1, size) -> #替换表达示中的标记符,$index为当前项的索引值,$1为当前项的值,$size为数组长度 _fnstr = fnstr.replace( "$index", index ).replace( "$1", $1 ).replace( "$size", size ) return ( new Function "return " + _fnstr )() #循环处理数组 for ali, i in arr #当前值处理后得到的新值 nVal = fn i, ali, _len #添加到新数组 newArr.push nVal #如果old为真,则修改原数组对应值为新值 arr[i] = nVal if old return newArr #end P.forArr #兼容CMD if "function" is typeof require and "object" is typeof module and module and module.id and "object" is typeof exports and exports module.exports = P #兼容AMD else if "function" is typeof define and define.amd define 'jsplus', [], () -> return P define () -> return P else #将静态对象添加到顶级作用域上 this.P = P
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 197, "score": 0.9998787045478821, "start": 180, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\nThis softwa", "end": 213, "score": 0.9999290108680725, "start": 200, "tag": "EMAIL", "value": "ben@pxljs.com" } ]
examples/shapes.coffee
OniDaito/pxljs
1
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An example showing how we create basic shapes ### class ShapesExample init : () -> # Create the top node and add our camera @top_node = new PXL.Node() @c = new PXL.Camera.MousePerspCamera new PXL.Math.Vec3(0,0,25) @top_node.add @c # Create a cuboid with a basic material # then translate the cube a little cube_node = new PXL.Node new PXL.Geometry.Cuboid(new PXL.Math.Vec3(1,2,1)) cube_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(1,0,0) cube_node.matrix.translate new PXL.Math.Vec3(1,1,3) # Create a cylinder with a basic material # then translate it a litle cylinder_node = new PXL.Node new PXL.Geometry.Cylinder(1,5,2,4) cylinder_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(0,1,0) cylinder_node.matrix.translate new PXL.Math.Vec3(-1,0,-3) # Create a sphere but add a per-vertex colour sphere_node = new PXL.Node new PXL.Geometry.Sphere(1,12,new PXL.Colour.RGBA(0,0,1,1)) sphere_node.add new PXL.Material.VertexColourMaterial() # Alter the first 27 vertices to be red for i in [0..27] sphere_node.geometry.vertices[i].c = new PXL.Colour.RGBA(1,0,0,1) # Add all the nodes to the top node and call our ubershader @top_node.add(cube_node).add(cylinder_node).add(sphere_node) uber = new PXL.GL.UberShader @top_node @top_node.add uber # Basic GL Functions GL.enable(GL.CULL_FACE) GL.cullFace(GL.BACK) GL.enable(GL.DEPTH_TEST) # Create an angle in radians from degrees angle = PXL.Math.degToRad 1 @rmatrix = new PXL.Math.Matrix4() # Create a rotation matrix @rmatrix.rotate new PXL.Math.Vec3(1,0,0), angle @rmatrix.rotate new PXL.Math.Vec3(0,1,0), angle @rmatrix.rotate new PXL.Math.Vec3(0,0,1), angle draw : () -> # Clear and draw our shapes GL.clearColor(0.95, 0.95, 0.95, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @top_node.draw() # for each child node, multiply its matrix by the rotation matrix for n in @top_node.children n.matrix.mult @rmatrix example = new ShapesExample() params = canvas : 'webgl-canvas' context : example init : example.init draw : example.draw debug : true cgl = new PXL.App params
121566
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An example showing how we create basic shapes ### class ShapesExample init : () -> # Create the top node and add our camera @top_node = new PXL.Node() @c = new PXL.Camera.MousePerspCamera new PXL.Math.Vec3(0,0,25) @top_node.add @c # Create a cuboid with a basic material # then translate the cube a little cube_node = new PXL.Node new PXL.Geometry.Cuboid(new PXL.Math.Vec3(1,2,1)) cube_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(1,0,0) cube_node.matrix.translate new PXL.Math.Vec3(1,1,3) # Create a cylinder with a basic material # then translate it a litle cylinder_node = new PXL.Node new PXL.Geometry.Cylinder(1,5,2,4) cylinder_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(0,1,0) cylinder_node.matrix.translate new PXL.Math.Vec3(-1,0,-3) # Create a sphere but add a per-vertex colour sphere_node = new PXL.Node new PXL.Geometry.Sphere(1,12,new PXL.Colour.RGBA(0,0,1,1)) sphere_node.add new PXL.Material.VertexColourMaterial() # Alter the first 27 vertices to be red for i in [0..27] sphere_node.geometry.vertices[i].c = new PXL.Colour.RGBA(1,0,0,1) # Add all the nodes to the top node and call our ubershader @top_node.add(cube_node).add(cylinder_node).add(sphere_node) uber = new PXL.GL.UberShader @top_node @top_node.add uber # Basic GL Functions GL.enable(GL.CULL_FACE) GL.cullFace(GL.BACK) GL.enable(GL.DEPTH_TEST) # Create an angle in radians from degrees angle = PXL.Math.degToRad 1 @rmatrix = new PXL.Math.Matrix4() # Create a rotation matrix @rmatrix.rotate new PXL.Math.Vec3(1,0,0), angle @rmatrix.rotate new PXL.Math.Vec3(0,1,0), angle @rmatrix.rotate new PXL.Math.Vec3(0,0,1), angle draw : () -> # Clear and draw our shapes GL.clearColor(0.95, 0.95, 0.95, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @top_node.draw() # for each child node, multiply its matrix by the rotation matrix for n in @top_node.children n.matrix.mult @rmatrix example = new ShapesExample() params = canvas : 'webgl-canvas' context : example init : example.init draw : example.draw debug : true cgl = new PXL.App params
true
### ABOUT .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An example showing how we create basic shapes ### class ShapesExample init : () -> # Create the top node and add our camera @top_node = new PXL.Node() @c = new PXL.Camera.MousePerspCamera new PXL.Math.Vec3(0,0,25) @top_node.add @c # Create a cuboid with a basic material # then translate the cube a little cube_node = new PXL.Node new PXL.Geometry.Cuboid(new PXL.Math.Vec3(1,2,1)) cube_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(1,0,0) cube_node.matrix.translate new PXL.Math.Vec3(1,1,3) # Create a cylinder with a basic material # then translate it a litle cylinder_node = new PXL.Node new PXL.Geometry.Cylinder(1,5,2,4) cylinder_node.add new PXL.Material.BasicColourMaterial new PXL.Colour.RGB(0,1,0) cylinder_node.matrix.translate new PXL.Math.Vec3(-1,0,-3) # Create a sphere but add a per-vertex colour sphere_node = new PXL.Node new PXL.Geometry.Sphere(1,12,new PXL.Colour.RGBA(0,0,1,1)) sphere_node.add new PXL.Material.VertexColourMaterial() # Alter the first 27 vertices to be red for i in [0..27] sphere_node.geometry.vertices[i].c = new PXL.Colour.RGBA(1,0,0,1) # Add all the nodes to the top node and call our ubershader @top_node.add(cube_node).add(cylinder_node).add(sphere_node) uber = new PXL.GL.UberShader @top_node @top_node.add uber # Basic GL Functions GL.enable(GL.CULL_FACE) GL.cullFace(GL.BACK) GL.enable(GL.DEPTH_TEST) # Create an angle in radians from degrees angle = PXL.Math.degToRad 1 @rmatrix = new PXL.Math.Matrix4() # Create a rotation matrix @rmatrix.rotate new PXL.Math.Vec3(1,0,0), angle @rmatrix.rotate new PXL.Math.Vec3(0,1,0), angle @rmatrix.rotate new PXL.Math.Vec3(0,0,1), angle draw : () -> # Clear and draw our shapes GL.clearColor(0.95, 0.95, 0.95, 1.0) GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT) @top_node.draw() # for each child node, multiply its matrix by the rotation matrix for n in @top_node.children n.matrix.mult @rmatrix example = new ShapesExample() params = canvas : 'webgl-canvas' context : example init : example.init draw : example.draw debug : true cgl = new PXL.App params
[ { "context": "model.user.getMe()\n place: @place\n name: @name\n isActionLoading: false\n\n getThumbnailU", "end": 953, "score": 0.5571628212928772, "start": 953, "tag": "NAME", "value": "" }, { "context": "@state.getValue()\n\n place ?= @place\n name ?= @name\n\n thumbnailSrc = @getThumbnailUrl place\n ", "end": 1628, "score": 0.41165590286254883, "start": 1628, "tag": "NAME", "value": "" } ]
src/components/place_list_campground/index.coffee
FreeRoamApp/free-roam
14
z = require 'zorium' _map = require 'lodash/map' RxObservable = require('rxjs/Observable').Observable Icon = require '../icon' Rating = require '../rating' SecondaryButton = require '../secondary_button' MapService = require '../../services/map' colors = require '../../colors' config = require '../../config' if window? require './index.styl' module.exports = class PlaceListCampground constructor: ({@model, @router, @place, @name, @action}) -> @$actionButton = new SecondaryButton() @$rating = new Rating { value: if @place?.map then @place else RxObservable.of @place?.rating } @defaultImages = [ "#{config.CDN_URL}/places/empty_campground.svg" "#{config.CDN_URL}/places/empty_campground_green.svg" "#{config.CDN_URL}/places/empty_campground_blue.svg" "#{config.CDN_URL}/places/empty_campground_beige.svg" ] @state = z.state me: @model.user.getMe() place: @place name: @name isActionLoading: false getThumbnailUrl: (place) => url = @model.image.getSrcByPrefix( place?.thumbnailPrefix, {size: 'tiny'} ) if url url else lastChar = place?.id?.substr(place?.id?.length - 1, 1) or 'a' @defaultImages[\ Math.ceil (parseInt(lastChar, 16) / 16) * (@defaultImages.length - 1) ] checkIn: (place) => @model.checkIn.upsert { name: place.name sourceType: place.type sourceId: place.id status: 'visited' setUserLocation: true } render: ({hideRating} = {}) => {me, isActionLoading, place, name} = @state.getValue() place ?= @place name ?= @name thumbnailSrc = @getThumbnailUrl place hasInfoButton = @action is 'info' and place?.type is 'campground' z '.z-place-list-campground', z '.thumbnail', style: backgroundImage: "url(#{thumbnailSrc})" z '.info', z '.name', name or place?.name if place?.distance z '.caption', @model.l.get 'placeList.distance', { replacements: distance: place?.distance.distance time: place?.distance.time } if place?.address?.administrativeArea z '.location', if place?.address?.locality "#{place?.address?.locality}, " place?.address?.administrativeArea if not hideRating z '.rating', z @$rating if @action z '.actions', z '.action', z @$actionButton, text: if isActionLoading \ then @model.l.get 'general.loading' else if @action in ['info', 'openCheckIn'] then @model.l.get 'general.info' else if @action is 'directions' then @model.l.get 'general.directions' else @model.l.get 'placeInfo.checkIn' isOutline: true heightPx: 28 onclick: => if @action is 'info' @router.goPlace place else if @action is 'openCheckIn' @router.goOverlay 'checkIn', { id: place.checkInId } else if @action is 'directions' MapService.getDirections place, {@model} else @state.set isActionLoading: true @checkIn place .then => @state.set isActionLoading: false
91909
z = require 'zorium' _map = require 'lodash/map' RxObservable = require('rxjs/Observable').Observable Icon = require '../icon' Rating = require '../rating' SecondaryButton = require '../secondary_button' MapService = require '../../services/map' colors = require '../../colors' config = require '../../config' if window? require './index.styl' module.exports = class PlaceListCampground constructor: ({@model, @router, @place, @name, @action}) -> @$actionButton = new SecondaryButton() @$rating = new Rating { value: if @place?.map then @place else RxObservable.of @place?.rating } @defaultImages = [ "#{config.CDN_URL}/places/empty_campground.svg" "#{config.CDN_URL}/places/empty_campground_green.svg" "#{config.CDN_URL}/places/empty_campground_blue.svg" "#{config.CDN_URL}/places/empty_campground_beige.svg" ] @state = z.state me: @model.user.getMe() place: @place name:<NAME> @name isActionLoading: false getThumbnailUrl: (place) => url = @model.image.getSrcByPrefix( place?.thumbnailPrefix, {size: 'tiny'} ) if url url else lastChar = place?.id?.substr(place?.id?.length - 1, 1) or 'a' @defaultImages[\ Math.ceil (parseInt(lastChar, 16) / 16) * (@defaultImages.length - 1) ] checkIn: (place) => @model.checkIn.upsert { name: place.name sourceType: place.type sourceId: place.id status: 'visited' setUserLocation: true } render: ({hideRating} = {}) => {me, isActionLoading, place, name} = @state.getValue() place ?= @place name ?=<NAME> @name thumbnailSrc = @getThumbnailUrl place hasInfoButton = @action is 'info' and place?.type is 'campground' z '.z-place-list-campground', z '.thumbnail', style: backgroundImage: "url(#{thumbnailSrc})" z '.info', z '.name', name or place?.name if place?.distance z '.caption', @model.l.get 'placeList.distance', { replacements: distance: place?.distance.distance time: place?.distance.time } if place?.address?.administrativeArea z '.location', if place?.address?.locality "#{place?.address?.locality}, " place?.address?.administrativeArea if not hideRating z '.rating', z @$rating if @action z '.actions', z '.action', z @$actionButton, text: if isActionLoading \ then @model.l.get 'general.loading' else if @action in ['info', 'openCheckIn'] then @model.l.get 'general.info' else if @action is 'directions' then @model.l.get 'general.directions' else @model.l.get 'placeInfo.checkIn' isOutline: true heightPx: 28 onclick: => if @action is 'info' @router.goPlace place else if @action is 'openCheckIn' @router.goOverlay 'checkIn', { id: place.checkInId } else if @action is 'directions' MapService.getDirections place, {@model} else @state.set isActionLoading: true @checkIn place .then => @state.set isActionLoading: false
true
z = require 'zorium' _map = require 'lodash/map' RxObservable = require('rxjs/Observable').Observable Icon = require '../icon' Rating = require '../rating' SecondaryButton = require '../secondary_button' MapService = require '../../services/map' colors = require '../../colors' config = require '../../config' if window? require './index.styl' module.exports = class PlaceListCampground constructor: ({@model, @router, @place, @name, @action}) -> @$actionButton = new SecondaryButton() @$rating = new Rating { value: if @place?.map then @place else RxObservable.of @place?.rating } @defaultImages = [ "#{config.CDN_URL}/places/empty_campground.svg" "#{config.CDN_URL}/places/empty_campground_green.svg" "#{config.CDN_URL}/places/empty_campground_blue.svg" "#{config.CDN_URL}/places/empty_campground_beige.svg" ] @state = z.state me: @model.user.getMe() place: @place name:PI:NAME:<NAME>END_PI @name isActionLoading: false getThumbnailUrl: (place) => url = @model.image.getSrcByPrefix( place?.thumbnailPrefix, {size: 'tiny'} ) if url url else lastChar = place?.id?.substr(place?.id?.length - 1, 1) or 'a' @defaultImages[\ Math.ceil (parseInt(lastChar, 16) / 16) * (@defaultImages.length - 1) ] checkIn: (place) => @model.checkIn.upsert { name: place.name sourceType: place.type sourceId: place.id status: 'visited' setUserLocation: true } render: ({hideRating} = {}) => {me, isActionLoading, place, name} = @state.getValue() place ?= @place name ?=PI:NAME:<NAME>END_PI @name thumbnailSrc = @getThumbnailUrl place hasInfoButton = @action is 'info' and place?.type is 'campground' z '.z-place-list-campground', z '.thumbnail', style: backgroundImage: "url(#{thumbnailSrc})" z '.info', z '.name', name or place?.name if place?.distance z '.caption', @model.l.get 'placeList.distance', { replacements: distance: place?.distance.distance time: place?.distance.time } if place?.address?.administrativeArea z '.location', if place?.address?.locality "#{place?.address?.locality}, " place?.address?.administrativeArea if not hideRating z '.rating', z @$rating if @action z '.actions', z '.action', z @$actionButton, text: if isActionLoading \ then @model.l.get 'general.loading' else if @action in ['info', 'openCheckIn'] then @model.l.get 'general.info' else if @action is 'directions' then @model.l.get 'general.directions' else @model.l.get 'placeInfo.checkIn' isOutline: true heightPx: 28 onclick: => if @action is 'info' @router.goPlace place else if @action is 'openCheckIn' @router.goOverlay 'checkIn', { id: place.checkInId } else if @action is 'directions' MapService.getDirections place, {@model} else @state.set isActionLoading: true @checkIn place .then => @state.set isActionLoading: false
[ { "context": "rd, action, uid} = req.get()\n sentVerifyKey = \"sentverify:#{phoneNumber}\"\n\n switch action\n\n when 'signup'\n #", "end": 1516, "score": 0.937126100063324, "start": 1490, "tag": "KEY", "value": "sentverify:#{phoneNumber}\"" }, { "context": "or req.ip\n _userId: 'new'\n password: password\n uid: uid\n\n switch action\n whe", "end": 2413, "score": 0.9992679953575134, "start": 2405, "tag": "PASSWORD", "value": "password" }, { "context": "户\n user = new UserModel\n user.password = user.genPassword verifyData.password\n\n mobile = new MobileMod", "end": 4199, "score": 0.9945029020309448, "start": 4183, "tag": "PASSWORD", "value": "user.genPassword" }, { "context": "q, res, user, callback) ->\n user.accountToken = user.genAccountToken login: 'mobile'\n callback null,", "end": 8363, "score": 0.6266684532165527, "start": 8359, "tag": "PASSWORD", "value": "user" } ]
talk-account/server/apis/mobile.coffee
ikingye/talk-os
3,084
###* * 手机验证码登录/注册接口 ### Err = require 'err1st' limbo = require 'limbo' config = require 'config' Promise = require 'bluebird' _ = require 'lodash' app = require '../server' util = require '../util' redis = require '../components/redis' { MobileModel UserModel } = limbo.use 'account' module.exports = mobileController = app.controller 'mobile', -> @mixin require './mixins/auth' @mixin require './mixins/cookie' @ratelimit '6,60 15,300', only: 'sendVerifyCode' unless config.debug @ratelimit '20,60 80,300', only: 'bind signin change' @ensure 'phoneNumber', only: 'sendVerifyCode unbind' @ensure 'randomCode verifyCode', only: 'bind change signup' @ensure 'newPassword', only: 'resetPassword' @ensure 'bindCode', only: 'forcebind' @before 'delay1s', only: 'signin signup bind change' unless config.debug @before 'verifyAccount', only: 'bind unbind forcebind change resetPassword' @after 'mobileToUser', only: 'signin signup bind forcebind change signinByVerifyCode' @after 'setAccountToken', only: 'signin signup bind forcebind unbind change signinByVerifyCode resetPassword' @after 'setCookie', only: 'signin signup bind forcebind unbind change signinByVerifyCode' ################################# ACTIONS ################################# ###* * 发送手机验证码,同一号码 30 秒内只可发送一次,有效期 10 分钟 * @return {Object} ok: 1 ### @action 'sendVerifyCode', (req, res, callback) -> {phoneNumber, password, action, uid} = req.get() sentVerifyKey = "sentverify:#{phoneNumber}" switch action when 'signup' # 如果是注册操作,验证手机号是否存在,验证是否有 password 参数 if password?.length $check = MobileModel.findOneAsync phoneNumber: phoneNumber .then (mobile) -> throw new Err('ACCOUNT_EXISTS') if mobile else $check = Promise.reject(new Err('PARAMS_MISSING', 'password')) when 'resetpassword' # 如果是重置密码操作,先确认手机号存在 $check = MobileModel.findOneAsync phoneNumber: phoneNumber .then (mobile) -> throw new Err('ACCOUNT_NOT_EXIST') unless mobile # @todo Remove else $check = Promise.resolve() $sent = $check.then -> redis.getAsync sentVerifyKey .then (sent) -> throw new Err('RESEND_TOO_OFTEN') if sent and not process.env.DEBUG options = phoneNumber: phoneNumber ip: req.headers['x-real-ip'] or req.ip _userId: 'new' password: password uid: uid switch action when 'signup' then options.refer = 'jianliao_register' when 'resetpassword' then options.refer = 'jianliao_resetpassword' else options.refer = 'jianliao_register' $verifyData = MobileModel.sendVerifyCodeAsync options $setSentFlag = $verifyData.then -> redis.setexAsync sentVerifyKey, 60, 1 Promise.all [$verifyData, $setSentFlag] .spread (verifyData) -> verifyData .then (verifyData) -> if config.debug data = _.pick(verifyData, 'randomCode', 'verifyCode') else data = _.pick(verifyData, 'randomCode') .nodeify callback ###* * 验证手机号并返回账号信息,如果手机号已存在,则返回原账号信息 * @return {Model} user - 用户信息 ### @action 'signin', (req, res, callback) -> {phoneNumber, password, randomCode, verifyCode} = req.get() if phoneNumber and password return @signinByPassword req, res, callback if randomCode and verifyCode return @signinByVerifyCode req, res, callback callback(new Err('PARAMS_MISSING', 'phoneNumber, password')) ###* * 手机注册 ### @action 'signup', (req, res, callback) -> {phoneNumber, randomCode, verifyCode} = req.get() # 读取验证码 $verifyData = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> throw new Err('PARAMS_MISSING', 'password') unless verifyData.password verifyData # 检测手机号是否存在 $mobileNotExists = $verifyData.then (verifyData) -> MobileModel.findOneAsync phoneNumber: verifyData.phoneNumber .then (mobile) -> throw new Err('ACCOUNT_EXISTS') if mobile # 创建手机号与用户账号 $mobile = Promise.all [$verifyData, $mobileNotExists] .spread (verifyData) -> # 创建新用户 user = new UserModel user.password = user.genPassword verifyData.password mobile = new MobileModel phoneNumber: verifyData.phoneNumber user: user Promise.all [user.$save(), mobile.$save()] .spread (user, mobile) -> mobile # 返回结果 $mobile.nodeify callback @action 'bind', (req, res, callback) -> {user, verifyCode, randomCode} = req.get() $phoneNumber = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> verifyData.phoneNumber $mobile = $phoneNumber.then (phoneNumber) -> MobileModel.findOne phoneNumber: phoneNumber .execAsync() .then (mobile) -> if mobile?.user # 生成 bindCode 并返回错误信息 return $bindCode = mobile.genBindCodeAsync().then (bindCode) -> err = new Err('BIND_CONFLICT') err.data = bindCode: bindCode showname: phoneNumber throw err if mobile mobile.user = user else mobile = new MobileModel phoneNumber: phoneNumber user: user mobile.updatedAt = new Date mobile $cleanupOtherMobiles = $mobile.then (mobile) -> MobileModel.removeAsync user: user._id phoneNumber: $ne: mobile.phoneNumber $mobile = Promise.all [$mobile, $cleanupOtherMobiles] .spread (mobile) -> mobile.$save() $mobile.nodeify callback @action 'change', (req, res, callback) -> @bind req, res, callback @action 'forcebind', (req, res, callback) -> {user, bindCode} = req.get() $mobile = MobileModel.verifyBindCodeAsync bindCode $mobile = $mobile.then (mobile) -> mobile.user = user mobile.updatedAt = new Date mobile.$save() $cleanupOtherMobiles = $mobile.then (mobile) -> MobileModel.removeAsync user: user._id phoneNumber: $ne: mobile.phoneNumber Promise.all [$mobile, $cleanupOtherMobiles] .spread (mobile) -> mobile .nodeify callback @action 'unbind', (req, res, callback) -> {user, phoneNumber} = req.get() $mobile = MobileModel.findOneAsync user: user._id phoneNumber: phoneNumber .then (mobile) -> if mobile?.user mobile.$remove() $user = $mobile.then -> user .nodeify callback @action 'signinByPassword', (req, res, callback) -> {phoneNumber, password} = req.get() $mobile = MobileModel.findOne phoneNumber: phoneNumber .populate 'user' .execAsync() .then (mobile) -> throw new Err('LOGIN_VERIFY_FAILED') unless mobile?.user throw new Err('NO_PASSWORD') unless mobile?.user?.password mobile.user.verifyPasswordAsync password .then -> mobile $mobile.nodeify callback @action 'signinByVerifyCode', (req, res, callback) -> {verifyCode, randomCode, action} = req.get() $phoneNumber = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> verifyData.phoneNumber $mobile = $phoneNumber.then (phoneNumber) -> # 根据手机号查找老用户 MobileModel.findOne phoneNumber: phoneNumber .populate 'user' .execAsync() .then (mobile) -> return mobile if mobile?.user if action is 'resetpassword' throw new Err('ACCOUNT_NOT_EXIST') else # 针对老版本通过手机验证码就可以进行账号的创建 user = new UserModel unless mobile mobile = new MobileModel mobile.user = user mobile.phoneNumber = phoneNumber Promise.all [user.$save(), mobile.$save()] .spread (user, mobile) -> mobile .nodeify callback @action 'resetPassword', (req, res, callback) -> {user, newPassword} = req.get() user.password = user.genPassword newPassword $user = user.$save() $user.nodeify callback ################################# HOOKS ################################# # @action 'mobileToUser', (req, res, mobile, callback) -> {user} = mobile return callback(new Err('LOGIN_FAILED', '未成功绑定用户账号')) unless user user.phoneNumber = mobile.phoneNumber user.showname = mobile.showname callback null, user @action 'setAccountToken', (req, res, user, callback) -> user.accountToken = user.genAccountToken login: 'mobile' callback null, user
27509
###* * 手机验证码登录/注册接口 ### Err = require 'err1st' limbo = require 'limbo' config = require 'config' Promise = require 'bluebird' _ = require 'lodash' app = require '../server' util = require '../util' redis = require '../components/redis' { MobileModel UserModel } = limbo.use 'account' module.exports = mobileController = app.controller 'mobile', -> @mixin require './mixins/auth' @mixin require './mixins/cookie' @ratelimit '6,60 15,300', only: 'sendVerifyCode' unless config.debug @ratelimit '20,60 80,300', only: 'bind signin change' @ensure 'phoneNumber', only: 'sendVerifyCode unbind' @ensure 'randomCode verifyCode', only: 'bind change signup' @ensure 'newPassword', only: 'resetPassword' @ensure 'bindCode', only: 'forcebind' @before 'delay1s', only: 'signin signup bind change' unless config.debug @before 'verifyAccount', only: 'bind unbind forcebind change resetPassword' @after 'mobileToUser', only: 'signin signup bind forcebind change signinByVerifyCode' @after 'setAccountToken', only: 'signin signup bind forcebind unbind change signinByVerifyCode resetPassword' @after 'setCookie', only: 'signin signup bind forcebind unbind change signinByVerifyCode' ################################# ACTIONS ################################# ###* * 发送手机验证码,同一号码 30 秒内只可发送一次,有效期 10 分钟 * @return {Object} ok: 1 ### @action 'sendVerifyCode', (req, res, callback) -> {phoneNumber, password, action, uid} = req.get() sentVerifyKey = "<KEY> switch action when 'signup' # 如果是注册操作,验证手机号是否存在,验证是否有 password 参数 if password?.length $check = MobileModel.findOneAsync phoneNumber: phoneNumber .then (mobile) -> throw new Err('ACCOUNT_EXISTS') if mobile else $check = Promise.reject(new Err('PARAMS_MISSING', 'password')) when 'resetpassword' # 如果是重置密码操作,先确认手机号存在 $check = MobileModel.findOneAsync phoneNumber: phoneNumber .then (mobile) -> throw new Err('ACCOUNT_NOT_EXIST') unless mobile # @todo Remove else $check = Promise.resolve() $sent = $check.then -> redis.getAsync sentVerifyKey .then (sent) -> throw new Err('RESEND_TOO_OFTEN') if sent and not process.env.DEBUG options = phoneNumber: phoneNumber ip: req.headers['x-real-ip'] or req.ip _userId: 'new' password: <PASSWORD> uid: uid switch action when 'signup' then options.refer = 'jianliao_register' when 'resetpassword' then options.refer = 'jianliao_resetpassword' else options.refer = 'jianliao_register' $verifyData = MobileModel.sendVerifyCodeAsync options $setSentFlag = $verifyData.then -> redis.setexAsync sentVerifyKey, 60, 1 Promise.all [$verifyData, $setSentFlag] .spread (verifyData) -> verifyData .then (verifyData) -> if config.debug data = _.pick(verifyData, 'randomCode', 'verifyCode') else data = _.pick(verifyData, 'randomCode') .nodeify callback ###* * 验证手机号并返回账号信息,如果手机号已存在,则返回原账号信息 * @return {Model} user - 用户信息 ### @action 'signin', (req, res, callback) -> {phoneNumber, password, randomCode, verifyCode} = req.get() if phoneNumber and password return @signinByPassword req, res, callback if randomCode and verifyCode return @signinByVerifyCode req, res, callback callback(new Err('PARAMS_MISSING', 'phoneNumber, password')) ###* * 手机注册 ### @action 'signup', (req, res, callback) -> {phoneNumber, randomCode, verifyCode} = req.get() # 读取验证码 $verifyData = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> throw new Err('PARAMS_MISSING', 'password') unless verifyData.password verifyData # 检测手机号是否存在 $mobileNotExists = $verifyData.then (verifyData) -> MobileModel.findOneAsync phoneNumber: verifyData.phoneNumber .then (mobile) -> throw new Err('ACCOUNT_EXISTS') if mobile # 创建手机号与用户账号 $mobile = Promise.all [$verifyData, $mobileNotExists] .spread (verifyData) -> # 创建新用户 user = new UserModel user.password = <PASSWORD> verifyData.password mobile = new MobileModel phoneNumber: verifyData.phoneNumber user: user Promise.all [user.$save(), mobile.$save()] .spread (user, mobile) -> mobile # 返回结果 $mobile.nodeify callback @action 'bind', (req, res, callback) -> {user, verifyCode, randomCode} = req.get() $phoneNumber = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> verifyData.phoneNumber $mobile = $phoneNumber.then (phoneNumber) -> MobileModel.findOne phoneNumber: phoneNumber .execAsync() .then (mobile) -> if mobile?.user # 生成 bindCode 并返回错误信息 return $bindCode = mobile.genBindCodeAsync().then (bindCode) -> err = new Err('BIND_CONFLICT') err.data = bindCode: bindCode showname: phoneNumber throw err if mobile mobile.user = user else mobile = new MobileModel phoneNumber: phoneNumber user: user mobile.updatedAt = new Date mobile $cleanupOtherMobiles = $mobile.then (mobile) -> MobileModel.removeAsync user: user._id phoneNumber: $ne: mobile.phoneNumber $mobile = Promise.all [$mobile, $cleanupOtherMobiles] .spread (mobile) -> mobile.$save() $mobile.nodeify callback @action 'change', (req, res, callback) -> @bind req, res, callback @action 'forcebind', (req, res, callback) -> {user, bindCode} = req.get() $mobile = MobileModel.verifyBindCodeAsync bindCode $mobile = $mobile.then (mobile) -> mobile.user = user mobile.updatedAt = new Date mobile.$save() $cleanupOtherMobiles = $mobile.then (mobile) -> MobileModel.removeAsync user: user._id phoneNumber: $ne: mobile.phoneNumber Promise.all [$mobile, $cleanupOtherMobiles] .spread (mobile) -> mobile .nodeify callback @action 'unbind', (req, res, callback) -> {user, phoneNumber} = req.get() $mobile = MobileModel.findOneAsync user: user._id phoneNumber: phoneNumber .then (mobile) -> if mobile?.user mobile.$remove() $user = $mobile.then -> user .nodeify callback @action 'signinByPassword', (req, res, callback) -> {phoneNumber, password} = req.get() $mobile = MobileModel.findOne phoneNumber: phoneNumber .populate 'user' .execAsync() .then (mobile) -> throw new Err('LOGIN_VERIFY_FAILED') unless mobile?.user throw new Err('NO_PASSWORD') unless mobile?.user?.password mobile.user.verifyPasswordAsync password .then -> mobile $mobile.nodeify callback @action 'signinByVerifyCode', (req, res, callback) -> {verifyCode, randomCode, action} = req.get() $phoneNumber = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> verifyData.phoneNumber $mobile = $phoneNumber.then (phoneNumber) -> # 根据手机号查找老用户 MobileModel.findOne phoneNumber: phoneNumber .populate 'user' .execAsync() .then (mobile) -> return mobile if mobile?.user if action is 'resetpassword' throw new Err('ACCOUNT_NOT_EXIST') else # 针对老版本通过手机验证码就可以进行账号的创建 user = new UserModel unless mobile mobile = new MobileModel mobile.user = user mobile.phoneNumber = phoneNumber Promise.all [user.$save(), mobile.$save()] .spread (user, mobile) -> mobile .nodeify callback @action 'resetPassword', (req, res, callback) -> {user, newPassword} = req.get() user.password = user.genPassword newPassword $user = user.$save() $user.nodeify callback ################################# HOOKS ################################# # @action 'mobileToUser', (req, res, mobile, callback) -> {user} = mobile return callback(new Err('LOGIN_FAILED', '未成功绑定用户账号')) unless user user.phoneNumber = mobile.phoneNumber user.showname = mobile.showname callback null, user @action 'setAccountToken', (req, res, user, callback) -> user.accountToken = <PASSWORD>.genAccountToken login: 'mobile' callback null, user
true
###* * 手机验证码登录/注册接口 ### Err = require 'err1st' limbo = require 'limbo' config = require 'config' Promise = require 'bluebird' _ = require 'lodash' app = require '../server' util = require '../util' redis = require '../components/redis' { MobileModel UserModel } = limbo.use 'account' module.exports = mobileController = app.controller 'mobile', -> @mixin require './mixins/auth' @mixin require './mixins/cookie' @ratelimit '6,60 15,300', only: 'sendVerifyCode' unless config.debug @ratelimit '20,60 80,300', only: 'bind signin change' @ensure 'phoneNumber', only: 'sendVerifyCode unbind' @ensure 'randomCode verifyCode', only: 'bind change signup' @ensure 'newPassword', only: 'resetPassword' @ensure 'bindCode', only: 'forcebind' @before 'delay1s', only: 'signin signup bind change' unless config.debug @before 'verifyAccount', only: 'bind unbind forcebind change resetPassword' @after 'mobileToUser', only: 'signin signup bind forcebind change signinByVerifyCode' @after 'setAccountToken', only: 'signin signup bind forcebind unbind change signinByVerifyCode resetPassword' @after 'setCookie', only: 'signin signup bind forcebind unbind change signinByVerifyCode' ################################# ACTIONS ################################# ###* * 发送手机验证码,同一号码 30 秒内只可发送一次,有效期 10 分钟 * @return {Object} ok: 1 ### @action 'sendVerifyCode', (req, res, callback) -> {phoneNumber, password, action, uid} = req.get() sentVerifyKey = "PI:KEY:<KEY>END_PI switch action when 'signup' # 如果是注册操作,验证手机号是否存在,验证是否有 password 参数 if password?.length $check = MobileModel.findOneAsync phoneNumber: phoneNumber .then (mobile) -> throw new Err('ACCOUNT_EXISTS') if mobile else $check = Promise.reject(new Err('PARAMS_MISSING', 'password')) when 'resetpassword' # 如果是重置密码操作,先确认手机号存在 $check = MobileModel.findOneAsync phoneNumber: phoneNumber .then (mobile) -> throw new Err('ACCOUNT_NOT_EXIST') unless mobile # @todo Remove else $check = Promise.resolve() $sent = $check.then -> redis.getAsync sentVerifyKey .then (sent) -> throw new Err('RESEND_TOO_OFTEN') if sent and not process.env.DEBUG options = phoneNumber: phoneNumber ip: req.headers['x-real-ip'] or req.ip _userId: 'new' password: PI:PASSWORD:<PASSWORD>END_PI uid: uid switch action when 'signup' then options.refer = 'jianliao_register' when 'resetpassword' then options.refer = 'jianliao_resetpassword' else options.refer = 'jianliao_register' $verifyData = MobileModel.sendVerifyCodeAsync options $setSentFlag = $verifyData.then -> redis.setexAsync sentVerifyKey, 60, 1 Promise.all [$verifyData, $setSentFlag] .spread (verifyData) -> verifyData .then (verifyData) -> if config.debug data = _.pick(verifyData, 'randomCode', 'verifyCode') else data = _.pick(verifyData, 'randomCode') .nodeify callback ###* * 验证手机号并返回账号信息,如果手机号已存在,则返回原账号信息 * @return {Model} user - 用户信息 ### @action 'signin', (req, res, callback) -> {phoneNumber, password, randomCode, verifyCode} = req.get() if phoneNumber and password return @signinByPassword req, res, callback if randomCode and verifyCode return @signinByVerifyCode req, res, callback callback(new Err('PARAMS_MISSING', 'phoneNumber, password')) ###* * 手机注册 ### @action 'signup', (req, res, callback) -> {phoneNumber, randomCode, verifyCode} = req.get() # 读取验证码 $verifyData = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> throw new Err('PARAMS_MISSING', 'password') unless verifyData.password verifyData # 检测手机号是否存在 $mobileNotExists = $verifyData.then (verifyData) -> MobileModel.findOneAsync phoneNumber: verifyData.phoneNumber .then (mobile) -> throw new Err('ACCOUNT_EXISTS') if mobile # 创建手机号与用户账号 $mobile = Promise.all [$verifyData, $mobileNotExists] .spread (verifyData) -> # 创建新用户 user = new UserModel user.password = PI:PASSWORD:<PASSWORD>END_PI verifyData.password mobile = new MobileModel phoneNumber: verifyData.phoneNumber user: user Promise.all [user.$save(), mobile.$save()] .spread (user, mobile) -> mobile # 返回结果 $mobile.nodeify callback @action 'bind', (req, res, callback) -> {user, verifyCode, randomCode} = req.get() $phoneNumber = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> verifyData.phoneNumber $mobile = $phoneNumber.then (phoneNumber) -> MobileModel.findOne phoneNumber: phoneNumber .execAsync() .then (mobile) -> if mobile?.user # 生成 bindCode 并返回错误信息 return $bindCode = mobile.genBindCodeAsync().then (bindCode) -> err = new Err('BIND_CONFLICT') err.data = bindCode: bindCode showname: phoneNumber throw err if mobile mobile.user = user else mobile = new MobileModel phoneNumber: phoneNumber user: user mobile.updatedAt = new Date mobile $cleanupOtherMobiles = $mobile.then (mobile) -> MobileModel.removeAsync user: user._id phoneNumber: $ne: mobile.phoneNumber $mobile = Promise.all [$mobile, $cleanupOtherMobiles] .spread (mobile) -> mobile.$save() $mobile.nodeify callback @action 'change', (req, res, callback) -> @bind req, res, callback @action 'forcebind', (req, res, callback) -> {user, bindCode} = req.get() $mobile = MobileModel.verifyBindCodeAsync bindCode $mobile = $mobile.then (mobile) -> mobile.user = user mobile.updatedAt = new Date mobile.$save() $cleanupOtherMobiles = $mobile.then (mobile) -> MobileModel.removeAsync user: user._id phoneNumber: $ne: mobile.phoneNumber Promise.all [$mobile, $cleanupOtherMobiles] .spread (mobile) -> mobile .nodeify callback @action 'unbind', (req, res, callback) -> {user, phoneNumber} = req.get() $mobile = MobileModel.findOneAsync user: user._id phoneNumber: phoneNumber .then (mobile) -> if mobile?.user mobile.$remove() $user = $mobile.then -> user .nodeify callback @action 'signinByPassword', (req, res, callback) -> {phoneNumber, password} = req.get() $mobile = MobileModel.findOne phoneNumber: phoneNumber .populate 'user' .execAsync() .then (mobile) -> throw new Err('LOGIN_VERIFY_FAILED') unless mobile?.user throw new Err('NO_PASSWORD') unless mobile?.user?.password mobile.user.verifyPasswordAsync password .then -> mobile $mobile.nodeify callback @action 'signinByVerifyCode', (req, res, callback) -> {verifyCode, randomCode, action} = req.get() $phoneNumber = MobileModel.verifyAsync randomCode, verifyCode .then (verifyData) -> verifyData.phoneNumber $mobile = $phoneNumber.then (phoneNumber) -> # 根据手机号查找老用户 MobileModel.findOne phoneNumber: phoneNumber .populate 'user' .execAsync() .then (mobile) -> return mobile if mobile?.user if action is 'resetpassword' throw new Err('ACCOUNT_NOT_EXIST') else # 针对老版本通过手机验证码就可以进行账号的创建 user = new UserModel unless mobile mobile = new MobileModel mobile.user = user mobile.phoneNumber = phoneNumber Promise.all [user.$save(), mobile.$save()] .spread (user, mobile) -> mobile .nodeify callback @action 'resetPassword', (req, res, callback) -> {user, newPassword} = req.get() user.password = user.genPassword newPassword $user = user.$save() $user.nodeify callback ################################# HOOKS ################################# # @action 'mobileToUser', (req, res, mobile, callback) -> {user} = mobile return callback(new Err('LOGIN_FAILED', '未成功绑定用户账号')) unless user user.phoneNumber = mobile.phoneNumber user.showname = mobile.showname callback null, user @action 'setAccountToken', (req, res, user, callback) -> user.accountToken = PI:PASSWORD:<PASSWORD>END_PI.genAccountToken login: 'mobile' callback null, user
[ { "context": "erface and experience for your app.\n *\n * @author André Lademann <vergissberlin@googlemail.com>\n * @link https:", "end": 462, "score": 0.9998708963394165, "start": 448, "tag": "NAME", "value": "André Lademann" }, { "context": "ence for your app.\n *\n * @author André Lademann <vergissberlin@googlemail.com>\n * @link https://www.firebase.com/docs/web/gu", "end": 492, "score": 0.9999324083328247, "start": 464, "tag": "EMAIL", "value": "vergissberlin@googlemail.com" } ]
src/firebase-login-custom.coffee
vergissberlin/firebase-login-custom
1
###* * FirebaseLoginCustom * * Authenticating Users with Custom login * Firebase makes it easy to integrate email and password authentication * into your app. Firebase automatically stores your users' credentials * securely (using bcrypt) and redundantly (daily off-site backups). * This separates sensitive user credentials from your application data, * and lets you focus on the user interface and experience for your app. * * @author André Lademann <vergissberlin@googlemail.com> * @link https://www.firebase.com/docs/web/guide/login/password.html * @param {*} ref Firebase object reference * @param {*} data Authentication object with uid and secret * @param {*} option Option object with admin, debug and expire settingst * @param {*} callback Callback function * @return {*} FirebaseLoginCustom ### class FirebaseLoginCustom constructor: (ref, data = {}, option = { admin: false expires: false debug: false notBefore: false }, callback = ->) -> # Requirements FirebaseTokenGenerator = require('firebase-token-generator') ## Defaults # admin (Boolean) - Set to true if you want to disable all security # rules for this client. This will provide the client with read and # write access to your entire Firebase. if typeof option.admin isnt 'boolean' option.admin = false # debug (Boolean) - Set to true to enable debug output from your # security rules. his debug output will be automatically output to # the JavaScript console. You should generally not leave this set to # true in production (as it slows down the rules implementation and # gives your users visibility into your rules), but it can be helpful # for debugging. if typeof option.debug isnt 'boolean' option.debug = false # expires (Number) - A timestamp (as number of seconds since the epoch) # denoting the time after which this token should no longer be valid. if typeof option.expires isnt 'number' option.expires = +new Date / 1000 + 86400 # notBefore (Number) - A timestamp (as number of seconds since the epoch) # denoting the time before which this token should be rejected by the # server. if typeof option.notBefore isnt 'number' option.notBefore = +new Date / 1000 ## Validation if typeof ref isnt 'object' throw new Error 'Ref must be an object!' if typeof data.uid isnt 'string' throw new Error 'Data object must have an "uid" field!' if typeof option.secret isnt 'string' throw new Error 'Option object must have an "secret" field!' if typeof callback isnt "function" throw new Error 'Callback must be a function!' # Generate token tokenGenerator = new FirebaseTokenGenerator(option.secret) authToken = tokenGenerator.createToken( data, { admin: option.admin debug: option.debug expires: option.expires notBefore: option.notBefore } ) # Authentication ref.authWithCustomToken authToken, (error, authData)-> if error switch error.code when 'INVALID_EMAIL' error = 'The specified user account email is invalid.' when 'INVALID_PASSWORD' error = 'The specified user account password is incorrect.' when 'INVALID_USER' error = 'The specified user account does not exist.' else error = 'Error logging user in: ' + error.toString() callback error, authData module.exports = FirebaseLoginCustom
129441
###* * FirebaseLoginCustom * * Authenticating Users with Custom login * Firebase makes it easy to integrate email and password authentication * into your app. Firebase automatically stores your users' credentials * securely (using bcrypt) and redundantly (daily off-site backups). * This separates sensitive user credentials from your application data, * and lets you focus on the user interface and experience for your app. * * @author <NAME> <<EMAIL>> * @link https://www.firebase.com/docs/web/guide/login/password.html * @param {*} ref Firebase object reference * @param {*} data Authentication object with uid and secret * @param {*} option Option object with admin, debug and expire settingst * @param {*} callback Callback function * @return {*} FirebaseLoginCustom ### class FirebaseLoginCustom constructor: (ref, data = {}, option = { admin: false expires: false debug: false notBefore: false }, callback = ->) -> # Requirements FirebaseTokenGenerator = require('firebase-token-generator') ## Defaults # admin (Boolean) - Set to true if you want to disable all security # rules for this client. This will provide the client with read and # write access to your entire Firebase. if typeof option.admin isnt 'boolean' option.admin = false # debug (Boolean) - Set to true to enable debug output from your # security rules. his debug output will be automatically output to # the JavaScript console. You should generally not leave this set to # true in production (as it slows down the rules implementation and # gives your users visibility into your rules), but it can be helpful # for debugging. if typeof option.debug isnt 'boolean' option.debug = false # expires (Number) - A timestamp (as number of seconds since the epoch) # denoting the time after which this token should no longer be valid. if typeof option.expires isnt 'number' option.expires = +new Date / 1000 + 86400 # notBefore (Number) - A timestamp (as number of seconds since the epoch) # denoting the time before which this token should be rejected by the # server. if typeof option.notBefore isnt 'number' option.notBefore = +new Date / 1000 ## Validation if typeof ref isnt 'object' throw new Error 'Ref must be an object!' if typeof data.uid isnt 'string' throw new Error 'Data object must have an "uid" field!' if typeof option.secret isnt 'string' throw new Error 'Option object must have an "secret" field!' if typeof callback isnt "function" throw new Error 'Callback must be a function!' # Generate token tokenGenerator = new FirebaseTokenGenerator(option.secret) authToken = tokenGenerator.createToken( data, { admin: option.admin debug: option.debug expires: option.expires notBefore: option.notBefore } ) # Authentication ref.authWithCustomToken authToken, (error, authData)-> if error switch error.code when 'INVALID_EMAIL' error = 'The specified user account email is invalid.' when 'INVALID_PASSWORD' error = 'The specified user account password is incorrect.' when 'INVALID_USER' error = 'The specified user account does not exist.' else error = 'Error logging user in: ' + error.toString() callback error, authData module.exports = FirebaseLoginCustom
true
###* * FirebaseLoginCustom * * Authenticating Users with Custom login * Firebase makes it easy to integrate email and password authentication * into your app. Firebase automatically stores your users' credentials * securely (using bcrypt) and redundantly (daily off-site backups). * This separates sensitive user credentials from your application data, * and lets you focus on the user interface and experience for your app. * * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * @link https://www.firebase.com/docs/web/guide/login/password.html * @param {*} ref Firebase object reference * @param {*} data Authentication object with uid and secret * @param {*} option Option object with admin, debug and expire settingst * @param {*} callback Callback function * @return {*} FirebaseLoginCustom ### class FirebaseLoginCustom constructor: (ref, data = {}, option = { admin: false expires: false debug: false notBefore: false }, callback = ->) -> # Requirements FirebaseTokenGenerator = require('firebase-token-generator') ## Defaults # admin (Boolean) - Set to true if you want to disable all security # rules for this client. This will provide the client with read and # write access to your entire Firebase. if typeof option.admin isnt 'boolean' option.admin = false # debug (Boolean) - Set to true to enable debug output from your # security rules. his debug output will be automatically output to # the JavaScript console. You should generally not leave this set to # true in production (as it slows down the rules implementation and # gives your users visibility into your rules), but it can be helpful # for debugging. if typeof option.debug isnt 'boolean' option.debug = false # expires (Number) - A timestamp (as number of seconds since the epoch) # denoting the time after which this token should no longer be valid. if typeof option.expires isnt 'number' option.expires = +new Date / 1000 + 86400 # notBefore (Number) - A timestamp (as number of seconds since the epoch) # denoting the time before which this token should be rejected by the # server. if typeof option.notBefore isnt 'number' option.notBefore = +new Date / 1000 ## Validation if typeof ref isnt 'object' throw new Error 'Ref must be an object!' if typeof data.uid isnt 'string' throw new Error 'Data object must have an "uid" field!' if typeof option.secret isnt 'string' throw new Error 'Option object must have an "secret" field!' if typeof callback isnt "function" throw new Error 'Callback must be a function!' # Generate token tokenGenerator = new FirebaseTokenGenerator(option.secret) authToken = tokenGenerator.createToken( data, { admin: option.admin debug: option.debug expires: option.expires notBefore: option.notBefore } ) # Authentication ref.authWithCustomToken authToken, (error, authData)-> if error switch error.code when 'INVALID_EMAIL' error = 'The specified user account email is invalid.' when 'INVALID_PASSWORD' error = 'The specified user account password is incorrect.' when 'INVALID_USER' error = 'The specified user account does not exist.' else error = 'Error logging user in: ' + error.toString() callback error, authData module.exports = FirebaseLoginCustom
[ { "context": "itPresence @cName, @docName, {v:0, val:{id:{name:'seph'}}}, (err) =>\n throw new Error err if err\n", "end": 869, "score": 0.9987878203392029, "start": 865, "tag": "NAME", "value": "seph" }, { "context": ">\n assert.deepEqual presence, {id:{name:'seph'}}\n done()\n\n it \"lets you set a user'", "end": 1038, "score": 0.9985549449920654, "start": 1034, "tag": "NAME", "value": "seph" }, { "context": "ence @cName, @docName, {v:0, p:['id'], val:{name:'seph'}}, (err) =>\n throw new Error err if err\n ", "end": 1194, "score": 0.998355507850647, "start": 1190, "tag": "NAME", "value": "seph" }, { "context": ">\n assert.deepEqual presence, {id:{name:'seph'}}\n done()\n\n it 'lets you set a field", "end": 1362, "score": 0.9987008571624756, "start": 1358, "tag": "NAME", "value": "seph" }, { "context": ">\n assert.deepEqual presence, {id:{name:'ian'}}\n done()\n\n it 'lets you edit withou", "end": 1681, "score": 0.9984941482543945, "start": 1678, "tag": "NAME", "value": "ian" }, { "context": ">\n assert.deepEqual presence, {id:{name:'ian'}}\n done()\n\n it 'lets you change a fi", "end": 2016, "score": 0.9981845021247864, "start": 2013, "tag": "NAME", "value": "ian" }, { "context": "ence @cName, @docName, {v:0, p:['id'], val:{name:'seph'}}, (err) =>\n throw new Error err if err\n ", "end": 2160, "score": 0.9981367588043213, "start": 2156, "tag": "NAME", "value": "seph" }, { "context": "ce @cName, @docName, {v:0, p:['id', 'name'], val:'nate'}, (err) =>\n throw new Error err if err\n", "end": 2291, "score": 0.983778715133667, "start": 2287, "tag": "NAME", "value": "nate" }, { "context": " assert.deepEqual presence, {id:{name:'nate'}}\n done()\n\n it 'does not let you s", "end": 2464, "score": 0.9986070990562439, "start": 2460, "tag": "NAME", "value": "nate" }, { "context": "nce @cName, @docName, {v:0, p:['id'], val:{_name:'seph'}}, (err) =>\n assert.strictEqual err, 'Can", "end": 2656, "score": 0.9710127115249634, "start": 2652, "tag": "NAME", "value": "seph" } ]
test/presence.coffee
kantele/k-livedb
1
assert = require 'assert' {createClient, createDoc, setup, teardown} = require './util' # This isn't working at the moment - we regressed. describe.skip 'presence', -> beforeEach setup afterEach teardown describe 'fetch and set', -> it 'fetchPresence on a doc with no presence data returns {}', (done) -> @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {} done() it 'subscribe returns empty presence data for an empty doc', (done) -> @client.subscribe @cName, @docName, 0, wantPresence:yes, (err, stream, presence) => throw new Error err if err assert.deepEqual presence, {} done() it 'lets you set presence data for the whole document', (done) -> @client.submitPresence @cName, @docName, {v:0, val:{id:{name:'seph'}}}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'seph'}} done() it "lets you set a user's presence data", (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{name:'seph'}}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'seph'}} done() it 'lets you set a field', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id', 'name'], val:'ian'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'ian'}} done() it 'lets you edit without a version specified', (done) -> @create => @client.submitPresence @cName, @docName, {p:['id', 'name'], val:'ian'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'ian'}} done() it 'lets you change a field', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{name:'seph'}}, (err) => throw new Error err if err @client.submitPresence @cName, @docName, {v:0, p:['id', 'name'], val:'nate'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'nate'}} done() it 'does not let you set reserved (underscored) values other than cursor', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{_name:'seph'}}, (err) => assert.strictEqual err, 'Cannot set reserved value' done() it.skip 'does not let you set _cursor for a nonexistant doc', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{_cursor:6}}, (err) => assert.strictEqual err, 'Cannot set reserved value' done() it 'does let you set _cursor for a document', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{_cursor:0}}, (err) => throw new Error err if err @client.submitPresence @cName, @docName, {v:1, p:['id', '_cursor'], val:1}, (err) => throw new Error err if err done() describe 'edits from ops', -> it 'deletes the cursor when a document is deleted', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{x:'y', _cursor:0}}, (err) => throw new Error err if err @collection.submit @docName, v:1, del:true, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {id:{x:'y'}} done() it 'moves the cursor when text is edited', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{_cursor:[1,1]}}, (err) => throw new Error err if err @collection.submit @docName, v:1, op:['hi'], (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {id:{_cursor:[3,3]}} done() describe 'subscribe', -> it.skip 'propogates presence ops to subscribers', (done) -> @create => # This test currently fails @client.subscribe @cName, @docName, 0, wantPresence:yes, (err, stream, presence) => @client.submit @cName, @docName, v:1, op:['hi'] throw new Error err if err assert.deepEqual presence, {} stream.on 'data', (data) -> console.log 'got data', data # assert.deepEqual data, {} # done() @client.submitPresence @cName, @docName, {v:0, id:'id', value:{x:'y'}}, (err) => throw new Error err if err
125194
assert = require 'assert' {createClient, createDoc, setup, teardown} = require './util' # This isn't working at the moment - we regressed. describe.skip 'presence', -> beforeEach setup afterEach teardown describe 'fetch and set', -> it 'fetchPresence on a doc with no presence data returns {}', (done) -> @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {} done() it 'subscribe returns empty presence data for an empty doc', (done) -> @client.subscribe @cName, @docName, 0, wantPresence:yes, (err, stream, presence) => throw new Error err if err assert.deepEqual presence, {} done() it 'lets you set presence data for the whole document', (done) -> @client.submitPresence @cName, @docName, {v:0, val:{id:{name:'<NAME>'}}}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'<NAME>'}} done() it "lets you set a user's presence data", (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{name:'<NAME>'}}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'<NAME>'}} done() it 'lets you set a field', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id', 'name'], val:'ian'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'<NAME>'}} done() it 'lets you edit without a version specified', (done) -> @create => @client.submitPresence @cName, @docName, {p:['id', 'name'], val:'ian'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'<NAME>'}} done() it 'lets you change a field', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{name:'<NAME>'}}, (err) => throw new Error err if err @client.submitPresence @cName, @docName, {v:0, p:['id', 'name'], val:'<NAME>'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'<NAME>'}} done() it 'does not let you set reserved (underscored) values other than cursor', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{_name:'<NAME>'}}, (err) => assert.strictEqual err, 'Cannot set reserved value' done() it.skip 'does not let you set _cursor for a nonexistant doc', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{_cursor:6}}, (err) => assert.strictEqual err, 'Cannot set reserved value' done() it 'does let you set _cursor for a document', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{_cursor:0}}, (err) => throw new Error err if err @client.submitPresence @cName, @docName, {v:1, p:['id', '_cursor'], val:1}, (err) => throw new Error err if err done() describe 'edits from ops', -> it 'deletes the cursor when a document is deleted', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{x:'y', _cursor:0}}, (err) => throw new Error err if err @collection.submit @docName, v:1, del:true, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {id:{x:'y'}} done() it 'moves the cursor when text is edited', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{_cursor:[1,1]}}, (err) => throw new Error err if err @collection.submit @docName, v:1, op:['hi'], (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {id:{_cursor:[3,3]}} done() describe 'subscribe', -> it.skip 'propogates presence ops to subscribers', (done) -> @create => # This test currently fails @client.subscribe @cName, @docName, 0, wantPresence:yes, (err, stream, presence) => @client.submit @cName, @docName, v:1, op:['hi'] throw new Error err if err assert.deepEqual presence, {} stream.on 'data', (data) -> console.log 'got data', data # assert.deepEqual data, {} # done() @client.submitPresence @cName, @docName, {v:0, id:'id', value:{x:'y'}}, (err) => throw new Error err if err
true
assert = require 'assert' {createClient, createDoc, setup, teardown} = require './util' # This isn't working at the moment - we regressed. describe.skip 'presence', -> beforeEach setup afterEach teardown describe 'fetch and set', -> it 'fetchPresence on a doc with no presence data returns {}', (done) -> @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {} done() it 'subscribe returns empty presence data for an empty doc', (done) -> @client.subscribe @cName, @docName, 0, wantPresence:yes, (err, stream, presence) => throw new Error err if err assert.deepEqual presence, {} done() it 'lets you set presence data for the whole document', (done) -> @client.submitPresence @cName, @docName, {v:0, val:{id:{name:'PI:NAME:<NAME>END_PI'}}}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'PI:NAME:<NAME>END_PI'}} done() it "lets you set a user's presence data", (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{name:'PI:NAME:<NAME>END_PI'}}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'PI:NAME:<NAME>END_PI'}} done() it 'lets you set a field', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id', 'name'], val:'ian'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'PI:NAME:<NAME>END_PI'}} done() it 'lets you edit without a version specified', (done) -> @create => @client.submitPresence @cName, @docName, {p:['id', 'name'], val:'ian'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'PI:NAME:<NAME>END_PI'}} done() it 'lets you change a field', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{name:'PI:NAME:<NAME>END_PI'}}, (err) => throw new Error err if err @client.submitPresence @cName, @docName, {v:0, p:['id', 'name'], val:'PI:NAME:<NAME>END_PI'}, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> assert.deepEqual presence, {id:{name:'PI:NAME:<NAME>END_PI'}} done() it 'does not let you set reserved (underscored) values other than cursor', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{_name:'PI:NAME:<NAME>END_PI'}}, (err) => assert.strictEqual err, 'Cannot set reserved value' done() it.skip 'does not let you set _cursor for a nonexistant doc', (done) -> @client.submitPresence @cName, @docName, {v:0, p:['id'], val:{_cursor:6}}, (err) => assert.strictEqual err, 'Cannot set reserved value' done() it 'does let you set _cursor for a document', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{_cursor:0}}, (err) => throw new Error err if err @client.submitPresence @cName, @docName, {v:1, p:['id', '_cursor'], val:1}, (err) => throw new Error err if err done() describe 'edits from ops', -> it 'deletes the cursor when a document is deleted', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{x:'y', _cursor:0}}, (err) => throw new Error err if err @collection.submit @docName, v:1, del:true, (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {id:{x:'y'}} done() it 'moves the cursor when text is edited', (done) -> @create => @client.submitPresence @cName, @docName, {v:1, p:['id'], val:{_cursor:[1,1]}}, (err) => throw new Error err if err @collection.submit @docName, v:1, op:['hi'], (err) => throw new Error err if err @client.fetchPresence @cName, @docName, (err, presence) -> throw new Error err if err assert.deepEqual presence, {id:{_cursor:[3,3]}} done() describe 'subscribe', -> it.skip 'propogates presence ops to subscribers', (done) -> @create => # This test currently fails @client.subscribe @cName, @docName, 0, wantPresence:yes, (err, stream, presence) => @client.submit @cName, @docName, v:1, op:['hi'] throw new Error err if err assert.deepEqual presence, {} stream.on 'data', (data) -> console.log 'got data', data # assert.deepEqual data, {} # done() @client.submitPresence @cName, @docName, {v:0, id:'id', value:{x:'y'}}, (err) => throw new Error err if err
[ { "context": "qualizer on config change\n showEqualizerKey = \"Rdio.#{RdioView.CONFIGS.showEqualizer.key}\"\n this.subs", "end": 2402, "score": 0.8745219111442566, "start": 2395, "tag": "KEY", "value": "Rdio.#{" } ]
lib/rdio-view.coffee
stramel/atom-music
1
{View} = require 'atom' open = require 'open' md5 = require 'MD5' RdioDesktop = require './rdio-desktop' module.exports = class RdioView extends View @CONFIGS = { showEqualizer: key: 'showEqualizer (WindowResizePerformanceIssue )' action: 'toggleEqualizer' default: true } @content: -> @div class: 'rdio', => @div outlet: 'container', class: 'rdio-container inline-block', => @span outlet: 'soundBars', class: 'rdio-sound-bars', => @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @a outlet: 'currentlyPlaying', href: 'javascript:','' initialize: -> @currentTrack = {} @currentState = null @initiated = false @rdioDesktop = new RdioDesktop this.addCommands() # Make sure the view gets added last if atom.workspaceView.statusBar this.attach() else this.subscribe atom.packages.once 'activated', => setTimeout this.attach, 1 destroy: -> this.detach() # Commands addCommands: -> # Defaults for command in RdioDesktop.COMMANDS do (command) => atom.workspaceView.command "rdio:#{command.name}", '.editor', => @rdioDesktop[command.name]() # Open current track with Rdio.app atom.workspaceView.command 'rdio:open-current-track', '.editor', => this.openWithRdio(@currentlyPlaying.attr('href')) # Play song based on current file or selection atom.workspaceView.command 'rdio:play-code-mood', '.editor', this.currentMood # Current mood currentMood: => editor = atom.workspaceView.getActivePaneItem() content = (editor.getSelectedText() || editor.getText()).replace(/(\n)/gm, '') # Get the first 7 digits of the md5 string digits = md5(content).replace(/\D/g, '').substring(0, 6) console.log "Rdio Code Mood: See http://rdioconsole.appspot.com/#keys%3Dt#{digits}%26method%3Dget for more track info." @rdioDesktop.playTrack(digits) # Attach the view to the farthest right of the status bar attach: => atom.workspaceView.statusBar.appendRight(this) # Navigate to current track inside Rdio @currentlyPlaying.on 'click', (e) => this.openWithRdio(e.currentTarget.href) # Toggle equalizer on config change showEqualizerKey = "Rdio.#{RdioView.CONFIGS.showEqualizer.key}" this.subscribe atom.config.observe showEqualizerKey, callNow: true, => if atom.config.get(showEqualizerKey) @soundBars.removeAttr('data-hidden') else @soundBars.attr('data-hidden', true) openWithRdio: (href) -> open(href) afterAttach: => setInterval => @rdioDesktop.currentState (state) => if state isnt @currentState @currentState = state @soundBars.attr('data-state', state) # Rdio is closed if state is undefined if @initiated @initiated = false @currentTrack = {} @container.removeAttr('data-initiated') return # Rdio is paused, but we know about the current track return if state is 'paused' and @initiated # Get current track data @rdioDesktop.currentlyPlaying (data) => return unless data.artist and data.track return if data.artist is @currentTrack.artist and data.track is @currentTrack.track @currentlyPlaying.text "#{data.artist} - #{data.track}" @currentlyPlaying.attr 'href', "rdio://www.rdio.com#{data.url}" @currentTrack = data # Display container when hidden return if @initiated @initiated = true @container.attr('data-initiated', true) , 1500
93713
{View} = require 'atom' open = require 'open' md5 = require 'MD5' RdioDesktop = require './rdio-desktop' module.exports = class RdioView extends View @CONFIGS = { showEqualizer: key: 'showEqualizer (WindowResizePerformanceIssue )' action: 'toggleEqualizer' default: true } @content: -> @div class: 'rdio', => @div outlet: 'container', class: 'rdio-container inline-block', => @span outlet: 'soundBars', class: 'rdio-sound-bars', => @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @a outlet: 'currentlyPlaying', href: 'javascript:','' initialize: -> @currentTrack = {} @currentState = null @initiated = false @rdioDesktop = new RdioDesktop this.addCommands() # Make sure the view gets added last if atom.workspaceView.statusBar this.attach() else this.subscribe atom.packages.once 'activated', => setTimeout this.attach, 1 destroy: -> this.detach() # Commands addCommands: -> # Defaults for command in RdioDesktop.COMMANDS do (command) => atom.workspaceView.command "rdio:#{command.name}", '.editor', => @rdioDesktop[command.name]() # Open current track with Rdio.app atom.workspaceView.command 'rdio:open-current-track', '.editor', => this.openWithRdio(@currentlyPlaying.attr('href')) # Play song based on current file or selection atom.workspaceView.command 'rdio:play-code-mood', '.editor', this.currentMood # Current mood currentMood: => editor = atom.workspaceView.getActivePaneItem() content = (editor.getSelectedText() || editor.getText()).replace(/(\n)/gm, '') # Get the first 7 digits of the md5 string digits = md5(content).replace(/\D/g, '').substring(0, 6) console.log "Rdio Code Mood: See http://rdioconsole.appspot.com/#keys%3Dt#{digits}%26method%3Dget for more track info." @rdioDesktop.playTrack(digits) # Attach the view to the farthest right of the status bar attach: => atom.workspaceView.statusBar.appendRight(this) # Navigate to current track inside Rdio @currentlyPlaying.on 'click', (e) => this.openWithRdio(e.currentTarget.href) # Toggle equalizer on config change showEqualizerKey = "<KEY>RdioView.CONFIGS.showEqualizer.key}" this.subscribe atom.config.observe showEqualizerKey, callNow: true, => if atom.config.get(showEqualizerKey) @soundBars.removeAttr('data-hidden') else @soundBars.attr('data-hidden', true) openWithRdio: (href) -> open(href) afterAttach: => setInterval => @rdioDesktop.currentState (state) => if state isnt @currentState @currentState = state @soundBars.attr('data-state', state) # Rdio is closed if state is undefined if @initiated @initiated = false @currentTrack = {} @container.removeAttr('data-initiated') return # Rdio is paused, but we know about the current track return if state is 'paused' and @initiated # Get current track data @rdioDesktop.currentlyPlaying (data) => return unless data.artist and data.track return if data.artist is @currentTrack.artist and data.track is @currentTrack.track @currentlyPlaying.text "#{data.artist} - #{data.track}" @currentlyPlaying.attr 'href', "rdio://www.rdio.com#{data.url}" @currentTrack = data # Display container when hidden return if @initiated @initiated = true @container.attr('data-initiated', true) , 1500
true
{View} = require 'atom' open = require 'open' md5 = require 'MD5' RdioDesktop = require './rdio-desktop' module.exports = class RdioView extends View @CONFIGS = { showEqualizer: key: 'showEqualizer (WindowResizePerformanceIssue )' action: 'toggleEqualizer' default: true } @content: -> @div class: 'rdio', => @div outlet: 'container', class: 'rdio-container inline-block', => @span outlet: 'soundBars', class: 'rdio-sound-bars', => @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @span class: 'rdio-sound-bar' @a outlet: 'currentlyPlaying', href: 'javascript:','' initialize: -> @currentTrack = {} @currentState = null @initiated = false @rdioDesktop = new RdioDesktop this.addCommands() # Make sure the view gets added last if atom.workspaceView.statusBar this.attach() else this.subscribe atom.packages.once 'activated', => setTimeout this.attach, 1 destroy: -> this.detach() # Commands addCommands: -> # Defaults for command in RdioDesktop.COMMANDS do (command) => atom.workspaceView.command "rdio:#{command.name}", '.editor', => @rdioDesktop[command.name]() # Open current track with Rdio.app atom.workspaceView.command 'rdio:open-current-track', '.editor', => this.openWithRdio(@currentlyPlaying.attr('href')) # Play song based on current file or selection atom.workspaceView.command 'rdio:play-code-mood', '.editor', this.currentMood # Current mood currentMood: => editor = atom.workspaceView.getActivePaneItem() content = (editor.getSelectedText() || editor.getText()).replace(/(\n)/gm, '') # Get the first 7 digits of the md5 string digits = md5(content).replace(/\D/g, '').substring(0, 6) console.log "Rdio Code Mood: See http://rdioconsole.appspot.com/#keys%3Dt#{digits}%26method%3Dget for more track info." @rdioDesktop.playTrack(digits) # Attach the view to the farthest right of the status bar attach: => atom.workspaceView.statusBar.appendRight(this) # Navigate to current track inside Rdio @currentlyPlaying.on 'click', (e) => this.openWithRdio(e.currentTarget.href) # Toggle equalizer on config change showEqualizerKey = "PI:KEY:<KEY>END_PIRdioView.CONFIGS.showEqualizer.key}" this.subscribe atom.config.observe showEqualizerKey, callNow: true, => if atom.config.get(showEqualizerKey) @soundBars.removeAttr('data-hidden') else @soundBars.attr('data-hidden', true) openWithRdio: (href) -> open(href) afterAttach: => setInterval => @rdioDesktop.currentState (state) => if state isnt @currentState @currentState = state @soundBars.attr('data-state', state) # Rdio is closed if state is undefined if @initiated @initiated = false @currentTrack = {} @container.removeAttr('data-initiated') return # Rdio is paused, but we know about the current track return if state is 'paused' and @initiated # Get current track data @rdioDesktop.currentlyPlaying (data) => return unless data.artist and data.track return if data.artist is @currentTrack.artist and data.track is @currentTrack.track @currentlyPlaying.text "#{data.artist} - #{data.track}" @currentlyPlaying.attr 'href', "rdio://www.rdio.com#{data.url}" @currentTrack = data # Display container when hidden return if @initiated @initiated = true @container.attr('data-initiated', true) , 1500
[ { "context": "###\nToshiro Ken Sugihara 2013\n###\n\n$ ->\n\n class World\n\n constructor: (", "end": 24, "score": 0.9998784065246582, "start": 4, "tag": "NAME", "value": "Toshiro Ken Sugihara" } ]
game_of_life.coffee
tshr/game_of_life
0
### Toshiro Ken Sugihara 2013 ### $ -> class World constructor: (numRows, numColumns, canvasHeight, canvasWidth, aliveColor) -> @numRows = numRows @numColumns = numColumns @aliveColor = aliveColor @grid = [] @fillGrid() @createCells canvasWidth, canvasHeight fillGrid: -> for i in [0...@numRows] row = [] for [0...@numColumns] row.push { alive : false } @grid.push row createCells: (canvasWidth, canvasHeight) -> paper = Raphael("canvas", canvasWidth, canvasHeight) gridCellHeight = canvasHeight / @numRows gridCellWidth = canvasWidth / @numColumns createCell = (paper, row, column, height, width, world) -> cell = paper.rect(column * width, row * height, width, height) cell.node.id = "cell_" + row + "_" + column cell.attr(stroke: "#d8d8d8").data("row", row).data("column", column).click -> cellData = world.grid[@data("row")][@data("column")] cellData.alive = !cellData.alive world.colorCell @, cellData.alive for j in [0...@numRows] for k in [0...@numColumns] createCell(paper, j, k, gridCellHeight, gridCellWidth, @) colorCell: (cell, alive) -> if alive then cell.attr fill: @aliveColor else cell.attr fill: "#ffffff" draw: -> for j in [0...@numRows] for k in [0...@numColumns] cellIdString = "cell_" + j + "_" + k cell = $("#" + cellIdString) @colorCell cell, @grid[j][k].alive updateGrid: (resultsGrid) -> for j in [0...resultsGrid.length] arr = [] for k in [0...resultsGrid[j].length] @grid[j][k].alive = resultsGrid[j][k] update: -> @draw() @updateGrid(@getNextGenerationCellStates()) getNextGenerationCellStates: -> nextGenGrid = [] for j in [0...@grid.length] arr = [] for k in [0...@grid[j].length] arr.push @calculateIfCellAlive(j, k) nextGenGrid.push arr nextGenGrid wrapped: (point, dimensionSize) -> switch when (point < 0) then dimensionSize - 1 when (point >= dimensionSize) then 0 else point countNeighbors: (row, column) -> count = 0 relPositions = [-1, 0, 1] for rowPosition in relPositions for columnPosition in relPositions unless rowPosition is 0 and columnPosition is 0 cellRow = @wrapped(row + rowPosition, @numRows) cellColumn = @wrapped(column + columnPosition, @numColumns) count += (if @grid[cellRow][cellColumn].alive then 1 else 0) count calculateIfCellAlive: (row, column) -> count = @countNeighbors(row, column) if @grid[row][column].alive then (2 <= count <= 3) else (count == 3) populate: -> #GLIDER @grid[0][8].alive = true @grid[1][9].alive = true @grid[2][9].alive = true @grid[2][8].alive = true @grid[2][7].alive = true #BEEHIVES @grid[13][22].alive = true @grid[14][21].alive = true @grid[14][23].alive = true @grid[15][21].alive = true @grid[15][23].alive = true @grid[16][22].alive = true @grid[16][23].alive = true ### Main ### tickInterval = 50 paused = false setPauseListener = -> $(window).keydown (event) -> if event.keyCode is 80 if paused paused = false run() else paused = true setPauseListener() world = new World(30, 48, 300, 480, "#50c0a8") world.populate() do run = -> world.update() unless paused setTimeout run, tickInterval
159926
### <NAME> 2013 ### $ -> class World constructor: (numRows, numColumns, canvasHeight, canvasWidth, aliveColor) -> @numRows = numRows @numColumns = numColumns @aliveColor = aliveColor @grid = [] @fillGrid() @createCells canvasWidth, canvasHeight fillGrid: -> for i in [0...@numRows] row = [] for [0...@numColumns] row.push { alive : false } @grid.push row createCells: (canvasWidth, canvasHeight) -> paper = Raphael("canvas", canvasWidth, canvasHeight) gridCellHeight = canvasHeight / @numRows gridCellWidth = canvasWidth / @numColumns createCell = (paper, row, column, height, width, world) -> cell = paper.rect(column * width, row * height, width, height) cell.node.id = "cell_" + row + "_" + column cell.attr(stroke: "#d8d8d8").data("row", row).data("column", column).click -> cellData = world.grid[@data("row")][@data("column")] cellData.alive = !cellData.alive world.colorCell @, cellData.alive for j in [0...@numRows] for k in [0...@numColumns] createCell(paper, j, k, gridCellHeight, gridCellWidth, @) colorCell: (cell, alive) -> if alive then cell.attr fill: @aliveColor else cell.attr fill: "#ffffff" draw: -> for j in [0...@numRows] for k in [0...@numColumns] cellIdString = "cell_" + j + "_" + k cell = $("#" + cellIdString) @colorCell cell, @grid[j][k].alive updateGrid: (resultsGrid) -> for j in [0...resultsGrid.length] arr = [] for k in [0...resultsGrid[j].length] @grid[j][k].alive = resultsGrid[j][k] update: -> @draw() @updateGrid(@getNextGenerationCellStates()) getNextGenerationCellStates: -> nextGenGrid = [] for j in [0...@grid.length] arr = [] for k in [0...@grid[j].length] arr.push @calculateIfCellAlive(j, k) nextGenGrid.push arr nextGenGrid wrapped: (point, dimensionSize) -> switch when (point < 0) then dimensionSize - 1 when (point >= dimensionSize) then 0 else point countNeighbors: (row, column) -> count = 0 relPositions = [-1, 0, 1] for rowPosition in relPositions for columnPosition in relPositions unless rowPosition is 0 and columnPosition is 0 cellRow = @wrapped(row + rowPosition, @numRows) cellColumn = @wrapped(column + columnPosition, @numColumns) count += (if @grid[cellRow][cellColumn].alive then 1 else 0) count calculateIfCellAlive: (row, column) -> count = @countNeighbors(row, column) if @grid[row][column].alive then (2 <= count <= 3) else (count == 3) populate: -> #GLIDER @grid[0][8].alive = true @grid[1][9].alive = true @grid[2][9].alive = true @grid[2][8].alive = true @grid[2][7].alive = true #BEEHIVES @grid[13][22].alive = true @grid[14][21].alive = true @grid[14][23].alive = true @grid[15][21].alive = true @grid[15][23].alive = true @grid[16][22].alive = true @grid[16][23].alive = true ### Main ### tickInterval = 50 paused = false setPauseListener = -> $(window).keydown (event) -> if event.keyCode is 80 if paused paused = false run() else paused = true setPauseListener() world = new World(30, 48, 300, 480, "#50c0a8") world.populate() do run = -> world.update() unless paused setTimeout run, tickInterval
true
### PI:NAME:<NAME>END_PI 2013 ### $ -> class World constructor: (numRows, numColumns, canvasHeight, canvasWidth, aliveColor) -> @numRows = numRows @numColumns = numColumns @aliveColor = aliveColor @grid = [] @fillGrid() @createCells canvasWidth, canvasHeight fillGrid: -> for i in [0...@numRows] row = [] for [0...@numColumns] row.push { alive : false } @grid.push row createCells: (canvasWidth, canvasHeight) -> paper = Raphael("canvas", canvasWidth, canvasHeight) gridCellHeight = canvasHeight / @numRows gridCellWidth = canvasWidth / @numColumns createCell = (paper, row, column, height, width, world) -> cell = paper.rect(column * width, row * height, width, height) cell.node.id = "cell_" + row + "_" + column cell.attr(stroke: "#d8d8d8").data("row", row).data("column", column).click -> cellData = world.grid[@data("row")][@data("column")] cellData.alive = !cellData.alive world.colorCell @, cellData.alive for j in [0...@numRows] for k in [0...@numColumns] createCell(paper, j, k, gridCellHeight, gridCellWidth, @) colorCell: (cell, alive) -> if alive then cell.attr fill: @aliveColor else cell.attr fill: "#ffffff" draw: -> for j in [0...@numRows] for k in [0...@numColumns] cellIdString = "cell_" + j + "_" + k cell = $("#" + cellIdString) @colorCell cell, @grid[j][k].alive updateGrid: (resultsGrid) -> for j in [0...resultsGrid.length] arr = [] for k in [0...resultsGrid[j].length] @grid[j][k].alive = resultsGrid[j][k] update: -> @draw() @updateGrid(@getNextGenerationCellStates()) getNextGenerationCellStates: -> nextGenGrid = [] for j in [0...@grid.length] arr = [] for k in [0...@grid[j].length] arr.push @calculateIfCellAlive(j, k) nextGenGrid.push arr nextGenGrid wrapped: (point, dimensionSize) -> switch when (point < 0) then dimensionSize - 1 when (point >= dimensionSize) then 0 else point countNeighbors: (row, column) -> count = 0 relPositions = [-1, 0, 1] for rowPosition in relPositions for columnPosition in relPositions unless rowPosition is 0 and columnPosition is 0 cellRow = @wrapped(row + rowPosition, @numRows) cellColumn = @wrapped(column + columnPosition, @numColumns) count += (if @grid[cellRow][cellColumn].alive then 1 else 0) count calculateIfCellAlive: (row, column) -> count = @countNeighbors(row, column) if @grid[row][column].alive then (2 <= count <= 3) else (count == 3) populate: -> #GLIDER @grid[0][8].alive = true @grid[1][9].alive = true @grid[2][9].alive = true @grid[2][8].alive = true @grid[2][7].alive = true #BEEHIVES @grid[13][22].alive = true @grid[14][21].alive = true @grid[14][23].alive = true @grid[15][21].alive = true @grid[15][23].alive = true @grid[16][22].alive = true @grid[16][23].alive = true ### Main ### tickInterval = 50 paused = false setPauseListener = -> $(window).keydown (event) -> if event.keyCode is 80 if paused paused = false run() else paused = true setPauseListener() world = new World(30, 48, 300, 480, "#50c0a8") world.populate() do run = -> world.update() unless paused setTimeout run, tickInterval
[ { "context": "rage['purpleUserId']\n token: localStorage['purpleToken']\n os: Ext.os.name\n subscripti", "end": 11109, "score": 0.5962790846824646, "start": 11103, "tag": "KEY", "value": "purple" } ]
src/app/controller/Subscriptions.coffee
Purple-Services/app
2
Ext.define 'Purple.controller.Subscriptions', extend: 'Ext.app.Controller' requires: [ 'Purple.view.Subscriptions' ] config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' accountTabContainer: '#accountTabContainer' accountForm: 'accountform' requestGasTabContainer: '#requestGasTabContainer' requestConfirmationForm: 'requestconfirmationform' subscriptions: 'subscriptions' # the Subscriptions page subscriptionChoicesContainer: '#subscriptionChoicesContainer' accountSubscriptionsField: '#accountSubscriptionsField' autoRenewField: '[ctype=autoRenewField]' control: subscriptions: loadSubscriptions: 'loadSubscriptions' subscribe: 'subscribe' accountSubscriptionsField: initialize: 'initAccountSubscriptionsField' autoRenewField: change: 'setAutoRenew' subscriptions: null # not guaranteed to be up-to-date; but it is a holding place for this info # every time the dispatch/availability endpoint is hit subscriptionUsage: null launch: -> @callParent arguments initAccountSubscriptionsField: (field) -> @refreshSubscriptionsField() field.element.on 'tap', => @subscriptionsFieldTap() refreshSubscriptionsField: -> @getAccountSubscriptionsField()?.setValue "None" if localStorage['purpleSubscriptionId']? and localStorage['purpleSubscriptionId'] isnt '0' @getAccountSubscriptionsField()?.setValue( localStorage['purpleSubscriptionName'] ) # give it a user/details response (or similar format) updateSubscriptionLocalStorageData: (response) -> localStorage['purpleSubscriptionId'] = response.user.subscription_id localStorage['purpleSubscriptionExpirationTime'] = response.user.subscription_expiration_time localStorage['purpleSubscriptionAutoRenew'] = response.user.subscription_auto_renew localStorage['purpleSubscriptionPeriodStartTime'] = response.user.subscription_period_start_time localStorage['purpleSubscriptionName'] = if response.user.subscription_id then response.system.subscriptions[response.user.subscription_id].name else "None" @refreshSubscriptionsField() # give it a user/details response (or similar format) updateSubscriptionRelatedData: (response) -> @updateSubscriptionLocalStorageData response @subscriptions = response.system.subscriptions @renderSubscriptions @subscriptions showAd: (passThruCallbackFn, actionCallbackFn) -> Ext.Msg.show cls: 'subscription-ad' title: '' message: """ <span class="fake-title">Try our Monthly<br />Membership</span> <br />Get deliveries free when you join! """ buttons: [ { ui: 'action' text: "More Info" itemId: "more-info" } { ui: 'normal' text: "Not Now" itemId: "hide" } ] fn: (buttonId) -> switch buttonId when 'hide' then passThruCallbackFn?() when 'more-info' then actionCallbackFn?() hideOnMaskTap: no loadSubscriptions: (forceUpdate = no, callback = null) -> if not forceUpdate and @subscriptions? @renderSubscriptions @subscriptions else Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/details" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response callback?() else navigator.notification.alert response.message, (->), "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response isSubscribed: -> localStorage['purpleSubscriptionId']? and localStorage['purpleSubscriptionId'] isnt "0" hasAutoRenewOn: -> localStorage['purpleSubscriptionAutoRenew']? and localStorage['purpleSubscriptionAutoRenew'] is "true" displayDiscount: (discount) -> "$" + util.centsToDollarsShort(Math.abs(discount)) renderSubscriptions: (subscriptions) -> subChoicesContainer = @getSubscriptionChoicesContainer() if not subChoicesContainer? return subChoicesContainer.removeAll yes, yes items = [] items.push xtype: 'component' flex: 0 html: if @isSubscribed() if @hasAutoRenewOn() """ You're subscribed! You can cancel at any time. """ else """ You have unsubscribed, your membership ends #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """ else """ Select a plan. You can cancel at any time. """ cls: 'loose-text' for s in Object.keys(subscriptions).sort( (a, b) -> # always list a currently subscribed option first switch localStorage['purpleSubscriptionId'] when a then -1 when b then 1 else parseInt(a) - parseInt(b) # otherwise, order by subscription id ) sub = subscriptions[s] cls = [ 'bottom-margin' 'faq-question' ] if localStorage['purpleSubscriptionId'] isnt "" + sub.id cls = cls.concat [ 'click-to-edit' 'point-down' ] else cls = cls.concat [ 'highlighted' ] items.push xtype: 'textfield' flex: 0 label: "#{sub.name} - $#{util.centsToDollars(sub.price)}" labelWidth: '100%' cls: cls disabled: yes listeners: initialize: ((subId) -> (field) -> field.element.on 'tap', -> if localStorage['purpleSubscriptionId'] isnt "" + subId text = Ext.ComponentQuery.query("#level-#{subId}-details")[0] if text.isHidden() text.show() field.addCls 'point-up' else text.hide() field.removeCls 'point-up')(sub.id) innerItems = [ { xtype: 'component' margin: '5 0 10 0' width: '100%' style: "text-align: center;" html: """ <ul style="list-style: bullet;"> <li #{if sub.num_free_one_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_one_hour} one-hour deliveries per month </li> <li #{if sub.discount_one_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_one_hour)} discount on #{if sub.num_free_one_hour then 'additional ' else ''}one-hour orders </li> <li #{if sub.num_free_three_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_three_hour} three-hour deliveries per month </li> <li #{if sub.discount_three_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_three_hour)} discount on #{if sub.num_free_three_hour then 'additional ' else ''}three-hour orders </li> <li #{if sub.num_free_five_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_five_hour} five-hour deliveries per month </li> <li #{if sub.discount_five_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_five_hour)} discount on #{if sub.num_free_five_hour then 'additional ' else ''}five-hour orders </li> <li #{if sub.num_free_tire_pressure_check then '' else 'style="display: none;"'}> #{sub.num_free_tire_pressure_check} tire pressure fill-up per month </li> </ul> """ } ] if localStorage['purpleSubscriptionId'] is "" + sub.id if @hasAutoRenewOn() innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Unsubscribe" flex: 0 margin: '0 0 15 0' handler: => @unsubscribe() else innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Restore Subscription" flex: 0 margin: '0 0 15 0' handler: => @restoreSubscription() else innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Subscribe to #{sub.name}" flex: 0 margin: '0 0 15 0' handler: ((subId) => => @askSubscribe subId, (=> util.ctl('Menu').popOffBackButton() @getMainContainer().getItems().getAt(0).select 0, no, no ) )(sub.id) items.push xtype: 'container' flex: 0 width: '100%' id: "level-#{sub.id}-details" cls: [ 'accordion-text' 'smaller-button-pop' ] showAnimation: 'fadeIn' hidden: localStorage['purpleSubscriptionId'] isnt "" + sub.id items: innerItems subChoicesContainer.add items subscriptionsFieldTap: (suppressBackButtonBehavior = no, requestGasTabActive = no) -> @requestGasTabActive = requestGasTabActive if @requestGasTabActive @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.Subscriptions' ) else @getAccountTabContainer().setActiveItem( Ext.create 'Purple.view.Subscriptions' ) if not suppressBackButtonBehavior util.ctl('Menu').pushOntoBackButton => @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getSubscriptions(), yes ) askSubscribe: (id, callback) -> util.confirm( "", "Subscribe to the #{@subscriptions[id].name} plan?", (=> @subscribe id, callback), null, 'Yes', 'No' ) subscribe: (id, callback) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/subscriptions/subscribe" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name subscription_id: id headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response callback?() util.alert( """ Your subscription will automatically renew on #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """, "Welcome to the #{@subscriptions[localStorage['purpleSubscriptionId']].name} Plan!" ) else util.alert response.message, "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response unsubscribe: -> util.confirm( """ Your monthly membership will expire #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """, 'Unsubscribe?', (=> @setAutoRenew null, 0), null, 'Yes', 'No' ) # unlikely, but possible, bug: what if their subscription has just expired # while they were on this page, and then they hit Restore Subscription # or, how about if they hit Unsubscribe restoreSubscription: -> @setAutoRenew null, 1 # the signature of this funciton is such that it could be the 'change' event # for a toggle field setAutoRenew: (_, value) -> currAutoRenewVal = switch localStorage['purpleSubscriptionAutoRenew'] when 'true' then 1 when 'false' then 0 else 0 if currAutoRenewVal isnt value Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/subscriptions/set-auto-renew" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name subscription_auto_renew: not not value headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response else navigator.notification.alert response.message, (->), "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response
37367
Ext.define 'Purple.controller.Subscriptions', extend: 'Ext.app.Controller' requires: [ 'Purple.view.Subscriptions' ] config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' accountTabContainer: '#accountTabContainer' accountForm: 'accountform' requestGasTabContainer: '#requestGasTabContainer' requestConfirmationForm: 'requestconfirmationform' subscriptions: 'subscriptions' # the Subscriptions page subscriptionChoicesContainer: '#subscriptionChoicesContainer' accountSubscriptionsField: '#accountSubscriptionsField' autoRenewField: '[ctype=autoRenewField]' control: subscriptions: loadSubscriptions: 'loadSubscriptions' subscribe: 'subscribe' accountSubscriptionsField: initialize: 'initAccountSubscriptionsField' autoRenewField: change: 'setAutoRenew' subscriptions: null # not guaranteed to be up-to-date; but it is a holding place for this info # every time the dispatch/availability endpoint is hit subscriptionUsage: null launch: -> @callParent arguments initAccountSubscriptionsField: (field) -> @refreshSubscriptionsField() field.element.on 'tap', => @subscriptionsFieldTap() refreshSubscriptionsField: -> @getAccountSubscriptionsField()?.setValue "None" if localStorage['purpleSubscriptionId']? and localStorage['purpleSubscriptionId'] isnt '0' @getAccountSubscriptionsField()?.setValue( localStorage['purpleSubscriptionName'] ) # give it a user/details response (or similar format) updateSubscriptionLocalStorageData: (response) -> localStorage['purpleSubscriptionId'] = response.user.subscription_id localStorage['purpleSubscriptionExpirationTime'] = response.user.subscription_expiration_time localStorage['purpleSubscriptionAutoRenew'] = response.user.subscription_auto_renew localStorage['purpleSubscriptionPeriodStartTime'] = response.user.subscription_period_start_time localStorage['purpleSubscriptionName'] = if response.user.subscription_id then response.system.subscriptions[response.user.subscription_id].name else "None" @refreshSubscriptionsField() # give it a user/details response (or similar format) updateSubscriptionRelatedData: (response) -> @updateSubscriptionLocalStorageData response @subscriptions = response.system.subscriptions @renderSubscriptions @subscriptions showAd: (passThruCallbackFn, actionCallbackFn) -> Ext.Msg.show cls: 'subscription-ad' title: '' message: """ <span class="fake-title">Try our Monthly<br />Membership</span> <br />Get deliveries free when you join! """ buttons: [ { ui: 'action' text: "More Info" itemId: "more-info" } { ui: 'normal' text: "Not Now" itemId: "hide" } ] fn: (buttonId) -> switch buttonId when 'hide' then passThruCallbackFn?() when 'more-info' then actionCallbackFn?() hideOnMaskTap: no loadSubscriptions: (forceUpdate = no, callback = null) -> if not forceUpdate and @subscriptions? @renderSubscriptions @subscriptions else Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/details" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response callback?() else navigator.notification.alert response.message, (->), "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response isSubscribed: -> localStorage['purpleSubscriptionId']? and localStorage['purpleSubscriptionId'] isnt "0" hasAutoRenewOn: -> localStorage['purpleSubscriptionAutoRenew']? and localStorage['purpleSubscriptionAutoRenew'] is "true" displayDiscount: (discount) -> "$" + util.centsToDollarsShort(Math.abs(discount)) renderSubscriptions: (subscriptions) -> subChoicesContainer = @getSubscriptionChoicesContainer() if not subChoicesContainer? return subChoicesContainer.removeAll yes, yes items = [] items.push xtype: 'component' flex: 0 html: if @isSubscribed() if @hasAutoRenewOn() """ You're subscribed! You can cancel at any time. """ else """ You have unsubscribed, your membership ends #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """ else """ Select a plan. You can cancel at any time. """ cls: 'loose-text' for s in Object.keys(subscriptions).sort( (a, b) -> # always list a currently subscribed option first switch localStorage['purpleSubscriptionId'] when a then -1 when b then 1 else parseInt(a) - parseInt(b) # otherwise, order by subscription id ) sub = subscriptions[s] cls = [ 'bottom-margin' 'faq-question' ] if localStorage['purpleSubscriptionId'] isnt "" + sub.id cls = cls.concat [ 'click-to-edit' 'point-down' ] else cls = cls.concat [ 'highlighted' ] items.push xtype: 'textfield' flex: 0 label: "#{sub.name} - $#{util.centsToDollars(sub.price)}" labelWidth: '100%' cls: cls disabled: yes listeners: initialize: ((subId) -> (field) -> field.element.on 'tap', -> if localStorage['purpleSubscriptionId'] isnt "" + subId text = Ext.ComponentQuery.query("#level-#{subId}-details")[0] if text.isHidden() text.show() field.addCls 'point-up' else text.hide() field.removeCls 'point-up')(sub.id) innerItems = [ { xtype: 'component' margin: '5 0 10 0' width: '100%' style: "text-align: center;" html: """ <ul style="list-style: bullet;"> <li #{if sub.num_free_one_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_one_hour} one-hour deliveries per month </li> <li #{if sub.discount_one_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_one_hour)} discount on #{if sub.num_free_one_hour then 'additional ' else ''}one-hour orders </li> <li #{if sub.num_free_three_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_three_hour} three-hour deliveries per month </li> <li #{if sub.discount_three_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_three_hour)} discount on #{if sub.num_free_three_hour then 'additional ' else ''}three-hour orders </li> <li #{if sub.num_free_five_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_five_hour} five-hour deliveries per month </li> <li #{if sub.discount_five_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_five_hour)} discount on #{if sub.num_free_five_hour then 'additional ' else ''}five-hour orders </li> <li #{if sub.num_free_tire_pressure_check then '' else 'style="display: none;"'}> #{sub.num_free_tire_pressure_check} tire pressure fill-up per month </li> </ul> """ } ] if localStorage['purpleSubscriptionId'] is "" + sub.id if @hasAutoRenewOn() innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Unsubscribe" flex: 0 margin: '0 0 15 0' handler: => @unsubscribe() else innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Restore Subscription" flex: 0 margin: '0 0 15 0' handler: => @restoreSubscription() else innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Subscribe to #{sub.name}" flex: 0 margin: '0 0 15 0' handler: ((subId) => => @askSubscribe subId, (=> util.ctl('Menu').popOffBackButton() @getMainContainer().getItems().getAt(0).select 0, no, no ) )(sub.id) items.push xtype: 'container' flex: 0 width: '100%' id: "level-#{sub.id}-details" cls: [ 'accordion-text' 'smaller-button-pop' ] showAnimation: 'fadeIn' hidden: localStorage['purpleSubscriptionId'] isnt "" + sub.id items: innerItems subChoicesContainer.add items subscriptionsFieldTap: (suppressBackButtonBehavior = no, requestGasTabActive = no) -> @requestGasTabActive = requestGasTabActive if @requestGasTabActive @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.Subscriptions' ) else @getAccountTabContainer().setActiveItem( Ext.create 'Purple.view.Subscriptions' ) if not suppressBackButtonBehavior util.ctl('Menu').pushOntoBackButton => @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getSubscriptions(), yes ) askSubscribe: (id, callback) -> util.confirm( "", "Subscribe to the #{@subscriptions[id].name} plan?", (=> @subscribe id, callback), null, 'Yes', 'No' ) subscribe: (id, callback) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/subscriptions/subscribe" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['<KEY>Token'] os: Ext.os.name subscription_id: id headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response callback?() util.alert( """ Your subscription will automatically renew on #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """, "Welcome to the #{@subscriptions[localStorage['purpleSubscriptionId']].name} Plan!" ) else util.alert response.message, "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response unsubscribe: -> util.confirm( """ Your monthly membership will expire #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """, 'Unsubscribe?', (=> @setAutoRenew null, 0), null, 'Yes', 'No' ) # unlikely, but possible, bug: what if their subscription has just expired # while they were on this page, and then they hit Restore Subscription # or, how about if they hit Unsubscribe restoreSubscription: -> @setAutoRenew null, 1 # the signature of this funciton is such that it could be the 'change' event # for a toggle field setAutoRenew: (_, value) -> currAutoRenewVal = switch localStorage['purpleSubscriptionAutoRenew'] when 'true' then 1 when 'false' then 0 else 0 if currAutoRenewVal isnt value Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/subscriptions/set-auto-renew" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name subscription_auto_renew: not not value headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response else navigator.notification.alert response.message, (->), "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response
true
Ext.define 'Purple.controller.Subscriptions', extend: 'Ext.app.Controller' requires: [ 'Purple.view.Subscriptions' ] config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' accountTabContainer: '#accountTabContainer' accountForm: 'accountform' requestGasTabContainer: '#requestGasTabContainer' requestConfirmationForm: 'requestconfirmationform' subscriptions: 'subscriptions' # the Subscriptions page subscriptionChoicesContainer: '#subscriptionChoicesContainer' accountSubscriptionsField: '#accountSubscriptionsField' autoRenewField: '[ctype=autoRenewField]' control: subscriptions: loadSubscriptions: 'loadSubscriptions' subscribe: 'subscribe' accountSubscriptionsField: initialize: 'initAccountSubscriptionsField' autoRenewField: change: 'setAutoRenew' subscriptions: null # not guaranteed to be up-to-date; but it is a holding place for this info # every time the dispatch/availability endpoint is hit subscriptionUsage: null launch: -> @callParent arguments initAccountSubscriptionsField: (field) -> @refreshSubscriptionsField() field.element.on 'tap', => @subscriptionsFieldTap() refreshSubscriptionsField: -> @getAccountSubscriptionsField()?.setValue "None" if localStorage['purpleSubscriptionId']? and localStorage['purpleSubscriptionId'] isnt '0' @getAccountSubscriptionsField()?.setValue( localStorage['purpleSubscriptionName'] ) # give it a user/details response (or similar format) updateSubscriptionLocalStorageData: (response) -> localStorage['purpleSubscriptionId'] = response.user.subscription_id localStorage['purpleSubscriptionExpirationTime'] = response.user.subscription_expiration_time localStorage['purpleSubscriptionAutoRenew'] = response.user.subscription_auto_renew localStorage['purpleSubscriptionPeriodStartTime'] = response.user.subscription_period_start_time localStorage['purpleSubscriptionName'] = if response.user.subscription_id then response.system.subscriptions[response.user.subscription_id].name else "None" @refreshSubscriptionsField() # give it a user/details response (or similar format) updateSubscriptionRelatedData: (response) -> @updateSubscriptionLocalStorageData response @subscriptions = response.system.subscriptions @renderSubscriptions @subscriptions showAd: (passThruCallbackFn, actionCallbackFn) -> Ext.Msg.show cls: 'subscription-ad' title: '' message: """ <span class="fake-title">Try our Monthly<br />Membership</span> <br />Get deliveries free when you join! """ buttons: [ { ui: 'action' text: "More Info" itemId: "more-info" } { ui: 'normal' text: "Not Now" itemId: "hide" } ] fn: (buttonId) -> switch buttonId when 'hide' then passThruCallbackFn?() when 'more-info' then actionCallbackFn?() hideOnMaskTap: no loadSubscriptions: (forceUpdate = no, callback = null) -> if not forceUpdate and @subscriptions? @renderSubscriptions @subscriptions else Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/details" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response callback?() else navigator.notification.alert response.message, (->), "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response isSubscribed: -> localStorage['purpleSubscriptionId']? and localStorage['purpleSubscriptionId'] isnt "0" hasAutoRenewOn: -> localStorage['purpleSubscriptionAutoRenew']? and localStorage['purpleSubscriptionAutoRenew'] is "true" displayDiscount: (discount) -> "$" + util.centsToDollarsShort(Math.abs(discount)) renderSubscriptions: (subscriptions) -> subChoicesContainer = @getSubscriptionChoicesContainer() if not subChoicesContainer? return subChoicesContainer.removeAll yes, yes items = [] items.push xtype: 'component' flex: 0 html: if @isSubscribed() if @hasAutoRenewOn() """ You're subscribed! You can cancel at any time. """ else """ You have unsubscribed, your membership ends #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """ else """ Select a plan. You can cancel at any time. """ cls: 'loose-text' for s in Object.keys(subscriptions).sort( (a, b) -> # always list a currently subscribed option first switch localStorage['purpleSubscriptionId'] when a then -1 when b then 1 else parseInt(a) - parseInt(b) # otherwise, order by subscription id ) sub = subscriptions[s] cls = [ 'bottom-margin' 'faq-question' ] if localStorage['purpleSubscriptionId'] isnt "" + sub.id cls = cls.concat [ 'click-to-edit' 'point-down' ] else cls = cls.concat [ 'highlighted' ] items.push xtype: 'textfield' flex: 0 label: "#{sub.name} - $#{util.centsToDollars(sub.price)}" labelWidth: '100%' cls: cls disabled: yes listeners: initialize: ((subId) -> (field) -> field.element.on 'tap', -> if localStorage['purpleSubscriptionId'] isnt "" + subId text = Ext.ComponentQuery.query("#level-#{subId}-details")[0] if text.isHidden() text.show() field.addCls 'point-up' else text.hide() field.removeCls 'point-up')(sub.id) innerItems = [ { xtype: 'component' margin: '5 0 10 0' width: '100%' style: "text-align: center;" html: """ <ul style="list-style: bullet;"> <li #{if sub.num_free_one_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_one_hour} one-hour deliveries per month </li> <li #{if sub.discount_one_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_one_hour)} discount on #{if sub.num_free_one_hour then 'additional ' else ''}one-hour orders </li> <li #{if sub.num_free_three_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_three_hour} three-hour deliveries per month </li> <li #{if sub.discount_three_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_three_hour)} discount on #{if sub.num_free_three_hour then 'additional ' else ''}three-hour orders </li> <li #{if sub.num_free_five_hour then 'style="font-weight: bold;"' else 'style="display: none;"'}> #{sub.num_free_five_hour} five-hour deliveries per month </li> <li #{if sub.discount_five_hour then 'style="margin-bottom: 10px;"' else 'style="display: none;"'}> #{@displayDiscount(sub.discount_five_hour)} discount on #{if sub.num_free_five_hour then 'additional ' else ''}five-hour orders </li> <li #{if sub.num_free_tire_pressure_check then '' else 'style="display: none;"'}> #{sub.num_free_tire_pressure_check} tire pressure fill-up per month </li> </ul> """ } ] if localStorage['purpleSubscriptionId'] is "" + sub.id if @hasAutoRenewOn() innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Unsubscribe" flex: 0 margin: '0 0 15 0' handler: => @unsubscribe() else innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Restore Subscription" flex: 0 margin: '0 0 15 0' handler: => @restoreSubscription() else innerItems.push xtype: 'button' ui: 'action' cls: 'button-pop' text: "Subscribe to #{sub.name}" flex: 0 margin: '0 0 15 0' handler: ((subId) => => @askSubscribe subId, (=> util.ctl('Menu').popOffBackButton() @getMainContainer().getItems().getAt(0).select 0, no, no ) )(sub.id) items.push xtype: 'container' flex: 0 width: '100%' id: "level-#{sub.id}-details" cls: [ 'accordion-text' 'smaller-button-pop' ] showAnimation: 'fadeIn' hidden: localStorage['purpleSubscriptionId'] isnt "" + sub.id items: innerItems subChoicesContainer.add items subscriptionsFieldTap: (suppressBackButtonBehavior = no, requestGasTabActive = no) -> @requestGasTabActive = requestGasTabActive if @requestGasTabActive @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.Subscriptions' ) else @getAccountTabContainer().setActiveItem( Ext.create 'Purple.view.Subscriptions' ) if not suppressBackButtonBehavior util.ctl('Menu').pushOntoBackButton => @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getSubscriptions(), yes ) askSubscribe: (id, callback) -> util.confirm( "", "Subscribe to the #{@subscriptions[id].name} plan?", (=> @subscribe id, callback), null, 'Yes', 'No' ) subscribe: (id, callback) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/subscriptions/subscribe" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['PI:KEY:<KEY>END_PIToken'] os: Ext.os.name subscription_id: id headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response callback?() util.alert( """ Your subscription will automatically renew on #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """, "Welcome to the #{@subscriptions[localStorage['purpleSubscriptionId']].name} Plan!" ) else util.alert response.message, "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response unsubscribe: -> util.confirm( """ Your monthly membership will expire #{ Ext.util.Format.date( new Date(localStorage['purpleSubscriptionExpirationTime'] * 1000), "F j, Y" )}. """, 'Unsubscribe?', (=> @setAutoRenew null, 0), null, 'Yes', 'No' ) # unlikely, but possible, bug: what if their subscription has just expired # while they were on this page, and then they hit Restore Subscription # or, how about if they hit Unsubscribe restoreSubscription: -> @setAutoRenew null, 1 # the signature of this funciton is such that it could be the 'change' event # for a toggle field setAutoRenew: (_, value) -> currAutoRenewVal = switch localStorage['purpleSubscriptionAutoRenew'] when 'true' then 1 when 'false' then 0 else 0 if currAutoRenewVal isnt value Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/subscriptions/set-auto-renew" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] os: Ext.os.name subscription_auto_renew: not not value headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @updateSubscriptionRelatedData response else navigator.notification.alert response.message, (->), "Error" failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response
[ { "context": "tor: 10\n app:\n port: 3000\n sessionSecret: 'secret key'\n\nmodule.exports = config\n", "end": 185, "score": 0.7038788795471191, "start": 175, "tag": "KEY", "value": "secret key" } ]
config.example.coffee
zodoz/EC2Manager
0
config = db: url: 'mongodb://localhost/ec2Manager' passport: secret: 'EC2ManagerSecret' bcrypt: saltWorkFactor: 10 app: port: 3000 sessionSecret: 'secret key' module.exports = config
175160
config = db: url: 'mongodb://localhost/ec2Manager' passport: secret: 'EC2ManagerSecret' bcrypt: saltWorkFactor: 10 app: port: 3000 sessionSecret: '<KEY>' module.exports = config
true
config = db: url: 'mongodb://localhost/ec2Manager' passport: secret: 'EC2ManagerSecret' bcrypt: saltWorkFactor: 10 app: port: 3000 sessionSecret: 'PI:KEY:<KEY>END_PI' module.exports = config
[ { "context": "ontSize: 17\n \"exception-reporting\":\n userId: \"1effa0b2-2ee8-4a52-b80e-098d95a88836\"\n \"fuzzy-finder\":\n scoringSystem: \"fast\"\n ", "end": 513, "score": 0.7570253014564514, "start": 477, "tag": "PASSWORD", "value": "1effa0b2-2ee8-4a52-b80e-098d95a88836" } ]
config.cson
special-k/atom-multimode-config
0
"*": "atom-package-deps": ignored: [ "linter-pylint" ] "autocomplete-plus": enableAutoActivation: false enableAutoConfirmSingleSuggestion: false minimumWordLength: 1 "command-palette": defaultCommandPath: "vim:" core: disabledPackages: [ "vim-mode-plus-macros" ] telemetryConsent: "limited" themes: [ "one-dark-ui" "atom-dark-syntax" ] editor: fontSize: 17 "exception-reporting": userId: "1effa0b2-2ee8-4a52-b80e-098d95a88836" "fuzzy-finder": scoringSystem: "fast" useRipGrep: true "linter-eslint": disabling: {} "tree-view": alwaysOpenExisting: true welcome: showOnStartup: false zentabs: {}
222234
"*": "atom-package-deps": ignored: [ "linter-pylint" ] "autocomplete-plus": enableAutoActivation: false enableAutoConfirmSingleSuggestion: false minimumWordLength: 1 "command-palette": defaultCommandPath: "vim:" core: disabledPackages: [ "vim-mode-plus-macros" ] telemetryConsent: "limited" themes: [ "one-dark-ui" "atom-dark-syntax" ] editor: fontSize: 17 "exception-reporting": userId: "<PASSWORD>" "fuzzy-finder": scoringSystem: "fast" useRipGrep: true "linter-eslint": disabling: {} "tree-view": alwaysOpenExisting: true welcome: showOnStartup: false zentabs: {}
true
"*": "atom-package-deps": ignored: [ "linter-pylint" ] "autocomplete-plus": enableAutoActivation: false enableAutoConfirmSingleSuggestion: false minimumWordLength: 1 "command-palette": defaultCommandPath: "vim:" core: disabledPackages: [ "vim-mode-plus-macros" ] telemetryConsent: "limited" themes: [ "one-dark-ui" "atom-dark-syntax" ] editor: fontSize: 17 "exception-reporting": userId: "PI:PASSWORD:<PASSWORD>END_PI" "fuzzy-finder": scoringSystem: "fast" useRipGrep: true "linter-eslint": disabling: {} "tree-view": alwaysOpenExisting: true welcome: showOnStartup: false zentabs: {}
[ { "context": " service\n\n userA = yield User.create\n email: 'user1@example.com'\n password: 'password1'\n organizationId: or", "end": 2291, "score": 0.999921977519989, "start": 2274, "tag": "EMAIL", "value": "user1@example.com" }, { "context": "ate\n email: 'user1@example.com'\n password: 'password1'\n organizationId: orgs[0].id\n\n userB = yield ", "end": 2317, "score": 0.9993104934692383, "start": 2308, "tag": "PASSWORD", "value": "password1" }, { "context": "gs[0].id\n\n userB = yield User.create\n email: 'user2@example.com'\n password: 'password2'\n organizationId: or", "end": 2408, "score": 0.9999203681945801, "start": 2391, "tag": "EMAIL", "value": "user2@example.com" }, { "context": "ate\n email: 'user2@example.com'\n password: 'password2'\n organizationId: orgs[1].id\n\n userC = yield ", "end": 2434, "score": 0.9993090033531189, "start": 2425, "tag": "PASSWORD", "value": "password2" }, { "context": "gs[1].id\n\n userC = yield User.create\n email: 'user3@example.com'\n password: 'password3'\n organizationId: or", "end": 2525, "score": 0.9999186396598816, "start": 2508, "tag": "EMAIL", "value": "user3@example.com" }, { "context": "ate\n email: 'user3@example.com'\n password: 'password3'\n organizationId: orgs[2].id\n\n users = [userA", "end": 2551, "score": 0.9993091821670532, "start": 2542, "tag": "PASSWORD", "value": "password3" } ]
preset.coffee
evanhuang8/teresa
0
#!/usr/bin/env coffee fs = require 'fs' _ = require 'lodash' moment = require 'moment-timezone' co = require 'co' faker = require 'faker' csv = require 'csv' Q = require 'q' parseCSV = Q.denodeify csv.parse configs = 5: 'shelter' 6: 'housing' 7: 'job' 8: 'health' 9: 'food' 10: 'funding' co -> db = require './src/db' yield db.client.sync force: true Community = db.model 'Community' Organization = db.model 'Organization' User = db.model 'User' Client = db.model 'Client' Service = db.model 'Service' Referral = db.model 'Referral' community = yield Community.create name: 'St. Louis CoC' description: 'St. Louis Continuum of Care' rawData = fs.readFileSync './preset.csv' data = yield parseCSV rawData orgs = [] services = [] hours = [] for i in [0...7] hours.push always: true for row, i in data if i > 1 # Start at row 3 img = null if row[12]?.trim().length > 0 img = "https://s3.us-east-2.amazonaws.com/ghack16/logos/#{row[12]}" org = yield Organization.create name: row[0] description: row[0] # FIXME address: row[0] # FIXME lat: row[3] lng: row[4] phone: row[2] image: img tz: 'US/Central' communityId: community.id orgs.push org for j in [5..10] if 1 is parseInt row[j] completionCost = _.random 50, 350 factor = _.random 0.1, 0.7 missedCost = completionCost * factor service = yield Service.create type: configs[j] name: row[0] + ' (' + configs[j] + ')' description: row[0] + ' (' + configs[j] + ')' businessHours: hours maxCapacity: _.sample [150..217] openCapacity: _.sample [42..133] isConfirmationRequired: _.sample [true, false] completionCost: completionCost missedCost: missedCost organizationId: org.id services.push service servicesByTypes = shelter: [] health: [] housing: [] job: [] food: [] funding: [] types = Object.keys servicesByTypes for service in services servicesByTypes[service.type].push service userA = yield User.create email: 'user1@example.com' password: 'password1' organizationId: orgs[0].id userB = yield User.create email: 'user2@example.com' password: 'password2' organizationId: orgs[1].id userC = yield User.create email: 'user3@example.com' password: 'password3' organizationId: orgs[2].id users = [userA, userB, userC] clients = [] initials = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'Z'] stages = ['unknown', 'emergent', 'homeless', 'rehab'] for i in [0..2000] delta = _.sample [15..70] createdAt = new Date moment().subtract(delta, 'days').valueOf() clients.push firstName: faker.name.firstName() middleName: initials[i % initials.length] lastName: faker.name.lastName() phone: faker.phone.phoneNumberFormat() stage: _.sample stages createdAt: createdAt yield Client.bulkCreate clients clients = yield Client.findAll {} for client in clients if client.stage is 'homeless' for type in types if Math.random() > 0.5 service = _.sample servicesByTypes[type] isComplete = _.sample [true, false] completedAt = null if isComplete delta = _.sample [1..11] completedAt = new Date moment().subtract(delta, 'days').valueOf() referral = yield Referral.create isInitialized: true type: type isConfirmed: true isDirectionSent: _.sample [true, false] isComplete: isComplete completedAt: completedAt clientId: client.id serviceId: service.id refereeId: service.organizationId refererId: _.sample(orgs).id userId: _.sample(users).id else if client.stage is 'rehab' for type in types if type is 'housing' or Math.random() > 0.7 service = _.sample servicesByTypes[type] delta = _.sample [1..11] completedAt = new Date moment().subtract(delta, 'days').valueOf() referral = yield Referral.create isInitialized: true type: type isConfirmed: true isDirectionSent: _.sample [true, false] isComplete: true completedAt: completedAt clientId: client.id serviceId: service.id referee: service.organizationId referer: _.sample(orgs).id userId: _.sample(users).id process.exit() .catch (err) -> console.log err.stack return
112533
#!/usr/bin/env coffee fs = require 'fs' _ = require 'lodash' moment = require 'moment-timezone' co = require 'co' faker = require 'faker' csv = require 'csv' Q = require 'q' parseCSV = Q.denodeify csv.parse configs = 5: 'shelter' 6: 'housing' 7: 'job' 8: 'health' 9: 'food' 10: 'funding' co -> db = require './src/db' yield db.client.sync force: true Community = db.model 'Community' Organization = db.model 'Organization' User = db.model 'User' Client = db.model 'Client' Service = db.model 'Service' Referral = db.model 'Referral' community = yield Community.create name: 'St. Louis CoC' description: 'St. Louis Continuum of Care' rawData = fs.readFileSync './preset.csv' data = yield parseCSV rawData orgs = [] services = [] hours = [] for i in [0...7] hours.push always: true for row, i in data if i > 1 # Start at row 3 img = null if row[12]?.trim().length > 0 img = "https://s3.us-east-2.amazonaws.com/ghack16/logos/#{row[12]}" org = yield Organization.create name: row[0] description: row[0] # FIXME address: row[0] # FIXME lat: row[3] lng: row[4] phone: row[2] image: img tz: 'US/Central' communityId: community.id orgs.push org for j in [5..10] if 1 is parseInt row[j] completionCost = _.random 50, 350 factor = _.random 0.1, 0.7 missedCost = completionCost * factor service = yield Service.create type: configs[j] name: row[0] + ' (' + configs[j] + ')' description: row[0] + ' (' + configs[j] + ')' businessHours: hours maxCapacity: _.sample [150..217] openCapacity: _.sample [42..133] isConfirmationRequired: _.sample [true, false] completionCost: completionCost missedCost: missedCost organizationId: org.id services.push service servicesByTypes = shelter: [] health: [] housing: [] job: [] food: [] funding: [] types = Object.keys servicesByTypes for service in services servicesByTypes[service.type].push service userA = yield User.create email: '<EMAIL>' password: '<PASSWORD>' organizationId: orgs[0].id userB = yield User.create email: '<EMAIL>' password: '<PASSWORD>' organizationId: orgs[1].id userC = yield User.create email: '<EMAIL>' password: '<PASSWORD>' organizationId: orgs[2].id users = [userA, userB, userC] clients = [] initials = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'Z'] stages = ['unknown', 'emergent', 'homeless', 'rehab'] for i in [0..2000] delta = _.sample [15..70] createdAt = new Date moment().subtract(delta, 'days').valueOf() clients.push firstName: faker.name.firstName() middleName: initials[i % initials.length] lastName: faker.name.lastName() phone: faker.phone.phoneNumberFormat() stage: _.sample stages createdAt: createdAt yield Client.bulkCreate clients clients = yield Client.findAll {} for client in clients if client.stage is 'homeless' for type in types if Math.random() > 0.5 service = _.sample servicesByTypes[type] isComplete = _.sample [true, false] completedAt = null if isComplete delta = _.sample [1..11] completedAt = new Date moment().subtract(delta, 'days').valueOf() referral = yield Referral.create isInitialized: true type: type isConfirmed: true isDirectionSent: _.sample [true, false] isComplete: isComplete completedAt: completedAt clientId: client.id serviceId: service.id refereeId: service.organizationId refererId: _.sample(orgs).id userId: _.sample(users).id else if client.stage is 'rehab' for type in types if type is 'housing' or Math.random() > 0.7 service = _.sample servicesByTypes[type] delta = _.sample [1..11] completedAt = new Date moment().subtract(delta, 'days').valueOf() referral = yield Referral.create isInitialized: true type: type isConfirmed: true isDirectionSent: _.sample [true, false] isComplete: true completedAt: completedAt clientId: client.id serviceId: service.id referee: service.organizationId referer: _.sample(orgs).id userId: _.sample(users).id process.exit() .catch (err) -> console.log err.stack return
true
#!/usr/bin/env coffee fs = require 'fs' _ = require 'lodash' moment = require 'moment-timezone' co = require 'co' faker = require 'faker' csv = require 'csv' Q = require 'q' parseCSV = Q.denodeify csv.parse configs = 5: 'shelter' 6: 'housing' 7: 'job' 8: 'health' 9: 'food' 10: 'funding' co -> db = require './src/db' yield db.client.sync force: true Community = db.model 'Community' Organization = db.model 'Organization' User = db.model 'User' Client = db.model 'Client' Service = db.model 'Service' Referral = db.model 'Referral' community = yield Community.create name: 'St. Louis CoC' description: 'St. Louis Continuum of Care' rawData = fs.readFileSync './preset.csv' data = yield parseCSV rawData orgs = [] services = [] hours = [] for i in [0...7] hours.push always: true for row, i in data if i > 1 # Start at row 3 img = null if row[12]?.trim().length > 0 img = "https://s3.us-east-2.amazonaws.com/ghack16/logos/#{row[12]}" org = yield Organization.create name: row[0] description: row[0] # FIXME address: row[0] # FIXME lat: row[3] lng: row[4] phone: row[2] image: img tz: 'US/Central' communityId: community.id orgs.push org for j in [5..10] if 1 is parseInt row[j] completionCost = _.random 50, 350 factor = _.random 0.1, 0.7 missedCost = completionCost * factor service = yield Service.create type: configs[j] name: row[0] + ' (' + configs[j] + ')' description: row[0] + ' (' + configs[j] + ')' businessHours: hours maxCapacity: _.sample [150..217] openCapacity: _.sample [42..133] isConfirmationRequired: _.sample [true, false] completionCost: completionCost missedCost: missedCost organizationId: org.id services.push service servicesByTypes = shelter: [] health: [] housing: [] job: [] food: [] funding: [] types = Object.keys servicesByTypes for service in services servicesByTypes[service.type].push service userA = yield User.create email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' organizationId: orgs[0].id userB = yield User.create email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' organizationId: orgs[1].id userC = yield User.create email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' organizationId: orgs[2].id users = [userA, userB, userC] clients = [] initials = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'I', 'Z'] stages = ['unknown', 'emergent', 'homeless', 'rehab'] for i in [0..2000] delta = _.sample [15..70] createdAt = new Date moment().subtract(delta, 'days').valueOf() clients.push firstName: faker.name.firstName() middleName: initials[i % initials.length] lastName: faker.name.lastName() phone: faker.phone.phoneNumberFormat() stage: _.sample stages createdAt: createdAt yield Client.bulkCreate clients clients = yield Client.findAll {} for client in clients if client.stage is 'homeless' for type in types if Math.random() > 0.5 service = _.sample servicesByTypes[type] isComplete = _.sample [true, false] completedAt = null if isComplete delta = _.sample [1..11] completedAt = new Date moment().subtract(delta, 'days').valueOf() referral = yield Referral.create isInitialized: true type: type isConfirmed: true isDirectionSent: _.sample [true, false] isComplete: isComplete completedAt: completedAt clientId: client.id serviceId: service.id refereeId: service.organizationId refererId: _.sample(orgs).id userId: _.sample(users).id else if client.stage is 'rehab' for type in types if type is 'housing' or Math.random() > 0.7 service = _.sample servicesByTypes[type] delta = _.sample [1..11] completedAt = new Date moment().subtract(delta, 'days').valueOf() referral = yield Referral.create isInitialized: true type: type isConfirmed: true isDirectionSent: _.sample [true, false] isComplete: true completedAt: completedAt clientId: client.id serviceId: service.id referee: service.organizationId referer: _.sample(orgs).id userId: _.sample(users).id process.exit() .catch (err) -> console.log err.stack return
[ { "context": "\t\tnodename = os.hostname().split(\".\")[0]\n\t\tkey = \"nodes/#{config.get('env')}-#{nodename}/reassignment-status", "end": 3238, "score": 0.8318449258804321, "start": 3230, "tag": "KEY", "value": "nodes/#{" }, { "context": ").split(\".\")[0]\n\t\tkey = \"nodes/#{config.get('env')}-#{nodename}/reassignment-status\"\n\t\tstatus = new Promise (resolve, reject) =>\n\t\t\tr", "end": 3288, "score": 0.9888179302215576, "start": 3257, "tag": "KEY", "value": "#{nodename}/reassignment-status" } ]
server/lib/consul.coffee
willroberts/duelyst
5
os = require 'os' config = require '../../config/config.js' Logger = require '../../app/common/logger.coffee' Colors = require 'colors' Promise = require 'bluebird' request = require 'superagent' _ = require 'underscore' class Consul @baseUrl = "http://#{config.get('consul.ip')}:#{config.get('consul.port')}/v1/" @kvUrl = @baseUrl + "kv/" @gameServiceHealthUrl = @baseUrl + "health/service/#{config.get('consul.gameServiceName')}?passing" @aiServiceHealthUrl = @baseUrl + "health/service/#{process.env.NODE_ENV}-ai?passing" @kv: get: (key, callback) => return new Promise (resolve, reject) => # Make 'raw' request to Consul which returns the value directly (not encoded) # Without 'raw', the value will be base64 encoded, you can decode with: # decoded = new Buffer(value, 'base64').toString() request.get(@kvUrl + key + "?raw").end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, kv.get(#{key}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! kv.get(#{key}) failed: #{err.message} ".red return reject(err) else # Logger.module("CONSUL").log "kv.get(#{key}): #{res.text} ".green return resolve(res.text) .nodeify(callback) @getHealthyServers: (callback) -> return new Promise (resolve, reject) => request.get(@gameServiceHealthUrl).end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, get(#{@gameServiceHealthUrl}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! getHealthyServers() failed: #{err.message} ".red return reject(err) else Logger.module("CONSUL").debug "getHealthyServers()".green return resolve(res.body) .nodeify(callback) @getHealthySinglePlayerServers: (callback) -> return new Promise (resolve, reject) => request.get(@aiServiceHealthUrl).end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, kv.get(#{key}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! getHealthySinglePlayerServers() failed: #{err.message} ".red return reject(err) else Logger.module("CONSUL").debug "getHealthySinglePlayerServers()".green return resolve(res.body) .nodeify(callback) # Get whether or not this server should re-assign players on shutdown # Value is stored in Consul KV under /nodes tree # Note in most cases, this will default to true (even if no flag is found in Consul) @getReassignmentStatus: (callback) -> nodename = os.hostname().split(".")[0] key = "nodes/#{config.get('env')}-#{nodename}/reassignment-status" status = new Promise (resolve, reject) => request .get(@kvUrl + key + "?raw") .accept('json') .end (err, res) -> if err # If there's an error, we still want to default true return resolve(true) if res.status >= 400 # If no reassignment-status flag is found (ie 404), we want to default true return resolve(true) return resolve(res.text) # Parse the reassignment-status result, note JSON.parse(true) = true # Value in Consul looks like {"enabled":true} return status.then(JSON.parse).then (result) -> if result.enabled == false Logger.module("CONSUL").debug "getReassignmentStatus() == false".red return false Logger.module("CONSUL").debug "getReassignmentStatus() == true".green return true .nodeify(callback) module.exports = Consul
47243
os = require 'os' config = require '../../config/config.js' Logger = require '../../app/common/logger.coffee' Colors = require 'colors' Promise = require 'bluebird' request = require 'superagent' _ = require 'underscore' class Consul @baseUrl = "http://#{config.get('consul.ip')}:#{config.get('consul.port')}/v1/" @kvUrl = @baseUrl + "kv/" @gameServiceHealthUrl = @baseUrl + "health/service/#{config.get('consul.gameServiceName')}?passing" @aiServiceHealthUrl = @baseUrl + "health/service/#{process.env.NODE_ENV}-ai?passing" @kv: get: (key, callback) => return new Promise (resolve, reject) => # Make 'raw' request to Consul which returns the value directly (not encoded) # Without 'raw', the value will be base64 encoded, you can decode with: # decoded = new Buffer(value, 'base64').toString() request.get(@kvUrl + key + "?raw").end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, kv.get(#{key}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! kv.get(#{key}) failed: #{err.message} ".red return reject(err) else # Logger.module("CONSUL").log "kv.get(#{key}): #{res.text} ".green return resolve(res.text) .nodeify(callback) @getHealthyServers: (callback) -> return new Promise (resolve, reject) => request.get(@gameServiceHealthUrl).end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, get(#{@gameServiceHealthUrl}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! getHealthyServers() failed: #{err.message} ".red return reject(err) else Logger.module("CONSUL").debug "getHealthyServers()".green return resolve(res.body) .nodeify(callback) @getHealthySinglePlayerServers: (callback) -> return new Promise (resolve, reject) => request.get(@aiServiceHealthUrl).end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, kv.get(#{key}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! getHealthySinglePlayerServers() failed: #{err.message} ".red return reject(err) else Logger.module("CONSUL").debug "getHealthySinglePlayerServers()".green return resolve(res.body) .nodeify(callback) # Get whether or not this server should re-assign players on shutdown # Value is stored in Consul KV under /nodes tree # Note in most cases, this will default to true (even if no flag is found in Consul) @getReassignmentStatus: (callback) -> nodename = os.hostname().split(".")[0] key = "<KEY>config.get('env')}-<KEY>" status = new Promise (resolve, reject) => request .get(@kvUrl + key + "?raw") .accept('json') .end (err, res) -> if err # If there's an error, we still want to default true return resolve(true) if res.status >= 400 # If no reassignment-status flag is found (ie 404), we want to default true return resolve(true) return resolve(res.text) # Parse the reassignment-status result, note JSON.parse(true) = true # Value in Consul looks like {"enabled":true} return status.then(JSON.parse).then (result) -> if result.enabled == false Logger.module("CONSUL").debug "getReassignmentStatus() == false".red return false Logger.module("CONSUL").debug "getReassignmentStatus() == true".green return true .nodeify(callback) module.exports = Consul
true
os = require 'os' config = require '../../config/config.js' Logger = require '../../app/common/logger.coffee' Colors = require 'colors' Promise = require 'bluebird' request = require 'superagent' _ = require 'underscore' class Consul @baseUrl = "http://#{config.get('consul.ip')}:#{config.get('consul.port')}/v1/" @kvUrl = @baseUrl + "kv/" @gameServiceHealthUrl = @baseUrl + "health/service/#{config.get('consul.gameServiceName')}?passing" @aiServiceHealthUrl = @baseUrl + "health/service/#{process.env.NODE_ENV}-ai?passing" @kv: get: (key, callback) => return new Promise (resolve, reject) => # Make 'raw' request to Consul which returns the value directly (not encoded) # Without 'raw', the value will be base64 encoded, you can decode with: # decoded = new Buffer(value, 'base64').toString() request.get(@kvUrl + key + "?raw").end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, kv.get(#{key}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! kv.get(#{key}) failed: #{err.message} ".red return reject(err) else # Logger.module("CONSUL").log "kv.get(#{key}): #{res.text} ".green return resolve(res.text) .nodeify(callback) @getHealthyServers: (callback) -> return new Promise (resolve, reject) => request.get(@gameServiceHealthUrl).end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, get(#{@gameServiceHealthUrl}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! getHealthyServers() failed: #{err.message} ".red return reject(err) else Logger.module("CONSUL").debug "getHealthyServers()".green return resolve(res.body) .nodeify(callback) @getHealthySinglePlayerServers: (callback) -> return new Promise (resolve, reject) => request.get(@aiServiceHealthUrl).end (err, res) -> if res? && res.status >= 400 # Network failure, we should probably return a more intuitive error object Logger.module("CONSUL").debug "ERROR! Failed to connect to Consul, kv.get(#{key}) failed: #{res.status} ".red return reject(new Error("Failed to connect to Consul.")) else if err # Internal failure Logger.module("CONSUL").debug "ERROR! getHealthySinglePlayerServers() failed: #{err.message} ".red return reject(err) else Logger.module("CONSUL").debug "getHealthySinglePlayerServers()".green return resolve(res.body) .nodeify(callback) # Get whether or not this server should re-assign players on shutdown # Value is stored in Consul KV under /nodes tree # Note in most cases, this will default to true (even if no flag is found in Consul) @getReassignmentStatus: (callback) -> nodename = os.hostname().split(".")[0] key = "PI:KEY:<KEY>END_PIconfig.get('env')}-PI:KEY:<KEY>END_PI" status = new Promise (resolve, reject) => request .get(@kvUrl + key + "?raw") .accept('json') .end (err, res) -> if err # If there's an error, we still want to default true return resolve(true) if res.status >= 400 # If no reassignment-status flag is found (ie 404), we want to default true return resolve(true) return resolve(res.text) # Parse the reassignment-status result, note JSON.parse(true) = true # Value in Consul looks like {"enabled":true} return status.then(JSON.parse).then (result) -> if result.enabled == false Logger.module("CONSUL").debug "getReassignmentStatus() == false".red return false Logger.module("CONSUL").debug "getReassignmentStatus() == true".green return true .nodeify(callback) module.exports = Consul
[ { "context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan", "end": 18, "score": 0.9998895525932312, "start": 10, "tag": "NAME", "value": "Tim Knip" }, { "context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\nclass Input\n constructor: ->\n @semantic = \"\"", "end": 110, "score": 0.9999273419380188, "start": 86, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/loaders/collada/input.coffee
andrew-aladev/three.js
0
# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com # @author aladjev.andrew@gmail.com class Input constructor: -> @semantic = "" @offset = 0 @source = "" @set = 0 parse: (element) -> @semantic = element.getAttribute "semantic" @source = element.getAttribute("source").replace /^#/, "" @set = THREE.ColladaLoader._attr_as_int element, "set", -1 @offset = THREE.ColladaLoader._attr_as_int element, "offset", 0 if @semantic is "TEXCOORD" and @set < 0 @set = 0 this namespace "THREE.Collada", (exports) -> exports.Input = Input
199247
# @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com # @author <EMAIL> class Input constructor: -> @semantic = "" @offset = 0 @source = "" @set = 0 parse: (element) -> @semantic = element.getAttribute "semantic" @source = element.getAttribute("source").replace /^#/, "" @set = THREE.ColladaLoader._attr_as_int element, "set", -1 @offset = THREE.ColladaLoader._attr_as_int element, "offset", 0 if @semantic is "TEXCOORD" and @set < 0 @set = 0 this namespace "THREE.Collada", (exports) -> exports.Input = Input
true
# @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com # @author PI:EMAIL:<EMAIL>END_PI class Input constructor: -> @semantic = "" @offset = 0 @source = "" @set = 0 parse: (element) -> @semantic = element.getAttribute "semantic" @source = element.getAttribute("source").replace /^#/, "" @set = THREE.ColladaLoader._attr_as_int element, "set", -1 @offset = THREE.ColladaLoader._attr_as_int element, "offset", 0 if @semantic is "TEXCOORD" and @set < 0 @set = 0 this namespace "THREE.Collada", (exports) -> exports.Input = Input
[ { "context": "STAR On-Line\n\n\t\t\nReturn to Request STAR On-Line\n\t\nRandom Guy\n\t\n \nPREPARED: 01/30/13 - 08:31\nGuy,Random 1\nPROGR", "end": 121, "score": 0.9798430800437927, "start": 111, "tag": "NAME", "value": "Random Guy" }, { "context": "ck Titan Web for your registration date\n \nADVISOR: Krohn,Erik A UGLS J34007222\n \nSTUDENT ACAD", "end": 577, "score": 0.9997984766960144, "start": 572, "tag": "NAME", "value": "Krohn" }, { "context": "n Web for your registration date\n \nADVISOR: Krohn,Erik A UGLS J34007222\n \nSTUDENT ACADEMIC P", "end": 584, "score": 0.9017218947410583, "start": 578, "tag": "NAME", "value": "Erik A" } ]
tempstar.coffee
seiyria/star-report-reader
0
@tempStar = """ New Window | Help | Customize Page STAR On-Line Return to Request STAR On-Line Random Guy PREPARED: 01/30/13 - 08:31 Guy,Random 1 PROGRAM CODE: 222234007 CATALOG YEAR: 2010 CAMPUS ID : xxxxxxx BACHELOR OF SCIENCE DEGREE - COLLEGE OF LETTERS AND SCIENCE COMPUTER SC & SOFTWARE ENGINEERING (SOFTWARE ENGINEERING) MAJOR ================================================================= UNIVERSITY OF WISCONSIN OSHKOSH STUDENT ACADEMIC REPORT (STAR) REPORT NO. Check Titan Web for your registration date ADVISOR: Krohn,Erik A UGLS J34007222 STUDENT ACADEMIC PROGRAM PROGRAM : UGLS 2010 PLAN : J34007222 Comp Sci(Software Eng)-BS 2010 UW-OSHKOSH PLACEMENT AT TIME OF ADMISSION ENGLISH : Gen Ed English Comp MATH : Math Math 122 or 171 (3/12/05) ACADEMIC STANDING : GOOD COMMENTS : OFFICIAL GRADE EARNED GPA CREDS POINTS GPA CREDS TRANSFER INST 0.00 UWO OFFICIAL 81.00 227.38 2.807 84.00 ================================================================= ------> AT LEAST ONE REQUIREMENT HAS NOT BEEN SATISFIED <------ ================================================================= COMBINED GPA (IPLIST) UWO AND TRANSFER COURSE COMBINED GPA (Amnesty courses excluded) 84.00 CRS EARNED 81.00 ATTEMPTED HOURS 227.38 POINTS 2.807 GPA IN-PROG 15.00 CREDITS ======================================================= IN-PROGRESS COURSES 1232 34-331 3.00 .00 IP Programming Languages 1232 34-342 3.00 .00 IP Software Engineering II 1232 34-350 1.00 .00 IP Ethical Issues in Computing 1232 34-361 3.00 .00 IP Database Systems 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) 1232 94-208 1.00 .00 IP Career Sklls in Math & Nat Sc * ======================================================= ADJUSTMENTS TO THE COURSE REGISTRATIONS LISTED ABOVE OR COURSES NOT COMPLETED SUCCESSFULLY WILL CHANGE THE STATUS OF THIS REPORT. COURSES CURRENTLY BEING REPEATED WILL NOT BE LISTED WITH THE IN-PROGRESS COURSE BUT WILL BE LISTED IN THE REQUIREMENT TO WHICH THEY APPLY. ======================================================= YOU MUST APPLY FOR GRADUATION THE SEMESTER PRIOR TO YOUR GRADUATION SEMESTER: FALL GRADUATION, APPLY BY END OF PREVIOUS SPRING SEMESTER; SPRING & SUMMER GRADUATION, APPLY BY END OF PREVIOUS FALL SEMESTER. AN APPLICATION FORM IS AVAILABLE ON LINE AT (WWW.UWOSH.EDU/REGISTRAR). CLICK ON GRADUATION. FOLLOW INSTRUCTIONS TO COMPLETE & SUBMIT APPLICATION FORM. ================================================================= NO GENERAL EDUCATION COMPOSITION (GCOMP) 2008-10 MINIMUM 2.00 GPA REQUIRED IN ALL APPLICABLE COURSES TWO COURSES (6 CREDITS) REQUIRED EARNED 3.670 GPA + 1) COMPLETE A WRITING-BASED COMPOSITION COURSE: 1012 88-188 3.00 A- 11.01 Wrtng-Bsd Inq Sem (WBIS) (EN) - 2) COMPLETE A SECOND COMPOSITION COURSE: (MINIMUM OF 45 CREDITS REQUIRED TO ENROLL) SELECT FROM: 38-203 38-302 38-307 38-309 38-310 38-316 38-317 38-318 38-321 38-389 ================================================================= OK MATHEMATICS REQUIREMENT FOR THE L&S (GMATH2BS) BACHELOR OF SCIENCE DEGREE + 1) LEVEL II MATH 2.467 GPA 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) + 2) LEVEL I MATH EXEMPTED/COMPLETED WITH LEVEL II 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I ================================================================= OK GENERAL EDUCATION PHYSICAL EDUCATION (GPED) ONE COURSE (TWO CREDITS) REQUIRED (1995-2010) 1121 79-105 2.00 A- 7.34 Active Lifestyle (PE) ================================================================= OK GENERAL EDUCATION NON-WESTERN CULTURE (GNWST) ONE COURSE (THREE CREDITS) REQUIRED 1231 50-102 3.00 C- 5.01 World Reg Geog (NW) (SS) ================================================================= OK COMMUNICATION REQUIREMENT FOR THE L&S (GSPCH2BSA) BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES 1011 96-111 3.00 B- 8.01 Fund Spch Comm (GE) ================================================================= NO HUMANITIES REQUIREMENT FOR THE L&S (GHUM2BS) BACHELOR OF SCIENCE DEGREE EARNED 9.00 CREDITS 3 SUB-REQS --> NEEDS: 3.00 CREDITS +R 1) COMPLETE ONE LITERATURE COURSE FROM THE FOLLOWING LIST: 1122 38-221 3.00 B+ 9.99 Asian Am Lit (HU) (ES) SELECT FROM: 38-210 38-211 38-212 38-213 38-214 38-218 38-219 OR 38-229 38-220 38-224 OR 98-224 38-225 38-226 38-227 38-228 38-231 38-238 38-239 38-240 38-247 38-367 38-393 31-201 31-202 37-243 OR 38-243 94-245 37-244 OR 38-244 + 2) COMPLETE A MINIMUM OF ONE COURSE FROM TWO OF THE FOLLOWING THREE AREAS: FINE ARTS AREA (ART, DRAMA AND MUSIC) 1121 22-105 3.00 A 12.00 Understanding the Arts (HU) SELECT FROM: 00-275 22-243 OR 73-243 OR 97-243 OR 98-243 22-101 22-115 22-203 22-209 22-210 95-101 97-161 97-162 73-014 73-102 73-133 73-134 73-135 73-216 73-217 73-218 73-219 73-221 94-104 + 3) PHILOSOPHY AND RELIGIOUS STUDIES AREA: 1122 76-109 3.00 C+ 6.99 Intro to Philosophy (HU) SELECT FROM: 76-101 76-105 76-106 76-207 76-215 76-225 87-101(92.1-09.4) 87-103(92.1-09.4) 87-104 87-105 87-106 87-107(92.1-09.4) 87-204 87-210 87-162 OR 37-162(98.1-99.9) 87-275(92.1-09.4) 87-265 4) FOREIGN LANGUAGE AREA: NEEDS: 1 COURSE SELECT FROM: 41-110 41-111 41-203 41-204 41-208 41-248 42-110 42-111 42-210 42-211 43-110 43-111 43-203 43-204 43-207 43-248 44-110 44-111 44-210 44-211 48-110 48-111 48-203 48-204 49-101 49-102 49-103 49-104 49-110 49-111 49-112 49-113 49-203 49-204 49-207 49-208 49-248 56-110 56-111 56-210 56-211 5) COURSES IN THIS LIST MAY COUNT TOWARD THE 12 CREDITS REQUIRED FOR HUMANITIES/FINE ARTS, BUT WILL NOT COUNT TOWARD ONE OF THE THREE AREAS REQUIRED: NEEDS: 1 COURSE SELECT FROM: 00-175 23-100 38-220 38-238 38-239 38-240 31-200 37-282 41-110 41-111 41-203 41-204 41-207 41-208 43-110 43-111 43-203 43-204 43-207 43-208 44-110 44-203 44-204 44-207 44-208 48-110 48-111 48-203 48-204 49-108 49-110 49-111 49-112 49-113 49-203 49-204 49-207 87-265 OR 98-265 87-265 94-200 94-245 94-283 94-298 ================================================================= COMPLETION OF THE B.S. LAB SCIENCE AREA REQUIRES FOUR (4) COURSES AS DESCRIBED BELOW IN AREAS 1-3. SELECT FROM LAB SCIENCES IN BIOLOGY, CHEMISTRY, GEOGRAPHY, GEOLOGY, PHYSICS/ASTRONOMY (NEW1) ------------ AREA #1 ------------------------------------------ TWO LABORATORY SCIENCE COURSES FROM THE SAME DEPARTMENT, ONE OF WHICH REQUIRES THE SECOND AS A PREREQUISITE. ------------ AREA #2 ------------------------------------------ ONE NATURAL SCIENCE LABORATORY COURSE FROM A DIFFERENT DEPARTMENT THAN THE DEPARTMENT SELECTED IN AREA #1 ------------ AREA #3 ------------------------------------------ ONE COURSE THAT MATCHES ONE OF THE OPTIONS BELOW: A) A COURSE FROM THE SAME DEPARTMENT AS THE ONE SELECTED FOR AREA #2 AND WHICH HAS THAT COURSE AS A PREREQUISITE B) A LAB SCIENCE COURSE FROM A 3RD DEPARTMENT C) A COURSE FROM THOSE LISTED UNDER THE B.S. MATH REQUIREMENT ================================================================= NO TWO PAIRS (ONE PAIR FROM EACH OF TWO DEPARTMENTS) (NEW3) + 1) GEOGRAPHY DEPARTMENTAL APPROVED PAIR 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) ================================================================= COMPLETE TWO COURSES FROM THE SAME NATURAL SCIENCE DEPARTMENT. (THE FIRST COURSE MUST BE THE PREREQUISITE OF THE SECOND COURSE) NOTE: PLEASE SEE THE LIST OF APPROVED PAIRS LOCATED IN THE PREVIOUS REQUIREMENT. --------------------------------------------- NO OR ONE PAIR PLUS 2 OTHER DEPARTMENTS OPTION (NEW2) + 1) GEOGRAPHY DEPARTMENTAL APPROVED PAIR 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) - 2) CHEMISTRY - 3) ----------------------------------------------- COMPLETE A LAB SCIENCE COURSE FROM EACH OF TWO SCIENCE DEPARTMENTS OTHER THAN THE DEPARTMENT SELECTED FOR THE REQUIRED LAB PAIR. ......THE COURSES USED TO SATISFY THE PAIR ABOVE WILL ALSO PRINT IN THE APPROPRIATE AREA BELOW, BUT WILL NOT SATISFY THE DEPARTMENTAL REQUIREMENT (A TOTAL OF THREE DEPARTMENTS REQUIRED -- INCLUDING THE PAIR) BIOLOGY + 4) GEOGRAPHY 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) - 5) GEOLOGY - 6) PHYSICS/ASTRONOMY - 7) ANTHROPOLOGY + 8) YOU MAY TAKE A SECOND MATH/STATS/COMPUTER SC. AREA (AS DESCRIBED IN THE MATH REQUIREMENT FOR YOUR THIRD DEPARTMENT REQUIREMENT. 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I ================================================================= OK SOCIAL SCIENCE REQUIREMENT FOR THE L&S (GSOSC2BSA) BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES EARNED 18.00 CREDITS +R 1) YOU MUST COMPLETE A MINIMUM OF THREE CREDITS OF HISTORY 3.00 CRS EARNED 1012 57-102 3.00 B 9.00 Modern Civilization (SS) + 3) ANTHROPOLOGY (ANY COURSE EXCEPT 21-202) 3.00 CRS EARNED 1012 21-102 3.00 B- 8.01 Intro to Anthropology (SS) + 5) ECONOMICS (ANY COURSE) 6.00 CRS EARNED 1011 36-106 3.00 B- 8.01 General Economics (SS) 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) + 7) GEOGRAPHY (ANY COURSE EXCEPT GEOG 121, 122, 304, 335, 342, 352, AND 363) 3.00 CRS EARNED 1231 50-102 3.00 C- 5.01 World Reg Geog (NW) (SS) + 11) PSYCHOLOGY (ANY COURSE EXCEPT PSYCH 203, 303, 305, 310, 341,367,371,380,383,384,391,411,455,481,498 & 499) 3.00 CRS EARNED 1011 86-101 3.00 B- 8.01 General Psychology (SS) ================================================================= OK GENERAL EDUCATION ETHNIC STUDIES (GETHNIC) ONE COURSE (THREE CREDITS) REQUIRED (IF SELECTED, 74-215 MUST BE COMPLETED FOR 3 CREDITS) 1122 38-221 3.00 B+ 9.99 Asian Am Lit (HU) (ES) ================================================================= OPTIONAL GENERAL EDUCATION COURSES (NOT REQUIRED, BUT MAY BE APPLIED TOWARD 42 CREDIT MINIMUM IN GENERAL EDUCATION) (GOPT) (SEE E-BULLETIN OR E-TIMETABLE FOR LIST) ================================================================= OK GENERAL EDUCATION SUMMARY (GENEDSUM) A MINIMUM OF 42 CREDITS IN GENERAL EDUCATION IS REQUIRED. PLEASE REFER TO THE E-BULLETIN OR E-TIMETABLE FOR THE APPROVED GENERAL EDUCATION LIST. EARNED 43.00 CREDITS 43.00 ATTEMPTED HOURS 115.71 POINTS 2.690 GPA IN-PROGRESS 4.00 CREDITS ================================================================= NO COMPUTER SCIENCE MAJ (SOFTWARE ENG)(J34007/09-99) 60 CREDITS AND A 2.00 MINIMUM G.P.A. REQUIRED EARNED 44.00 CREDITS 2.813 GPA IN-PROGRESS 10.00 CREDITS --> NEEDS: 6.00 CREDITS 2 SUB-REQS 2.000 GPA - 1) COMPLETE THE FOLLOWING CORE COURSES: 17.00 CRS EARNED 2.668 GPA IN-PROG 3.00 CREDITS 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 34-251 3.00 C 6.00 Comp Org & Assembly Language 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1121 34-271 4.00 B- 10.68 Data Structures 1121 67-212 3.00 C 6.00 Mathematics for Comp Sci 1232 34-331 3.00 .00 IP Programming Languages NEEDS: 2 COURSES SELECT FROM: 34-399 OR 34-490 82-311 - 2) COMPLETE THE FOLLOWING COURSES IN ADDITION TO THE COMPUTER SCIENCE CORE COURSES: 14.00 CRS EARNED 2.500 GPA IN-PROG 7.00 CREDITS 1011 67-171 4.00 C 8.00 Calculus I (MA) 1122 34-421 4.00 B 12.00 Operating Systems 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I 1232 34-342 3.00 .00 IP Software Engineering II 1232 34-350 1.00 .00 IP Ethical Issues in Computing 1232 34-361 3.00 .00 IP Database Systems NEEDS: 1 COURSE SELECT FROM: 34-321 + 3) COMPLETE A MINIMUM OF THREE CREDITS FROM THE FOLLOWING LIST A ELECTIVES: 6.00 CRS EARNED 3.500 GPA 1121 34-371 3.00 B 9.00 Computer Graphics 1231 34-346 3.00 A 12.00 Web Software Dev SELECT FROM: 34-300 34-310 34-381 34-391 34-421 34-431 34-480 + 4) SELECT A MINIMUM OF 6 CREDITS FROM THE FOLLOWING LIST B AND C COURSES COMBINED: 6.00 CRS EARNED 3.000 GPA 1122 28-315 3.00 B 9.00 Database Systems-Business 1231 28-314 3.00 B 9.00 IS Analysis-Design SELECT FROM: 28-260 28-319 28-355 28-410 82-305 82-319 82-405 67-222 67-256 67-302 67-304 67-342 67-346 67-347 67-349 67-355 67-356 67-357 67-385 67-401 67-402 + 5) A MINIMUM GRADE POINT AVERAGE OF 2.00 IN ALL COURSES NUMBERED 300 OR ABOVE (EXCEPT 34-399, 34-446, 34-456, 34-474, AND 34-490) IS REQUIRED. 1.00 CR APPLIED 1 COURSE TAKEN 4.000 GPA 1231 34-314 1.00 A 4.00 Practice of ICPC Competition NEEDS: 2.000 GPA -> NOT FROM: 34-334 34-335 34-399 34-446 34-456 34-474 34-490 SELECT FROM: 34-300 TO 34-499 ================================================================= ELECTIVE CREDITS WHICH APPLY TO THE UNDERGRADUATE DEGREE (ELECTIVE) 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) 1232 94-208 1.00 .00 IP Career Sklls in Math & Nat Sc ================================================================= CHECK LIMITS FOR MUSIC, DRAMA, PHY-ED PARTICIPATION AND PROFESSIONAL COURSES (PRESUM2) 1) ONLY 4 CREDITS OF MUSIC PARTICIPATION COURSES MAY BE APPLIED TO DEGREE CREDIT FOR NON-MUSIC MAJORS OR MINORS. 2) ONLY 4 CREDITS OF DRAMA OR THEATRE PARTICIPATION COURSES MAY APPLY TO DEGREE CREDITS 3) ONLY 4 CREDITS OF PHYSICAL EDUCATION ACTIVITY COURSES MAY APPLY TO THE DEGREE CREDITS IN THIS AREA. (ANY CREDITS OVER 4 WILL BE COUNTED AS PREPROFESSIONAL) 1121 79-105 2.00 A- 7.34 Active Lifestyle (PE) 4) A MAXIMUM OF 24 PREPROFESSIONAL CREDITS MAY COUNT TOWARD THE 120 REQUIRED TO GRADUATE. 1122 28-315 3.00 B 9.00 Database Systems-Business 1231 28-314 3.00 B 9.00 IS Analysis-Design ================================================================= NO GENERAL BACCALAUREATE DEGREE REQUIREMENTS (SUMMARY) - 1) EARN A MINIMUM OF 120 DEGREE CREDITS 84.00 CRS EARNED IN-PROG 15.00 CREDITS NEEDS: 21.00 CREDITS + 3) EARN A MINIMUM 2.00 GPA IN UWO CREDITS ATTEMPTED 81.00 ATTEMPTED HOURS 227.38 POINTS 2.807 GPA + 4) EARN A MINIMUM 2.00 GPA IN ALL COURSES APPLICABLE TO THE UNIVERSITY'S GENERAL EDUCATION ENGLISH COMPOSITION REQUIREMENT 3.670 GPA + 5) EARN AT LEAST 30 SEMESTER CREDITS AT UW OSHKOSH ( 84.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS + 6) EARN AT LEAST 48 CREDITS FROM A 4 YEAR INSTITUTION ( 84.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS - 7) EARN AT LEAST 35 CREDITS AT THE UPPER LEVEL (300/400) WITH A MINIMUM 2.00 GPA ( 20.00 CREDITS TAKEN) 20.00 ATTEMPTED HOURS 64.99 POINTS 3.249 GPA IN-PROG 10.00 CREDITS NEEDS: 5.00 CREDITS + 8) 15 OF THE LAST 30 CREDITS MUST BE TAKEN AT UWO. ( 17.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS ================================================================= **** LEGEND **** NO = REQUIREMENT NOT COMPLETE >D = DUPLICATE COURSE - CREDIT OK = REQUIREMENT COMPLETE & GPA EFFECT REMOVED ON - = SUBREQUIREMENT NOT COMPLETE COURSE EXCEEDING LIMIT + = SUBREQUIREMENT COMPLETE >X = REPEATED COURSE - CREDIT * = SUBREQUIREMENT IS OPTIONAL & GPA EFFECT REMOVED ON (R)= REQUIRED COURSE ORIGINAL COURSE +R = REQUIRED SUBREQUIREMENT >S = COURSE CREDIT SPLIT COMPLETED BETWEEN REQUIREMENTS -R = REQUIRED SUBREQUIREMENT >R = REPEATABLE COURSE - CREDIT NOT COMPLETED MAY BE EARNED MORE THAN CS = COURSE SUBSTITUTION ONCE WC = WAIVED COURSE WH = WAIVED CREDIT HOUR <> = CONTINUED REQUIREMENT >C = DUPLICAT CROSS-LINKED COUR S = SATISFACTORY GRADE IN RETRO., MILITARY, DEPT., TEST OUT CR. ****** PLEASE NOTE: THE FOUR NUMBERS BEFORE A COURSE INDICATE THE TERM IN WHICH THE COURSE WAS TAKEN. THE FIRST THREE NUMBERS INDICATE THE ACADEMIC YEAR (078 IS USED FOR THE 2007-08 ACADEMIC YEAR). THE LAST NUMBER INDICATES THE TERM (1 = FALL, 2 = SPRING, 4 = SUMMER). FOR EXAMPLE, 0782 IS THE SPRING TERM OF 2007-08. **************************************************************** ****** THIS NOTICE OF ACADEMIC PROGRESS HAS BEEN PREPARED TO ASSIST YOU DURING YOUR COLLEGE EXPERIENCE. ALTHOUGH EFFORTS HAVE BEEN MADE TO ASSESS THE ACCURACY OF THIS REPORT, YOU ARE RESPONSIBLE FOR MAKING SURE THAT ALL REQUIREMENTS HAVE BEEN COMPLETED. THE REGISTRAR'S OFFICE WILL ULTIMATELY AUTHORIZE THE AWARDING OF YOUR DEGREE; THEREFORE, IF YOU HAVE ANY QUESTIONS ABOUT THE ACCURACY OF THIS PROGRESS REPORT, PLEASE SEE AN ACADEMIC ADVISOR IN DEMPSEY 130. ******* **************************************************************** ================================================================= THIS AUDIT ASSUMES SUCCESSFUL COMPLETION OF ALL IN-PROGRESS COURSES; ANY IN-PROGRESS COURSES NOT COMPLETED SUCCESSFULLY MAY CHANGE THIS AUDIT'S EVALUATION. ----------------------------------------------------------------- **** CONFIDENTIAL - STUDENT/ADVISOR USE ONLY **** **** FEDERAL LAW PROHIBITS TRANSMITTAL TO A THIRD PARTY **** ----------------------------------------------------------------- DEPARTMENT CONVERSION TABLE HONORS 00 HEALTH 55 SERVICE COURSES IN EDUC 11 HEALTH EDUCATION 55 EDUCATIONAL FOUNDATIONS 12 CHINESE 56 ELEMENTARY EDUCATION 13 HISTORY 57 SECONDARY EDUCATION 14 INTERNATIONAL STUDIES 59 READING EDUCATION 15 JOURNALISM 61 SPECIAL EDUCATION 16 KINESIOLOGY 77 EDUCATIONAL LEADERSHIP 17 MATHEMATICS 67 HUMAN SERVICES 18 MEDICAL TECHNOLOGY 68 ANTHROPOLOGY 21 MILITARY SCIENCE 70 ART 22 NURSING COLLABORATIVE 71 AFRICAN AMERICAN STUDIES 23 MUSIC 73 BIOLOGY 26 NURSING 74 BUSINESS 28 PHILOSOPHY 76 COUNSELOR EDUCATION 29 PHYSICAL EDUCATION 79 PROFESSIONAL COUNSELING 29 PHYSICAL SCIENCE 80 LIBERAL STUDIES 31 PUBLIC ADMINISTRATION 81 CHEMISTRY 32 PHYSICS/ASTRONOMY 82 COMPUTER SCIENCE 34 POLITICAL SCIENCE 84 CRIMINAL JUSTICE 35 PRACTICAL ARTS 85 ECONOMICS 36 PSYCHOLOGY 86 ENVIRONMENTAL STUDIES 37 RELIGIOUS STUDIES 87 ENGLISH 38 WRITING-BASED INQ SEM 88 FRENCH 41 PROBLEM-BASED INQ SEM 89 GERMAN 43 SOCIAL JUSTICE 91 JAPANESE 44 SOCIOLOGY 92 RUSSIAN 48 SOCIAL WORK 93 SPANISH 49 INTERDISCIPLINARY STDS 94 GEOGRAPHY 50 COMMUNICATION 96 GEOLOGY 51 THEATRE 97 ARAPAHO 53 WOMEN'S STUDIES 98 SHOSHONE 54 URBAN PLANNING 99 ----------------------------------------------------------------- ================================================================= ********************* END OF ANALYSIS ********************* Return to Academics """;
2980
@tempStar = """ New Window | Help | Customize Page STAR On-Line Return to Request STAR On-Line <NAME> PREPARED: 01/30/13 - 08:31 Guy,Random 1 PROGRAM CODE: 222234007 CATALOG YEAR: 2010 CAMPUS ID : xxxxxxx BACHELOR OF SCIENCE DEGREE - COLLEGE OF LETTERS AND SCIENCE COMPUTER SC & SOFTWARE ENGINEERING (SOFTWARE ENGINEERING) MAJOR ================================================================= UNIVERSITY OF WISCONSIN OSHKOSH STUDENT ACADEMIC REPORT (STAR) REPORT NO. Check Titan Web for your registration date ADVISOR: <NAME>,<NAME> UGLS J34007222 STUDENT ACADEMIC PROGRAM PROGRAM : UGLS 2010 PLAN : J34007222 Comp Sci(Software Eng)-BS 2010 UW-OSHKOSH PLACEMENT AT TIME OF ADMISSION ENGLISH : Gen Ed English Comp MATH : Math Math 122 or 171 (3/12/05) ACADEMIC STANDING : GOOD COMMENTS : OFFICIAL GRADE EARNED GPA CREDS POINTS GPA CREDS TRANSFER INST 0.00 UWO OFFICIAL 81.00 227.38 2.807 84.00 ================================================================= ------> AT LEAST ONE REQUIREMENT HAS NOT BEEN SATISFIED <------ ================================================================= COMBINED GPA (IPLIST) UWO AND TRANSFER COURSE COMBINED GPA (Amnesty courses excluded) 84.00 CRS EARNED 81.00 ATTEMPTED HOURS 227.38 POINTS 2.807 GPA IN-PROG 15.00 CREDITS ======================================================= IN-PROGRESS COURSES 1232 34-331 3.00 .00 IP Programming Languages 1232 34-342 3.00 .00 IP Software Engineering II 1232 34-350 1.00 .00 IP Ethical Issues in Computing 1232 34-361 3.00 .00 IP Database Systems 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) 1232 94-208 1.00 .00 IP Career Sklls in Math & Nat Sc * ======================================================= ADJUSTMENTS TO THE COURSE REGISTRATIONS LISTED ABOVE OR COURSES NOT COMPLETED SUCCESSFULLY WILL CHANGE THE STATUS OF THIS REPORT. COURSES CURRENTLY BEING REPEATED WILL NOT BE LISTED WITH THE IN-PROGRESS COURSE BUT WILL BE LISTED IN THE REQUIREMENT TO WHICH THEY APPLY. ======================================================= YOU MUST APPLY FOR GRADUATION THE SEMESTER PRIOR TO YOUR GRADUATION SEMESTER: FALL GRADUATION, APPLY BY END OF PREVIOUS SPRING SEMESTER; SPRING & SUMMER GRADUATION, APPLY BY END OF PREVIOUS FALL SEMESTER. AN APPLICATION FORM IS AVAILABLE ON LINE AT (WWW.UWOSH.EDU/REGISTRAR). CLICK ON GRADUATION. FOLLOW INSTRUCTIONS TO COMPLETE & SUBMIT APPLICATION FORM. ================================================================= NO GENERAL EDUCATION COMPOSITION (GCOMP) 2008-10 MINIMUM 2.00 GPA REQUIRED IN ALL APPLICABLE COURSES TWO COURSES (6 CREDITS) REQUIRED EARNED 3.670 GPA + 1) COMPLETE A WRITING-BASED COMPOSITION COURSE: 1012 88-188 3.00 A- 11.01 Wrtng-Bsd Inq Sem (WBIS) (EN) - 2) COMPLETE A SECOND COMPOSITION COURSE: (MINIMUM OF 45 CREDITS REQUIRED TO ENROLL) SELECT FROM: 38-203 38-302 38-307 38-309 38-310 38-316 38-317 38-318 38-321 38-389 ================================================================= OK MATHEMATICS REQUIREMENT FOR THE L&S (GMATH2BS) BACHELOR OF SCIENCE DEGREE + 1) LEVEL II MATH 2.467 GPA 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) + 2) LEVEL I MATH EXEMPTED/COMPLETED WITH LEVEL II 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I ================================================================= OK GENERAL EDUCATION PHYSICAL EDUCATION (GPED) ONE COURSE (TWO CREDITS) REQUIRED (1995-2010) 1121 79-105 2.00 A- 7.34 Active Lifestyle (PE) ================================================================= OK GENERAL EDUCATION NON-WESTERN CULTURE (GNWST) ONE COURSE (THREE CREDITS) REQUIRED 1231 50-102 3.00 C- 5.01 World Reg Geog (NW) (SS) ================================================================= OK COMMUNICATION REQUIREMENT FOR THE L&S (GSPCH2BSA) BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES 1011 96-111 3.00 B- 8.01 Fund Spch Comm (GE) ================================================================= NO HUMANITIES REQUIREMENT FOR THE L&S (GHUM2BS) BACHELOR OF SCIENCE DEGREE EARNED 9.00 CREDITS 3 SUB-REQS --> NEEDS: 3.00 CREDITS +R 1) COMPLETE ONE LITERATURE COURSE FROM THE FOLLOWING LIST: 1122 38-221 3.00 B+ 9.99 Asian Am Lit (HU) (ES) SELECT FROM: 38-210 38-211 38-212 38-213 38-214 38-218 38-219 OR 38-229 38-220 38-224 OR 98-224 38-225 38-226 38-227 38-228 38-231 38-238 38-239 38-240 38-247 38-367 38-393 31-201 31-202 37-243 OR 38-243 94-245 37-244 OR 38-244 + 2) COMPLETE A MINIMUM OF ONE COURSE FROM TWO OF THE FOLLOWING THREE AREAS: FINE ARTS AREA (ART, DRAMA AND MUSIC) 1121 22-105 3.00 A 12.00 Understanding the Arts (HU) SELECT FROM: 00-275 22-243 OR 73-243 OR 97-243 OR 98-243 22-101 22-115 22-203 22-209 22-210 95-101 97-161 97-162 73-014 73-102 73-133 73-134 73-135 73-216 73-217 73-218 73-219 73-221 94-104 + 3) PHILOSOPHY AND RELIGIOUS STUDIES AREA: 1122 76-109 3.00 C+ 6.99 Intro to Philosophy (HU) SELECT FROM: 76-101 76-105 76-106 76-207 76-215 76-225 87-101(92.1-09.4) 87-103(92.1-09.4) 87-104 87-105 87-106 87-107(92.1-09.4) 87-204 87-210 87-162 OR 37-162(98.1-99.9) 87-275(92.1-09.4) 87-265 4) FOREIGN LANGUAGE AREA: NEEDS: 1 COURSE SELECT FROM: 41-110 41-111 41-203 41-204 41-208 41-248 42-110 42-111 42-210 42-211 43-110 43-111 43-203 43-204 43-207 43-248 44-110 44-111 44-210 44-211 48-110 48-111 48-203 48-204 49-101 49-102 49-103 49-104 49-110 49-111 49-112 49-113 49-203 49-204 49-207 49-208 49-248 56-110 56-111 56-210 56-211 5) COURSES IN THIS LIST MAY COUNT TOWARD THE 12 CREDITS REQUIRED FOR HUMANITIES/FINE ARTS, BUT WILL NOT COUNT TOWARD ONE OF THE THREE AREAS REQUIRED: NEEDS: 1 COURSE SELECT FROM: 00-175 23-100 38-220 38-238 38-239 38-240 31-200 37-282 41-110 41-111 41-203 41-204 41-207 41-208 43-110 43-111 43-203 43-204 43-207 43-208 44-110 44-203 44-204 44-207 44-208 48-110 48-111 48-203 48-204 49-108 49-110 49-111 49-112 49-113 49-203 49-204 49-207 87-265 OR 98-265 87-265 94-200 94-245 94-283 94-298 ================================================================= COMPLETION OF THE B.S. LAB SCIENCE AREA REQUIRES FOUR (4) COURSES AS DESCRIBED BELOW IN AREAS 1-3. SELECT FROM LAB SCIENCES IN BIOLOGY, CHEMISTRY, GEOGRAPHY, GEOLOGY, PHYSICS/ASTRONOMY (NEW1) ------------ AREA #1 ------------------------------------------ TWO LABORATORY SCIENCE COURSES FROM THE SAME DEPARTMENT, ONE OF WHICH REQUIRES THE SECOND AS A PREREQUISITE. ------------ AREA #2 ------------------------------------------ ONE NATURAL SCIENCE LABORATORY COURSE FROM A DIFFERENT DEPARTMENT THAN THE DEPARTMENT SELECTED IN AREA #1 ------------ AREA #3 ------------------------------------------ ONE COURSE THAT MATCHES ONE OF THE OPTIONS BELOW: A) A COURSE FROM THE SAME DEPARTMENT AS THE ONE SELECTED FOR AREA #2 AND WHICH HAS THAT COURSE AS A PREREQUISITE B) A LAB SCIENCE COURSE FROM A 3RD DEPARTMENT C) A COURSE FROM THOSE LISTED UNDER THE B.S. MATH REQUIREMENT ================================================================= NO TWO PAIRS (ONE PAIR FROM EACH OF TWO DEPARTMENTS) (NEW3) + 1) GEOGRAPHY DEPARTMENTAL APPROVED PAIR 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) ================================================================= COMPLETE TWO COURSES FROM THE SAME NATURAL SCIENCE DEPARTMENT. (THE FIRST COURSE MUST BE THE PREREQUISITE OF THE SECOND COURSE) NOTE: PLEASE SEE THE LIST OF APPROVED PAIRS LOCATED IN THE PREVIOUS REQUIREMENT. --------------------------------------------- NO OR ONE PAIR PLUS 2 OTHER DEPARTMENTS OPTION (NEW2) + 1) GEOGRAPHY DEPARTMENTAL APPROVED PAIR 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) - 2) CHEMISTRY - 3) ----------------------------------------------- COMPLETE A LAB SCIENCE COURSE FROM EACH OF TWO SCIENCE DEPARTMENTS OTHER THAN THE DEPARTMENT SELECTED FOR THE REQUIRED LAB PAIR. ......THE COURSES USED TO SATISFY THE PAIR ABOVE WILL ALSO PRINT IN THE APPROPRIATE AREA BELOW, BUT WILL NOT SATISFY THE DEPARTMENTAL REQUIREMENT (A TOTAL OF THREE DEPARTMENTS REQUIRED -- INCLUDING THE PAIR) BIOLOGY + 4) GEOGRAPHY 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) - 5) GEOLOGY - 6) PHYSICS/ASTRONOMY - 7) ANTHROPOLOGY + 8) YOU MAY TAKE A SECOND MATH/STATS/COMPUTER SC. AREA (AS DESCRIBED IN THE MATH REQUIREMENT FOR YOUR THIRD DEPARTMENT REQUIREMENT. 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I ================================================================= OK SOCIAL SCIENCE REQUIREMENT FOR THE L&S (GSOSC2BSA) BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES EARNED 18.00 CREDITS +R 1) YOU MUST COMPLETE A MINIMUM OF THREE CREDITS OF HISTORY 3.00 CRS EARNED 1012 57-102 3.00 B 9.00 Modern Civilization (SS) + 3) ANTHROPOLOGY (ANY COURSE EXCEPT 21-202) 3.00 CRS EARNED 1012 21-102 3.00 B- 8.01 Intro to Anthropology (SS) + 5) ECONOMICS (ANY COURSE) 6.00 CRS EARNED 1011 36-106 3.00 B- 8.01 General Economics (SS) 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) + 7) GEOGRAPHY (ANY COURSE EXCEPT GEOG 121, 122, 304, 335, 342, 352, AND 363) 3.00 CRS EARNED 1231 50-102 3.00 C- 5.01 World Reg Geog (NW) (SS) + 11) PSYCHOLOGY (ANY COURSE EXCEPT PSYCH 203, 303, 305, 310, 341,367,371,380,383,384,391,411,455,481,498 & 499) 3.00 CRS EARNED 1011 86-101 3.00 B- 8.01 General Psychology (SS) ================================================================= OK GENERAL EDUCATION ETHNIC STUDIES (GETHNIC) ONE COURSE (THREE CREDITS) REQUIRED (IF SELECTED, 74-215 MUST BE COMPLETED FOR 3 CREDITS) 1122 38-221 3.00 B+ 9.99 Asian Am Lit (HU) (ES) ================================================================= OPTIONAL GENERAL EDUCATION COURSES (NOT REQUIRED, BUT MAY BE APPLIED TOWARD 42 CREDIT MINIMUM IN GENERAL EDUCATION) (GOPT) (SEE E-BULLETIN OR E-TIMETABLE FOR LIST) ================================================================= OK GENERAL EDUCATION SUMMARY (GENEDSUM) A MINIMUM OF 42 CREDITS IN GENERAL EDUCATION IS REQUIRED. PLEASE REFER TO THE E-BULLETIN OR E-TIMETABLE FOR THE APPROVED GENERAL EDUCATION LIST. EARNED 43.00 CREDITS 43.00 ATTEMPTED HOURS 115.71 POINTS 2.690 GPA IN-PROGRESS 4.00 CREDITS ================================================================= NO COMPUTER SCIENCE MAJ (SOFTWARE ENG)(J34007/09-99) 60 CREDITS AND A 2.00 MINIMUM G.P.A. REQUIRED EARNED 44.00 CREDITS 2.813 GPA IN-PROGRESS 10.00 CREDITS --> NEEDS: 6.00 CREDITS 2 SUB-REQS 2.000 GPA - 1) COMPLETE THE FOLLOWING CORE COURSES: 17.00 CRS EARNED 2.668 GPA IN-PROG 3.00 CREDITS 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 34-251 3.00 C 6.00 Comp Org & Assembly Language 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1121 34-271 4.00 B- 10.68 Data Structures 1121 67-212 3.00 C 6.00 Mathematics for Comp Sci 1232 34-331 3.00 .00 IP Programming Languages NEEDS: 2 COURSES SELECT FROM: 34-399 OR 34-490 82-311 - 2) COMPLETE THE FOLLOWING COURSES IN ADDITION TO THE COMPUTER SCIENCE CORE COURSES: 14.00 CRS EARNED 2.500 GPA IN-PROG 7.00 CREDITS 1011 67-171 4.00 C 8.00 Calculus I (MA) 1122 34-421 4.00 B 12.00 Operating Systems 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I 1232 34-342 3.00 .00 IP Software Engineering II 1232 34-350 1.00 .00 IP Ethical Issues in Computing 1232 34-361 3.00 .00 IP Database Systems NEEDS: 1 COURSE SELECT FROM: 34-321 + 3) COMPLETE A MINIMUM OF THREE CREDITS FROM THE FOLLOWING LIST A ELECTIVES: 6.00 CRS EARNED 3.500 GPA 1121 34-371 3.00 B 9.00 Computer Graphics 1231 34-346 3.00 A 12.00 Web Software Dev SELECT FROM: 34-300 34-310 34-381 34-391 34-421 34-431 34-480 + 4) SELECT A MINIMUM OF 6 CREDITS FROM THE FOLLOWING LIST B AND C COURSES COMBINED: 6.00 CRS EARNED 3.000 GPA 1122 28-315 3.00 B 9.00 Database Systems-Business 1231 28-314 3.00 B 9.00 IS Analysis-Design SELECT FROM: 28-260 28-319 28-355 28-410 82-305 82-319 82-405 67-222 67-256 67-302 67-304 67-342 67-346 67-347 67-349 67-355 67-356 67-357 67-385 67-401 67-402 + 5) A MINIMUM GRADE POINT AVERAGE OF 2.00 IN ALL COURSES NUMBERED 300 OR ABOVE (EXCEPT 34-399, 34-446, 34-456, 34-474, AND 34-490) IS REQUIRED. 1.00 CR APPLIED 1 COURSE TAKEN 4.000 GPA 1231 34-314 1.00 A 4.00 Practice of ICPC Competition NEEDS: 2.000 GPA -> NOT FROM: 34-334 34-335 34-399 34-446 34-456 34-474 34-490 SELECT FROM: 34-300 TO 34-499 ================================================================= ELECTIVE CREDITS WHICH APPLY TO THE UNDERGRADUATE DEGREE (ELECTIVE) 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) 1232 94-208 1.00 .00 IP Career Sklls in Math & Nat Sc ================================================================= CHECK LIMITS FOR MUSIC, DRAMA, PHY-ED PARTICIPATION AND PROFESSIONAL COURSES (PRESUM2) 1) ONLY 4 CREDITS OF MUSIC PARTICIPATION COURSES MAY BE APPLIED TO DEGREE CREDIT FOR NON-MUSIC MAJORS OR MINORS. 2) ONLY 4 CREDITS OF DRAMA OR THEATRE PARTICIPATION COURSES MAY APPLY TO DEGREE CREDITS 3) ONLY 4 CREDITS OF PHYSICAL EDUCATION ACTIVITY COURSES MAY APPLY TO THE DEGREE CREDITS IN THIS AREA. (ANY CREDITS OVER 4 WILL BE COUNTED AS PREPROFESSIONAL) 1121 79-105 2.00 A- 7.34 Active Lifestyle (PE) 4) A MAXIMUM OF 24 PREPROFESSIONAL CREDITS MAY COUNT TOWARD THE 120 REQUIRED TO GRADUATE. 1122 28-315 3.00 B 9.00 Database Systems-Business 1231 28-314 3.00 B 9.00 IS Analysis-Design ================================================================= NO GENERAL BACCALAUREATE DEGREE REQUIREMENTS (SUMMARY) - 1) EARN A MINIMUM OF 120 DEGREE CREDITS 84.00 CRS EARNED IN-PROG 15.00 CREDITS NEEDS: 21.00 CREDITS + 3) EARN A MINIMUM 2.00 GPA IN UWO CREDITS ATTEMPTED 81.00 ATTEMPTED HOURS 227.38 POINTS 2.807 GPA + 4) EARN A MINIMUM 2.00 GPA IN ALL COURSES APPLICABLE TO THE UNIVERSITY'S GENERAL EDUCATION ENGLISH COMPOSITION REQUIREMENT 3.670 GPA + 5) EARN AT LEAST 30 SEMESTER CREDITS AT UW OSHKOSH ( 84.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS + 6) EARN AT LEAST 48 CREDITS FROM A 4 YEAR INSTITUTION ( 84.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS - 7) EARN AT LEAST 35 CREDITS AT THE UPPER LEVEL (300/400) WITH A MINIMUM 2.00 GPA ( 20.00 CREDITS TAKEN) 20.00 ATTEMPTED HOURS 64.99 POINTS 3.249 GPA IN-PROG 10.00 CREDITS NEEDS: 5.00 CREDITS + 8) 15 OF THE LAST 30 CREDITS MUST BE TAKEN AT UWO. ( 17.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS ================================================================= **** LEGEND **** NO = REQUIREMENT NOT COMPLETE >D = DUPLICATE COURSE - CREDIT OK = REQUIREMENT COMPLETE & GPA EFFECT REMOVED ON - = SUBREQUIREMENT NOT COMPLETE COURSE EXCEEDING LIMIT + = SUBREQUIREMENT COMPLETE >X = REPEATED COURSE - CREDIT * = SUBREQUIREMENT IS OPTIONAL & GPA EFFECT REMOVED ON (R)= REQUIRED COURSE ORIGINAL COURSE +R = REQUIRED SUBREQUIREMENT >S = COURSE CREDIT SPLIT COMPLETED BETWEEN REQUIREMENTS -R = REQUIRED SUBREQUIREMENT >R = REPEATABLE COURSE - CREDIT NOT COMPLETED MAY BE EARNED MORE THAN CS = COURSE SUBSTITUTION ONCE WC = WAIVED COURSE WH = WAIVED CREDIT HOUR <> = CONTINUED REQUIREMENT >C = DUPLICAT CROSS-LINKED COUR S = SATISFACTORY GRADE IN RETRO., MILITARY, DEPT., TEST OUT CR. ****** PLEASE NOTE: THE FOUR NUMBERS BEFORE A COURSE INDICATE THE TERM IN WHICH THE COURSE WAS TAKEN. THE FIRST THREE NUMBERS INDICATE THE ACADEMIC YEAR (078 IS USED FOR THE 2007-08 ACADEMIC YEAR). THE LAST NUMBER INDICATES THE TERM (1 = FALL, 2 = SPRING, 4 = SUMMER). FOR EXAMPLE, 0782 IS THE SPRING TERM OF 2007-08. **************************************************************** ****** THIS NOTICE OF ACADEMIC PROGRESS HAS BEEN PREPARED TO ASSIST YOU DURING YOUR COLLEGE EXPERIENCE. ALTHOUGH EFFORTS HAVE BEEN MADE TO ASSESS THE ACCURACY OF THIS REPORT, YOU ARE RESPONSIBLE FOR MAKING SURE THAT ALL REQUIREMENTS HAVE BEEN COMPLETED. THE REGISTRAR'S OFFICE WILL ULTIMATELY AUTHORIZE THE AWARDING OF YOUR DEGREE; THEREFORE, IF YOU HAVE ANY QUESTIONS ABOUT THE ACCURACY OF THIS PROGRESS REPORT, PLEASE SEE AN ACADEMIC ADVISOR IN DEMPSEY 130. ******* **************************************************************** ================================================================= THIS AUDIT ASSUMES SUCCESSFUL COMPLETION OF ALL IN-PROGRESS COURSES; ANY IN-PROGRESS COURSES NOT COMPLETED SUCCESSFULLY MAY CHANGE THIS AUDIT'S EVALUATION. ----------------------------------------------------------------- **** CONFIDENTIAL - STUDENT/ADVISOR USE ONLY **** **** FEDERAL LAW PROHIBITS TRANSMITTAL TO A THIRD PARTY **** ----------------------------------------------------------------- DEPARTMENT CONVERSION TABLE HONORS 00 HEALTH 55 SERVICE COURSES IN EDUC 11 HEALTH EDUCATION 55 EDUCATIONAL FOUNDATIONS 12 CHINESE 56 ELEMENTARY EDUCATION 13 HISTORY 57 SECONDARY EDUCATION 14 INTERNATIONAL STUDIES 59 READING EDUCATION 15 JOURNALISM 61 SPECIAL EDUCATION 16 KINESIOLOGY 77 EDUCATIONAL LEADERSHIP 17 MATHEMATICS 67 HUMAN SERVICES 18 MEDICAL TECHNOLOGY 68 ANTHROPOLOGY 21 MILITARY SCIENCE 70 ART 22 NURSING COLLABORATIVE 71 AFRICAN AMERICAN STUDIES 23 MUSIC 73 BIOLOGY 26 NURSING 74 BUSINESS 28 PHILOSOPHY 76 COUNSELOR EDUCATION 29 PHYSICAL EDUCATION 79 PROFESSIONAL COUNSELING 29 PHYSICAL SCIENCE 80 LIBERAL STUDIES 31 PUBLIC ADMINISTRATION 81 CHEMISTRY 32 PHYSICS/ASTRONOMY 82 COMPUTER SCIENCE 34 POLITICAL SCIENCE 84 CRIMINAL JUSTICE 35 PRACTICAL ARTS 85 ECONOMICS 36 PSYCHOLOGY 86 ENVIRONMENTAL STUDIES 37 RELIGIOUS STUDIES 87 ENGLISH 38 WRITING-BASED INQ SEM 88 FRENCH 41 PROBLEM-BASED INQ SEM 89 GERMAN 43 SOCIAL JUSTICE 91 JAPANESE 44 SOCIOLOGY 92 RUSSIAN 48 SOCIAL WORK 93 SPANISH 49 INTERDISCIPLINARY STDS 94 GEOGRAPHY 50 COMMUNICATION 96 GEOLOGY 51 THEATRE 97 ARAPAHO 53 WOMEN'S STUDIES 98 SHOSHONE 54 URBAN PLANNING 99 ----------------------------------------------------------------- ================================================================= ********************* END OF ANALYSIS ********************* Return to Academics """;
true
@tempStar = """ New Window | Help | Customize Page STAR On-Line Return to Request STAR On-Line PI:NAME:<NAME>END_PI PREPARED: 01/30/13 - 08:31 Guy,Random 1 PROGRAM CODE: 222234007 CATALOG YEAR: 2010 CAMPUS ID : xxxxxxx BACHELOR OF SCIENCE DEGREE - COLLEGE OF LETTERS AND SCIENCE COMPUTER SC & SOFTWARE ENGINEERING (SOFTWARE ENGINEERING) MAJOR ================================================================= UNIVERSITY OF WISCONSIN OSHKOSH STUDENT ACADEMIC REPORT (STAR) REPORT NO. Check Titan Web for your registration date ADVISOR: PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI UGLS J34007222 STUDENT ACADEMIC PROGRAM PROGRAM : UGLS 2010 PLAN : J34007222 Comp Sci(Software Eng)-BS 2010 UW-OSHKOSH PLACEMENT AT TIME OF ADMISSION ENGLISH : Gen Ed English Comp MATH : Math Math 122 or 171 (3/12/05) ACADEMIC STANDING : GOOD COMMENTS : OFFICIAL GRADE EARNED GPA CREDS POINTS GPA CREDS TRANSFER INST 0.00 UWO OFFICIAL 81.00 227.38 2.807 84.00 ================================================================= ------> AT LEAST ONE REQUIREMENT HAS NOT BEEN SATISFIED <------ ================================================================= COMBINED GPA (IPLIST) UWO AND TRANSFER COURSE COMBINED GPA (Amnesty courses excluded) 84.00 CRS EARNED 81.00 ATTEMPTED HOURS 227.38 POINTS 2.807 GPA IN-PROG 15.00 CREDITS ======================================================= IN-PROGRESS COURSES 1232 34-331 3.00 .00 IP Programming Languages 1232 34-342 3.00 .00 IP Software Engineering II 1232 34-350 1.00 .00 IP Ethical Issues in Computing 1232 34-361 3.00 .00 IP Database Systems 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) 1232 94-208 1.00 .00 IP Career Sklls in Math & Nat Sc * ======================================================= ADJUSTMENTS TO THE COURSE REGISTRATIONS LISTED ABOVE OR COURSES NOT COMPLETED SUCCESSFULLY WILL CHANGE THE STATUS OF THIS REPORT. COURSES CURRENTLY BEING REPEATED WILL NOT BE LISTED WITH THE IN-PROGRESS COURSE BUT WILL BE LISTED IN THE REQUIREMENT TO WHICH THEY APPLY. ======================================================= YOU MUST APPLY FOR GRADUATION THE SEMESTER PRIOR TO YOUR GRADUATION SEMESTER: FALL GRADUATION, APPLY BY END OF PREVIOUS SPRING SEMESTER; SPRING & SUMMER GRADUATION, APPLY BY END OF PREVIOUS FALL SEMESTER. AN APPLICATION FORM IS AVAILABLE ON LINE AT (WWW.UWOSH.EDU/REGISTRAR). CLICK ON GRADUATION. FOLLOW INSTRUCTIONS TO COMPLETE & SUBMIT APPLICATION FORM. ================================================================= NO GENERAL EDUCATION COMPOSITION (GCOMP) 2008-10 MINIMUM 2.00 GPA REQUIRED IN ALL APPLICABLE COURSES TWO COURSES (6 CREDITS) REQUIRED EARNED 3.670 GPA + 1) COMPLETE A WRITING-BASED COMPOSITION COURSE: 1012 88-188 3.00 A- 11.01 Wrtng-Bsd Inq Sem (WBIS) (EN) - 2) COMPLETE A SECOND COMPOSITION COURSE: (MINIMUM OF 45 CREDITS REQUIRED TO ENROLL) SELECT FROM: 38-203 38-302 38-307 38-309 38-310 38-316 38-317 38-318 38-321 38-389 ================================================================= OK MATHEMATICS REQUIREMENT FOR THE L&S (GMATH2BS) BACHELOR OF SCIENCE DEGREE + 1) LEVEL II MATH 2.467 GPA 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) + 2) LEVEL I MATH EXEMPTED/COMPLETED WITH LEVEL II 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I ================================================================= OK GENERAL EDUCATION PHYSICAL EDUCATION (GPED) ONE COURSE (TWO CREDITS) REQUIRED (1995-2010) 1121 79-105 2.00 A- 7.34 Active Lifestyle (PE) ================================================================= OK GENERAL EDUCATION NON-WESTERN CULTURE (GNWST) ONE COURSE (THREE CREDITS) REQUIRED 1231 50-102 3.00 C- 5.01 World Reg Geog (NW) (SS) ================================================================= OK COMMUNICATION REQUIREMENT FOR THE L&S (GSPCH2BSA) BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES 1011 96-111 3.00 B- 8.01 Fund Spch Comm (GE) ================================================================= NO HUMANITIES REQUIREMENT FOR THE L&S (GHUM2BS) BACHELOR OF SCIENCE DEGREE EARNED 9.00 CREDITS 3 SUB-REQS --> NEEDS: 3.00 CREDITS +R 1) COMPLETE ONE LITERATURE COURSE FROM THE FOLLOWING LIST: 1122 38-221 3.00 B+ 9.99 Asian Am Lit (HU) (ES) SELECT FROM: 38-210 38-211 38-212 38-213 38-214 38-218 38-219 OR 38-229 38-220 38-224 OR 98-224 38-225 38-226 38-227 38-228 38-231 38-238 38-239 38-240 38-247 38-367 38-393 31-201 31-202 37-243 OR 38-243 94-245 37-244 OR 38-244 + 2) COMPLETE A MINIMUM OF ONE COURSE FROM TWO OF THE FOLLOWING THREE AREAS: FINE ARTS AREA (ART, DRAMA AND MUSIC) 1121 22-105 3.00 A 12.00 Understanding the Arts (HU) SELECT FROM: 00-275 22-243 OR 73-243 OR 97-243 OR 98-243 22-101 22-115 22-203 22-209 22-210 95-101 97-161 97-162 73-014 73-102 73-133 73-134 73-135 73-216 73-217 73-218 73-219 73-221 94-104 + 3) PHILOSOPHY AND RELIGIOUS STUDIES AREA: 1122 76-109 3.00 C+ 6.99 Intro to Philosophy (HU) SELECT FROM: 76-101 76-105 76-106 76-207 76-215 76-225 87-101(92.1-09.4) 87-103(92.1-09.4) 87-104 87-105 87-106 87-107(92.1-09.4) 87-204 87-210 87-162 OR 37-162(98.1-99.9) 87-275(92.1-09.4) 87-265 4) FOREIGN LANGUAGE AREA: NEEDS: 1 COURSE SELECT FROM: 41-110 41-111 41-203 41-204 41-208 41-248 42-110 42-111 42-210 42-211 43-110 43-111 43-203 43-204 43-207 43-248 44-110 44-111 44-210 44-211 48-110 48-111 48-203 48-204 49-101 49-102 49-103 49-104 49-110 49-111 49-112 49-113 49-203 49-204 49-207 49-208 49-248 56-110 56-111 56-210 56-211 5) COURSES IN THIS LIST MAY COUNT TOWARD THE 12 CREDITS REQUIRED FOR HUMANITIES/FINE ARTS, BUT WILL NOT COUNT TOWARD ONE OF THE THREE AREAS REQUIRED: NEEDS: 1 COURSE SELECT FROM: 00-175 23-100 38-220 38-238 38-239 38-240 31-200 37-282 41-110 41-111 41-203 41-204 41-207 41-208 43-110 43-111 43-203 43-204 43-207 43-208 44-110 44-203 44-204 44-207 44-208 48-110 48-111 48-203 48-204 49-108 49-110 49-111 49-112 49-113 49-203 49-204 49-207 87-265 OR 98-265 87-265 94-200 94-245 94-283 94-298 ================================================================= COMPLETION OF THE B.S. LAB SCIENCE AREA REQUIRES FOUR (4) COURSES AS DESCRIBED BELOW IN AREAS 1-3. SELECT FROM LAB SCIENCES IN BIOLOGY, CHEMISTRY, GEOGRAPHY, GEOLOGY, PHYSICS/ASTRONOMY (NEW1) ------------ AREA #1 ------------------------------------------ TWO LABORATORY SCIENCE COURSES FROM THE SAME DEPARTMENT, ONE OF WHICH REQUIRES THE SECOND AS A PREREQUISITE. ------------ AREA #2 ------------------------------------------ ONE NATURAL SCIENCE LABORATORY COURSE FROM A DIFFERENT DEPARTMENT THAN THE DEPARTMENT SELECTED IN AREA #1 ------------ AREA #3 ------------------------------------------ ONE COURSE THAT MATCHES ONE OF THE OPTIONS BELOW: A) A COURSE FROM THE SAME DEPARTMENT AS THE ONE SELECTED FOR AREA #2 AND WHICH HAS THAT COURSE AS A PREREQUISITE B) A LAB SCIENCE COURSE FROM A 3RD DEPARTMENT C) A COURSE FROM THOSE LISTED UNDER THE B.S. MATH REQUIREMENT ================================================================= NO TWO PAIRS (ONE PAIR FROM EACH OF TWO DEPARTMENTS) (NEW3) + 1) GEOGRAPHY DEPARTMENTAL APPROVED PAIR 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) ================================================================= COMPLETE TWO COURSES FROM THE SAME NATURAL SCIENCE DEPARTMENT. (THE FIRST COURSE MUST BE THE PREREQUISITE OF THE SECOND COURSE) NOTE: PLEASE SEE THE LIST OF APPROVED PAIRS LOCATED IN THE PREVIOUS REQUIREMENT. --------------------------------------------- NO OR ONE PAIR PLUS 2 OTHER DEPARTMENTS OPTION (NEW2) + 1) GEOGRAPHY DEPARTMENTAL APPROVED PAIR 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) - 2) CHEMISTRY - 3) ----------------------------------------------- COMPLETE A LAB SCIENCE COURSE FROM EACH OF TWO SCIENCE DEPARTMENTS OTHER THAN THE DEPARTMENT SELECTED FOR THE REQUIRED LAB PAIR. ......THE COURSES USED TO SATISFY THE PAIR ABOVE WILL ALSO PRINT IN THE APPROPRIATE AREA BELOW, BUT WILL NOT SATISFY THE DEPARTMENTAL REQUIREMENT (A TOTAL OF THREE DEPARTMENTS REQUIRED -- INCLUDING THE PAIR) BIOLOGY + 4) GEOGRAPHY 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) - 5) GEOLOGY - 6) PHYSICS/ASTRONOMY - 7) ANTHROPOLOGY + 8) YOU MAY TAKE A SECOND MATH/STATS/COMPUTER SC. AREA (AS DESCRIBED IN THE MATH REQUIREMENT FOR YOUR THIRD DEPARTMENT REQUIREMENT. 1011 67-171 4.00 C 8.00 Calculus I (MA) 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1012 67-172 4.00 C+ 9.32 Calculus II 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I ================================================================= OK SOCIAL SCIENCE REQUIREMENT FOR THE L&S (GSOSC2BSA) BACHELOR OF SCIENCE AND BACHELOR OF ARTS DEGREES EARNED 18.00 CREDITS +R 1) YOU MUST COMPLETE A MINIMUM OF THREE CREDITS OF HISTORY 3.00 CRS EARNED 1012 57-102 3.00 B 9.00 Modern Civilization (SS) + 3) ANTHROPOLOGY (ANY COURSE EXCEPT 21-202) 3.00 CRS EARNED 1012 21-102 3.00 B- 8.01 Intro to Anthropology (SS) + 5) ECONOMICS (ANY COURSE) 6.00 CRS EARNED 1011 36-106 3.00 B- 8.01 General Economics (SS) 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) + 7) GEOGRAPHY (ANY COURSE EXCEPT GEOG 121, 122, 304, 335, 342, 352, AND 363) 3.00 CRS EARNED 1231 50-102 3.00 C- 5.01 World Reg Geog (NW) (SS) + 11) PSYCHOLOGY (ANY COURSE EXCEPT PSYCH 203, 303, 305, 310, 341,367,371,380,383,384,391,411,455,481,498 & 499) 3.00 CRS EARNED 1011 86-101 3.00 B- 8.01 General Psychology (SS) ================================================================= OK GENERAL EDUCATION ETHNIC STUDIES (GETHNIC) ONE COURSE (THREE CREDITS) REQUIRED (IF SELECTED, 74-215 MUST BE COMPLETED FOR 3 CREDITS) 1122 38-221 3.00 B+ 9.99 Asian Am Lit (HU) (ES) ================================================================= OPTIONAL GENERAL EDUCATION COURSES (NOT REQUIRED, BUT MAY BE APPLIED TOWARD 42 CREDIT MINIMUM IN GENERAL EDUCATION) (GOPT) (SEE E-BULLETIN OR E-TIMETABLE FOR LIST) ================================================================= OK GENERAL EDUCATION SUMMARY (GENEDSUM) A MINIMUM OF 42 CREDITS IN GENERAL EDUCATION IS REQUIRED. PLEASE REFER TO THE E-BULLETIN OR E-TIMETABLE FOR THE APPROVED GENERAL EDUCATION LIST. EARNED 43.00 CREDITS 43.00 ATTEMPTED HOURS 115.71 POINTS 2.690 GPA IN-PROGRESS 4.00 CREDITS ================================================================= NO COMPUTER SCIENCE MAJ (SOFTWARE ENG)(J34007/09-99) 60 CREDITS AND A 2.00 MINIMUM G.P.A. REQUIRED EARNED 44.00 CREDITS 2.813 GPA IN-PROGRESS 10.00 CREDITS --> NEEDS: 6.00 CREDITS 2 SUB-REQS 2.000 GPA - 1) COMPLETE THE FOLLOWING CORE COURSES: 17.00 CRS EARNED 2.668 GPA IN-PROG 3.00 CREDITS 1011 34-221 3.00 S .00 OTHR - TRN - OO Design & Prog 1011 34-251 3.00 C 6.00 Comp Org & Assembly Language 1012 34-262 4.00 A- 14.68 OO Design & Programming II 1121 34-271 4.00 B- 10.68 Data Structures 1121 67-212 3.00 C 6.00 Mathematics for Comp Sci 1232 34-331 3.00 .00 IP Programming Languages NEEDS: 2 COURSES SELECT FROM: 34-399 OR 34-490 82-311 - 2) COMPLETE THE FOLLOWING COURSES IN ADDITION TO THE COMPUTER SCIENCE CORE COURSES: 14.00 CRS EARNED 2.500 GPA IN-PROG 7.00 CREDITS 1011 67-171 4.00 C 8.00 Calculus I (MA) 1122 34-421 4.00 B 12.00 Operating Systems 1122 36-210 3.00 C- 5.01 Econ Bus Statistics (SS) 1231 34-341 3.00 B+ 9.99 Software Engineering I 1232 34-342 3.00 .00 IP Software Engineering II 1232 34-350 1.00 .00 IP Ethical Issues in Computing 1232 34-361 3.00 .00 IP Database Systems NEEDS: 1 COURSE SELECT FROM: 34-321 + 3) COMPLETE A MINIMUM OF THREE CREDITS FROM THE FOLLOWING LIST A ELECTIVES: 6.00 CRS EARNED 3.500 GPA 1121 34-371 3.00 B 9.00 Computer Graphics 1231 34-346 3.00 A 12.00 Web Software Dev SELECT FROM: 34-300 34-310 34-381 34-391 34-421 34-431 34-480 + 4) SELECT A MINIMUM OF 6 CREDITS FROM THE FOLLOWING LIST B AND C COURSES COMBINED: 6.00 CRS EARNED 3.000 GPA 1122 28-315 3.00 B 9.00 Database Systems-Business 1231 28-314 3.00 B 9.00 IS Analysis-Design SELECT FROM: 28-260 28-319 28-355 28-410 82-305 82-319 82-405 67-222 67-256 67-302 67-304 67-342 67-346 67-347 67-349 67-355 67-356 67-357 67-385 67-401 67-402 + 5) A MINIMUM GRADE POINT AVERAGE OF 2.00 IN ALL COURSES NUMBERED 300 OR ABOVE (EXCEPT 34-399, 34-446, 34-456, 34-474, AND 34-490) IS REQUIRED. 1.00 CR APPLIED 1 COURSE TAKEN 4.000 GPA 1231 34-314 1.00 A 4.00 Practice of ICPC Competition NEEDS: 2.000 GPA -> NOT FROM: 34-334 34-335 34-399 34-446 34-456 34-474 34-490 SELECT FROM: 34-300 TO 34-499 ================================================================= ELECTIVE CREDITS WHICH APPLY TO THE UNDERGRADUATE DEGREE (ELECTIVE) 1231 50-121 4.00 C+ 9.32 Phy Geog Wthr (NS) 1232 50-122 4.00 .00 IP Phy Geog 2 Land (NS) 1232 94-208 1.00 .00 IP Career Sklls in Math & Nat Sc ================================================================= CHECK LIMITS FOR MUSIC, DRAMA, PHY-ED PARTICIPATION AND PROFESSIONAL COURSES (PRESUM2) 1) ONLY 4 CREDITS OF MUSIC PARTICIPATION COURSES MAY BE APPLIED TO DEGREE CREDIT FOR NON-MUSIC MAJORS OR MINORS. 2) ONLY 4 CREDITS OF DRAMA OR THEATRE PARTICIPATION COURSES MAY APPLY TO DEGREE CREDITS 3) ONLY 4 CREDITS OF PHYSICAL EDUCATION ACTIVITY COURSES MAY APPLY TO THE DEGREE CREDITS IN THIS AREA. (ANY CREDITS OVER 4 WILL BE COUNTED AS PREPROFESSIONAL) 1121 79-105 2.00 A- 7.34 Active Lifestyle (PE) 4) A MAXIMUM OF 24 PREPROFESSIONAL CREDITS MAY COUNT TOWARD THE 120 REQUIRED TO GRADUATE. 1122 28-315 3.00 B 9.00 Database Systems-Business 1231 28-314 3.00 B 9.00 IS Analysis-Design ================================================================= NO GENERAL BACCALAUREATE DEGREE REQUIREMENTS (SUMMARY) - 1) EARN A MINIMUM OF 120 DEGREE CREDITS 84.00 CRS EARNED IN-PROG 15.00 CREDITS NEEDS: 21.00 CREDITS + 3) EARN A MINIMUM 2.00 GPA IN UWO CREDITS ATTEMPTED 81.00 ATTEMPTED HOURS 227.38 POINTS 2.807 GPA + 4) EARN A MINIMUM 2.00 GPA IN ALL COURSES APPLICABLE TO THE UNIVERSITY'S GENERAL EDUCATION ENGLISH COMPOSITION REQUIREMENT 3.670 GPA + 5) EARN AT LEAST 30 SEMESTER CREDITS AT UW OSHKOSH ( 84.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS + 6) EARN AT LEAST 48 CREDITS FROM A 4 YEAR INSTITUTION ( 84.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS - 7) EARN AT LEAST 35 CREDITS AT THE UPPER LEVEL (300/400) WITH A MINIMUM 2.00 GPA ( 20.00 CREDITS TAKEN) 20.00 ATTEMPTED HOURS 64.99 POINTS 3.249 GPA IN-PROG 10.00 CREDITS NEEDS: 5.00 CREDITS + 8) 15 OF THE LAST 30 CREDITS MUST BE TAKEN AT UWO. ( 17.00 CREDITS TAKEN) IN-PROG 15.00 CREDITS ================================================================= **** LEGEND **** NO = REQUIREMENT NOT COMPLETE >D = DUPLICATE COURSE - CREDIT OK = REQUIREMENT COMPLETE & GPA EFFECT REMOVED ON - = SUBREQUIREMENT NOT COMPLETE COURSE EXCEEDING LIMIT + = SUBREQUIREMENT COMPLETE >X = REPEATED COURSE - CREDIT * = SUBREQUIREMENT IS OPTIONAL & GPA EFFECT REMOVED ON (R)= REQUIRED COURSE ORIGINAL COURSE +R = REQUIRED SUBREQUIREMENT >S = COURSE CREDIT SPLIT COMPLETED BETWEEN REQUIREMENTS -R = REQUIRED SUBREQUIREMENT >R = REPEATABLE COURSE - CREDIT NOT COMPLETED MAY BE EARNED MORE THAN CS = COURSE SUBSTITUTION ONCE WC = WAIVED COURSE WH = WAIVED CREDIT HOUR <> = CONTINUED REQUIREMENT >C = DUPLICAT CROSS-LINKED COUR S = SATISFACTORY GRADE IN RETRO., MILITARY, DEPT., TEST OUT CR. ****** PLEASE NOTE: THE FOUR NUMBERS BEFORE A COURSE INDICATE THE TERM IN WHICH THE COURSE WAS TAKEN. THE FIRST THREE NUMBERS INDICATE THE ACADEMIC YEAR (078 IS USED FOR THE 2007-08 ACADEMIC YEAR). THE LAST NUMBER INDICATES THE TERM (1 = FALL, 2 = SPRING, 4 = SUMMER). FOR EXAMPLE, 0782 IS THE SPRING TERM OF 2007-08. **************************************************************** ****** THIS NOTICE OF ACADEMIC PROGRESS HAS BEEN PREPARED TO ASSIST YOU DURING YOUR COLLEGE EXPERIENCE. ALTHOUGH EFFORTS HAVE BEEN MADE TO ASSESS THE ACCURACY OF THIS REPORT, YOU ARE RESPONSIBLE FOR MAKING SURE THAT ALL REQUIREMENTS HAVE BEEN COMPLETED. THE REGISTRAR'S OFFICE WILL ULTIMATELY AUTHORIZE THE AWARDING OF YOUR DEGREE; THEREFORE, IF YOU HAVE ANY QUESTIONS ABOUT THE ACCURACY OF THIS PROGRESS REPORT, PLEASE SEE AN ACADEMIC ADVISOR IN DEMPSEY 130. ******* **************************************************************** ================================================================= THIS AUDIT ASSUMES SUCCESSFUL COMPLETION OF ALL IN-PROGRESS COURSES; ANY IN-PROGRESS COURSES NOT COMPLETED SUCCESSFULLY MAY CHANGE THIS AUDIT'S EVALUATION. ----------------------------------------------------------------- **** CONFIDENTIAL - STUDENT/ADVISOR USE ONLY **** **** FEDERAL LAW PROHIBITS TRANSMITTAL TO A THIRD PARTY **** ----------------------------------------------------------------- DEPARTMENT CONVERSION TABLE HONORS 00 HEALTH 55 SERVICE COURSES IN EDUC 11 HEALTH EDUCATION 55 EDUCATIONAL FOUNDATIONS 12 CHINESE 56 ELEMENTARY EDUCATION 13 HISTORY 57 SECONDARY EDUCATION 14 INTERNATIONAL STUDIES 59 READING EDUCATION 15 JOURNALISM 61 SPECIAL EDUCATION 16 KINESIOLOGY 77 EDUCATIONAL LEADERSHIP 17 MATHEMATICS 67 HUMAN SERVICES 18 MEDICAL TECHNOLOGY 68 ANTHROPOLOGY 21 MILITARY SCIENCE 70 ART 22 NURSING COLLABORATIVE 71 AFRICAN AMERICAN STUDIES 23 MUSIC 73 BIOLOGY 26 NURSING 74 BUSINESS 28 PHILOSOPHY 76 COUNSELOR EDUCATION 29 PHYSICAL EDUCATION 79 PROFESSIONAL COUNSELING 29 PHYSICAL SCIENCE 80 LIBERAL STUDIES 31 PUBLIC ADMINISTRATION 81 CHEMISTRY 32 PHYSICS/ASTRONOMY 82 COMPUTER SCIENCE 34 POLITICAL SCIENCE 84 CRIMINAL JUSTICE 35 PRACTICAL ARTS 85 ECONOMICS 36 PSYCHOLOGY 86 ENVIRONMENTAL STUDIES 37 RELIGIOUS STUDIES 87 ENGLISH 38 WRITING-BASED INQ SEM 88 FRENCH 41 PROBLEM-BASED INQ SEM 89 GERMAN 43 SOCIAL JUSTICE 91 JAPANESE 44 SOCIOLOGY 92 RUSSIAN 48 SOCIAL WORK 93 SPANISH 49 INTERDISCIPLINARY STDS 94 GEOGRAPHY 50 COMMUNICATION 96 GEOLOGY 51 THEATRE 97 ARAPAHO 53 WOMEN'S STUDIES 98 SHOSHONE 54 URBAN PLANNING 99 ----------------------------------------------------------------- ================================================================= ********************* END OF ANALYSIS ********************* Return to Academics """;
[ { "context": "8-201f-4a1b-85bd-f925a01d551c\"\n username: \"user@example.com\"\n full_name: null\n serialized_data:", "end": 782, "score": 0.9999250173568726, "start": 766, "tag": "EMAIL", "value": "user@example.com" }, { "context": " ->\n parameters =\n username: \"john.doe@example.com\"\n full_name: \"John Doe\"\n ac", "end": 1937, "score": 0.99992835521698, "start": 1917, "tag": "EMAIL", "value": "john.doe@example.com" }, { "context": "e: \"john.doe@example.com\"\n full_name: \"John Doe\"\n active: true\n \n ga", "end": 1971, "score": 0.9998531341552734, "start": 1963, "tag": "NAME", "value": "John Doe" }, { "context": "d.id\n expect(result.username).toEqual \"john.doe@example.com\"\n expect(result.full_name).toEqual \"Jo", "end": 2480, "score": 0.9998959302902222, "start": 2460, "tag": "EMAIL", "value": "john.doe@example.com" }, { "context": "om\"\n expect(result.full_name).toEqual \"John Doe\"\n expect(result.serialized_data).toEqu", "end": 2536, "score": 0.9998745918273926, "start": 2528, "tag": "NAME", "value": "John Doe" }, { "context": "sor = gateway.find isActive: true, withLastName: \"Doe\"\n \n cursor.toArray (error, resu", "end": 3513, "score": 0.9964612126350403, "start": 3510, "tag": "NAME", "value": "Doe" }, { "context": "ord.id\n expect(user.username).toEqual \"john.doe@example.com\"\n expect(user.firstName).toEqual \"John", "end": 4880, "score": 0.999909520149231, "start": 4860, "tag": "EMAIL", "value": "john.doe@example.com" }, { "context": ".com\"\n expect(user.firstName).toEqual \"John\"\n expect(user.lastName).toEqual \"Doe\"\n", "end": 4930, "score": 0.9997991919517517, "start": 4926, "tag": "NAME", "value": "John" }, { "context": "\"John\"\n expect(user.lastName).toEqual \"Doe\"\n expect(user.data.foo).toEqual \"bar\"\n", "end": 4978, "score": 0.9996469020843506, "start": 4975, "tag": "NAME", "value": "Doe" } ]
spec/boco-knex-rdb.spec.coffee
bocodigitalmedia/boco-knex-rdb
0
$files = {} describe "boco-knex-rdb", -> describe "Usage", -> [BocoKnexRDB, knex, defineUsersTable, table, createUsersTable, createUsersPromise, record] = [] beforeEach -> BocoKnexRDB = require "boco-knex-rdb" knex = require("knex") client: "sqlite3", connection: "test.db" defineUsersTable = (table) -> table.uuid("id").primary() table.string("username") table.string("full_name") table.json("serialized_data") table.boolean("active").defaultTo(true) createUsersTable = -> knex.schema.createTableIfNotExists("users", defineUsersTable) createUsersPromise = createUsersTable() record = id: "aaeab0c8-201f-4a1b-85bd-f925a01d551c" username: "user@example.com" full_name: null serialized_data: JSON.stringify(foo: "bar") active: false it "Make sure the table was created before continuing...", (ok) -> createUsersPromise.asCallback (error, result) -> expect(error?).toBe false ok() describe "Table Gateway", -> [gateway] = [] beforeEach -> gateway = new BocoKnexRDB.TableGateway knex: knex, table: "users" describe "Modifying record construction", -> beforeEach -> gateway.constructRecord = (record) -> record.active = Boolean(record.active) record it "is ok", -> expect(true).toEqual(true) describe "Inserting a record", -> it "Insert a new record by passing in the record data.", (ok) -> gateway.insert record, (error, incrementId) -> throw error if error? expect(incrementId).toBe 1 ok() describe "Updating a record", -> it "Update a record by passing in the identifier, followed by a set of update parameters.", (ok) -> parameters = username: "john.doe@example.com" full_name: "John Doe" active: true gateway.update record.id, parameters, (error, updateCount) -> throw error if error? expect(updateCount).toEqual 1 ok() describe "Reading a record", -> it "Read a record by passing in the identifier.", (ok) -> gateway.read record.id, (error, result) -> throw error if error? expect(result.id).toEqual record.id expect(result.username).toEqual "john.doe@example.com" expect(result.full_name).toEqual "John Doe" expect(result.serialized_data).toEqual '{"foo":"bar"}' expect(result.active).toEqual 1 ok() describe "Reading all records", -> it "Just call `all` to get a `Cursor` for all records", (ok) -> cursor = gateway.all() cursor.toArray (error, records) -> throw error if error? expect(records.length).toEqual(1) expect(records[0].id).toEqual record.id ok() describe "Finding records with scopes", -> [query, activeState, last] = [] beforeEach -> gateway.defineScope "isActive", (query, activeState) -> query.where active: activeState gateway.defineScope "withLastName", (query, last) -> query.where "full_name", "like", "% #{last}" it "Call `find` with scopes and their parameters to get a cursor.", (ok) -> cursor = gateway.find isActive: true, withLastName: "Doe" cursor.toArray (error, results) -> throw error if error? expect(results.length).toBe 1 ok() describe "DataMapper", -> [usersGateway, mapper, user] = [] beforeEach -> usersGateway = new BocoKnexRDB.TableGateway knex: knex, table: "users" mapper = new BocoKnexRDB.DataMapper tableGateway: usersGateway mapper.defineObjectSourceMap id: null username: null firstName: (record) -> record.full_name.split(" ")[0] lastName: (record) -> record.full_name.split(" ")[1] data: ["serialized_data", JSON.parse] active: null mapper.defineRecordSourceMap id: null username: null full_name: (user) -> [user.firstName, user.lastName].join(" ") serialized_data: ["data", JSON.stringify] active: null describe "Using the DataMapper", -> it "The methods of the DataMapper mimic the underlying TableGateway interface.\nThe only difference being that your model objects are converted to and from records.", (ok) -> userId = record.id mapper.read userId, (error, user) -> throw error if error? expect(user.id).toEqual record.id expect(user.username).toEqual "john.doe@example.com" expect(user.firstName).toEqual "John" expect(user.lastName).toEqual "Doe" expect(user.data.foo).toEqual "bar" ok()
47484
$files = {} describe "boco-knex-rdb", -> describe "Usage", -> [BocoKnexRDB, knex, defineUsersTable, table, createUsersTable, createUsersPromise, record] = [] beforeEach -> BocoKnexRDB = require "boco-knex-rdb" knex = require("knex") client: "sqlite3", connection: "test.db" defineUsersTable = (table) -> table.uuid("id").primary() table.string("username") table.string("full_name") table.json("serialized_data") table.boolean("active").defaultTo(true) createUsersTable = -> knex.schema.createTableIfNotExists("users", defineUsersTable) createUsersPromise = createUsersTable() record = id: "aaeab0c8-201f-4a1b-85bd-f925a01d551c" username: "<EMAIL>" full_name: null serialized_data: JSON.stringify(foo: "bar") active: false it "Make sure the table was created before continuing...", (ok) -> createUsersPromise.asCallback (error, result) -> expect(error?).toBe false ok() describe "Table Gateway", -> [gateway] = [] beforeEach -> gateway = new BocoKnexRDB.TableGateway knex: knex, table: "users" describe "Modifying record construction", -> beforeEach -> gateway.constructRecord = (record) -> record.active = Boolean(record.active) record it "is ok", -> expect(true).toEqual(true) describe "Inserting a record", -> it "Insert a new record by passing in the record data.", (ok) -> gateway.insert record, (error, incrementId) -> throw error if error? expect(incrementId).toBe 1 ok() describe "Updating a record", -> it "Update a record by passing in the identifier, followed by a set of update parameters.", (ok) -> parameters = username: "<EMAIL>" full_name: "<NAME>" active: true gateway.update record.id, parameters, (error, updateCount) -> throw error if error? expect(updateCount).toEqual 1 ok() describe "Reading a record", -> it "Read a record by passing in the identifier.", (ok) -> gateway.read record.id, (error, result) -> throw error if error? expect(result.id).toEqual record.id expect(result.username).toEqual "<EMAIL>" expect(result.full_name).toEqual "<NAME>" expect(result.serialized_data).toEqual '{"foo":"bar"}' expect(result.active).toEqual 1 ok() describe "Reading all records", -> it "Just call `all` to get a `Cursor` for all records", (ok) -> cursor = gateway.all() cursor.toArray (error, records) -> throw error if error? expect(records.length).toEqual(1) expect(records[0].id).toEqual record.id ok() describe "Finding records with scopes", -> [query, activeState, last] = [] beforeEach -> gateway.defineScope "isActive", (query, activeState) -> query.where active: activeState gateway.defineScope "withLastName", (query, last) -> query.where "full_name", "like", "% #{last}" it "Call `find` with scopes and their parameters to get a cursor.", (ok) -> cursor = gateway.find isActive: true, withLastName: "<NAME>" cursor.toArray (error, results) -> throw error if error? expect(results.length).toBe 1 ok() describe "DataMapper", -> [usersGateway, mapper, user] = [] beforeEach -> usersGateway = new BocoKnexRDB.TableGateway knex: knex, table: "users" mapper = new BocoKnexRDB.DataMapper tableGateway: usersGateway mapper.defineObjectSourceMap id: null username: null firstName: (record) -> record.full_name.split(" ")[0] lastName: (record) -> record.full_name.split(" ")[1] data: ["serialized_data", JSON.parse] active: null mapper.defineRecordSourceMap id: null username: null full_name: (user) -> [user.firstName, user.lastName].join(" ") serialized_data: ["data", JSON.stringify] active: null describe "Using the DataMapper", -> it "The methods of the DataMapper mimic the underlying TableGateway interface.\nThe only difference being that your model objects are converted to and from records.", (ok) -> userId = record.id mapper.read userId, (error, user) -> throw error if error? expect(user.id).toEqual record.id expect(user.username).toEqual "<EMAIL>" expect(user.firstName).toEqual "<NAME>" expect(user.lastName).toEqual "<NAME>" expect(user.data.foo).toEqual "bar" ok()
true
$files = {} describe "boco-knex-rdb", -> describe "Usage", -> [BocoKnexRDB, knex, defineUsersTable, table, createUsersTable, createUsersPromise, record] = [] beforeEach -> BocoKnexRDB = require "boco-knex-rdb" knex = require("knex") client: "sqlite3", connection: "test.db" defineUsersTable = (table) -> table.uuid("id").primary() table.string("username") table.string("full_name") table.json("serialized_data") table.boolean("active").defaultTo(true) createUsersTable = -> knex.schema.createTableIfNotExists("users", defineUsersTable) createUsersPromise = createUsersTable() record = id: "aaeab0c8-201f-4a1b-85bd-f925a01d551c" username: "PI:EMAIL:<EMAIL>END_PI" full_name: null serialized_data: JSON.stringify(foo: "bar") active: false it "Make sure the table was created before continuing...", (ok) -> createUsersPromise.asCallback (error, result) -> expect(error?).toBe false ok() describe "Table Gateway", -> [gateway] = [] beforeEach -> gateway = new BocoKnexRDB.TableGateway knex: knex, table: "users" describe "Modifying record construction", -> beforeEach -> gateway.constructRecord = (record) -> record.active = Boolean(record.active) record it "is ok", -> expect(true).toEqual(true) describe "Inserting a record", -> it "Insert a new record by passing in the record data.", (ok) -> gateway.insert record, (error, incrementId) -> throw error if error? expect(incrementId).toBe 1 ok() describe "Updating a record", -> it "Update a record by passing in the identifier, followed by a set of update parameters.", (ok) -> parameters = username: "PI:EMAIL:<EMAIL>END_PI" full_name: "PI:NAME:<NAME>END_PI" active: true gateway.update record.id, parameters, (error, updateCount) -> throw error if error? expect(updateCount).toEqual 1 ok() describe "Reading a record", -> it "Read a record by passing in the identifier.", (ok) -> gateway.read record.id, (error, result) -> throw error if error? expect(result.id).toEqual record.id expect(result.username).toEqual "PI:EMAIL:<EMAIL>END_PI" expect(result.full_name).toEqual "PI:NAME:<NAME>END_PI" expect(result.serialized_data).toEqual '{"foo":"bar"}' expect(result.active).toEqual 1 ok() describe "Reading all records", -> it "Just call `all` to get a `Cursor` for all records", (ok) -> cursor = gateway.all() cursor.toArray (error, records) -> throw error if error? expect(records.length).toEqual(1) expect(records[0].id).toEqual record.id ok() describe "Finding records with scopes", -> [query, activeState, last] = [] beforeEach -> gateway.defineScope "isActive", (query, activeState) -> query.where active: activeState gateway.defineScope "withLastName", (query, last) -> query.where "full_name", "like", "% #{last}" it "Call `find` with scopes and their parameters to get a cursor.", (ok) -> cursor = gateway.find isActive: true, withLastName: "PI:NAME:<NAME>END_PI" cursor.toArray (error, results) -> throw error if error? expect(results.length).toBe 1 ok() describe "DataMapper", -> [usersGateway, mapper, user] = [] beforeEach -> usersGateway = new BocoKnexRDB.TableGateway knex: knex, table: "users" mapper = new BocoKnexRDB.DataMapper tableGateway: usersGateway mapper.defineObjectSourceMap id: null username: null firstName: (record) -> record.full_name.split(" ")[0] lastName: (record) -> record.full_name.split(" ")[1] data: ["serialized_data", JSON.parse] active: null mapper.defineRecordSourceMap id: null username: null full_name: (user) -> [user.firstName, user.lastName].join(" ") serialized_data: ["data", JSON.stringify] active: null describe "Using the DataMapper", -> it "The methods of the DataMapper mimic the underlying TableGateway interface.\nThe only difference being that your model objects are converted to and from records.", (ok) -> userId = record.id mapper.read userId, (error, user) -> throw error if error? expect(user.id).toEqual record.id expect(user.username).toEqual "PI:EMAIL:<EMAIL>END_PI" expect(user.firstName).toEqual "PI:NAME:<NAME>END_PI" expect(user.lastName).toEqual "PI:NAME:<NAME>END_PI" expect(user.data.foo).toEqual "bar" ok()
[ { "context": "t 'drop', obj\n #@Cache = -> if @name? then Cache[@name] else Cache['NodeBase'] \n #remove Objects f", "end": 4716, "score": 0.6425732970237732, "start": 4716, "tag": "USERNAME", "value": "" }, { "context": "ts created\n @getTotalIds = -> if @name? then cids[@name] || 0 else cids['NodeBase'] || 0\n #CLASS level l", "end": 4949, "score": 0.6567281484603882, "start": 4944, "tag": "USERNAME", "value": "@name" }, { "context": "module.exports.glue = glue;\n\n###\n Code taken from Robert Kieffer UUID\n\n Math.uuid.js (v1.4)\n http://www.broofa.c", "end": 8873, "score": 0.8319065570831299, "start": 8859, "tag": "NAME", "value": "Robert Kieffer" }, { "context": "h.uuid.js (v1.4)\n http://www.broofa.com\n mailto:robert@broofa.com\n\n Copyright (c) 2010 Robert Kieffer\n Dual licen", "end": 8952, "score": 0.9999340772628784, "start": 8935, "tag": "EMAIL", "value": "robert@broofa.com" }, { "context": "m\n mailto:robert@broofa.com\n\n Copyright (c) 2010 Robert Kieffer\n Dual licensed under the MIT and GPL licenses.\n\n", "end": 8989, "score": 0.9998607039451599, "start": 8975, "tag": "NAME", "value": "Robert Kieffer" }, { "context": "tructor.name\n if @options.autoId then id = \" id:#{@_id}\"\n message = \"-- #{now()} [#{classAndFunction + ", "end": 15501, "score": 0.997523307800293, "start": 15497, "tag": "USERNAME", "value": "@_id" } ]
nodeBase-coffee.coffee
dotmaster/NodeBase
2
events = require('events') util = require(if process.binding('natives').util then 'util' else 'sys') CappedObject = require './CappedObject' #extend the stacktracelimit for coffeescript Error.stackTraceLimit = 50; stringify = (obj) -> JSON.stringify(obj, null, " ") #from underscore.coffee isEmpty = (obj) -> return obj.length is 0 if isArray(obj) or isString(obj) return false for own key of obj true isElement = (obj) -> obj and obj.nodeType is 1 isArguments = (obj) -> obj and obj.callee isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply) isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr)) isArray = Array.isArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee) ### # # MERGE # a mixin function similar to _.extend but more powerful # it can also deal with non objects like functions # # @desc A cool merge function, that emits warnings # # @args obj, args..., last # the first argunment is the object we merge in,, which can also be a function, or better if the first obj is not an object we just set it to the merge value, # the last can be a boolean, in such case it is a switch for turning on and off warnings, on overwriting existing variables # logging of warnings is turned on by default # ### module.exports.merge = module.exports.extend = module.exports.mixin = merge = (obj, args..., last) -> if not obj? then throw new Error('merge: first parameter must not be undefined') log = true #logging of merge conflict is turned on by default initialProps = {} initialProps[prop] = true for own prop of obj if typeof last isnt 'boolean' then args.push last else log = last for source in args if obj is source then return obj #if it's the same just return if (typeof source isnt 'object') and source? #if source is not an object and not undefined set obj to source, but log if we overwrite an existing obj if (typeof obj isnt 'object' and obj?) or not isEmpty(obj) #obj can be a function or string or an object containing something, then we warn if log then @warn "Object #{stringify(obj) or obj.name or typeof obj} exists and will be overwritten with #{stringify(source) or obj.name or typeof obj}" obj = source else for own prop of source if initialProps[prop]? #if the property already exists in the iniotial properties the object had before merge if log # and we log @warn "property #{prop} exists and value #{stringify(obj[prop]) or typeof obj[prop]} will be overwritten with #{stringify(source[prop]) or typeof obj[prop]}" #give a warning about overwriting and existing initial Property of Object ###at #{new Error().stack}### obj[prop] = source[prop] return obj #Coffeescript is anoying on this, all you don't define before, will be undefined #NodeBase.options = NodeBase.defaults = merge NodeBase.defaults, NodeBase.objdefaults #LOG LEVELS L = 0 LL = ALL: L++ LOG : L++ INFO : L++ WARN : L++ ERROR : L++ LL[LL[L]] = L for L of LL #yeah! ### @desc this is the mother of all Objects; a node Base Class with (logging and options, defaults) NodeBase is an EventEmitter ### class NodeBase extends events.EventEmitter #static Functions @now = now @static = (superClass) -> superClass[i]?=NodeBase[i] for own i, val of NodeBase merge superClass.options or= {}, superClass.defaults, false #superClass options has already nodeBases @options merged in through extend #superClass.Cache ?= new CappedObject(NodeBase.options.maxCap, superClass.name) #emit CLASS level cache events #superClass.Cache.on 'add', (obj) => superClass.emit 'add', obj #superClass.Cache.on 'remove', (obj) => superClass.emit 'remove', obj #superClass.Cache.on 'drop', (obj) => superClass.emit 'drop', obj @objdefaults = logging: true logLevel: 'ERROR' printLevel: true printContext: true useStack: true emitLog: false @defaults = merge @objdefaults, #see above Coffescript is annoying on using functions that are defined later in context addToCollection: false maxCap: 10000 @options = @defaults @merge = merge @mixin = merge @extend = merge @node_ver = node_ver #Class Collection specific @lookupId = (id)-> if @name? then @Cache?.getId(id) else NodeBase?.getId(id) #the CLASS level NODEBASE cache (=Capped Hash) #@Cache ?= new CappedObject(NodeBase.options.maxCap, @name) #emit CLASS level cache events #@Cache.on 'add', (obj) => @emit 'add', obj #@Cache.on 'remove', (obj) => @emit 'remove', obj #@Cache.on 'drop', (obj) => @emit 'drop', obj #@Cache = -> if @name? then Cache[@name] else Cache['NodeBase'] #remove Objects from the CLASS collection, see also @_remove() on Object level @_remove = (obj) -> _remove(obj) #get the number of objects created @getTotalIds = -> if @name? then cids[@name] || 0 else cids['NodeBase'] || 0 #CLASS level logging @log = -> if @options.logging and @_checkLogLevel 'LOG' then console.log (@_addContext arguments..., 'LOG') @warn = -> if @options.logging and @_checkLogLevel 'WARN' then console.log (@_addContext arguments..., 'WARN') @info = -> if @options.logging and @_checkLogLevel 'INFO' then console.log (@_addContext arguments..., 'INFO') @error = -> if @options.logging and @_checkLogLevel 'ERROR' then console.log (@_addContext arguments..., 'ERROR') @_addContext = -> _addStaticContext.apply @, arguments @_checkLogLevel = (level)-> LL[@options.logLevel] <= LL[level] #event emitting of CLASS @emit: -> @_emitter.emit.apply @, arguments @_emitter = new events.EventEmitter(); @_emitter.on 'error', (err) -> console.log stringify(err, null, " ") #CLASS level combined log emitters @ermit= -> _ermit.apply @, arguments @wamit= -> _wamit.apply @, arguments @inmit= -> _inmit.apply @, arguments constructor:(opts, defaults) -> super() @init(opts, defaults) init: (opts, defaults) -> self=this #merge defaults but don't make them public -> defaults will become options _defaults = merge {}, logging: true logLevel: 'ERROR' printLevel: true printContext: true useStack: true emitLog: false autoId: true autoUuid: true cacheSize: 5 ,@defaults, defaults, false # merge constructor level Object defaults before object level defaults @options = merge @options or= {}, @constructor.objdefaults, _defaults, opts, true #@on 'error', (err) -> @log 'emitted error ' + JSON.stringify(err) @LOG_LEVELS = LL #make log levels available in the object @_checkLogLevel = (level)-> LL[@options.logLevel] <= LL[level] if @_id and @options.autoId then @warn 'overwriting _id' @_id = if @options.autoId then cid(this) else @_id @_uuid = if @options.autoUuid then UUID.uuid() else "" if @options.autoId then @_getTotalIds = -> getTotalIds @ #actually this is just a counter of times the constructor was called if @constructor?.options?.addToCollection then addId(this) remove: -> _remove(this) #ADD THE CLASSNAME AND A TIMESTAMP TO THE LOGGING OUTPUT _addContext: -> _addContext.apply @, arguments ### # # OBJECT LOGGING # error is special in that the first argument is interpretated as message, second as type, third, ... as arguments # # ### log: => if @options.logging and @_checkLogLevel 'LOG' then console.log (@_addContext arguments..., 'LOG') warn: => if @options.logging and @_checkLogLevel 'WARN' then console.log (@_addContext arguments..., 'WARN') info: => if @options.logging and @_checkLogLevel 'INFO' then console.log (@_addContext arguments..., 'INFO') error: => if @options.logging and @_checkLogLevel 'ERROR' then console.log (@_addContext arguments..., 'ERROR') ermit: => _ermit.apply @, arguments wamit: => _wamit.apply @, arguments inmit: => _inmit.apply @, arguments #export the base class # module.exports = NodeBase module.exports.LOG_LEVELS = LL; module.exports.now = now = -> new Date().toUTCString(); #the node version node_ver = null do -> return node_ver if node_ver? ver = process.version rex = /^v(\d+)\.(\d+)\.(\d+)/i matches = ver.match(rex) throw "Unable to determine node version" unless matches? node_ver = major: ~~matches[1] minor: ~~matches[2] release: ~~matches[3] module.exports.node_ver = node_ver; #Convert arguments to array arrize = (ary, from = 0 ) -> return Array.prototype.slice.call(ary, from) #a bind function similar to _.bind #Bind proxy objects to function glue = (f, obj, oargs...) -> (iargs...) -> f.apply? obj, oargs.concat iargs module.exports.glue = glue; ### Code taken from Robert Kieffer UUID Math.uuid.js (v1.4) http://www.broofa.com mailto:robert@broofa.com Copyright (c) 2010 Robert Kieffer Dual licensed under the MIT and GPL licenses. A UUID GENERATROR FUNCTION Private array of chars to use ### CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') UUID = {} UUID.uuid = (len, radix=CHARS.length) -> chars = CHARS uuid = [] if len? # Compact form for i in [0..len] uuid[i] = chars[0 | Math.random()*radix] else # rfc4122, version 4 form r # rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' uuid[14] = '4' # Fill in random data. At i==19 set the high bits of clock sequence as # per rfc4122, sec. 4.1.5 for i in [0...36] if not uuid[i] r = 0 | Math.random()*16 uuid[i] = chars[if (i == 19) then (r & 0x3) | 0x8 else r] uuid.join('') module.exports.uuid = UUID.uuid module.exports.UUID = UUID #Cid Handling cids={} cid = (obj)-> if obj?.constructor.name? ++cids[obj.constructor.name] || cids[obj.constructor.name]= 1 else ++cids['NodeBase'] || cids['NodeBase']= 1 getTotalCids = (obj) -> if obj?.constructor.name? cids[obj.constructor.name] || 0 else cids['NodeBase'] || 0 #add Ids to a global collection, can be looked up with the static function className.lookupId #Cache = {} _remove = (obj)-> if not obj._id then module.exports.error "Obj to add has no propety _id, please turn on autoId or give the object an _id before passing it to super" if obj?.constructor.name? #(Cache[obj.constructor.name]?=new CappedObject(NodeBase.options.maxCap, obj.constructor.name)).remove(obj) obj.constructor.Cache.remove(obj) else #(Cache['NodeBase']?={})[obj._id] = obj #(Cache['NodeBase']?=new CappedObject(NodeBase.options.maxCap, 'NodeBase')).remove(obj) NodeBase.Cache.remove(obj) addId = (obj)-> #check if autoId is turned on or the object has an id if not obj._id then module.exports.error "Obj to add has no propety _id, please turn on autoId or give the object an _id before passing it to super" if obj?.constructor.name? #(Cache[obj.constructor.name]?={})[obj._id] = obj #(Cache[obj.constructor.name]?=new CappedObject(NodeBase.options.maxCap, obj.constructor.name)).addId(obj) (obj.constructor.Cache?=new CappedObject(NodeBase.options.maxCap, obj.constructor)).addId(obj) else #(Cache['NodeBase']?={})[obj._id] = obj #(Cache['NodeBase']?=new CappedObject(NodeBase.options.maxCap, 'NodeBase')).addId(obj) (NodeBase.Cache?=new CappedObject(NodeBase.options.maxCap, NodeBase)).addId(obj) module.exports.cid = cid # http://en.wikipedia.org/wiki/ANSI_escape_code#graphics styles = 'bold' : [1, 22] 'italic' : [3, 23] 'underline' : [4, 24] 'inverse' : [7, 27] 'white' : [37, 39] 'grey' : [90, 39] 'black' : [30, 39] 'blue' : [34, 39] 'cyan' : [36, 39] 'green' : [32, 39] 'magenta' : [35, 39] 'red' : [31, 39] 'yellow' : [33, 39] levelStylesMapping = 'WARN': 'magenta' 'ERROR': 'red' 'INFO': 'cyan' 'LOG': 'green' colorize = (string, color) -> #can be a color or level color = levelStylesMapping[color]?=color return '\033[' + styles[color][0] + 'm' + string + '\033[' + styles[color][1] + 'm' #Stylize color helper stylize = (level) -> style = levelStylesMapping[level] if (style) return '\033[' + styles[style][0] + 'm' + '[' + level + ']' + '\033[' + styles[style][1] + 'm' else return str if global? colors = true else stylize = (level) -> return '['+ level + '] ' colorize = (string, color) -> string #common LOGGING functionality ->! this comes over caller _addStaticContext = ( args..., level ) -> args.unshift stylize(level) if level? and @options.printLevel stack = @name + ' static' message = "[-- #{now()} #{stack}] #{args.join ' '}" messageColor = " -- #{now()} #{colorize('[ '+ stack + ']', level)} #{args.join ' '}" if @options.emitLog @_emitter.emit level.toLowerCase(), 'message': message 'data': 'class': @name 'args': args[1...args.length] 'type': args[1] return messageColor _addContext = ( args..., level ) -> args.unshift stylize(level) if level? and @options.printLevel try #reg = new RegExp /at\s(.*)\s\(/g #reg = new RegExp /at\s(.*)\s\(.*:(\d+):\d+/i reg = new RegExp /at\s(.*)\s\(.*[\/\\]([^\/\\\.]+\.js|[^\/\\\.]+\.coffee):(\d+):\d+/i #RegExp.multiLine = true stackArray = new Error().stack.split reg #debugger #console.log util.inspect stackArray #this is a hardcore hack, but what shalls if @options.useStack #stack = if stackArray[9].indexOf('new') is -1 and stackArray[11].indexOf('anonymous') is -1 then stackArray[11] else stackArray[9] # select everything before parenthesis for stack in stackArray #stack = if stackArray[13].indexOf('new') is -1 and stackArray[19].indexOf('anonymous') is -1 then "#{stackArray[19]}[#{stackArray[20]}]"else "#{stackArray[13]}[#{stackArray[14]}]" # select everything before parenthesis for stack in stackArray if stackArray[17].indexOf('new') is -1 and stackArray[25]?.indexOf('anonymous') is -1 stack = "#{stackArray[25]} (#{stackArray[26]}:[#{stackArray[27]}])" fileNameAndLine = " in #{stackArray[26]}:[#{stackArray[27]}]" classAndFunction = "#{stackArray[25]}" isnew = false else stack = "#{stackArray[17]} (#{stackArray[18]}:[#{stackArray[19]}])" # select everything before parenthesis for stack in stackArray fileNameAndLine = " in #{stackArray[18]}:[#{stackArray[19]}]" classAndFunction = "#{stackArray[17]}" isnew = true #wamit handling if stack.indexOf('inmit') isnt -1 or stack.indexOf('wamit') isnt -1 or stack.indexOf('ermit') isnt -1 #then stack = stackArray[13] #then stack = "#{stackArray[22]}[#{stackArray[23]}]" if not isnew stack = "[#{stackArray[29]}: (#{stackArray[30]}:[#{stackArray[31]}])" fileNameAndLine = " in #{stackArray[30]}:[#{stackArray[31]}]" classAndFunction = "#{stackArray[29]}" else stack = "[#{stackArray[21]}: (#{stackArray[22]}:[#{stackArray[23]}])" fileNameAndLine = " in #{stackArray[22]}:[#{stackArray[23]}]" classAndFunction = "#{stackArray[21]}" catch e stack ?= @constructor.name if @options.autoId then id = " id:#{@_id}" message = "-- #{now()} [#{classAndFunction + id}] #{args.join ' '} #{fileNameAndLine}" messageColor = "-- #{now()} #{colorize('['+ classAndFunction + id + ']', level)} #{args.join ' '} #{colorize(fileNameAndLine, level)}" if @options.emitLog @emit level.toLowerCase(), 'message': message 'data': 'class': @constructor.name 'id': @_id 'uuid': @_uuid 'args': args[1...args.length] 'type': args[1] #let's say that the first argument is the message, the second the type return messageColor #combined emit logging functions -> ! this comes over caller _ermit = (message, errObj={}) -> mes = if typeof message isnt 'string' and message.message? if typeof message.message isnt 'string' and message.message.message? # message instanceof Error message.message.message else message.message else #ducktype for passing in an error object message if arguments.length < 1 or typeof mes isnt 'string' then throw "Ermit needs at least one arguments: a message and an optional error Object" ### message data - message -stack (the current stack) -err (the underlying errorObj) ### err = 'stack': new Error().stack 'message': message 'err': errObj @error mes @emit 'error', err _wamit = (type, dataObj={}, message="") -> if arguments.length <1 or typeof message isnt 'string' or typeof type isnt 'string' then throw "wamit needs at least one arguments: a type, an optional Data Object and an optional message" ### data dataOb - message ### if typeof dataObj is "string" then message = dataObj mes = if message is "" then type else message dataObj.message ?= "" if typeof dataObj.message is "string" then dataObj.message += ' - ' + mes #don't override if dataObj has an existing message property @warn mes @emit type, dataObj _inmit = (type, dataObj={}, message="") -> if arguments.length <1 or typeof message isnt 'string' or typeof type isnt 'string' then throw "inmit needs at least one arguments: a type, an optional Data Object and an optional message" if typeof dataObj is "string" then message = dataObj mes = if message is "" then type else message ### data dataOb - message ### if dataObj.message then dataObj.message + " - " else "" #don't override if dataObj has an existing message property dataObj.message += mes @info mes @emit type, dataObj
181988
events = require('events') util = require(if process.binding('natives').util then 'util' else 'sys') CappedObject = require './CappedObject' #extend the stacktracelimit for coffeescript Error.stackTraceLimit = 50; stringify = (obj) -> JSON.stringify(obj, null, " ") #from underscore.coffee isEmpty = (obj) -> return obj.length is 0 if isArray(obj) or isString(obj) return false for own key of obj true isElement = (obj) -> obj and obj.nodeType is 1 isArguments = (obj) -> obj and obj.callee isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply) isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr)) isArray = Array.isArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee) ### # # MERGE # a mixin function similar to _.extend but more powerful # it can also deal with non objects like functions # # @desc A cool merge function, that emits warnings # # @args obj, args..., last # the first argunment is the object we merge in,, which can also be a function, or better if the first obj is not an object we just set it to the merge value, # the last can be a boolean, in such case it is a switch for turning on and off warnings, on overwriting existing variables # logging of warnings is turned on by default # ### module.exports.merge = module.exports.extend = module.exports.mixin = merge = (obj, args..., last) -> if not obj? then throw new Error('merge: first parameter must not be undefined') log = true #logging of merge conflict is turned on by default initialProps = {} initialProps[prop] = true for own prop of obj if typeof last isnt 'boolean' then args.push last else log = last for source in args if obj is source then return obj #if it's the same just return if (typeof source isnt 'object') and source? #if source is not an object and not undefined set obj to source, but log if we overwrite an existing obj if (typeof obj isnt 'object' and obj?) or not isEmpty(obj) #obj can be a function or string or an object containing something, then we warn if log then @warn "Object #{stringify(obj) or obj.name or typeof obj} exists and will be overwritten with #{stringify(source) or obj.name or typeof obj}" obj = source else for own prop of source if initialProps[prop]? #if the property already exists in the iniotial properties the object had before merge if log # and we log @warn "property #{prop} exists and value #{stringify(obj[prop]) or typeof obj[prop]} will be overwritten with #{stringify(source[prop]) or typeof obj[prop]}" #give a warning about overwriting and existing initial Property of Object ###at #{new Error().stack}### obj[prop] = source[prop] return obj #Coffeescript is anoying on this, all you don't define before, will be undefined #NodeBase.options = NodeBase.defaults = merge NodeBase.defaults, NodeBase.objdefaults #LOG LEVELS L = 0 LL = ALL: L++ LOG : L++ INFO : L++ WARN : L++ ERROR : L++ LL[LL[L]] = L for L of LL #yeah! ### @desc this is the mother of all Objects; a node Base Class with (logging and options, defaults) NodeBase is an EventEmitter ### class NodeBase extends events.EventEmitter #static Functions @now = now @static = (superClass) -> superClass[i]?=NodeBase[i] for own i, val of NodeBase merge superClass.options or= {}, superClass.defaults, false #superClass options has already nodeBases @options merged in through extend #superClass.Cache ?= new CappedObject(NodeBase.options.maxCap, superClass.name) #emit CLASS level cache events #superClass.Cache.on 'add', (obj) => superClass.emit 'add', obj #superClass.Cache.on 'remove', (obj) => superClass.emit 'remove', obj #superClass.Cache.on 'drop', (obj) => superClass.emit 'drop', obj @objdefaults = logging: true logLevel: 'ERROR' printLevel: true printContext: true useStack: true emitLog: false @defaults = merge @objdefaults, #see above Coffescript is annoying on using functions that are defined later in context addToCollection: false maxCap: 10000 @options = @defaults @merge = merge @mixin = merge @extend = merge @node_ver = node_ver #Class Collection specific @lookupId = (id)-> if @name? then @Cache?.getId(id) else NodeBase?.getId(id) #the CLASS level NODEBASE cache (=Capped Hash) #@Cache ?= new CappedObject(NodeBase.options.maxCap, @name) #emit CLASS level cache events #@Cache.on 'add', (obj) => @emit 'add', obj #@Cache.on 'remove', (obj) => @emit 'remove', obj #@Cache.on 'drop', (obj) => @emit 'drop', obj #@Cache = -> if @name? then Cache[@name] else Cache['NodeBase'] #remove Objects from the CLASS collection, see also @_remove() on Object level @_remove = (obj) -> _remove(obj) #get the number of objects created @getTotalIds = -> if @name? then cids[@name] || 0 else cids['NodeBase'] || 0 #CLASS level logging @log = -> if @options.logging and @_checkLogLevel 'LOG' then console.log (@_addContext arguments..., 'LOG') @warn = -> if @options.logging and @_checkLogLevel 'WARN' then console.log (@_addContext arguments..., 'WARN') @info = -> if @options.logging and @_checkLogLevel 'INFO' then console.log (@_addContext arguments..., 'INFO') @error = -> if @options.logging and @_checkLogLevel 'ERROR' then console.log (@_addContext arguments..., 'ERROR') @_addContext = -> _addStaticContext.apply @, arguments @_checkLogLevel = (level)-> LL[@options.logLevel] <= LL[level] #event emitting of CLASS @emit: -> @_emitter.emit.apply @, arguments @_emitter = new events.EventEmitter(); @_emitter.on 'error', (err) -> console.log stringify(err, null, " ") #CLASS level combined log emitters @ermit= -> _ermit.apply @, arguments @wamit= -> _wamit.apply @, arguments @inmit= -> _inmit.apply @, arguments constructor:(opts, defaults) -> super() @init(opts, defaults) init: (opts, defaults) -> self=this #merge defaults but don't make them public -> defaults will become options _defaults = merge {}, logging: true logLevel: 'ERROR' printLevel: true printContext: true useStack: true emitLog: false autoId: true autoUuid: true cacheSize: 5 ,@defaults, defaults, false # merge constructor level Object defaults before object level defaults @options = merge @options or= {}, @constructor.objdefaults, _defaults, opts, true #@on 'error', (err) -> @log 'emitted error ' + JSON.stringify(err) @LOG_LEVELS = LL #make log levels available in the object @_checkLogLevel = (level)-> LL[@options.logLevel] <= LL[level] if @_id and @options.autoId then @warn 'overwriting _id' @_id = if @options.autoId then cid(this) else @_id @_uuid = if @options.autoUuid then UUID.uuid() else "" if @options.autoId then @_getTotalIds = -> getTotalIds @ #actually this is just a counter of times the constructor was called if @constructor?.options?.addToCollection then addId(this) remove: -> _remove(this) #ADD THE CLASSNAME AND A TIMESTAMP TO THE LOGGING OUTPUT _addContext: -> _addContext.apply @, arguments ### # # OBJECT LOGGING # error is special in that the first argument is interpretated as message, second as type, third, ... as arguments # # ### log: => if @options.logging and @_checkLogLevel 'LOG' then console.log (@_addContext arguments..., 'LOG') warn: => if @options.logging and @_checkLogLevel 'WARN' then console.log (@_addContext arguments..., 'WARN') info: => if @options.logging and @_checkLogLevel 'INFO' then console.log (@_addContext arguments..., 'INFO') error: => if @options.logging and @_checkLogLevel 'ERROR' then console.log (@_addContext arguments..., 'ERROR') ermit: => _ermit.apply @, arguments wamit: => _wamit.apply @, arguments inmit: => _inmit.apply @, arguments #export the base class # module.exports = NodeBase module.exports.LOG_LEVELS = LL; module.exports.now = now = -> new Date().toUTCString(); #the node version node_ver = null do -> return node_ver if node_ver? ver = process.version rex = /^v(\d+)\.(\d+)\.(\d+)/i matches = ver.match(rex) throw "Unable to determine node version" unless matches? node_ver = major: ~~matches[1] minor: ~~matches[2] release: ~~matches[3] module.exports.node_ver = node_ver; #Convert arguments to array arrize = (ary, from = 0 ) -> return Array.prototype.slice.call(ary, from) #a bind function similar to _.bind #Bind proxy objects to function glue = (f, obj, oargs...) -> (iargs...) -> f.apply? obj, oargs.concat iargs module.exports.glue = glue; ### Code taken from <NAME> UUID Math.uuid.js (v1.4) http://www.broofa.com mailto:<EMAIL> Copyright (c) 2010 <NAME> Dual licensed under the MIT and GPL licenses. A UUID GENERATROR FUNCTION Private array of chars to use ### CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') UUID = {} UUID.uuid = (len, radix=CHARS.length) -> chars = CHARS uuid = [] if len? # Compact form for i in [0..len] uuid[i] = chars[0 | Math.random()*radix] else # rfc4122, version 4 form r # rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' uuid[14] = '4' # Fill in random data. At i==19 set the high bits of clock sequence as # per rfc4122, sec. 4.1.5 for i in [0...36] if not uuid[i] r = 0 | Math.random()*16 uuid[i] = chars[if (i == 19) then (r & 0x3) | 0x8 else r] uuid.join('') module.exports.uuid = UUID.uuid module.exports.UUID = UUID #Cid Handling cids={} cid = (obj)-> if obj?.constructor.name? ++cids[obj.constructor.name] || cids[obj.constructor.name]= 1 else ++cids['NodeBase'] || cids['NodeBase']= 1 getTotalCids = (obj) -> if obj?.constructor.name? cids[obj.constructor.name] || 0 else cids['NodeBase'] || 0 #add Ids to a global collection, can be looked up with the static function className.lookupId #Cache = {} _remove = (obj)-> if not obj._id then module.exports.error "Obj to add has no propety _id, please turn on autoId or give the object an _id before passing it to super" if obj?.constructor.name? #(Cache[obj.constructor.name]?=new CappedObject(NodeBase.options.maxCap, obj.constructor.name)).remove(obj) obj.constructor.Cache.remove(obj) else #(Cache['NodeBase']?={})[obj._id] = obj #(Cache['NodeBase']?=new CappedObject(NodeBase.options.maxCap, 'NodeBase')).remove(obj) NodeBase.Cache.remove(obj) addId = (obj)-> #check if autoId is turned on or the object has an id if not obj._id then module.exports.error "Obj to add has no propety _id, please turn on autoId or give the object an _id before passing it to super" if obj?.constructor.name? #(Cache[obj.constructor.name]?={})[obj._id] = obj #(Cache[obj.constructor.name]?=new CappedObject(NodeBase.options.maxCap, obj.constructor.name)).addId(obj) (obj.constructor.Cache?=new CappedObject(NodeBase.options.maxCap, obj.constructor)).addId(obj) else #(Cache['NodeBase']?={})[obj._id] = obj #(Cache['NodeBase']?=new CappedObject(NodeBase.options.maxCap, 'NodeBase')).addId(obj) (NodeBase.Cache?=new CappedObject(NodeBase.options.maxCap, NodeBase)).addId(obj) module.exports.cid = cid # http://en.wikipedia.org/wiki/ANSI_escape_code#graphics styles = 'bold' : [1, 22] 'italic' : [3, 23] 'underline' : [4, 24] 'inverse' : [7, 27] 'white' : [37, 39] 'grey' : [90, 39] 'black' : [30, 39] 'blue' : [34, 39] 'cyan' : [36, 39] 'green' : [32, 39] 'magenta' : [35, 39] 'red' : [31, 39] 'yellow' : [33, 39] levelStylesMapping = 'WARN': 'magenta' 'ERROR': 'red' 'INFO': 'cyan' 'LOG': 'green' colorize = (string, color) -> #can be a color or level color = levelStylesMapping[color]?=color return '\033[' + styles[color][0] + 'm' + string + '\033[' + styles[color][1] + 'm' #Stylize color helper stylize = (level) -> style = levelStylesMapping[level] if (style) return '\033[' + styles[style][0] + 'm' + '[' + level + ']' + '\033[' + styles[style][1] + 'm' else return str if global? colors = true else stylize = (level) -> return '['+ level + '] ' colorize = (string, color) -> string #common LOGGING functionality ->! this comes over caller _addStaticContext = ( args..., level ) -> args.unshift stylize(level) if level? and @options.printLevel stack = @name + ' static' message = "[-- #{now()} #{stack}] #{args.join ' '}" messageColor = " -- #{now()} #{colorize('[ '+ stack + ']', level)} #{args.join ' '}" if @options.emitLog @_emitter.emit level.toLowerCase(), 'message': message 'data': 'class': @name 'args': args[1...args.length] 'type': args[1] return messageColor _addContext = ( args..., level ) -> args.unshift stylize(level) if level? and @options.printLevel try #reg = new RegExp /at\s(.*)\s\(/g #reg = new RegExp /at\s(.*)\s\(.*:(\d+):\d+/i reg = new RegExp /at\s(.*)\s\(.*[\/\\]([^\/\\\.]+\.js|[^\/\\\.]+\.coffee):(\d+):\d+/i #RegExp.multiLine = true stackArray = new Error().stack.split reg #debugger #console.log util.inspect stackArray #this is a hardcore hack, but what shalls if @options.useStack #stack = if stackArray[9].indexOf('new') is -1 and stackArray[11].indexOf('anonymous') is -1 then stackArray[11] else stackArray[9] # select everything before parenthesis for stack in stackArray #stack = if stackArray[13].indexOf('new') is -1 and stackArray[19].indexOf('anonymous') is -1 then "#{stackArray[19]}[#{stackArray[20]}]"else "#{stackArray[13]}[#{stackArray[14]}]" # select everything before parenthesis for stack in stackArray if stackArray[17].indexOf('new') is -1 and stackArray[25]?.indexOf('anonymous') is -1 stack = "#{stackArray[25]} (#{stackArray[26]}:[#{stackArray[27]}])" fileNameAndLine = " in #{stackArray[26]}:[#{stackArray[27]}]" classAndFunction = "#{stackArray[25]}" isnew = false else stack = "#{stackArray[17]} (#{stackArray[18]}:[#{stackArray[19]}])" # select everything before parenthesis for stack in stackArray fileNameAndLine = " in #{stackArray[18]}:[#{stackArray[19]}]" classAndFunction = "#{stackArray[17]}" isnew = true #wamit handling if stack.indexOf('inmit') isnt -1 or stack.indexOf('wamit') isnt -1 or stack.indexOf('ermit') isnt -1 #then stack = stackArray[13] #then stack = "#{stackArray[22]}[#{stackArray[23]}]" if not isnew stack = "[#{stackArray[29]}: (#{stackArray[30]}:[#{stackArray[31]}])" fileNameAndLine = " in #{stackArray[30]}:[#{stackArray[31]}]" classAndFunction = "#{stackArray[29]}" else stack = "[#{stackArray[21]}: (#{stackArray[22]}:[#{stackArray[23]}])" fileNameAndLine = " in #{stackArray[22]}:[#{stackArray[23]}]" classAndFunction = "#{stackArray[21]}" catch e stack ?= @constructor.name if @options.autoId then id = " id:#{@_id}" message = "-- #{now()} [#{classAndFunction + id}] #{args.join ' '} #{fileNameAndLine}" messageColor = "-- #{now()} #{colorize('['+ classAndFunction + id + ']', level)} #{args.join ' '} #{colorize(fileNameAndLine, level)}" if @options.emitLog @emit level.toLowerCase(), 'message': message 'data': 'class': @constructor.name 'id': @_id 'uuid': @_uuid 'args': args[1...args.length] 'type': args[1] #let's say that the first argument is the message, the second the type return messageColor #combined emit logging functions -> ! this comes over caller _ermit = (message, errObj={}) -> mes = if typeof message isnt 'string' and message.message? if typeof message.message isnt 'string' and message.message.message? # message instanceof Error message.message.message else message.message else #ducktype for passing in an error object message if arguments.length < 1 or typeof mes isnt 'string' then throw "Ermit needs at least one arguments: a message and an optional error Object" ### message data - message -stack (the current stack) -err (the underlying errorObj) ### err = 'stack': new Error().stack 'message': message 'err': errObj @error mes @emit 'error', err _wamit = (type, dataObj={}, message="") -> if arguments.length <1 or typeof message isnt 'string' or typeof type isnt 'string' then throw "wamit needs at least one arguments: a type, an optional Data Object and an optional message" ### data dataOb - message ### if typeof dataObj is "string" then message = dataObj mes = if message is "" then type else message dataObj.message ?= "" if typeof dataObj.message is "string" then dataObj.message += ' - ' + mes #don't override if dataObj has an existing message property @warn mes @emit type, dataObj _inmit = (type, dataObj={}, message="") -> if arguments.length <1 or typeof message isnt 'string' or typeof type isnt 'string' then throw "inmit needs at least one arguments: a type, an optional Data Object and an optional message" if typeof dataObj is "string" then message = dataObj mes = if message is "" then type else message ### data dataOb - message ### if dataObj.message then dataObj.message + " - " else "" #don't override if dataObj has an existing message property dataObj.message += mes @info mes @emit type, dataObj
true
events = require('events') util = require(if process.binding('natives').util then 'util' else 'sys') CappedObject = require './CappedObject' #extend the stacktracelimit for coffeescript Error.stackTraceLimit = 50; stringify = (obj) -> JSON.stringify(obj, null, " ") #from underscore.coffee isEmpty = (obj) -> return obj.length is 0 if isArray(obj) or isString(obj) return false for own key of obj true isElement = (obj) -> obj and obj.nodeType is 1 isArguments = (obj) -> obj and obj.callee isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply) isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr)) isArray = Array.isArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee) ### # # MERGE # a mixin function similar to _.extend but more powerful # it can also deal with non objects like functions # # @desc A cool merge function, that emits warnings # # @args obj, args..., last # the first argunment is the object we merge in,, which can also be a function, or better if the first obj is not an object we just set it to the merge value, # the last can be a boolean, in such case it is a switch for turning on and off warnings, on overwriting existing variables # logging of warnings is turned on by default # ### module.exports.merge = module.exports.extend = module.exports.mixin = merge = (obj, args..., last) -> if not obj? then throw new Error('merge: first parameter must not be undefined') log = true #logging of merge conflict is turned on by default initialProps = {} initialProps[prop] = true for own prop of obj if typeof last isnt 'boolean' then args.push last else log = last for source in args if obj is source then return obj #if it's the same just return if (typeof source isnt 'object') and source? #if source is not an object and not undefined set obj to source, but log if we overwrite an existing obj if (typeof obj isnt 'object' and obj?) or not isEmpty(obj) #obj can be a function or string or an object containing something, then we warn if log then @warn "Object #{stringify(obj) or obj.name or typeof obj} exists and will be overwritten with #{stringify(source) or obj.name or typeof obj}" obj = source else for own prop of source if initialProps[prop]? #if the property already exists in the iniotial properties the object had before merge if log # and we log @warn "property #{prop} exists and value #{stringify(obj[prop]) or typeof obj[prop]} will be overwritten with #{stringify(source[prop]) or typeof obj[prop]}" #give a warning about overwriting and existing initial Property of Object ###at #{new Error().stack}### obj[prop] = source[prop] return obj #Coffeescript is anoying on this, all you don't define before, will be undefined #NodeBase.options = NodeBase.defaults = merge NodeBase.defaults, NodeBase.objdefaults #LOG LEVELS L = 0 LL = ALL: L++ LOG : L++ INFO : L++ WARN : L++ ERROR : L++ LL[LL[L]] = L for L of LL #yeah! ### @desc this is the mother of all Objects; a node Base Class with (logging and options, defaults) NodeBase is an EventEmitter ### class NodeBase extends events.EventEmitter #static Functions @now = now @static = (superClass) -> superClass[i]?=NodeBase[i] for own i, val of NodeBase merge superClass.options or= {}, superClass.defaults, false #superClass options has already nodeBases @options merged in through extend #superClass.Cache ?= new CappedObject(NodeBase.options.maxCap, superClass.name) #emit CLASS level cache events #superClass.Cache.on 'add', (obj) => superClass.emit 'add', obj #superClass.Cache.on 'remove', (obj) => superClass.emit 'remove', obj #superClass.Cache.on 'drop', (obj) => superClass.emit 'drop', obj @objdefaults = logging: true logLevel: 'ERROR' printLevel: true printContext: true useStack: true emitLog: false @defaults = merge @objdefaults, #see above Coffescript is annoying on using functions that are defined later in context addToCollection: false maxCap: 10000 @options = @defaults @merge = merge @mixin = merge @extend = merge @node_ver = node_ver #Class Collection specific @lookupId = (id)-> if @name? then @Cache?.getId(id) else NodeBase?.getId(id) #the CLASS level NODEBASE cache (=Capped Hash) #@Cache ?= new CappedObject(NodeBase.options.maxCap, @name) #emit CLASS level cache events #@Cache.on 'add', (obj) => @emit 'add', obj #@Cache.on 'remove', (obj) => @emit 'remove', obj #@Cache.on 'drop', (obj) => @emit 'drop', obj #@Cache = -> if @name? then Cache[@name] else Cache['NodeBase'] #remove Objects from the CLASS collection, see also @_remove() on Object level @_remove = (obj) -> _remove(obj) #get the number of objects created @getTotalIds = -> if @name? then cids[@name] || 0 else cids['NodeBase'] || 0 #CLASS level logging @log = -> if @options.logging and @_checkLogLevel 'LOG' then console.log (@_addContext arguments..., 'LOG') @warn = -> if @options.logging and @_checkLogLevel 'WARN' then console.log (@_addContext arguments..., 'WARN') @info = -> if @options.logging and @_checkLogLevel 'INFO' then console.log (@_addContext arguments..., 'INFO') @error = -> if @options.logging and @_checkLogLevel 'ERROR' then console.log (@_addContext arguments..., 'ERROR') @_addContext = -> _addStaticContext.apply @, arguments @_checkLogLevel = (level)-> LL[@options.logLevel] <= LL[level] #event emitting of CLASS @emit: -> @_emitter.emit.apply @, arguments @_emitter = new events.EventEmitter(); @_emitter.on 'error', (err) -> console.log stringify(err, null, " ") #CLASS level combined log emitters @ermit= -> _ermit.apply @, arguments @wamit= -> _wamit.apply @, arguments @inmit= -> _inmit.apply @, arguments constructor:(opts, defaults) -> super() @init(opts, defaults) init: (opts, defaults) -> self=this #merge defaults but don't make them public -> defaults will become options _defaults = merge {}, logging: true logLevel: 'ERROR' printLevel: true printContext: true useStack: true emitLog: false autoId: true autoUuid: true cacheSize: 5 ,@defaults, defaults, false # merge constructor level Object defaults before object level defaults @options = merge @options or= {}, @constructor.objdefaults, _defaults, opts, true #@on 'error', (err) -> @log 'emitted error ' + JSON.stringify(err) @LOG_LEVELS = LL #make log levels available in the object @_checkLogLevel = (level)-> LL[@options.logLevel] <= LL[level] if @_id and @options.autoId then @warn 'overwriting _id' @_id = if @options.autoId then cid(this) else @_id @_uuid = if @options.autoUuid then UUID.uuid() else "" if @options.autoId then @_getTotalIds = -> getTotalIds @ #actually this is just a counter of times the constructor was called if @constructor?.options?.addToCollection then addId(this) remove: -> _remove(this) #ADD THE CLASSNAME AND A TIMESTAMP TO THE LOGGING OUTPUT _addContext: -> _addContext.apply @, arguments ### # # OBJECT LOGGING # error is special in that the first argument is interpretated as message, second as type, third, ... as arguments # # ### log: => if @options.logging and @_checkLogLevel 'LOG' then console.log (@_addContext arguments..., 'LOG') warn: => if @options.logging and @_checkLogLevel 'WARN' then console.log (@_addContext arguments..., 'WARN') info: => if @options.logging and @_checkLogLevel 'INFO' then console.log (@_addContext arguments..., 'INFO') error: => if @options.logging and @_checkLogLevel 'ERROR' then console.log (@_addContext arguments..., 'ERROR') ermit: => _ermit.apply @, arguments wamit: => _wamit.apply @, arguments inmit: => _inmit.apply @, arguments #export the base class # module.exports = NodeBase module.exports.LOG_LEVELS = LL; module.exports.now = now = -> new Date().toUTCString(); #the node version node_ver = null do -> return node_ver if node_ver? ver = process.version rex = /^v(\d+)\.(\d+)\.(\d+)/i matches = ver.match(rex) throw "Unable to determine node version" unless matches? node_ver = major: ~~matches[1] minor: ~~matches[2] release: ~~matches[3] module.exports.node_ver = node_ver; #Convert arguments to array arrize = (ary, from = 0 ) -> return Array.prototype.slice.call(ary, from) #a bind function similar to _.bind #Bind proxy objects to function glue = (f, obj, oargs...) -> (iargs...) -> f.apply? obj, oargs.concat iargs module.exports.glue = glue; ### Code taken from PI:NAME:<NAME>END_PI UUID Math.uuid.js (v1.4) http://www.broofa.com mailto:PI:EMAIL:<EMAIL>END_PI Copyright (c) 2010 PI:NAME:<NAME>END_PI Dual licensed under the MIT and GPL licenses. A UUID GENERATROR FUNCTION Private array of chars to use ### CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') UUID = {} UUID.uuid = (len, radix=CHARS.length) -> chars = CHARS uuid = [] if len? # Compact form for i in [0..len] uuid[i] = chars[0 | Math.random()*radix] else # rfc4122, version 4 form r # rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' uuid[14] = '4' # Fill in random data. At i==19 set the high bits of clock sequence as # per rfc4122, sec. 4.1.5 for i in [0...36] if not uuid[i] r = 0 | Math.random()*16 uuid[i] = chars[if (i == 19) then (r & 0x3) | 0x8 else r] uuid.join('') module.exports.uuid = UUID.uuid module.exports.UUID = UUID #Cid Handling cids={} cid = (obj)-> if obj?.constructor.name? ++cids[obj.constructor.name] || cids[obj.constructor.name]= 1 else ++cids['NodeBase'] || cids['NodeBase']= 1 getTotalCids = (obj) -> if obj?.constructor.name? cids[obj.constructor.name] || 0 else cids['NodeBase'] || 0 #add Ids to a global collection, can be looked up with the static function className.lookupId #Cache = {} _remove = (obj)-> if not obj._id then module.exports.error "Obj to add has no propety _id, please turn on autoId or give the object an _id before passing it to super" if obj?.constructor.name? #(Cache[obj.constructor.name]?=new CappedObject(NodeBase.options.maxCap, obj.constructor.name)).remove(obj) obj.constructor.Cache.remove(obj) else #(Cache['NodeBase']?={})[obj._id] = obj #(Cache['NodeBase']?=new CappedObject(NodeBase.options.maxCap, 'NodeBase')).remove(obj) NodeBase.Cache.remove(obj) addId = (obj)-> #check if autoId is turned on or the object has an id if not obj._id then module.exports.error "Obj to add has no propety _id, please turn on autoId or give the object an _id before passing it to super" if obj?.constructor.name? #(Cache[obj.constructor.name]?={})[obj._id] = obj #(Cache[obj.constructor.name]?=new CappedObject(NodeBase.options.maxCap, obj.constructor.name)).addId(obj) (obj.constructor.Cache?=new CappedObject(NodeBase.options.maxCap, obj.constructor)).addId(obj) else #(Cache['NodeBase']?={})[obj._id] = obj #(Cache['NodeBase']?=new CappedObject(NodeBase.options.maxCap, 'NodeBase')).addId(obj) (NodeBase.Cache?=new CappedObject(NodeBase.options.maxCap, NodeBase)).addId(obj) module.exports.cid = cid # http://en.wikipedia.org/wiki/ANSI_escape_code#graphics styles = 'bold' : [1, 22] 'italic' : [3, 23] 'underline' : [4, 24] 'inverse' : [7, 27] 'white' : [37, 39] 'grey' : [90, 39] 'black' : [30, 39] 'blue' : [34, 39] 'cyan' : [36, 39] 'green' : [32, 39] 'magenta' : [35, 39] 'red' : [31, 39] 'yellow' : [33, 39] levelStylesMapping = 'WARN': 'magenta' 'ERROR': 'red' 'INFO': 'cyan' 'LOG': 'green' colorize = (string, color) -> #can be a color or level color = levelStylesMapping[color]?=color return '\033[' + styles[color][0] + 'm' + string + '\033[' + styles[color][1] + 'm' #Stylize color helper stylize = (level) -> style = levelStylesMapping[level] if (style) return '\033[' + styles[style][0] + 'm' + '[' + level + ']' + '\033[' + styles[style][1] + 'm' else return str if global? colors = true else stylize = (level) -> return '['+ level + '] ' colorize = (string, color) -> string #common LOGGING functionality ->! this comes over caller _addStaticContext = ( args..., level ) -> args.unshift stylize(level) if level? and @options.printLevel stack = @name + ' static' message = "[-- #{now()} #{stack}] #{args.join ' '}" messageColor = " -- #{now()} #{colorize('[ '+ stack + ']', level)} #{args.join ' '}" if @options.emitLog @_emitter.emit level.toLowerCase(), 'message': message 'data': 'class': @name 'args': args[1...args.length] 'type': args[1] return messageColor _addContext = ( args..., level ) -> args.unshift stylize(level) if level? and @options.printLevel try #reg = new RegExp /at\s(.*)\s\(/g #reg = new RegExp /at\s(.*)\s\(.*:(\d+):\d+/i reg = new RegExp /at\s(.*)\s\(.*[\/\\]([^\/\\\.]+\.js|[^\/\\\.]+\.coffee):(\d+):\d+/i #RegExp.multiLine = true stackArray = new Error().stack.split reg #debugger #console.log util.inspect stackArray #this is a hardcore hack, but what shalls if @options.useStack #stack = if stackArray[9].indexOf('new') is -1 and stackArray[11].indexOf('anonymous') is -1 then stackArray[11] else stackArray[9] # select everything before parenthesis for stack in stackArray #stack = if stackArray[13].indexOf('new') is -1 and stackArray[19].indexOf('anonymous') is -1 then "#{stackArray[19]}[#{stackArray[20]}]"else "#{stackArray[13]}[#{stackArray[14]}]" # select everything before parenthesis for stack in stackArray if stackArray[17].indexOf('new') is -1 and stackArray[25]?.indexOf('anonymous') is -1 stack = "#{stackArray[25]} (#{stackArray[26]}:[#{stackArray[27]}])" fileNameAndLine = " in #{stackArray[26]}:[#{stackArray[27]}]" classAndFunction = "#{stackArray[25]}" isnew = false else stack = "#{stackArray[17]} (#{stackArray[18]}:[#{stackArray[19]}])" # select everything before parenthesis for stack in stackArray fileNameAndLine = " in #{stackArray[18]}:[#{stackArray[19]}]" classAndFunction = "#{stackArray[17]}" isnew = true #wamit handling if stack.indexOf('inmit') isnt -1 or stack.indexOf('wamit') isnt -1 or stack.indexOf('ermit') isnt -1 #then stack = stackArray[13] #then stack = "#{stackArray[22]}[#{stackArray[23]}]" if not isnew stack = "[#{stackArray[29]}: (#{stackArray[30]}:[#{stackArray[31]}])" fileNameAndLine = " in #{stackArray[30]}:[#{stackArray[31]}]" classAndFunction = "#{stackArray[29]}" else stack = "[#{stackArray[21]}: (#{stackArray[22]}:[#{stackArray[23]}])" fileNameAndLine = " in #{stackArray[22]}:[#{stackArray[23]}]" classAndFunction = "#{stackArray[21]}" catch e stack ?= @constructor.name if @options.autoId then id = " id:#{@_id}" message = "-- #{now()} [#{classAndFunction + id}] #{args.join ' '} #{fileNameAndLine}" messageColor = "-- #{now()} #{colorize('['+ classAndFunction + id + ']', level)} #{args.join ' '} #{colorize(fileNameAndLine, level)}" if @options.emitLog @emit level.toLowerCase(), 'message': message 'data': 'class': @constructor.name 'id': @_id 'uuid': @_uuid 'args': args[1...args.length] 'type': args[1] #let's say that the first argument is the message, the second the type return messageColor #combined emit logging functions -> ! this comes over caller _ermit = (message, errObj={}) -> mes = if typeof message isnt 'string' and message.message? if typeof message.message isnt 'string' and message.message.message? # message instanceof Error message.message.message else message.message else #ducktype for passing in an error object message if arguments.length < 1 or typeof mes isnt 'string' then throw "Ermit needs at least one arguments: a message and an optional error Object" ### message data - message -stack (the current stack) -err (the underlying errorObj) ### err = 'stack': new Error().stack 'message': message 'err': errObj @error mes @emit 'error', err _wamit = (type, dataObj={}, message="") -> if arguments.length <1 or typeof message isnt 'string' or typeof type isnt 'string' then throw "wamit needs at least one arguments: a type, an optional Data Object and an optional message" ### data dataOb - message ### if typeof dataObj is "string" then message = dataObj mes = if message is "" then type else message dataObj.message ?= "" if typeof dataObj.message is "string" then dataObj.message += ' - ' + mes #don't override if dataObj has an existing message property @warn mes @emit type, dataObj _inmit = (type, dataObj={}, message="") -> if arguments.length <1 or typeof message isnt 'string' or typeof type isnt 'string' then throw "inmit needs at least one arguments: a type, an optional Data Object and an optional message" if typeof dataObj is "string" then message = dataObj mes = if message is "" then type else message ### data dataOb - message ### if dataObj.message then dataObj.message + " - " else "" #don't override if dataObj has an existing message property dataObj.message += mes @info mes @emit type, dataObj
[ { "context": ".alice_and_bob()\n alice.secretKey = new Buffer('0000000000000000000000000000000000000000000000000000", "end": 2956, "score": 0.5452808737754822, "start": 2955, "tag": "KEY", "value": "0" }, { "context": "d.real_saltpack\n people_keys = [\n new Buffer('28536f6cd88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'),\n new Buffer('1247", "end": 4108, "score": 0.9939508438110352, "start": 4063, "tag": "KEY", "value": "28536f6cd88b94772fc82b248163c5c7da76f75099be9" }, { "context": "r('28536f6cd88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'),\n new Buffer('12474e6642d", "end": 4115, "score": 0.8672866225242615, "start": 4110, "tag": "KEY", "value": "bb3c7" }, { "context": "36f6cd88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'),\n new Buffer('12474e6642d963c6", "end": 4120, "score": 0.8353164196014404, "start": 4116, "tag": "KEY", "value": "37f3" }, { "context": "88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'),\n new Buffer('12474e6642d963c63bd8171", "end": 4127, "score": 0.9826059341430664, "start": 4122, "tag": "KEY", "value": "ab70f" }, { "context": "9be9e4bb3c7937f375ab70f', 'hex'),\n new Buffer('12474e6642d963c63bd8171cea7ddaef1120555ccaa15b8835c253ff8f67783c', 'hex'),\n new Buffer('915a08512f4fba8fccb9a25", "end": 4218, "score": 0.999721884727478, "start": 4154, "tag": "KEY", "value": "12474e6642d963c63bd8171cea7ddaef1120555ccaa15b8835c253ff8f67783c" }, { "context": "aa15b8835c253ff8f67783c', 'hex'),\n new Buffer('915a08512f4fba8fccb9a258998a3513679e457b6f444a6f4bfc6", "end": 4248, "score": 0.6208176016807556, "start": 4245, "tag": "KEY", "value": "915" }, { "context": "hex'),\n new Buffer('915a08512f4fba8fccb9a258998a3513679e457b6f444a6f4bfc613fe81b8b1c', 'hex'),\n new", "end": 4277, "score": 0.5723087787628174, "start": 4272, "tag": "KEY", "value": "a3513" }, { "context": "\n new Buffer('915a08512f4fba8fccb9a258998a3513679e457b6f444a6f4bfc613fe81b8b1c', 'hex'),\n new B", "end": 4279, "score": 0.5462631583213806, "start": 4278, "tag": "KEY", "value": "7" }, { "context": "5a08512f4fba8fccb9a258998a3513679e457b6f444a6f4bfc613fe81b8b1c', 'hex'),\n new Buffer('83711fb9664c47", "end": 4300, "score": 0.573350727558136, "start": 4297, "tag": "KEY", "value": "613" }, { "context": "12f4fba8fccb9a258998a3513679e457b6f444a6f4bfc613fe81b8b1c', 'hex'),\n new Buffer('83711fb9664c478e43", "end": 4304, "score": 0.5229562520980835, "start": 4302, "tag": "KEY", "value": "81" }, { "context": "f444a6f4bfc613fe81b8b1c', 'hex'),\n new Buffer('83711fb9664c478e43c62cf21040726b10d2670b7dbb49d3a6fcd92", "end": 4341, "score": 0.9056196212768555, "start": 4336, "tag": "KEY", "value": "83711" }, { "context": "4bfc613fe81b8b1c', 'hex'),\n new Buffer('83711fb9664c478e43c62cf21040726b10d2670b7dbb49d3a6fcd926a876ff1c', 'hex", "end": 4357, "score": 0.7278399467468262, "start": 4343, "tag": "KEY", "value": "9664c478e43c62" }, { "context": "', 'hex'),\n new Buffer('83711fb9664c478e43c62cf21040726b10d2670b7dbb49d3a6fcd926a876ff1c', 'hex'),\n new Buffer('28536", "end": 4382, "score": 0.8010877966880798, "start": 4359, "tag": "KEY", "value": "21040726b10d2670b7dbb49" }, { "context": "r('83711fb9664c478e43c62cf21040726b10d2670b7dbb49d3a6fcd926a876ff1c', 'hex'),\n new Buffer('28536f6cd88b94", "end": 4391, "score": 0.7876800894737244, "start": 4383, "tag": "KEY", "value": "3a6fcd92" }, { "context": "\n es.end()\n console.log('Send the following to Patrick, Jack, Mark, Max Krohn, Chris Coyne, or Chris Bal", "end": 5588, "score": 0.9998199939727783, "start": 5581, "tag": "NAME", "value": "Patrick" }, { "context": "nd()\n console.log('Send the following to Patrick, Jack, Mark, Max Krohn, Chris Coyne, or Chris Ball:')\n ", "end": 5594, "score": 0.9142604470252991, "start": 5590, "tag": "NAME", "value": "Jack" }, { "context": " console.log('Send the following to Patrick, Jack, Mark, Max Krohn, Chris Coyne, or Chris Ball:')\n conso", "end": 5600, "score": 0.9166443347930908, "start": 5596, "tag": "NAME", "value": "Mark" }, { "context": "le.log('Send the following to Patrick, Jack, Mark, Max Krohn, Chris Coyne, or Chris Ball:')\n console.log(stb.", "end": 5611, "score": 0.9997943639755249, "start": 5602, "tag": "NAME", "value": "Max Krohn" }, { "context": "d the following to Patrick, Jack, Mark, Max Krohn, Chris Coyne, or Chris Ball:')\n console.log(stb.getBuffer().t", "end": 5624, "score": 0.9998347163200378, "start": 5613, "tag": "NAME", "value": "Chris Coyne" }, { "context": "to Patrick, Jack, Mark, Max Krohn, Chris Coyne, or Chris Ball:')\n console.log(stb.getBuffer().toString())\n cb", "end": 5639, "score": 0.9998315572738647, "start": 5629, "tag": "NAME", "value": "Chris Ball" } ]
test/files/stream.iced
hummhive/node-saltpack
21
crypto = require('crypto') saltpack = require('../..') {make_esc} = require('iced-error') format = saltpack.lowlevel.format stream = saltpack.stream util = saltpack.lowlevel.util vectors = require('../vectors.iced') msg_length = (1024**2)/2 #=============================================================================== # Workhorse functions #=============================================================================== _test_stream = (T, {test_case, stream}, cb) -> input = test_case.input stb = new util.StreamToBuffer() stream.pipe(stb) # if the test case was invalid, then we'll get a callback with the error we want to test, before hitting the T.equal below err = null stream.on('error', (_err) -> err = _err ) stream.write(new Buffer(input)) await stream.on('finish', defer()) stream.end() if err? cb(err, null) else cb(null, stb.getBuffer()) _test_saltpack_pipeline = (T, {do_armoring, anon_recips}, cb) -> {alice, bob} = util.alice_and_bob() recipients_list = util.gen_recipients(bob.publicKey) if anon_recips anonymized_recipients = [] anonymized_recipients.push(null) for [0...recipients_list.length] es = new stream.EncryptStream({encryptor : alice, do_armoring, recipients : recipients_list, anonymized_recipients}) else es = new stream.EncryptStream({encryptor : alice, do_armoring, recipients : recipients_list}) ds = new stream.DecryptStream({decryptor : bob, do_armoring}) stb = new util.StreamToBuffer() es.pipe(ds.first_stream) ds.pipe(stb) await util.stream_random_data(es, msg_length, defer(data)) await stb.on('finish', defer()) es.end() out = stb.getBuffer() T.equal(data.length, out.length, 'Truncation or garbage bytes') T.equal(data, out, 'Plaintext mismatch') cb() #=============================================================================== # Unit tests #=============================================================================== exports.test_format_stream = (T, cb) -> test_case = vectors.valid.format await _test_stream(T, {test_case, stream: new format.FormatStream({})}, defer(err, res)) if err? then throw err T.equal(res, new Buffer(test_case.output), "Vector #{test_case.name} failed") cb() exports.test_short_single_block = (T, cb) -> test_case = vectors.valid.short_single_block await _test_stream(T, {test_case, stream: new format.DeformatStream({})}, defer(err, res)) if err? then throw err T.equal(res, new Buffer(test_case.output), "Vector #{test_case.name} failed") cb() exports.test_dog_end = (T, cb) -> test_case = vectors.invalid.dog_footer await _test_stream(T, {test_case, stream: new format.DeformatStream({})}, defer(err, _)) T.equal(err.message, test_case.error, "Vector #{test_case.name} failed") cb() exports.test_truncation = (T, cb) -> test_case = vectors.invalid.truncated_ending_packet {alice} = util.alice_and_bob() alice.secretKey = new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex') await _test_stream(T, {test_case, stream: new stream.DecryptStream({decryptor: alice, do_armoring: true})}, defer(err, _)) T.equal(err.message, test_case.error, "Vector #{test_case.name} failed") cb() exports.test_saltpack_with_armor = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: true, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_saltpack_without_armor = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: false, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_anonymous_recipients = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: false, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_real_saltpack = (T, cb) -> test_case = vectors.valid.real_saltpack people_keys = [ new Buffer('28536f6cd88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'), new Buffer('12474e6642d963c63bd8171cea7ddaef1120555ccaa15b8835c253ff8f67783c', 'hex'), new Buffer('915a08512f4fba8fccb9a258998a3513679e457b6f444a6f4bfc613fe81b8b1c', 'hex'), new Buffer('83711fb9664c478e43c62cf21040726b10d2670b7dbb49d3a6fcd926a876ff1c', 'hex'), new Buffer('28536f6cd88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'), new Buffer('7e1454c201e72d7f22ded1fe359d5817a4c969ad7f2b742450d4e5606372c87e', 'hex'), new Buffer('9322c883599f4440eda5c2d40b0e1590b569db171d6fec2a92fbe7e12f90b414', 'hex'), new Buffer('d8507ab27528c6118f525f2e4d0d99cfbebf1f399758f596057b573f6e01ed48', 'hex'), new Buffer('c51589346c15414cf18ab7c23fed27dc8055f69770d2f34f6ca141607cc34d63', 'hex'), new Buffer('720b0ce2a6f7a3aff279702d157aa78b1bd774273be18938f4c006c9aadac90d', 'hex'), new Buffer('196bcc720c24d0b9937e3d78b966d27ab3679eb23330d7d0ca39b57bb3bac256', 'hex'), new Buffer('5da375c0018da143c001fe426e39dde28f85d99d16a7d30b46dd235f4f6f5b59', 'hex'), new Buffer('ddc0f890b224bc698e4f843b046b1eeaf3455504b434837424bcb63132bec40c', 'hex'), new Buffer('d65361e0d119422d7fa2d461b1eb460fcf9e3d0ed864b5b06639526b787e3c3b', 'hex')] es = new stream.EncryptStream({encryptor: null, do_armoring: true, recipients: people_keys}) stb = new util.StreamToBuffer() es.pipe(stb) es.write(test_case.input) await stb.on('finish', defer()) es.end() console.log('Send the following to Patrick, Jack, Mark, Max Krohn, Chris Coyne, or Chris Ball:') console.log(stb.getBuffer().toString()) cb()
135920
crypto = require('crypto') saltpack = require('../..') {make_esc} = require('iced-error') format = saltpack.lowlevel.format stream = saltpack.stream util = saltpack.lowlevel.util vectors = require('../vectors.iced') msg_length = (1024**2)/2 #=============================================================================== # Workhorse functions #=============================================================================== _test_stream = (T, {test_case, stream}, cb) -> input = test_case.input stb = new util.StreamToBuffer() stream.pipe(stb) # if the test case was invalid, then we'll get a callback with the error we want to test, before hitting the T.equal below err = null stream.on('error', (_err) -> err = _err ) stream.write(new Buffer(input)) await stream.on('finish', defer()) stream.end() if err? cb(err, null) else cb(null, stb.getBuffer()) _test_saltpack_pipeline = (T, {do_armoring, anon_recips}, cb) -> {alice, bob} = util.alice_and_bob() recipients_list = util.gen_recipients(bob.publicKey) if anon_recips anonymized_recipients = [] anonymized_recipients.push(null) for [0...recipients_list.length] es = new stream.EncryptStream({encryptor : alice, do_armoring, recipients : recipients_list, anonymized_recipients}) else es = new stream.EncryptStream({encryptor : alice, do_armoring, recipients : recipients_list}) ds = new stream.DecryptStream({decryptor : bob, do_armoring}) stb = new util.StreamToBuffer() es.pipe(ds.first_stream) ds.pipe(stb) await util.stream_random_data(es, msg_length, defer(data)) await stb.on('finish', defer()) es.end() out = stb.getBuffer() T.equal(data.length, out.length, 'Truncation or garbage bytes') T.equal(data, out, 'Plaintext mismatch') cb() #=============================================================================== # Unit tests #=============================================================================== exports.test_format_stream = (T, cb) -> test_case = vectors.valid.format await _test_stream(T, {test_case, stream: new format.FormatStream({})}, defer(err, res)) if err? then throw err T.equal(res, new Buffer(test_case.output), "Vector #{test_case.name} failed") cb() exports.test_short_single_block = (T, cb) -> test_case = vectors.valid.short_single_block await _test_stream(T, {test_case, stream: new format.DeformatStream({})}, defer(err, res)) if err? then throw err T.equal(res, new Buffer(test_case.output), "Vector #{test_case.name} failed") cb() exports.test_dog_end = (T, cb) -> test_case = vectors.invalid.dog_footer await _test_stream(T, {test_case, stream: new format.DeformatStream({})}, defer(err, _)) T.equal(err.message, test_case.error, "Vector #{test_case.name} failed") cb() exports.test_truncation = (T, cb) -> test_case = vectors.invalid.truncated_ending_packet {alice} = util.alice_and_bob() alice.secretKey = new Buffer('0<KEY>00000000000000000000000000000000000000000000000000000000000000', 'hex') await _test_stream(T, {test_case, stream: new stream.DecryptStream({decryptor: alice, do_armoring: true})}, defer(err, _)) T.equal(err.message, test_case.error, "Vector #{test_case.name} failed") cb() exports.test_saltpack_with_armor = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: true, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_saltpack_without_armor = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: false, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_anonymous_recipients = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: false, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_real_saltpack = (T, cb) -> test_case = vectors.valid.real_saltpack people_keys = [ new Buffer('<KEY>e4<KEY>9<KEY>75<KEY>', 'hex'), new Buffer('<KEY>', 'hex'), new Buffer('<KEY>a08512f4fba8fccb9a258998<KEY>6<KEY>9e457b6f444a6f4bfc<KEY>fe<KEY>b8b1c', 'hex'), new Buffer('<KEY>fb<KEY>cf<KEY>d<KEY>6a876ff1c', 'hex'), new Buffer('28536f6cd88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'), new Buffer('7e1454c201e72d7f22ded1fe359d5817a4c969ad7f2b742450d4e5606372c87e', 'hex'), new Buffer('9322c883599f4440eda5c2d40b0e1590b569db171d6fec2a92fbe7e12f90b414', 'hex'), new Buffer('d8507ab27528c6118f525f2e4d0d99cfbebf1f399758f596057b573f6e01ed48', 'hex'), new Buffer('c51589346c15414cf18ab7c23fed27dc8055f69770d2f34f6ca141607cc34d63', 'hex'), new Buffer('720b0ce2a6f7a3aff279702d157aa78b1bd774273be18938f4c006c9aadac90d', 'hex'), new Buffer('196bcc720c24d0b9937e3d78b966d27ab3679eb23330d7d0ca39b57bb3bac256', 'hex'), new Buffer('5da375c0018da143c001fe426e39dde28f85d99d16a7d30b46dd235f4f6f5b59', 'hex'), new Buffer('ddc0f890b224bc698e4f843b046b1eeaf3455504b434837424bcb63132bec40c', 'hex'), new Buffer('d65361e0d119422d7fa2d461b1eb460fcf9e3d0ed864b5b06639526b787e3c3b', 'hex')] es = new stream.EncryptStream({encryptor: null, do_armoring: true, recipients: people_keys}) stb = new util.StreamToBuffer() es.pipe(stb) es.write(test_case.input) await stb.on('finish', defer()) es.end() console.log('Send the following to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, or <NAME>:') console.log(stb.getBuffer().toString()) cb()
true
crypto = require('crypto') saltpack = require('../..') {make_esc} = require('iced-error') format = saltpack.lowlevel.format stream = saltpack.stream util = saltpack.lowlevel.util vectors = require('../vectors.iced') msg_length = (1024**2)/2 #=============================================================================== # Workhorse functions #=============================================================================== _test_stream = (T, {test_case, stream}, cb) -> input = test_case.input stb = new util.StreamToBuffer() stream.pipe(stb) # if the test case was invalid, then we'll get a callback with the error we want to test, before hitting the T.equal below err = null stream.on('error', (_err) -> err = _err ) stream.write(new Buffer(input)) await stream.on('finish', defer()) stream.end() if err? cb(err, null) else cb(null, stb.getBuffer()) _test_saltpack_pipeline = (T, {do_armoring, anon_recips}, cb) -> {alice, bob} = util.alice_and_bob() recipients_list = util.gen_recipients(bob.publicKey) if anon_recips anonymized_recipients = [] anonymized_recipients.push(null) for [0...recipients_list.length] es = new stream.EncryptStream({encryptor : alice, do_armoring, recipients : recipients_list, anonymized_recipients}) else es = new stream.EncryptStream({encryptor : alice, do_armoring, recipients : recipients_list}) ds = new stream.DecryptStream({decryptor : bob, do_armoring}) stb = new util.StreamToBuffer() es.pipe(ds.first_stream) ds.pipe(stb) await util.stream_random_data(es, msg_length, defer(data)) await stb.on('finish', defer()) es.end() out = stb.getBuffer() T.equal(data.length, out.length, 'Truncation or garbage bytes') T.equal(data, out, 'Plaintext mismatch') cb() #=============================================================================== # Unit tests #=============================================================================== exports.test_format_stream = (T, cb) -> test_case = vectors.valid.format await _test_stream(T, {test_case, stream: new format.FormatStream({})}, defer(err, res)) if err? then throw err T.equal(res, new Buffer(test_case.output), "Vector #{test_case.name} failed") cb() exports.test_short_single_block = (T, cb) -> test_case = vectors.valid.short_single_block await _test_stream(T, {test_case, stream: new format.DeformatStream({})}, defer(err, res)) if err? then throw err T.equal(res, new Buffer(test_case.output), "Vector #{test_case.name} failed") cb() exports.test_dog_end = (T, cb) -> test_case = vectors.invalid.dog_footer await _test_stream(T, {test_case, stream: new format.DeformatStream({})}, defer(err, _)) T.equal(err.message, test_case.error, "Vector #{test_case.name} failed") cb() exports.test_truncation = (T, cb) -> test_case = vectors.invalid.truncated_ending_packet {alice} = util.alice_and_bob() alice.secretKey = new Buffer('0PI:KEY:<KEY>END_PI00000000000000000000000000000000000000000000000000000000000000', 'hex') await _test_stream(T, {test_case, stream: new stream.DecryptStream({decryptor: alice, do_armoring: true})}, defer(err, _)) T.equal(err.message, test_case.error, "Vector #{test_case.name} failed") cb() exports.test_saltpack_with_armor = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: true, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_saltpack_without_armor = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: false, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_anonymous_recipients = (T, cb) -> start = new Date().getTime() await _test_saltpack_pipeline(T, {do_armoring: false, anon_recips: false}, defer()) end = new Date().getTime() console.log("Time: #{end-start}") cb() exports.test_real_saltpack = (T, cb) -> test_case = vectors.valid.real_saltpack people_keys = [ new Buffer('PI:KEY:<KEY>END_PIe4PI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PI75PI:KEY:<KEY>END_PI', 'hex'), new Buffer('PI:KEY:<KEY>END_PI', 'hex'), new Buffer('PI:KEY:<KEY>END_PIa08512f4fba8fccb9a258998PI:KEY:<KEY>END_PI6PI:KEY:<KEY>END_PI9e457b6f444a6f4bfcPI:KEY:<KEY>END_PIfePI:KEY:<KEY>END_PIb8b1c', 'hex'), new Buffer('PI:KEY:<KEY>END_PIfbPI:KEY:<KEY>END_PIcfPI:KEY:<KEY>END_PIdPI:KEY:<KEY>END_PI6a876ff1c', 'hex'), new Buffer('28536f6cd88b94772fc82b248163c5c7da76f75099be9e4bb3c7937f375ab70f', 'hex'), new Buffer('7e1454c201e72d7f22ded1fe359d5817a4c969ad7f2b742450d4e5606372c87e', 'hex'), new Buffer('9322c883599f4440eda5c2d40b0e1590b569db171d6fec2a92fbe7e12f90b414', 'hex'), new Buffer('d8507ab27528c6118f525f2e4d0d99cfbebf1f399758f596057b573f6e01ed48', 'hex'), new Buffer('c51589346c15414cf18ab7c23fed27dc8055f69770d2f34f6ca141607cc34d63', 'hex'), new Buffer('720b0ce2a6f7a3aff279702d157aa78b1bd774273be18938f4c006c9aadac90d', 'hex'), new Buffer('196bcc720c24d0b9937e3d78b966d27ab3679eb23330d7d0ca39b57bb3bac256', 'hex'), new Buffer('5da375c0018da143c001fe426e39dde28f85d99d16a7d30b46dd235f4f6f5b59', 'hex'), new Buffer('ddc0f890b224bc698e4f843b046b1eeaf3455504b434837424bcb63132bec40c', 'hex'), new Buffer('d65361e0d119422d7fa2d461b1eb460fcf9e3d0ed864b5b06639526b787e3c3b', 'hex')] es = new stream.EncryptStream({encryptor: null, do_armoring: true, recipients: people_keys}) stb = new util.StreamToBuffer() es.pipe(stb) es.write(test_case.input) await stb.on('finish', defer()) es.end() console.log('Send the following to 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, or PI:NAME:<NAME>END_PI:') console.log(stb.getBuffer().toString()) cb()
[ { "context": "re '../index'\r\ntwitterKeys = {\r\n consumer_key : 'XXXXXXXXXXXXXXXXXXXXXXXXX',\r\n consumer_secret : 'XXXXXXXXXXXXXXXXXXXXXXXXX", "end": 206, "score": 0.9988781213760376, "start": 181, "tag": "KEY", "value": "XXXXXXXXXXXXXXXXXXXXXXXXX" }, { "context": "XXXXXXXXXXXXXXXXXXXXXXXXX',\r\n consumer_secret : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'\r\n};\r\n\r\n# Fake data to use as sinon stubs\r\nfakeDa", "end": 281, "score": 0.9992982149124146, "start": 231, "tag": "KEY", "value": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" } ]
client/node_modules/fetch-tweets/test/search-tweets.test.coffee
ggruessingUCB/tweetTweet
1
# Testing frameworks and tools expect = require('chai').expect sinon = require('sinon') # Modules to test fetchTweets = require '../index' twitterKeys = { consumer_key : 'XXXXXXXXXXXXXXXXXXXXXXXXX', consumer_secret : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' }; # Fake data to use as sinon stubs fakeData1 = require './fake-data/search-tweets-fake-data1' fakeData2 = require './fake-data/search-tweets-fake-data2' fakeData3 = require './fake-data/search-tweets-fake-data3' # Set up sinon stubs ftModuleShort = new fetchTweets(twitterKeys) ftModuleLong = new fetchTweets(twitterKeys, false) # will return full output callback1 = sinon.stub(ftModuleShort, "byTopic") callback1.withArgs({q: 'awesome', count: 3}).returns(fakeData1); callback1.withArgs('banana').returns(fakeData3); callback2 = sinon.stub(ftModuleLong, "byTopic") callback2.withArgs({q: 'javascript', count: 5}).returns(fakeData2); describe 'Check the search tweets methods work as they should', ()-> it 'Should accept a json object with Twtter options', ()-> expect(callback1({q: 'awesome', count: 3})).equal(fakeData1) it 'Should return full output for specified object', ()-> expect(callback2({q: 'javascript', count: 5})).equal(fakeData2) it 'Should also accept a plain string input', ()-> expect(callback1('banana')).equal(fakeData3)
135090
# Testing frameworks and tools expect = require('chai').expect sinon = require('sinon') # Modules to test fetchTweets = require '../index' twitterKeys = { consumer_key : '<KEY>', consumer_secret : '<KEY>' }; # Fake data to use as sinon stubs fakeData1 = require './fake-data/search-tweets-fake-data1' fakeData2 = require './fake-data/search-tweets-fake-data2' fakeData3 = require './fake-data/search-tweets-fake-data3' # Set up sinon stubs ftModuleShort = new fetchTweets(twitterKeys) ftModuleLong = new fetchTweets(twitterKeys, false) # will return full output callback1 = sinon.stub(ftModuleShort, "byTopic") callback1.withArgs({q: 'awesome', count: 3}).returns(fakeData1); callback1.withArgs('banana').returns(fakeData3); callback2 = sinon.stub(ftModuleLong, "byTopic") callback2.withArgs({q: 'javascript', count: 5}).returns(fakeData2); describe 'Check the search tweets methods work as they should', ()-> it 'Should accept a json object with Twtter options', ()-> expect(callback1({q: 'awesome', count: 3})).equal(fakeData1) it 'Should return full output for specified object', ()-> expect(callback2({q: 'javascript', count: 5})).equal(fakeData2) it 'Should also accept a plain string input', ()-> expect(callback1('banana')).equal(fakeData3)
true
# Testing frameworks and tools expect = require('chai').expect sinon = require('sinon') # Modules to test fetchTweets = require '../index' twitterKeys = { consumer_key : 'PI:KEY:<KEY>END_PI', consumer_secret : 'PI:KEY:<KEY>END_PI' }; # Fake data to use as sinon stubs fakeData1 = require './fake-data/search-tweets-fake-data1' fakeData2 = require './fake-data/search-tweets-fake-data2' fakeData3 = require './fake-data/search-tweets-fake-data3' # Set up sinon stubs ftModuleShort = new fetchTweets(twitterKeys) ftModuleLong = new fetchTweets(twitterKeys, false) # will return full output callback1 = sinon.stub(ftModuleShort, "byTopic") callback1.withArgs({q: 'awesome', count: 3}).returns(fakeData1); callback1.withArgs('banana').returns(fakeData3); callback2 = sinon.stub(ftModuleLong, "byTopic") callback2.withArgs({q: 'javascript', count: 5}).returns(fakeData2); describe 'Check the search tweets methods work as they should', ()-> it 'Should accept a json object with Twtter options', ()-> expect(callback1({q: 'awesome', count: 3})).equal(fakeData1) it 'Should return full output for specified object', ()-> expect(callback2({q: 'javascript', count: 5})).equal(fakeData2) it 'Should also accept a plain string input', ()-> expect(callback1('banana')).equal(fakeData3)
[ { "context": "od: 'GET'\n , JSON.stringify products: [ name: \"test\", cost: 20 ]\n\n @adapter.perform 'readAll', @Pr", "end": 2300, "score": 0.9979721307754517, "start": 2296, "tag": "NAME", "value": "test" }, { "context": "aData: \"foo\"\n products: [\n name: \"testA\"\n cost: 20\n ,\n name: \"te", "end": 2726, "score": 0.9919953942298889, "start": 2721, "tag": "NAME", "value": "testA" }, { "context": "tA\"\n cost: 20\n ,\n name: \"testB\"\n cost: 10\n ]\n\n @adapter.after", "end": 2779, "score": 0.9935593008995056, "start": 2774, "tag": "NAME", "value": "testB" }, { "context": " method: 'POST'\n data: '{\"product\":{\"name\":\"test\"}}'\n contentType: 'application/json'\n , p", "end": 3316, "score": 0.9977008104324341, "start": 3312, "tag": "NAME", "value": "test" }, { "context": " , productJSON\n\n product = new @Product(name: \"test\")\n @adapter.perform 'create', product, {}, (er", "end": 3416, "score": 0.9983083009719849, "start": 3412, "tag": "NAME", "value": "test" }, { "context": " ,\n product:\n id: 10\n name: 'test 8'\n\n MockRequest.expect\n url: '/products/10", "end": 8162, "score": 0.7715805172920227, "start": 8156, "tag": "NAME", "value": "test 8" }, { "context": " ,\n product:\n id: 10\n name: 'test 8'\n\n 'reading from storage: should callback with", "end": 8289, "score": 0.6930923461914062, "start": 8285, "tag": "NAME", "value": "test" }, { "context": " product:\n id: 10\n name: 'test 8'\n\n 'reading from storage: should callback with a", "end": 8291, "score": 0.48596182465553284, "start": 8290, "tag": "NAME", "value": "8" }, { "context": " method: 'POST'\n , product:\n name: \"testA\"\n cost: 20\n\n MockRequest.expect\n u", "end": 8690, "score": 0.9962852001190186, "start": 8685, "tag": "NAME", "value": "testA" }, { "context": " method: 'POST'\n , product:\n name: \"testB\"\n cost: 10\n\n MockRequest.expect\n u", "end": 8812, "score": 0.9966530799865723, "start": 8807, "tag": "NAME", "value": "testB" }, { "context": " method: 'GET'\n , products: [\n name: \"testA\"\n cost: 20\n ,\n name: \"testB\"\n ", "end": 8936, "score": 0.9969729781150818, "start": 8931, "tag": "NAME", "value": "testA" }, { "context": ": \"testA\"\n cost: 20\n ,\n name: \"testB\"\n cost: 10\n ]\n\n 'reading many from s", "end": 8983, "score": 0.997696578502655, "start": 8978, "tag": "NAME", "value": "testB" }, { "context": "hod: 'POST'\n , special_product:\n name: \"testA\"\n cost: 20\n\n MockRequest.expect\n u", "end": 9216, "score": 0.994931697845459, "start": 9211, "tag": "NAME", "value": "testA" }, { "context": "hod: 'POST'\n , special_product:\n name: \"testB\"\n cost: 10\n\n MockRequest.expect\n u", "end": 9354, "score": 0.996300220489502, "start": 9349, "tag": "NAME", "value": "testB" }, { "context": "d: 'GET'\n , special_products: [\n name: \"testA\"\n cost: 20\n ,\n name: \"testB\"\n ", "end": 9494, "score": 0.9967795014381409, "start": 9489, "tag": "NAME", "value": "testA" }, { "context": ": \"testA\"\n cost: 20\n ,\n name: \"testB\"\n cost: 10\n ]\n\n 'reading many from s", "end": 9541, "score": 0.9972121119499207, "start": 9536, "tag": "NAME", "value": "testB" }, { "context": " method: 'POST'\n ,product:\n name: \"testA\"\n cost: 20\n\n MockRequest.expect\n u", "end": 9760, "score": 0.9961501955986023, "start": 9755, "tag": "NAME", "value": "testA" }, { "context": " method: 'POST'\n , product:\n name: \"testB\"\n cost: 10\n\n MockRequest.expect\n u", "end": 9882, "score": 0.9960423707962036, "start": 9877, "tag": "NAME", "value": "testB" }, { "context": " method: 'GET'\n , products: [\n name: \"testA\"\n cost: 20\n ,\n name: \"testB\"\n ", "end": 10006, "score": 0.9969640970230103, "start": 10001, "tag": "NAME", "value": "testA" }, { "context": ": \"testA\"\n cost: 20\n ,\n name: \"testB\"\n cost: 10\n ]\n\n 'reading many from s", "end": 10053, "score": 0.9978444576263428, "start": 10048, "tag": "NAME", "value": "testB" }, { "context": " method: 'POST'\n ,product:\n name: \"testA\"\n cost: 10\n\n MockRequest.expect\n u", "end": 10283, "score": 0.996820330619812, "start": 10278, "tag": "NAME", "value": "testA" }, { "context": " method: 'POST'\n , product:\n name: \"testB\"\n cost: 10\n\n MockRequest.expect {\n ", "end": 10405, "score": 0.9975415468215942, "start": 10400, "tag": "NAME", "value": "testB" }, { "context": "ost: 10\n }, {\n products: [\n name: \"testA\"\n cost: 20\n ,\n name: \"testB\"\n ", "end": 10569, "score": 0.9969821572303772, "start": 10564, "tag": "NAME", "value": "testA" }, { "context": ": \"testA\"\n cost: 20\n ,\n name: \"testB\"\n cost: 10\n ]\n }\n\n 'reading many ", "end": 10616, "score": 0.9978100061416626, "start": 10611, "tag": "NAME", "value": "testB" }, { "context": " method: 'PUT'\n , product:\n name: 'test'\n cost: 10\n id: 10\n\n MockRequest", "end": 11090, "score": 0.9995095729827881, "start": 11086, "tag": "NAME", "value": "test" }, { "context": " method: 'GET'\n , product:\n name: 'test'\n cost: 10\n id: 10\n\n 'updating in ", "end": 11228, "score": 0.9995115995407104, "start": 11224, "tag": "NAME", "value": "test" }, { "context": "thod: 'PUT'\n , special_product:\n name: 'test'\n cost: 10\n id: 10\n\n MockRequest", "end": 11566, "score": 0.9989435076713562, "start": 11562, "tag": "NAME", "value": "test" }, { "context": "thod: 'GET'\n , special_product:\n name: 'test'\n cost: 10\n id: 10\n\n 'updating in ", "end": 11720, "score": 0.998862624168396, "start": 11716, "tag": "NAME", "value": "test" } ]
tests/batman/storage_adapter/rest_storage_helper.coffee
airhorns/batman
1
if typeof require isnt 'undefined' {sharedStorageTestSuite} = require('./storage_adapter_helper') else {sharedStorageTestSuite} = window productJSON = product: name: 'test' id: 10 specialProductJSON = special_product: name: 'test' id: 10 class MockRequest extends MockClass @dataHasFileUploads: Batman.Request.dataHasFileUploads @expects = {} @reset: -> MockClass.reset.call(@) @expects = {} @expect: (request, response) -> responses = @expects[request.url] ||= [] responses.push {request, response} CALLBACKS = ['success', 'loaded', 'loading', 'error'] for key in CALLBACKS @chainedCallback key @getExpectedForUrl: (url) -> @expects[url] || [] constructor: (requestOptions) -> super() for key in CALLBACKS @[key](requestOptions[key]) if requestOptions[key]? @fireLoading() allExpected = @constructor.getExpectedForUrl(requestOptions.url) expected = allExpected.shift() setTimeout => if ! expected? @fireError {message: "Unrecognized mocked request!", request: @} else {request, response} = expected for k in ['method', 'data', 'contentType'] if request[k]? && !QUnit.equiv(request[k], requestOptions[k]) throw "Wrong #{k} for expected request! Expected #{request[k]}, got #{requestOptions[k]}." if response.error if typeof response.error is 'string' @fireError {message: response.error, request: @} else response.error.request = @ @status = response.error.status @response = response.error.response @fireError response.error else @response = response @fireSuccess response @fireLoaded response , 1 get: (k) -> throw "Can't get anything other than 'response' and 'status' on the Requests" unless k in ['response', 'status'] @[k] restStorageTestSuite = -> test 'default options should be independent', -> otherAdapter = new @adapter.constructor(@Product) notEqual otherAdapter.defaultRequestOptions, @adapter.defaultRequestOptions asyncTest 'can readAll from JSON string', 3, -> MockRequest.expect url: '/products' method: 'GET' , JSON.stringify products: [ name: "test", cost: 20 ] @adapter.perform 'readAll', @Product::, {}, (err, readProducts) -> ok !err ok readProducts equal readProducts[0].get("name"), "test" QUnit.start() asyncTest 'response metadata should be available in the after read callbacks', 3, -> MockRequest.expect url: '/products' method: 'GET' , someMetaData: "foo" products: [ name: "testA" cost: 20 , name: "testB" cost: 10 ] @adapter.after 'readAll', (data, next) -> throw data.error if data.error equal data.data.someMetaData, "foo" next() @adapter.perform 'readAll', @Product::, {}, (err, readProducts) -> ok !err ok readProducts QUnit.start() asyncTest 'it should POST JSON instead of serialized parameters when configured to do so', -> @adapter.serializeAsForm = false MockRequest.expect url: '/products' method: 'POST' data: '{"product":{"name":"test"}}' contentType: 'application/json' , productJSON product = new @Product(name: "test") @adapter.perform 'create', product, {}, (err, record) => throw err if err ok record QUnit.start() sharedStorageTestSuite(restStorageTestSuite.sharedSuiteHooks) restStorageTestSuite.testOptionsGeneration = (urlSuffix = '') -> test 'string record urls should be gotten in the options', 1, -> product = new @Product product.url = '/some/url' url = @adapter.urlForRecord product, {} equal url, "/some/url#{urlSuffix}" test 'function record urls should be executed in the options', 1, -> product = new @Product product.url = -> '/some/url' url = @adapter.urlForRecord product, {} equal url, "/some/url#{urlSuffix}" test 'function record urls should be given the options for the storage operation', 1, -> product = new @Product opts = {foo: true} product.url = (passedOpts) -> equal passedOpts, opts '/some/url' @adapter.urlForRecord product, {options: opts} test 'string model urls should be gotten in the options', 1, -> @Product.url = '/some/url' url = @adapter.urlForCollection @Product, {} equal url, "/some/url#{urlSuffix}" test 'function model urls should be executed in the options', 1, -> @Product.url = -> '/some/url' url = @adapter.urlForCollection @Product, {} equal url, "/some/url#{urlSuffix}" test 'function model urls should be given the options for the storage operation', 1, -> opts = {foo: true} @Product.url = (passedOpts) -> equal passedOpts, opts '/some/url' @adapter.urlForCollection @Product, {options: opts} test 'records should take a urlPrefix option', 1, -> product = new @Product product.url = '/some/url' product.urlPrefix = '/admin' url = @adapter.urlForRecord product, {} equal url, "/admin/some/url#{urlSuffix}" test 'records should take a urlSuffix option', 1, -> product = new @Product product.url = '/some/url' product.urlSuffix = '.foo' url = @adapter.urlForRecord product, {} equal url, "/some/url.foo#{urlSuffix}" test 'models should be able to specify a urlPrefix', 1, -> @Product.url = '/some/url' @Product.urlPrefix = '/admin' url = @adapter.urlForCollection @Product, {} equal url, "/admin/some/url#{urlSuffix}" test 'models should be able to specify a urlSuffix', 1, -> @Product.url = '/some/url' @Product.urlSuffix = '.foo' url = @adapter.urlForCollection @Product, {} equal url, "/some/url.foo#{urlSuffix}" restStorageTestSuite.sharedSuiteHooks = 'creating in storage: should succeed if the record doesn\'t already exist': -> MockRequest.expect url: '/products' method: 'POST' , productJSON 'creating in storage: should fail if the record does already exist': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products' method: 'POST' , error: "Product already exists!" "creating in storage: should create a primary key if the record doesn't already have one": -> MockRequest.expect url: '/products' method: 'POST' , productJSON "creating in storage: should encode data before saving it": -> MockRequest.expect url: '/products' method: 'POST' , product: name: 'TEST' id: 10 'reading from storage: should callback with the record if the record has been created': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'GET' , productJSON 'reading from storage: should callback with the record if the record has been created and the record is an instance of a subclass': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'GET' , specialProductJSON 'reading from storage: should keep records of a class and records of a subclass separate': -> superJSON = product: name: 'test super' id: 10 subJSON = special_product: name: 'test sub' id: 10 MockRequest.expect url: '/special_products' method: 'POST' , subJSON MockRequest.expect url: '/products' method: 'POST' , superJSON MockRequest.expect url: '/products/10' method: 'GET' , superJSON MockRequest.expect url: '/special_products/10' method: 'GET' , subJSON 'reading from storage: should callback with decoded data after reading it': -> MockRequest.expect url: '/products' method: 'POST' , product: id: 10 name: 'test 8' MockRequest.expect url: '/products/10' method: 'GET' , product: id: 10 name: 'test 8' 'reading from storage: should callback with an error if the record hasn\'t been created': -> MockRequest.expect url: '/products/10' method: 'GET' , error: 'specified record doesn\'t exist' 'reading many from storage: should callback with the records if they exist': -> MockRequest.expect url: '/products' method: 'POST' , product: name: "testA" cost: 20 MockRequest.expect url: '/products' method: 'POST' , product: name: "testB" cost: 10 MockRequest.expect url: '/products' method: 'GET' , products: [ name: "testA" cost: 20 , name: "testB" cost: 10 ] 'reading many from storage: should callback with subclass records if they exist': -> MockRequest.expect url: '/special_products' method: 'POST' , special_product: name: "testA" cost: 20 MockRequest.expect url: '/special_products' method: 'POST' , special_product: name: "testB" cost: 10 MockRequest.expect url: '/special_products' method: 'GET' , special_products: [ name: "testA" cost: 20 , name: "testB" cost: 10 ] 'reading many from storage: should callback with the decoded records if they exist': -> MockRequest.expect url: '/products' method: 'POST' ,product: name: "testA" cost: 20 MockRequest.expect url: '/products' method: 'POST' , product: name: "testB" cost: 10 MockRequest.expect url: '/products' method: 'GET' , products: [ name: "testA" cost: 20 , name: "testB" cost: 10 ] 'reading many from storage: when given options should callback with the records if they exist': -> MockRequest.expect url: '/products' method: 'POST' ,product: name: "testA" cost: 10 MockRequest.expect url: '/products' method: 'POST' , product: name: "testB" cost: 10 MockRequest.expect { url: '/products' method: 'GET' data: cost: 10 }, { products: [ name: "testA" cost: 20 , name: "testB" cost: 10 ] } 'reading many from storage: should callback with an empty array if no records exist': -> MockRequest.expect url: '/products' method: 'GET' , products: [] 'updating in storage: should callback with the record if it exists': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'PUT' , product: name: 'test' cost: 10 id: 10 MockRequest.expect url: '/products/10' method: 'GET' , product: name: 'test' cost: 10 id: 10 'updating in storage: should callback with the subclass record if it exists': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'PUT' , special_product: name: 'test' cost: 10 id: 10 MockRequest.expect url: '/special_products/10' method: 'GET' , special_product: name: 'test' cost: 10 id: 10 'updating in storage: should callback with an error if the record hasn\'t been created': -> 'destroying in storage: should succeed if the record exists': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'DELETE' , success: true MockRequest.expect url: '/products/10' method: 'GET' , error: 'specified product couldn\'t be found!' 'destroying in storage: should succeed if the subclass record exists': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'DELETE' , success: true MockRequest.expect url: '/special_products/10' method: 'GET' , error: 'specified product couldn\'t be found!' 'destroying in storage: should callback with an error if the record hasn\'t been created': -> restStorageTestSuite.MockRequest = MockRequest if typeof exports is 'undefined' window.restStorageTestSuite = restStorageTestSuite else exports.restStorageTestSuite = restStorageTestSuite
76950
if typeof require isnt 'undefined' {sharedStorageTestSuite} = require('./storage_adapter_helper') else {sharedStorageTestSuite} = window productJSON = product: name: 'test' id: 10 specialProductJSON = special_product: name: 'test' id: 10 class MockRequest extends MockClass @dataHasFileUploads: Batman.Request.dataHasFileUploads @expects = {} @reset: -> MockClass.reset.call(@) @expects = {} @expect: (request, response) -> responses = @expects[request.url] ||= [] responses.push {request, response} CALLBACKS = ['success', 'loaded', 'loading', 'error'] for key in CALLBACKS @chainedCallback key @getExpectedForUrl: (url) -> @expects[url] || [] constructor: (requestOptions) -> super() for key in CALLBACKS @[key](requestOptions[key]) if requestOptions[key]? @fireLoading() allExpected = @constructor.getExpectedForUrl(requestOptions.url) expected = allExpected.shift() setTimeout => if ! expected? @fireError {message: "Unrecognized mocked request!", request: @} else {request, response} = expected for k in ['method', 'data', 'contentType'] if request[k]? && !QUnit.equiv(request[k], requestOptions[k]) throw "Wrong #{k} for expected request! Expected #{request[k]}, got #{requestOptions[k]}." if response.error if typeof response.error is 'string' @fireError {message: response.error, request: @} else response.error.request = @ @status = response.error.status @response = response.error.response @fireError response.error else @response = response @fireSuccess response @fireLoaded response , 1 get: (k) -> throw "Can't get anything other than 'response' and 'status' on the Requests" unless k in ['response', 'status'] @[k] restStorageTestSuite = -> test 'default options should be independent', -> otherAdapter = new @adapter.constructor(@Product) notEqual otherAdapter.defaultRequestOptions, @adapter.defaultRequestOptions asyncTest 'can readAll from JSON string', 3, -> MockRequest.expect url: '/products' method: 'GET' , JSON.stringify products: [ name: "<NAME>", cost: 20 ] @adapter.perform 'readAll', @Product::, {}, (err, readProducts) -> ok !err ok readProducts equal readProducts[0].get("name"), "test" QUnit.start() asyncTest 'response metadata should be available in the after read callbacks', 3, -> MockRequest.expect url: '/products' method: 'GET' , someMetaData: "foo" products: [ name: "<NAME>" cost: 20 , name: "<NAME>" cost: 10 ] @adapter.after 'readAll', (data, next) -> throw data.error if data.error equal data.data.someMetaData, "foo" next() @adapter.perform 'readAll', @Product::, {}, (err, readProducts) -> ok !err ok readProducts QUnit.start() asyncTest 'it should POST JSON instead of serialized parameters when configured to do so', -> @adapter.serializeAsForm = false MockRequest.expect url: '/products' method: 'POST' data: '{"product":{"name":"<NAME>"}}' contentType: 'application/json' , productJSON product = new @Product(name: "<NAME>") @adapter.perform 'create', product, {}, (err, record) => throw err if err ok record QUnit.start() sharedStorageTestSuite(restStorageTestSuite.sharedSuiteHooks) restStorageTestSuite.testOptionsGeneration = (urlSuffix = '') -> test 'string record urls should be gotten in the options', 1, -> product = new @Product product.url = '/some/url' url = @adapter.urlForRecord product, {} equal url, "/some/url#{urlSuffix}" test 'function record urls should be executed in the options', 1, -> product = new @Product product.url = -> '/some/url' url = @adapter.urlForRecord product, {} equal url, "/some/url#{urlSuffix}" test 'function record urls should be given the options for the storage operation', 1, -> product = new @Product opts = {foo: true} product.url = (passedOpts) -> equal passedOpts, opts '/some/url' @adapter.urlForRecord product, {options: opts} test 'string model urls should be gotten in the options', 1, -> @Product.url = '/some/url' url = @adapter.urlForCollection @Product, {} equal url, "/some/url#{urlSuffix}" test 'function model urls should be executed in the options', 1, -> @Product.url = -> '/some/url' url = @adapter.urlForCollection @Product, {} equal url, "/some/url#{urlSuffix}" test 'function model urls should be given the options for the storage operation', 1, -> opts = {foo: true} @Product.url = (passedOpts) -> equal passedOpts, opts '/some/url' @adapter.urlForCollection @Product, {options: opts} test 'records should take a urlPrefix option', 1, -> product = new @Product product.url = '/some/url' product.urlPrefix = '/admin' url = @adapter.urlForRecord product, {} equal url, "/admin/some/url#{urlSuffix}" test 'records should take a urlSuffix option', 1, -> product = new @Product product.url = '/some/url' product.urlSuffix = '.foo' url = @adapter.urlForRecord product, {} equal url, "/some/url.foo#{urlSuffix}" test 'models should be able to specify a urlPrefix', 1, -> @Product.url = '/some/url' @Product.urlPrefix = '/admin' url = @adapter.urlForCollection @Product, {} equal url, "/admin/some/url#{urlSuffix}" test 'models should be able to specify a urlSuffix', 1, -> @Product.url = '/some/url' @Product.urlSuffix = '.foo' url = @adapter.urlForCollection @Product, {} equal url, "/some/url.foo#{urlSuffix}" restStorageTestSuite.sharedSuiteHooks = 'creating in storage: should succeed if the record doesn\'t already exist': -> MockRequest.expect url: '/products' method: 'POST' , productJSON 'creating in storage: should fail if the record does already exist': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products' method: 'POST' , error: "Product already exists!" "creating in storage: should create a primary key if the record doesn't already have one": -> MockRequest.expect url: '/products' method: 'POST' , productJSON "creating in storage: should encode data before saving it": -> MockRequest.expect url: '/products' method: 'POST' , product: name: 'TEST' id: 10 'reading from storage: should callback with the record if the record has been created': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'GET' , productJSON 'reading from storage: should callback with the record if the record has been created and the record is an instance of a subclass': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'GET' , specialProductJSON 'reading from storage: should keep records of a class and records of a subclass separate': -> superJSON = product: name: 'test super' id: 10 subJSON = special_product: name: 'test sub' id: 10 MockRequest.expect url: '/special_products' method: 'POST' , subJSON MockRequest.expect url: '/products' method: 'POST' , superJSON MockRequest.expect url: '/products/10' method: 'GET' , superJSON MockRequest.expect url: '/special_products/10' method: 'GET' , subJSON 'reading from storage: should callback with decoded data after reading it': -> MockRequest.expect url: '/products' method: 'POST' , product: id: 10 name: '<NAME>' MockRequest.expect url: '/products/10' method: 'GET' , product: id: 10 name: '<NAME> <NAME>' 'reading from storage: should callback with an error if the record hasn\'t been created': -> MockRequest.expect url: '/products/10' method: 'GET' , error: 'specified record doesn\'t exist' 'reading many from storage: should callback with the records if they exist': -> MockRequest.expect url: '/products' method: 'POST' , product: name: "<NAME>" cost: 20 MockRequest.expect url: '/products' method: 'POST' , product: name: "<NAME>" cost: 10 MockRequest.expect url: '/products' method: 'GET' , products: [ name: "<NAME>" cost: 20 , name: "<NAME>" cost: 10 ] 'reading many from storage: should callback with subclass records if they exist': -> MockRequest.expect url: '/special_products' method: 'POST' , special_product: name: "<NAME>" cost: 20 MockRequest.expect url: '/special_products' method: 'POST' , special_product: name: "<NAME>" cost: 10 MockRequest.expect url: '/special_products' method: 'GET' , special_products: [ name: "<NAME>" cost: 20 , name: "<NAME>" cost: 10 ] 'reading many from storage: should callback with the decoded records if they exist': -> MockRequest.expect url: '/products' method: 'POST' ,product: name: "<NAME>" cost: 20 MockRequest.expect url: '/products' method: 'POST' , product: name: "<NAME>" cost: 10 MockRequest.expect url: '/products' method: 'GET' , products: [ name: "<NAME>" cost: 20 , name: "<NAME>" cost: 10 ] 'reading many from storage: when given options should callback with the records if they exist': -> MockRequest.expect url: '/products' method: 'POST' ,product: name: "<NAME>" cost: 10 MockRequest.expect url: '/products' method: 'POST' , product: name: "<NAME>" cost: 10 MockRequest.expect { url: '/products' method: 'GET' data: cost: 10 }, { products: [ name: "<NAME>" cost: 20 , name: "<NAME>" cost: 10 ] } 'reading many from storage: should callback with an empty array if no records exist': -> MockRequest.expect url: '/products' method: 'GET' , products: [] 'updating in storage: should callback with the record if it exists': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'PUT' , product: name: '<NAME>' cost: 10 id: 10 MockRequest.expect url: '/products/10' method: 'GET' , product: name: '<NAME>' cost: 10 id: 10 'updating in storage: should callback with the subclass record if it exists': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'PUT' , special_product: name: '<NAME>' cost: 10 id: 10 MockRequest.expect url: '/special_products/10' method: 'GET' , special_product: name: '<NAME>' cost: 10 id: 10 'updating in storage: should callback with an error if the record hasn\'t been created': -> 'destroying in storage: should succeed if the record exists': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'DELETE' , success: true MockRequest.expect url: '/products/10' method: 'GET' , error: 'specified product couldn\'t be found!' 'destroying in storage: should succeed if the subclass record exists': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'DELETE' , success: true MockRequest.expect url: '/special_products/10' method: 'GET' , error: 'specified product couldn\'t be found!' 'destroying in storage: should callback with an error if the record hasn\'t been created': -> restStorageTestSuite.MockRequest = MockRequest if typeof exports is 'undefined' window.restStorageTestSuite = restStorageTestSuite else exports.restStorageTestSuite = restStorageTestSuite
true
if typeof require isnt 'undefined' {sharedStorageTestSuite} = require('./storage_adapter_helper') else {sharedStorageTestSuite} = window productJSON = product: name: 'test' id: 10 specialProductJSON = special_product: name: 'test' id: 10 class MockRequest extends MockClass @dataHasFileUploads: Batman.Request.dataHasFileUploads @expects = {} @reset: -> MockClass.reset.call(@) @expects = {} @expect: (request, response) -> responses = @expects[request.url] ||= [] responses.push {request, response} CALLBACKS = ['success', 'loaded', 'loading', 'error'] for key in CALLBACKS @chainedCallback key @getExpectedForUrl: (url) -> @expects[url] || [] constructor: (requestOptions) -> super() for key in CALLBACKS @[key](requestOptions[key]) if requestOptions[key]? @fireLoading() allExpected = @constructor.getExpectedForUrl(requestOptions.url) expected = allExpected.shift() setTimeout => if ! expected? @fireError {message: "Unrecognized mocked request!", request: @} else {request, response} = expected for k in ['method', 'data', 'contentType'] if request[k]? && !QUnit.equiv(request[k], requestOptions[k]) throw "Wrong #{k} for expected request! Expected #{request[k]}, got #{requestOptions[k]}." if response.error if typeof response.error is 'string' @fireError {message: response.error, request: @} else response.error.request = @ @status = response.error.status @response = response.error.response @fireError response.error else @response = response @fireSuccess response @fireLoaded response , 1 get: (k) -> throw "Can't get anything other than 'response' and 'status' on the Requests" unless k in ['response', 'status'] @[k] restStorageTestSuite = -> test 'default options should be independent', -> otherAdapter = new @adapter.constructor(@Product) notEqual otherAdapter.defaultRequestOptions, @adapter.defaultRequestOptions asyncTest 'can readAll from JSON string', 3, -> MockRequest.expect url: '/products' method: 'GET' , JSON.stringify products: [ name: "PI:NAME:<NAME>END_PI", cost: 20 ] @adapter.perform 'readAll', @Product::, {}, (err, readProducts) -> ok !err ok readProducts equal readProducts[0].get("name"), "test" QUnit.start() asyncTest 'response metadata should be available in the after read callbacks', 3, -> MockRequest.expect url: '/products' method: 'GET' , someMetaData: "foo" products: [ name: "PI:NAME:<NAME>END_PI" cost: 20 , name: "PI:NAME:<NAME>END_PI" cost: 10 ] @adapter.after 'readAll', (data, next) -> throw data.error if data.error equal data.data.someMetaData, "foo" next() @adapter.perform 'readAll', @Product::, {}, (err, readProducts) -> ok !err ok readProducts QUnit.start() asyncTest 'it should POST JSON instead of serialized parameters when configured to do so', -> @adapter.serializeAsForm = false MockRequest.expect url: '/products' method: 'POST' data: '{"product":{"name":"PI:NAME:<NAME>END_PI"}}' contentType: 'application/json' , productJSON product = new @Product(name: "PI:NAME:<NAME>END_PI") @adapter.perform 'create', product, {}, (err, record) => throw err if err ok record QUnit.start() sharedStorageTestSuite(restStorageTestSuite.sharedSuiteHooks) restStorageTestSuite.testOptionsGeneration = (urlSuffix = '') -> test 'string record urls should be gotten in the options', 1, -> product = new @Product product.url = '/some/url' url = @adapter.urlForRecord product, {} equal url, "/some/url#{urlSuffix}" test 'function record urls should be executed in the options', 1, -> product = new @Product product.url = -> '/some/url' url = @adapter.urlForRecord product, {} equal url, "/some/url#{urlSuffix}" test 'function record urls should be given the options for the storage operation', 1, -> product = new @Product opts = {foo: true} product.url = (passedOpts) -> equal passedOpts, opts '/some/url' @adapter.urlForRecord product, {options: opts} test 'string model urls should be gotten in the options', 1, -> @Product.url = '/some/url' url = @adapter.urlForCollection @Product, {} equal url, "/some/url#{urlSuffix}" test 'function model urls should be executed in the options', 1, -> @Product.url = -> '/some/url' url = @adapter.urlForCollection @Product, {} equal url, "/some/url#{urlSuffix}" test 'function model urls should be given the options for the storage operation', 1, -> opts = {foo: true} @Product.url = (passedOpts) -> equal passedOpts, opts '/some/url' @adapter.urlForCollection @Product, {options: opts} test 'records should take a urlPrefix option', 1, -> product = new @Product product.url = '/some/url' product.urlPrefix = '/admin' url = @adapter.urlForRecord product, {} equal url, "/admin/some/url#{urlSuffix}" test 'records should take a urlSuffix option', 1, -> product = new @Product product.url = '/some/url' product.urlSuffix = '.foo' url = @adapter.urlForRecord product, {} equal url, "/some/url.foo#{urlSuffix}" test 'models should be able to specify a urlPrefix', 1, -> @Product.url = '/some/url' @Product.urlPrefix = '/admin' url = @adapter.urlForCollection @Product, {} equal url, "/admin/some/url#{urlSuffix}" test 'models should be able to specify a urlSuffix', 1, -> @Product.url = '/some/url' @Product.urlSuffix = '.foo' url = @adapter.urlForCollection @Product, {} equal url, "/some/url.foo#{urlSuffix}" restStorageTestSuite.sharedSuiteHooks = 'creating in storage: should succeed if the record doesn\'t already exist': -> MockRequest.expect url: '/products' method: 'POST' , productJSON 'creating in storage: should fail if the record does already exist': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products' method: 'POST' , error: "Product already exists!" "creating in storage: should create a primary key if the record doesn't already have one": -> MockRequest.expect url: '/products' method: 'POST' , productJSON "creating in storage: should encode data before saving it": -> MockRequest.expect url: '/products' method: 'POST' , product: name: 'TEST' id: 10 'reading from storage: should callback with the record if the record has been created': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'GET' , productJSON 'reading from storage: should callback with the record if the record has been created and the record is an instance of a subclass': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'GET' , specialProductJSON 'reading from storage: should keep records of a class and records of a subclass separate': -> superJSON = product: name: 'test super' id: 10 subJSON = special_product: name: 'test sub' id: 10 MockRequest.expect url: '/special_products' method: 'POST' , subJSON MockRequest.expect url: '/products' method: 'POST' , superJSON MockRequest.expect url: '/products/10' method: 'GET' , superJSON MockRequest.expect url: '/special_products/10' method: 'GET' , subJSON 'reading from storage: should callback with decoded data after reading it': -> MockRequest.expect url: '/products' method: 'POST' , product: id: 10 name: 'PI:NAME:<NAME>END_PI' MockRequest.expect url: '/products/10' method: 'GET' , product: id: 10 name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' 'reading from storage: should callback with an error if the record hasn\'t been created': -> MockRequest.expect url: '/products/10' method: 'GET' , error: 'specified record doesn\'t exist' 'reading many from storage: should callback with the records if they exist': -> MockRequest.expect url: '/products' method: 'POST' , product: name: "PI:NAME:<NAME>END_PI" cost: 20 MockRequest.expect url: '/products' method: 'POST' , product: name: "PI:NAME:<NAME>END_PI" cost: 10 MockRequest.expect url: '/products' method: 'GET' , products: [ name: "PI:NAME:<NAME>END_PI" cost: 20 , name: "PI:NAME:<NAME>END_PI" cost: 10 ] 'reading many from storage: should callback with subclass records if they exist': -> MockRequest.expect url: '/special_products' method: 'POST' , special_product: name: "PI:NAME:<NAME>END_PI" cost: 20 MockRequest.expect url: '/special_products' method: 'POST' , special_product: name: "PI:NAME:<NAME>END_PI" cost: 10 MockRequest.expect url: '/special_products' method: 'GET' , special_products: [ name: "PI:NAME:<NAME>END_PI" cost: 20 , name: "PI:NAME:<NAME>END_PI" cost: 10 ] 'reading many from storage: should callback with the decoded records if they exist': -> MockRequest.expect url: '/products' method: 'POST' ,product: name: "PI:NAME:<NAME>END_PI" cost: 20 MockRequest.expect url: '/products' method: 'POST' , product: name: "PI:NAME:<NAME>END_PI" cost: 10 MockRequest.expect url: '/products' method: 'GET' , products: [ name: "PI:NAME:<NAME>END_PI" cost: 20 , name: "PI:NAME:<NAME>END_PI" cost: 10 ] 'reading many from storage: when given options should callback with the records if they exist': -> MockRequest.expect url: '/products' method: 'POST' ,product: name: "PI:NAME:<NAME>END_PI" cost: 10 MockRequest.expect url: '/products' method: 'POST' , product: name: "PI:NAME:<NAME>END_PI" cost: 10 MockRequest.expect { url: '/products' method: 'GET' data: cost: 10 }, { products: [ name: "PI:NAME:<NAME>END_PI" cost: 20 , name: "PI:NAME:<NAME>END_PI" cost: 10 ] } 'reading many from storage: should callback with an empty array if no records exist': -> MockRequest.expect url: '/products' method: 'GET' , products: [] 'updating in storage: should callback with the record if it exists': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'PUT' , product: name: 'PI:NAME:<NAME>END_PI' cost: 10 id: 10 MockRequest.expect url: '/products/10' method: 'GET' , product: name: 'PI:NAME:<NAME>END_PI' cost: 10 id: 10 'updating in storage: should callback with the subclass record if it exists': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'PUT' , special_product: name: 'PI:NAME:<NAME>END_PI' cost: 10 id: 10 MockRequest.expect url: '/special_products/10' method: 'GET' , special_product: name: 'PI:NAME:<NAME>END_PI' cost: 10 id: 10 'updating in storage: should callback with an error if the record hasn\'t been created': -> 'destroying in storage: should succeed if the record exists': -> MockRequest.expect url: '/products' method: 'POST' , productJSON MockRequest.expect url: '/products/10' method: 'DELETE' , success: true MockRequest.expect url: '/products/10' method: 'GET' , error: 'specified product couldn\'t be found!' 'destroying in storage: should succeed if the subclass record exists': -> MockRequest.expect url: '/special_products' method: 'POST' , specialProductJSON MockRequest.expect url: '/special_products/10' method: 'DELETE' , success: true MockRequest.expect url: '/special_products/10' method: 'GET' , error: 'specified product couldn\'t be found!' 'destroying in storage: should callback with an error if the record hasn\'t been created': -> restStorageTestSuite.MockRequest = MockRequest if typeof exports is 'undefined' window.restStorageTestSuite = restStorageTestSuite else exports.restStorageTestSuite = restStorageTestSuite
[ { "context": ".org/ws/2005/05/identity/claims/emailaddress\": [ \"tuser@example.com\" ]\n \"http://schemas.xmlsoap.org/ws/2005/", "end": 7520, "score": 0.999898374080658, "start": 7503, "tag": "EMAIL", "value": "tuser@example.com" }, { "context": ".xmlsoap.org/ws/2005/05/identity/claims/name\": [ \"Test User\" ]\n \"http://schemas.xmlsoap.org/cla", "end": 7603, "score": 0.6761261820793152, "start": 7599, "tag": "NAME", "value": "Test" }, { "context": "st Group\" ]\n\n expected =\n email: \"tuser@example.com\"\n name: \"Test User\"\n group: \"Te", "end": 7737, "score": 0.9999062418937683, "start": 7720, "tag": "EMAIL", "value": "tuser@example.com" }, { "context": " email: \"tuser@example.com\"\n name: \"Test User\"\n group: \"Test Group\"\n\n assert.de", "end": 7765, "score": 0.9870387315750122, "start": 7756, "tag": "NAME", "value": "Test User" }, { "context": "adata.xml'\n assert.equal request.name_id, 'tstudent'\n assert.equal request.session_index, '_2'", "end": 9446, "score": 0.9759197235107422, "start": 9438, "tag": "USERNAME", "value": "tstudent" }, { "context": ".org/ws/2005/05/identity/claims/emailaddress': [ 'tstudent@example.com' ]\n 'http://schemas.xmlsoap.org/ws/200", "end": 10422, "score": 0.999093234539032, "start": 10402, "tag": "EMAIL", "value": "tstudent@example.com" }, { "context": "05/identity/claims/privatepersonalidentifier': [ 'tstudent' ]\n 'http://schemas.xmlsoap.org/claims", "end": 10532, "score": 0.7398667335510254, "start": 10524, "tag": "USERNAME", "value": "tstudent" }, { "context": "n_response'\n user:\n name_id: 'tstudent'\n session_index: '_3'\n give", "end": 13343, "score": 0.9996799230575562, "start": 13335, "tag": "USERNAME", "value": "tstudent" }, { "context": " session_index: '_3'\n given_name: 'Test',\n email: 'tstudent@example.com',\n ", "end": 13406, "score": 0.9883981347084045, "start": 13402, "tag": "NAME", "value": "Test" }, { "context": " given_name: 'Test',\n email: 'tstudent@example.com',\n ppid: 'tstudent',\n group", "end": 13449, "score": 0.9998977780342102, "start": 13429, "tag": "EMAIL", "value": "tstudent@example.com" }, { "context": ",DC=idp,DC=example,DC=com',\n surname: 'Student',\n common_name: 'Test Student',\n ", "end": 13579, "score": 0.5951433777809143, "start": 13572, "tag": "NAME", "value": "Student" }, { "context": " surname: 'Student',\n common_name: 'Test Student',\n attributes:\n 'http://s", "end": 13620, "score": 0.828487753868103, "start": 13608, "tag": "NAME", "value": "Test Student" }, { "context": ".org/ws/2005/05/identity/claims/emailaddress': [ 'tstudent@example.com' ]\n 'http://schemas.xmlsoap.org/ws/2", "end": 13846, "score": 0.9998500347137451, "start": 13826, "tag": "EMAIL", "value": "tstudent@example.com" }, { "context": "n_response'\n user:\n name_id: 'tstudent'\n session_index: '_3'\n give", "end": 16212, "score": 0.9996813535690308, "start": 16204, "tag": "USERNAME", "value": "tstudent" }, { "context": " session_index: '_3'\n given_name: 'Test',\n email: 'tstudent@example.com',\n ", "end": 16275, "score": 0.9995409250259399, "start": 16271, "tag": "NAME", "value": "Test" }, { "context": " given_name: 'Test',\n email: 'tstudent@example.com',\n ppid: 'tstudent',\n group", "end": 16318, "score": 0.9999050498008728, "start": 16298, "tag": "EMAIL", "value": "tstudent@example.com" }, { "context": ",DC=idp,DC=example,DC=com',\n surname: 'Student',\n common_name: 'Test Student',\n ", "end": 16448, "score": 0.9995707273483276, "start": 16441, "tag": "NAME", "value": "Student" }, { "context": " surname: 'Student',\n common_name: 'Test Student',\n attributes:\n '", "end": 16481, "score": 0.8054949045181274, "start": 16477, "tag": "NAME", "value": "Test" }, { "context": ".org/ws/2005/05/identity/claims/emailaddress': [ 'tstudent@example.com' ]\n 'http://schemas.xmlsoap.org/ws/2", "end": 16715, "score": 0.9995744228363037, "start": 16695, "tag": "EMAIL", "value": "tstudent@example.com" }, { "context": "logout'\n request_options =\n name_id: 'name_id'\n session_index: 'session_index'\n s", "end": 23665, "score": 0.5658760070800781, "start": 23658, "tag": "NAME", "value": "name_id" } ]
lambda/node_modules/saml2-js/test/saml2.coffee
realestate-com-au/sshephalopod
26
_ = require 'underscore' assert = require 'assert' async = require 'async' zlib = require 'zlib' crypto = require 'crypto' fs = require 'fs' saml2 = require "#{__dirname}/../index" url = require 'url' util = require 'util' xmldom = require 'xmldom' describe 'saml2', -> get_test_file = (filename) -> fs.readFileSync("#{__dirname}/data/#{filename}").toString() describe 'private helpers', -> dom_from_test_file = (filename) -> (new xmldom.DOMParser()).parseFromString get_test_file filename before => @good_response_dom = dom_from_test_file "good_response.xml" # Auth Request, before it is compressed and base-64 encoded describe 'create_authn_request', -> it 'contains expected fields', -> { id, xml } = saml2.create_authn_request 'https://sp.example.com/metadata.xml', 'https://sp.example.com/assert', 'https://idp.example.com/login' dom = (new xmldom.DOMParser()).parseFromString xml authn_request = dom.getElementsByTagName('AuthnRequest')[0] required_attributes = Version: '2.0' Destination: 'https://idp.example.com/login' AssertionConsumerServiceURL: 'https://sp.example.com/assert' ProtocolBinding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' _(required_attributes).each (req_value, req_name) -> assert _(authn_request.attributes).some((attr) -> attr.name is req_name and attr.value is req_value) , "Expected to find attribute '#{req_name}' with value '#{req_value}'!" assert _(authn_request.attributes).some((attr) -> attr.name is "ID"), "Missing required attribute 'ID'" assert.equal dom.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Issuer')[0].firstChild.data, 'https://sp.example.com/metadata.xml' it 'contains an AuthnContext if requested', -> { id, xml } = saml2.create_authn_request 'a', 'b', 'c', true, { comparison: 'exact', class_refs: ['context:class']} dom = (new xmldom.DOMParser()).parseFromString xml authn_request = dom.getElementsByTagName('AuthnRequest')[0] requested_authn_context = authn_request.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'RequestedAuthnContext')[0] assert _(requested_authn_context.attributes).some (attr) -> attr.name is 'Comparison' and attr.value is 'exact' assert.equal requested_authn_context.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AuthnContextClassRef')[0].firstChild.data, 'context:class' describe 'create_metadata', -> it 'contains expected fields', -> cert = get_test_file 'test.crt' cert2 = get_test_file 'test2.crt' metadata = saml2.create_metadata 'https://sp.example.com/metadata.xml', 'https://sp.example.com/assert', cert, cert2 dom = (new xmldom.DOMParser()).parseFromString metadata entity_descriptor = dom.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'EntityDescriptor')[0] assert _(entity_descriptor.attributes).some((attr) -> attr.name is 'entityID' and attr.value is 'https://sp.example.com/metadata.xml') , "Expected to find attribute 'entityID' with value 'https://sp.example.com/metadata.xml'." assert _(entity_descriptor.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'AssertionConsumerService')).some((assertion) -> _(assertion.attributes).some((attr) -> attr.name is 'Binding' and attr.value is 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST') and _(assertion.attributes).some((attr) -> attr.name is 'Location' and attr.value is 'https://sp.example.com/assert')) , "Expected to find an AssertionConsumerService with POST binding and location 'https://sp.example.com/assert'" assert _(entity_descriptor.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'SingleLogoutService')).some((assertion) -> _(assertion.attributes).some((attr) -> attr.name is 'Binding' and attr.value is 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect') and _(assertion.attributes).some((attr) -> attr.name is 'Location' and attr.value is 'https://sp.example.com/assert')) , "Expected to find a SingleLogoutService with redirect binding and location 'https://sp.example.com/assert'" describe 'format_pem', -> it 'formats an unformatted private key', -> raw_private_key = (/-----BEGIN PRIVATE KEY-----([^-]*)-----END PRIVATE KEY-----/g.exec get_test_file("test.pem"))[1] formatted_key = saml2.format_pem raw_private_key, 'PRIVATE KEY' assert.equal formatted_key.trim(), get_test_file("test.pem").trim() it 'does not change an already formatted private key', -> formatted_key = saml2.format_pem get_test_file("test.pem"), 'PRIVATE KEY' assert.equal formatted_key, get_test_file("test.pem") describe 'sign_request', -> it 'correctly signs a get request', -> signed = saml2.sign_request 'TESTMESSAGE', get_test_file("test.pem") verifier = crypto.createVerify 'RSA-SHA256' verifier.update 'SAMLRequest=TESTMESSAGE&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256' assert verifier.verify(get_test_file("test.crt"), signed.Signature, 'base64'), "Signature is not valid" assert.equal signed.SigAlg, 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' assert.equal signed.SAMLRequest, 'TESTMESSAGE' it 'correctly signs a get response with RelayState', -> signed = saml2.sign_request 'TESTMESSAGE', get_test_file("test.pem"), 'TESTSTATE', true verifier = crypto.createVerify 'RSA-SHA256' verifier.update 'SAMLResponse=TESTMESSAGE&RelayState=TESTSTATE&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256' assert verifier.verify(get_test_file("test.crt"), signed.Signature, 'base64'), "Signature is not valid" assert signed.SigAlg, 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' assert.equal signed.RelayState, 'TESTSTATE' assert.equal signed.SAMLResponse, 'TESTMESSAGE' describe 'check_saml_signature', -> it 'accepts signed xml', -> assert saml2.check_saml_signature(get_test_file("good_assertion.xml"), get_test_file("test.crt")) it 'rejects xml without a signature', -> assert.equal false, saml2.check_saml_signature(get_test_file("unsigned_assertion.xml"), get_test_file("test.crt")) it 'rejects xml with an invalid signature', -> assert.equal false, saml2.check_saml_signature(get_test_file("good_assertion.xml"), get_test_file("test2.crt")) describe 'check_status_success', => it 'accepts a valid success status', => assert saml2.check_status_success(@good_response_dom), "Did not get 'true' for valid response." it 'rejects a missing success status', -> assert not saml2.check_status_success(dom_from_test_file("response_error_status.xml")), "Did not get 'false' for invalid response." it 'rejects a missing status', -> assert not saml2.check_status_success(dom_from_test_file("response_no_status.xml")), "Did not get 'false' for invalid response." describe 'pretty_assertion_attributes', -> it 'creates a correct user object', -> test_attributes = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": [ "tuser@example.com" ] "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": [ "Test User" ] "http://schemas.xmlsoap.org/claims/Group": [ "Test Group" ] expected = email: "tuser@example.com" name: "Test User" group: "Test Group" assert.deepEqual saml2.pretty_assertion_attributes(test_attributes), expected describe 'decrypt_assertion', => it 'decrypts and extracts an assertion', (done) => key = get_test_file("test.pem") saml2.decrypt_assertion @good_response_dom, key, (err, result) -> assert not err?, "Got error: #{err}" assert.equal result, get_test_file("good_response_decrypted.xml") done() it 'errors if an incorrect key is used', (done) => key = get_test_file("test2.pem") saml2.decrypt_assertion @good_response_dom, key, (err, result) -> assert (err instanceof Error), "Did not get expected error." done() describe 'parse_response_header', => it 'correctly parses a response header', => response = saml2.parse_response_header @good_response_dom assert.equal response.destination, 'https://sp.example.com/assert' assert.equal response.in_response_to, '_1' it 'errors if there is no response', -> # An assertion is not a response, so this should fail. assert.throws -> saml2.parse_response_header dom_from_test_file("good_assertion.xml") it 'errors if given a response with the wrong version', -> assert.throws -> saml2.parse_response_header dom_from_test_file("response_bad_version.xml") describe 'parse_logout_request', => it 'correctly parses a logout request', => request = saml2.parse_logout_request dom_from_test_file('logout_request.xml') assert.equal request.issuer, 'http://idp.example.com/metadata.xml' assert.equal request.name_id, 'tstudent' assert.equal request.session_index, '_2' describe 'get_name_id', -> it 'gets the correct NameID', -> name_id = saml2.get_name_id dom_from_test_file('good_assertion.xml') assert.equal name_id, 'tstudent' it 'parses assertions with explicit namespaces', -> name_id = saml2.get_name_id dom_from_test_file('good_assertion_explicit_namespaces.xml') assert.equal name_id, 'tstudent' describe 'get_session_index', -> it 'gets the correct session index', -> session_index = saml2.get_session_index dom_from_test_file('good_assertion.xml') assert.equal session_index, '_3' describe 'parse_assertion_attributes', -> it 'correctly parses assertion attributes', -> expected_attributes = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ 'tstudent@example.com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] attributes = saml2.parse_assertion_attributes dom_from_test_file('good_assertion.xml') assert.deepEqual attributes, expected_attributes it 'correctly parses assertion attributes', -> expected_attributes = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ '' ] attributes = saml2.parse_assertion_attributes dom_from_test_file('empty_attribute_value.xml') assert.deepEqual attributes, expected_attributes it 'correctly parses no assertion attributes', -> attributes = saml2.parse_assertion_attributes dom_from_test_file('blank_assertion.xml') assert.deepEqual attributes, {} describe 'set option defaults', -> it 'sets defaults in the correct order', -> options_top = option1: "top" option4: "top" options_middle = option1: "middle" option2: "middle" option5: "middle" options_bottom = option1: "bottom" option2: "bottom" option3: "bottom" option6: "bottom" expected_options = option1: "top" option2: "middle" option3: "bottom" option4: "top" option5: "middle" option6: "bottom" actual_options = saml2.set_option_defaults options_top, options_middle, options_bottom assert.deepEqual actual_options, expected_options describe 'post assert', -> it 'returns a user object when passed a valid AuthnResponse', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: [ get_test_file('test.crt'), get_test_file('test2.crt') ] request_options = request_body: SAMLResponse: get_test_file("post_response.xml") sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.post_assert idp, request_options, (err, response) -> assert not err?, "Got error: #{err}" expected_response = response_header: id: '_2' in_response_to: '_1' destination: 'https://sp.example.com/assert' type: 'authn_response' user: name_id: 'tstudent' session_index: '_3' given_name: 'Test', email: 'tstudent@example.com', ppid: 'tstudent', group: 'CN=Students,CN=Users,DC=idp,DC=example,DC=com', surname: 'Student', common_name: 'Test Student', attributes: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ 'tstudent@example.com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] assert.deepEqual response, expected_response done() it 'errors if passed invalid data', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: get_test_file('test.crt') resquest_options = request_body: SAMLResponse: 'FAIL' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.post_assert idp, resquest_options, (err, user) -> assert (err instanceof Error), "Did not get expected error." done() describe 'redirect assert', -> it 'returns a user object with passed a valid AuthnResponse', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: [ get_test_file('test.crt'), get_test_file('test2.crt') ] request_options = request_body: SAMLResponse: get_test_file("redirect_response.xml") sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.redirect_assert idp, request_options, (err, response) -> assert not err?, "Got error: #{err}" expected_response = response_header: id: '_2' in_response_to: '_1' destination: 'https://sp.example.com/assert' type: 'authn_response' user: name_id: 'tstudent' session_index: '_3' given_name: 'Test', email: 'tstudent@example.com', ppid: 'tstudent', group: 'CN=Students,CN=Users,DC=idp,DC=example,DC=com', surname: 'Student', common_name: 'Test Student', attributes: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ 'tstudent@example.com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] assert.deepEqual response, expected_response # make sure response can be deflated, since redirect requests need to be inflated zlib.deflateRaw new Buffer(response, 'base64'), (err, deflated) => assert not err?, "Got error: #{err}" done() describe 'ServiceProvider', -> it 'can be constructed', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' sp = new saml2.ServiceProvider sp_options done() it 'can create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_login_request_url idp, {assert_endpoint:'https://sp.example.com/assert'}, cb_wf ], (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = parsed_url.query?.SAMLRequest? assert saml_request, 'Could not find SAMLRequest in url query parameters' done() it 'passes through RelayState in create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, {assert_endpoint: 'https://sp.example.com/assert', relay_state: 'Some Relay State!'}, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true assert.equal parsed_url.query?.RelayState, 'Some Relay State!' done() it 'can specify a nameid format in create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' request_options = assert_endpoint: 'https://sp.example.com/assert' relay_state: 'Some Relay State!' nameid_format: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, request_options, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = new Buffer(parsed_url.query?.SAMLRequest, 'base64') zlib.inflateRaw saml_request, (err, result) -> assert.notEqual result.toString('utf8').indexOf("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"), -1 done() it 'requests a nameid format type of urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified if none is specified', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' request_options = assert_endpoint: 'https://sp.example.com/assert' relay_state: 'Some Relay State!' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, request_options, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = new Buffer(parsed_url.query?.SAMLRequest, 'base64') zlib.inflateRaw saml_request, (err, result) -> assert.notEqual result.toString('utf8').indexOf("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"), -1 done() it 'can create logout request url using an idp', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: get_test_file('test.crt') request_options = name_id: 'name_id' session_index: 'session_index' sign_get_request: true sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_logout_request_url idp, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLRequest?, 'Could not find SAMLRequest in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutRequest is not signed' done() it 'can create logout request url using an string sso_logout_url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_logout_url : 'https://idp.example.com/logout' request_options = name_id: 'name_id' session_index: 'session_index' sign_get_request: true sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_logout_request_url idp, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLRequest?, 'Could not find SAMLRequest in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutRequest is not signed' done() it 'can create logout response url using an idp', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' sso_logout_url = 'https://idp.example.com/logout' request_options = in_response_to: '_1' sign_get_request: true sp = new saml2.ServiceProvider sp_options async.waterfall [ (cb_wf) -> sp.create_logout_response_url sso_logout_url, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating response logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLResponse?, 'Could not find SAMLResponse in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutResponse is not signed' done() it 'can create logout response url using an string sso_logout_url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' request_options = in_response_to: '_1' sign_get_request: true sso_logout_url = 'https://idp.example.com/logout' sp = new saml2.ServiceProvider sp_options async.waterfall [ (cb_wf) -> sp.create_logout_response_url sso_logout_url, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating response logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLResponse?, 'Could not find SAMLResponse in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutResponse is not signed' done() it 'can create metadata', (done) -> done()
203561
_ = require 'underscore' assert = require 'assert' async = require 'async' zlib = require 'zlib' crypto = require 'crypto' fs = require 'fs' saml2 = require "#{__dirname}/../index" url = require 'url' util = require 'util' xmldom = require 'xmldom' describe 'saml2', -> get_test_file = (filename) -> fs.readFileSync("#{__dirname}/data/#{filename}").toString() describe 'private helpers', -> dom_from_test_file = (filename) -> (new xmldom.DOMParser()).parseFromString get_test_file filename before => @good_response_dom = dom_from_test_file "good_response.xml" # Auth Request, before it is compressed and base-64 encoded describe 'create_authn_request', -> it 'contains expected fields', -> { id, xml } = saml2.create_authn_request 'https://sp.example.com/metadata.xml', 'https://sp.example.com/assert', 'https://idp.example.com/login' dom = (new xmldom.DOMParser()).parseFromString xml authn_request = dom.getElementsByTagName('AuthnRequest')[0] required_attributes = Version: '2.0' Destination: 'https://idp.example.com/login' AssertionConsumerServiceURL: 'https://sp.example.com/assert' ProtocolBinding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' _(required_attributes).each (req_value, req_name) -> assert _(authn_request.attributes).some((attr) -> attr.name is req_name and attr.value is req_value) , "Expected to find attribute '#{req_name}' with value '#{req_value}'!" assert _(authn_request.attributes).some((attr) -> attr.name is "ID"), "Missing required attribute 'ID'" assert.equal dom.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Issuer')[0].firstChild.data, 'https://sp.example.com/metadata.xml' it 'contains an AuthnContext if requested', -> { id, xml } = saml2.create_authn_request 'a', 'b', 'c', true, { comparison: 'exact', class_refs: ['context:class']} dom = (new xmldom.DOMParser()).parseFromString xml authn_request = dom.getElementsByTagName('AuthnRequest')[0] requested_authn_context = authn_request.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'RequestedAuthnContext')[0] assert _(requested_authn_context.attributes).some (attr) -> attr.name is 'Comparison' and attr.value is 'exact' assert.equal requested_authn_context.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AuthnContextClassRef')[0].firstChild.data, 'context:class' describe 'create_metadata', -> it 'contains expected fields', -> cert = get_test_file 'test.crt' cert2 = get_test_file 'test2.crt' metadata = saml2.create_metadata 'https://sp.example.com/metadata.xml', 'https://sp.example.com/assert', cert, cert2 dom = (new xmldom.DOMParser()).parseFromString metadata entity_descriptor = dom.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'EntityDescriptor')[0] assert _(entity_descriptor.attributes).some((attr) -> attr.name is 'entityID' and attr.value is 'https://sp.example.com/metadata.xml') , "Expected to find attribute 'entityID' with value 'https://sp.example.com/metadata.xml'." assert _(entity_descriptor.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'AssertionConsumerService')).some((assertion) -> _(assertion.attributes).some((attr) -> attr.name is 'Binding' and attr.value is 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST') and _(assertion.attributes).some((attr) -> attr.name is 'Location' and attr.value is 'https://sp.example.com/assert')) , "Expected to find an AssertionConsumerService with POST binding and location 'https://sp.example.com/assert'" assert _(entity_descriptor.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'SingleLogoutService')).some((assertion) -> _(assertion.attributes).some((attr) -> attr.name is 'Binding' and attr.value is 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect') and _(assertion.attributes).some((attr) -> attr.name is 'Location' and attr.value is 'https://sp.example.com/assert')) , "Expected to find a SingleLogoutService with redirect binding and location 'https://sp.example.com/assert'" describe 'format_pem', -> it 'formats an unformatted private key', -> raw_private_key = (/-----BEGIN PRIVATE KEY-----([^-]*)-----END PRIVATE KEY-----/g.exec get_test_file("test.pem"))[1] formatted_key = saml2.format_pem raw_private_key, 'PRIVATE KEY' assert.equal formatted_key.trim(), get_test_file("test.pem").trim() it 'does not change an already formatted private key', -> formatted_key = saml2.format_pem get_test_file("test.pem"), 'PRIVATE KEY' assert.equal formatted_key, get_test_file("test.pem") describe 'sign_request', -> it 'correctly signs a get request', -> signed = saml2.sign_request 'TESTMESSAGE', get_test_file("test.pem") verifier = crypto.createVerify 'RSA-SHA256' verifier.update 'SAMLRequest=TESTMESSAGE&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256' assert verifier.verify(get_test_file("test.crt"), signed.Signature, 'base64'), "Signature is not valid" assert.equal signed.SigAlg, 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' assert.equal signed.SAMLRequest, 'TESTMESSAGE' it 'correctly signs a get response with RelayState', -> signed = saml2.sign_request 'TESTMESSAGE', get_test_file("test.pem"), 'TESTSTATE', true verifier = crypto.createVerify 'RSA-SHA256' verifier.update 'SAMLResponse=TESTMESSAGE&RelayState=TESTSTATE&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256' assert verifier.verify(get_test_file("test.crt"), signed.Signature, 'base64'), "Signature is not valid" assert signed.SigAlg, 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' assert.equal signed.RelayState, 'TESTSTATE' assert.equal signed.SAMLResponse, 'TESTMESSAGE' describe 'check_saml_signature', -> it 'accepts signed xml', -> assert saml2.check_saml_signature(get_test_file("good_assertion.xml"), get_test_file("test.crt")) it 'rejects xml without a signature', -> assert.equal false, saml2.check_saml_signature(get_test_file("unsigned_assertion.xml"), get_test_file("test.crt")) it 'rejects xml with an invalid signature', -> assert.equal false, saml2.check_saml_signature(get_test_file("good_assertion.xml"), get_test_file("test2.crt")) describe 'check_status_success', => it 'accepts a valid success status', => assert saml2.check_status_success(@good_response_dom), "Did not get 'true' for valid response." it 'rejects a missing success status', -> assert not saml2.check_status_success(dom_from_test_file("response_error_status.xml")), "Did not get 'false' for invalid response." it 'rejects a missing status', -> assert not saml2.check_status_success(dom_from_test_file("response_no_status.xml")), "Did not get 'false' for invalid response." describe 'pretty_assertion_attributes', -> it 'creates a correct user object', -> test_attributes = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": [ "<EMAIL>" ] "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": [ "<NAME> User" ] "http://schemas.xmlsoap.org/claims/Group": [ "Test Group" ] expected = email: "<EMAIL>" name: "<NAME>" group: "Test Group" assert.deepEqual saml2.pretty_assertion_attributes(test_attributes), expected describe 'decrypt_assertion', => it 'decrypts and extracts an assertion', (done) => key = get_test_file("test.pem") saml2.decrypt_assertion @good_response_dom, key, (err, result) -> assert not err?, "Got error: #{err}" assert.equal result, get_test_file("good_response_decrypted.xml") done() it 'errors if an incorrect key is used', (done) => key = get_test_file("test2.pem") saml2.decrypt_assertion @good_response_dom, key, (err, result) -> assert (err instanceof Error), "Did not get expected error." done() describe 'parse_response_header', => it 'correctly parses a response header', => response = saml2.parse_response_header @good_response_dom assert.equal response.destination, 'https://sp.example.com/assert' assert.equal response.in_response_to, '_1' it 'errors if there is no response', -> # An assertion is not a response, so this should fail. assert.throws -> saml2.parse_response_header dom_from_test_file("good_assertion.xml") it 'errors if given a response with the wrong version', -> assert.throws -> saml2.parse_response_header dom_from_test_file("response_bad_version.xml") describe 'parse_logout_request', => it 'correctly parses a logout request', => request = saml2.parse_logout_request dom_from_test_file('logout_request.xml') assert.equal request.issuer, 'http://idp.example.com/metadata.xml' assert.equal request.name_id, 'tstudent' assert.equal request.session_index, '_2' describe 'get_name_id', -> it 'gets the correct NameID', -> name_id = saml2.get_name_id dom_from_test_file('good_assertion.xml') assert.equal name_id, 'tstudent' it 'parses assertions with explicit namespaces', -> name_id = saml2.get_name_id dom_from_test_file('good_assertion_explicit_namespaces.xml') assert.equal name_id, 'tstudent' describe 'get_session_index', -> it 'gets the correct session index', -> session_index = saml2.get_session_index dom_from_test_file('good_assertion.xml') assert.equal session_index, '_3' describe 'parse_assertion_attributes', -> it 'correctly parses assertion attributes', -> expected_attributes = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ '<EMAIL>' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] attributes = saml2.parse_assertion_attributes dom_from_test_file('good_assertion.xml') assert.deepEqual attributes, expected_attributes it 'correctly parses assertion attributes', -> expected_attributes = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ '' ] attributes = saml2.parse_assertion_attributes dom_from_test_file('empty_attribute_value.xml') assert.deepEqual attributes, expected_attributes it 'correctly parses no assertion attributes', -> attributes = saml2.parse_assertion_attributes dom_from_test_file('blank_assertion.xml') assert.deepEqual attributes, {} describe 'set option defaults', -> it 'sets defaults in the correct order', -> options_top = option1: "top" option4: "top" options_middle = option1: "middle" option2: "middle" option5: "middle" options_bottom = option1: "bottom" option2: "bottom" option3: "bottom" option6: "bottom" expected_options = option1: "top" option2: "middle" option3: "bottom" option4: "top" option5: "middle" option6: "bottom" actual_options = saml2.set_option_defaults options_top, options_middle, options_bottom assert.deepEqual actual_options, expected_options describe 'post assert', -> it 'returns a user object when passed a valid AuthnResponse', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: [ get_test_file('test.crt'), get_test_file('test2.crt') ] request_options = request_body: SAMLResponse: get_test_file("post_response.xml") sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.post_assert idp, request_options, (err, response) -> assert not err?, "Got error: #{err}" expected_response = response_header: id: '_2' in_response_to: '_1' destination: 'https://sp.example.com/assert' type: 'authn_response' user: name_id: 'tstudent' session_index: '_3' given_name: '<NAME>', email: '<EMAIL>', ppid: 'tstudent', group: 'CN=Students,CN=Users,DC=idp,DC=example,DC=com', surname: '<NAME>', common_name: '<NAME>', attributes: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ '<EMAIL>' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] assert.deepEqual response, expected_response done() it 'errors if passed invalid data', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: get_test_file('test.crt') resquest_options = request_body: SAMLResponse: 'FAIL' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.post_assert idp, resquest_options, (err, user) -> assert (err instanceof Error), "Did not get expected error." done() describe 'redirect assert', -> it 'returns a user object with passed a valid AuthnResponse', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: [ get_test_file('test.crt'), get_test_file('test2.crt') ] request_options = request_body: SAMLResponse: get_test_file("redirect_response.xml") sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.redirect_assert idp, request_options, (err, response) -> assert not err?, "Got error: #{err}" expected_response = response_header: id: '_2' in_response_to: '_1' destination: 'https://sp.example.com/assert' type: 'authn_response' user: name_id: 'tstudent' session_index: '_3' given_name: '<NAME>', email: '<EMAIL>', ppid: 'tstudent', group: 'CN=Students,CN=Users,DC=idp,DC=example,DC=com', surname: '<NAME>', common_name: '<NAME> Student', attributes: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ '<EMAIL>' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] assert.deepEqual response, expected_response # make sure response can be deflated, since redirect requests need to be inflated zlib.deflateRaw new Buffer(response, 'base64'), (err, deflated) => assert not err?, "Got error: #{err}" done() describe 'ServiceProvider', -> it 'can be constructed', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' sp = new saml2.ServiceProvider sp_options done() it 'can create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_login_request_url idp, {assert_endpoint:'https://sp.example.com/assert'}, cb_wf ], (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = parsed_url.query?.SAMLRequest? assert saml_request, 'Could not find SAMLRequest in url query parameters' done() it 'passes through RelayState in create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, {assert_endpoint: 'https://sp.example.com/assert', relay_state: 'Some Relay State!'}, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true assert.equal parsed_url.query?.RelayState, 'Some Relay State!' done() it 'can specify a nameid format in create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' request_options = assert_endpoint: 'https://sp.example.com/assert' relay_state: 'Some Relay State!' nameid_format: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, request_options, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = new Buffer(parsed_url.query?.SAMLRequest, 'base64') zlib.inflateRaw saml_request, (err, result) -> assert.notEqual result.toString('utf8').indexOf("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"), -1 done() it 'requests a nameid format type of urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified if none is specified', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' request_options = assert_endpoint: 'https://sp.example.com/assert' relay_state: 'Some Relay State!' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, request_options, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = new Buffer(parsed_url.query?.SAMLRequest, 'base64') zlib.inflateRaw saml_request, (err, result) -> assert.notEqual result.toString('utf8').indexOf("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"), -1 done() it 'can create logout request url using an idp', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: get_test_file('test.crt') request_options = name_id: 'name_id' session_index: 'session_index' sign_get_request: true sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_logout_request_url idp, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLRequest?, 'Could not find SAMLRequest in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutRequest is not signed' done() it 'can create logout request url using an string sso_logout_url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_logout_url : 'https://idp.example.com/logout' request_options = name_id: '<NAME>' session_index: 'session_index' sign_get_request: true sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_logout_request_url idp, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLRequest?, 'Could not find SAMLRequest in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutRequest is not signed' done() it 'can create logout response url using an idp', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' sso_logout_url = 'https://idp.example.com/logout' request_options = in_response_to: '_1' sign_get_request: true sp = new saml2.ServiceProvider sp_options async.waterfall [ (cb_wf) -> sp.create_logout_response_url sso_logout_url, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating response logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLResponse?, 'Could not find SAMLResponse in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutResponse is not signed' done() it 'can create logout response url using an string sso_logout_url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' request_options = in_response_to: '_1' sign_get_request: true sso_logout_url = 'https://idp.example.com/logout' sp = new saml2.ServiceProvider sp_options async.waterfall [ (cb_wf) -> sp.create_logout_response_url sso_logout_url, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating response logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLResponse?, 'Could not find SAMLResponse in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutResponse is not signed' done() it 'can create metadata', (done) -> done()
true
_ = require 'underscore' assert = require 'assert' async = require 'async' zlib = require 'zlib' crypto = require 'crypto' fs = require 'fs' saml2 = require "#{__dirname}/../index" url = require 'url' util = require 'util' xmldom = require 'xmldom' describe 'saml2', -> get_test_file = (filename) -> fs.readFileSync("#{__dirname}/data/#{filename}").toString() describe 'private helpers', -> dom_from_test_file = (filename) -> (new xmldom.DOMParser()).parseFromString get_test_file filename before => @good_response_dom = dom_from_test_file "good_response.xml" # Auth Request, before it is compressed and base-64 encoded describe 'create_authn_request', -> it 'contains expected fields', -> { id, xml } = saml2.create_authn_request 'https://sp.example.com/metadata.xml', 'https://sp.example.com/assert', 'https://idp.example.com/login' dom = (new xmldom.DOMParser()).parseFromString xml authn_request = dom.getElementsByTagName('AuthnRequest')[0] required_attributes = Version: '2.0' Destination: 'https://idp.example.com/login' AssertionConsumerServiceURL: 'https://sp.example.com/assert' ProtocolBinding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' _(required_attributes).each (req_value, req_name) -> assert _(authn_request.attributes).some((attr) -> attr.name is req_name and attr.value is req_value) , "Expected to find attribute '#{req_name}' with value '#{req_value}'!" assert _(authn_request.attributes).some((attr) -> attr.name is "ID"), "Missing required attribute 'ID'" assert.equal dom.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Issuer')[0].firstChild.data, 'https://sp.example.com/metadata.xml' it 'contains an AuthnContext if requested', -> { id, xml } = saml2.create_authn_request 'a', 'b', 'c', true, { comparison: 'exact', class_refs: ['context:class']} dom = (new xmldom.DOMParser()).parseFromString xml authn_request = dom.getElementsByTagName('AuthnRequest')[0] requested_authn_context = authn_request.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'RequestedAuthnContext')[0] assert _(requested_authn_context.attributes).some (attr) -> attr.name is 'Comparison' and attr.value is 'exact' assert.equal requested_authn_context.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AuthnContextClassRef')[0].firstChild.data, 'context:class' describe 'create_metadata', -> it 'contains expected fields', -> cert = get_test_file 'test.crt' cert2 = get_test_file 'test2.crt' metadata = saml2.create_metadata 'https://sp.example.com/metadata.xml', 'https://sp.example.com/assert', cert, cert2 dom = (new xmldom.DOMParser()).parseFromString metadata entity_descriptor = dom.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'EntityDescriptor')[0] assert _(entity_descriptor.attributes).some((attr) -> attr.name is 'entityID' and attr.value is 'https://sp.example.com/metadata.xml') , "Expected to find attribute 'entityID' with value 'https://sp.example.com/metadata.xml'." assert _(entity_descriptor.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'AssertionConsumerService')).some((assertion) -> _(assertion.attributes).some((attr) -> attr.name is 'Binding' and attr.value is 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST') and _(assertion.attributes).some((attr) -> attr.name is 'Location' and attr.value is 'https://sp.example.com/assert')) , "Expected to find an AssertionConsumerService with POST binding and location 'https://sp.example.com/assert'" assert _(entity_descriptor.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'SingleLogoutService')).some((assertion) -> _(assertion.attributes).some((attr) -> attr.name is 'Binding' and attr.value is 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect') and _(assertion.attributes).some((attr) -> attr.name is 'Location' and attr.value is 'https://sp.example.com/assert')) , "Expected to find a SingleLogoutService with redirect binding and location 'https://sp.example.com/assert'" describe 'format_pem', -> it 'formats an unformatted private key', -> raw_private_key = (/-----BEGIN PRIVATE KEY-----([^-]*)-----END PRIVATE KEY-----/g.exec get_test_file("test.pem"))[1] formatted_key = saml2.format_pem raw_private_key, 'PRIVATE KEY' assert.equal formatted_key.trim(), get_test_file("test.pem").trim() it 'does not change an already formatted private key', -> formatted_key = saml2.format_pem get_test_file("test.pem"), 'PRIVATE KEY' assert.equal formatted_key, get_test_file("test.pem") describe 'sign_request', -> it 'correctly signs a get request', -> signed = saml2.sign_request 'TESTMESSAGE', get_test_file("test.pem") verifier = crypto.createVerify 'RSA-SHA256' verifier.update 'SAMLRequest=TESTMESSAGE&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256' assert verifier.verify(get_test_file("test.crt"), signed.Signature, 'base64'), "Signature is not valid" assert.equal signed.SigAlg, 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' assert.equal signed.SAMLRequest, 'TESTMESSAGE' it 'correctly signs a get response with RelayState', -> signed = saml2.sign_request 'TESTMESSAGE', get_test_file("test.pem"), 'TESTSTATE', true verifier = crypto.createVerify 'RSA-SHA256' verifier.update 'SAMLResponse=TESTMESSAGE&RelayState=TESTSTATE&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rsa-sha256' assert verifier.verify(get_test_file("test.crt"), signed.Signature, 'base64'), "Signature is not valid" assert signed.SigAlg, 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' assert.equal signed.RelayState, 'TESTSTATE' assert.equal signed.SAMLResponse, 'TESTMESSAGE' describe 'check_saml_signature', -> it 'accepts signed xml', -> assert saml2.check_saml_signature(get_test_file("good_assertion.xml"), get_test_file("test.crt")) it 'rejects xml without a signature', -> assert.equal false, saml2.check_saml_signature(get_test_file("unsigned_assertion.xml"), get_test_file("test.crt")) it 'rejects xml with an invalid signature', -> assert.equal false, saml2.check_saml_signature(get_test_file("good_assertion.xml"), get_test_file("test2.crt")) describe 'check_status_success', => it 'accepts a valid success status', => assert saml2.check_status_success(@good_response_dom), "Did not get 'true' for valid response." it 'rejects a missing success status', -> assert not saml2.check_status_success(dom_from_test_file("response_error_status.xml")), "Did not get 'false' for invalid response." it 'rejects a missing status', -> assert not saml2.check_status_success(dom_from_test_file("response_no_status.xml")), "Did not get 'false' for invalid response." describe 'pretty_assertion_attributes', -> it 'creates a correct user object', -> test_attributes = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": [ "PI:EMAIL:<EMAIL>END_PI" ] "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": [ "PI:NAME:<NAME>END_PI User" ] "http://schemas.xmlsoap.org/claims/Group": [ "Test Group" ] expected = email: "PI:EMAIL:<EMAIL>END_PI" name: "PI:NAME:<NAME>END_PI" group: "Test Group" assert.deepEqual saml2.pretty_assertion_attributes(test_attributes), expected describe 'decrypt_assertion', => it 'decrypts and extracts an assertion', (done) => key = get_test_file("test.pem") saml2.decrypt_assertion @good_response_dom, key, (err, result) -> assert not err?, "Got error: #{err}" assert.equal result, get_test_file("good_response_decrypted.xml") done() it 'errors if an incorrect key is used', (done) => key = get_test_file("test2.pem") saml2.decrypt_assertion @good_response_dom, key, (err, result) -> assert (err instanceof Error), "Did not get expected error." done() describe 'parse_response_header', => it 'correctly parses a response header', => response = saml2.parse_response_header @good_response_dom assert.equal response.destination, 'https://sp.example.com/assert' assert.equal response.in_response_to, '_1' it 'errors if there is no response', -> # An assertion is not a response, so this should fail. assert.throws -> saml2.parse_response_header dom_from_test_file("good_assertion.xml") it 'errors if given a response with the wrong version', -> assert.throws -> saml2.parse_response_header dom_from_test_file("response_bad_version.xml") describe 'parse_logout_request', => it 'correctly parses a logout request', => request = saml2.parse_logout_request dom_from_test_file('logout_request.xml') assert.equal request.issuer, 'http://idp.example.com/metadata.xml' assert.equal request.name_id, 'tstudent' assert.equal request.session_index, '_2' describe 'get_name_id', -> it 'gets the correct NameID', -> name_id = saml2.get_name_id dom_from_test_file('good_assertion.xml') assert.equal name_id, 'tstudent' it 'parses assertions with explicit namespaces', -> name_id = saml2.get_name_id dom_from_test_file('good_assertion_explicit_namespaces.xml') assert.equal name_id, 'tstudent' describe 'get_session_index', -> it 'gets the correct session index', -> session_index = saml2.get_session_index dom_from_test_file('good_assertion.xml') assert.equal session_index, '_3' describe 'parse_assertion_attributes', -> it 'correctly parses assertion attributes', -> expected_attributes = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ 'PI:EMAIL:<EMAIL>END_PI' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] attributes = saml2.parse_assertion_attributes dom_from_test_file('good_assertion.xml') assert.deepEqual attributes, expected_attributes it 'correctly parses assertion attributes', -> expected_attributes = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ '' ] attributes = saml2.parse_assertion_attributes dom_from_test_file('empty_attribute_value.xml') assert.deepEqual attributes, expected_attributes it 'correctly parses no assertion attributes', -> attributes = saml2.parse_assertion_attributes dom_from_test_file('blank_assertion.xml') assert.deepEqual attributes, {} describe 'set option defaults', -> it 'sets defaults in the correct order', -> options_top = option1: "top" option4: "top" options_middle = option1: "middle" option2: "middle" option5: "middle" options_bottom = option1: "bottom" option2: "bottom" option3: "bottom" option6: "bottom" expected_options = option1: "top" option2: "middle" option3: "bottom" option4: "top" option5: "middle" option6: "bottom" actual_options = saml2.set_option_defaults options_top, options_middle, options_bottom assert.deepEqual actual_options, expected_options describe 'post assert', -> it 'returns a user object when passed a valid AuthnResponse', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: [ get_test_file('test.crt'), get_test_file('test2.crt') ] request_options = request_body: SAMLResponse: get_test_file("post_response.xml") sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.post_assert idp, request_options, (err, response) -> assert not err?, "Got error: #{err}" expected_response = response_header: id: '_2' in_response_to: '_1' destination: 'https://sp.example.com/assert' type: 'authn_response' user: name_id: 'tstudent' session_index: '_3' given_name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', ppid: 'tstudent', group: 'CN=Students,CN=Users,DC=idp,DC=example,DC=com', surname: 'PI:NAME:<NAME>END_PI', common_name: 'PI:NAME:<NAME>END_PI', attributes: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ 'PI:EMAIL:<EMAIL>END_PI' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] assert.deepEqual response, expected_response done() it 'errors if passed invalid data', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: get_test_file('test.crt') resquest_options = request_body: SAMLResponse: 'FAIL' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.post_assert idp, resquest_options, (err, user) -> assert (err instanceof Error), "Did not get expected error." done() describe 'redirect assert', -> it 'returns a user object with passed a valid AuthnResponse', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: [ get_test_file('test.crt'), get_test_file('test2.crt') ] request_options = request_body: SAMLResponse: get_test_file("redirect_response.xml") sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.redirect_assert idp, request_options, (err, response) -> assert not err?, "Got error: #{err}" expected_response = response_header: id: '_2' in_response_to: '_1' destination: 'https://sp.example.com/assert' type: 'authn_response' user: name_id: 'tstudent' session_index: '_3' given_name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', ppid: 'tstudent', group: 'CN=Students,CN=Users,DC=idp,DC=example,DC=com', surname: 'PI:NAME:<NAME>END_PI', common_name: 'PI:NAME:<NAME>END_PI Student', attributes: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress': [ 'PI:EMAIL:<EMAIL>END_PI' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier': [ 'tstudent' ] 'http://schemas.xmlsoap.org/claims/Group': [ 'CN=Students,CN=Users,DC=idp,DC=example,DC=com' ] 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname': [ 'Student' ] 'http://schemas.xmlsoap.org/claims/CommonName': [ 'Test Student' ] assert.deepEqual response, expected_response # make sure response can be deflated, since redirect requests need to be inflated zlib.deflateRaw new Buffer(response, 'base64'), (err, deflated) => assert not err?, "Got error: #{err}" done() describe 'ServiceProvider', -> it 'can be constructed', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' sp = new saml2.ServiceProvider sp_options done() it 'can create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_login_request_url idp, {assert_endpoint:'https://sp.example.com/assert'}, cb_wf ], (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = parsed_url.query?.SAMLRequest? assert saml_request, 'Could not find SAMLRequest in url query parameters' done() it 'passes through RelayState in create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, {assert_endpoint: 'https://sp.example.com/assert', relay_state: 'Some Relay State!'}, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true assert.equal parsed_url.query?.RelayState, 'Some Relay State!' done() it 'can specify a nameid format in create login request url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' request_options = assert_endpoint: 'https://sp.example.com/assert' relay_state: 'Some Relay State!' nameid_format: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, request_options, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = new Buffer(parsed_url.query?.SAMLRequest, 'base64') zlib.inflateRaw saml_request, (err, result) -> assert.notEqual result.toString('utf8').indexOf("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"), -1 done() it 'requests a nameid format type of urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified if none is specified', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: 'other_service_cert' request_options = assert_endpoint: 'https://sp.example.com/assert' relay_state: 'Some Relay State!' sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options sp.create_login_request_url idp, request_options, (err, login_url, id) -> assert not err?, "Error creating login URL: #{err}" parsed_url = url.parse login_url, true saml_request = new Buffer(parsed_url.query?.SAMLRequest, 'base64') zlib.inflateRaw saml_request, (err, result) -> assert.notEqual result.toString('utf8').indexOf("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"), -1 done() it 'can create logout request url using an idp', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_login_url: 'https://idp.example.com/login' sso_logout_url: 'https://idp.example.com/logout' certificates: get_test_file('test.crt') request_options = name_id: 'name_id' session_index: 'session_index' sign_get_request: true sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_logout_request_url idp, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLRequest?, 'Could not find SAMLRequest in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutRequest is not signed' done() it 'can create logout request url using an string sso_logout_url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' idp_options = sso_logout_url : 'https://idp.example.com/logout' request_options = name_id: 'PI:NAME:<NAME>END_PI' session_index: 'session_index' sign_get_request: true sp = new saml2.ServiceProvider sp_options idp = new saml2.IdentityProvider idp_options async.waterfall [ (cb_wf) -> sp.create_logout_request_url idp, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLRequest?, 'Could not find SAMLRequest in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutRequest is not signed' done() it 'can create logout response url using an idp', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' sso_logout_url = 'https://idp.example.com/logout' request_options = in_response_to: '_1' sign_get_request: true sp = new saml2.ServiceProvider sp_options async.waterfall [ (cb_wf) -> sp.create_logout_response_url sso_logout_url, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating response logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLResponse?, 'Could not find SAMLResponse in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutResponse is not signed' done() it 'can create logout response url using an string sso_logout_url', (done) -> sp_options = entity_id: 'https://sp.example.com/metadata.xml' private_key: get_test_file('test.pem') certificate: get_test_file('test.crt') assert_endpoint: 'https://sp.example.com/assert' request_options = in_response_to: '_1' sign_get_request: true sso_logout_url = 'https://idp.example.com/logout' sp = new saml2.ServiceProvider sp_options async.waterfall [ (cb_wf) -> sp.create_logout_response_url sso_logout_url, request_options, cb_wf ], (err, logout_url) -> assert not err?, "Error creating response logout URL: #{err}" parsed_url = url.parse logout_url, true assert parsed_url?.query?.SAMLResponse?, 'Could not find SAMLResponse in url query parameters' assert parsed_url?.query?.Signature?, 'LogoutResponse is not signed' done() it 'can create metadata', (done) -> done()
[ { "context": " tabLength: 4\n \"go-plus\":\n goPath: \"/Users/holman/Code/go\"\n \"linter-tidy\":\n grammarScopes: [\n ", "end": 1544, "score": 0.845687747001648, "start": 1538, "tag": "USERNAME", "value": "holman" }, { "context": "4cecf260bb8683eab060a7\"\n personalAccessToken: \"f2df5e29c7d56086c7a7703e37bf7e3cb7aafefe\"\n \"tree-view\":\n alwaysOpenExisting: true\n ", "end": 2209, "score": 0.928514838218689, "start": 2169, "tag": "KEY", "value": "f2df5e29c7d56086c7a7703e37bf7e3cb7aafefe" } ]
atom.symlink/config.cson
ritcheyer/dotfiles
2
"*": "atom-beautify": general: _analyticsUserId: "e426b16e-4437-4291-a506-5fa5465e114d" scss: beautify_on_save: true convert_quotes: "single" force_indentation: true indent_size: 2 no_lead_zero: true preserve_newlines: true "atom-clock": showClockIcon: true autosave: enabled: true core: disabledPackages: [ "background-tips" "exception-reporting" "metrics" "minimap" "linter" "linter-docker" "autocompiler-pug-jade" "linter-pug" "git-plus" "Sublime-Style-Column-Selection" "duplicate-line-or-selection" "emmet" "emmet-jsx-css-modules" "language-babel" "language-jade" "teletype" ] hideGitIgnoredFiles: true ignoredNames: [ ".git" ".hg" ".svn" ".DS_Store" "._*" "Thumbs.db" "desktop.ini" "*node_modules*" "ui.content" "target" "META-INF" "api.apps" "config" "core" "" ] projectHome: "~/bin" restorePreviousWindowsOnStart: "no" telemetryConsent: "limited" themes: [ "city-lights-ui" "city-lights-syntax" ] editor: fontFamily: "Fira Code" fontSize: 15 invisibles: {} scrollPastEnd: true showIndentGuide: true showInvisibles: true softWrapAtPreferredLineLength: true softWrapHangingIndent: 2 tabType: "soft" "git-plus": pullBeforePush: "pull" tabLength: 4 "go-plus": goPath: "/Users/holman/Code/go" "linter-tidy": grammarScopes: [ "text.html.basic text.html.twig" ] "markdown-preview": useGitHubStyle: true "merge-conflicts": {} minimap: absoluteMode: true adjustAbsoluteModeHeight: true react: {} "release-notes": viewedVersion: "0.89.0" "spell-check": grammars: [ "text.plain" "source.gfm" "text.git-commit" "text.html.basic" ] "svg-preview": openPreviewAutomatically: true "sync-settings": _lastBackupHash: "950d73b1a98c19a3913bf056ddd134c4337475e9" gistId: "08a0a2cd9d4cecf260bb8683eab060a7" personalAccessToken: "f2df5e29c7d56086c7a7703e37bf7e3cb7aafefe" "tree-view": alwaysOpenExisting: true autoReveal: true hideIgnoredNames: true hideVcsIgnoredFiles: true "webbox-color": fillColorAsBackground: false welcome: showOnStartup: false ".aem.htl": editor: commentEnd: " */-->" commentStart: "<!--/* " ".coffee.jsx.source": editor: autoIndentOnPaste: true showInvisibles: true tabLength: 4 ".css.source.twig": editor: autoIndentOnPaste: false ".diff.source": editor: scrollPastEnd: true showInvisibles: true softWrapAtPreferredLineLength: false "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true welcome: showOnStartup: false ".js.jsx.source": editor: autoIndentOnPaste: true tabLength: 4
83105
"*": "atom-beautify": general: _analyticsUserId: "e426b16e-4437-4291-a506-5fa5465e114d" scss: beautify_on_save: true convert_quotes: "single" force_indentation: true indent_size: 2 no_lead_zero: true preserve_newlines: true "atom-clock": showClockIcon: true autosave: enabled: true core: disabledPackages: [ "background-tips" "exception-reporting" "metrics" "minimap" "linter" "linter-docker" "autocompiler-pug-jade" "linter-pug" "git-plus" "Sublime-Style-Column-Selection" "duplicate-line-or-selection" "emmet" "emmet-jsx-css-modules" "language-babel" "language-jade" "teletype" ] hideGitIgnoredFiles: true ignoredNames: [ ".git" ".hg" ".svn" ".DS_Store" "._*" "Thumbs.db" "desktop.ini" "*node_modules*" "ui.content" "target" "META-INF" "api.apps" "config" "core" "" ] projectHome: "~/bin" restorePreviousWindowsOnStart: "no" telemetryConsent: "limited" themes: [ "city-lights-ui" "city-lights-syntax" ] editor: fontFamily: "Fira Code" fontSize: 15 invisibles: {} scrollPastEnd: true showIndentGuide: true showInvisibles: true softWrapAtPreferredLineLength: true softWrapHangingIndent: 2 tabType: "soft" "git-plus": pullBeforePush: "pull" tabLength: 4 "go-plus": goPath: "/Users/holman/Code/go" "linter-tidy": grammarScopes: [ "text.html.basic text.html.twig" ] "markdown-preview": useGitHubStyle: true "merge-conflicts": {} minimap: absoluteMode: true adjustAbsoluteModeHeight: true react: {} "release-notes": viewedVersion: "0.89.0" "spell-check": grammars: [ "text.plain" "source.gfm" "text.git-commit" "text.html.basic" ] "svg-preview": openPreviewAutomatically: true "sync-settings": _lastBackupHash: "950d73b1a98c19a3913bf056ddd134c4337475e9" gistId: "08a0a2cd9d4cecf260bb8683eab060a7" personalAccessToken: "<KEY>" "tree-view": alwaysOpenExisting: true autoReveal: true hideIgnoredNames: true hideVcsIgnoredFiles: true "webbox-color": fillColorAsBackground: false welcome: showOnStartup: false ".aem.htl": editor: commentEnd: " */-->" commentStart: "<!--/* " ".coffee.jsx.source": editor: autoIndentOnPaste: true showInvisibles: true tabLength: 4 ".css.source.twig": editor: autoIndentOnPaste: false ".diff.source": editor: scrollPastEnd: true showInvisibles: true softWrapAtPreferredLineLength: false "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true welcome: showOnStartup: false ".js.jsx.source": editor: autoIndentOnPaste: true tabLength: 4
true
"*": "atom-beautify": general: _analyticsUserId: "e426b16e-4437-4291-a506-5fa5465e114d" scss: beautify_on_save: true convert_quotes: "single" force_indentation: true indent_size: 2 no_lead_zero: true preserve_newlines: true "atom-clock": showClockIcon: true autosave: enabled: true core: disabledPackages: [ "background-tips" "exception-reporting" "metrics" "minimap" "linter" "linter-docker" "autocompiler-pug-jade" "linter-pug" "git-plus" "Sublime-Style-Column-Selection" "duplicate-line-or-selection" "emmet" "emmet-jsx-css-modules" "language-babel" "language-jade" "teletype" ] hideGitIgnoredFiles: true ignoredNames: [ ".git" ".hg" ".svn" ".DS_Store" "._*" "Thumbs.db" "desktop.ini" "*node_modules*" "ui.content" "target" "META-INF" "api.apps" "config" "core" "" ] projectHome: "~/bin" restorePreviousWindowsOnStart: "no" telemetryConsent: "limited" themes: [ "city-lights-ui" "city-lights-syntax" ] editor: fontFamily: "Fira Code" fontSize: 15 invisibles: {} scrollPastEnd: true showIndentGuide: true showInvisibles: true softWrapAtPreferredLineLength: true softWrapHangingIndent: 2 tabType: "soft" "git-plus": pullBeforePush: "pull" tabLength: 4 "go-plus": goPath: "/Users/holman/Code/go" "linter-tidy": grammarScopes: [ "text.html.basic text.html.twig" ] "markdown-preview": useGitHubStyle: true "merge-conflicts": {} minimap: absoluteMode: true adjustAbsoluteModeHeight: true react: {} "release-notes": viewedVersion: "0.89.0" "spell-check": grammars: [ "text.plain" "source.gfm" "text.git-commit" "text.html.basic" ] "svg-preview": openPreviewAutomatically: true "sync-settings": _lastBackupHash: "950d73b1a98c19a3913bf056ddd134c4337475e9" gistId: "08a0a2cd9d4cecf260bb8683eab060a7" personalAccessToken: "PI:KEY:<KEY>END_PI" "tree-view": alwaysOpenExisting: true autoReveal: true hideIgnoredNames: true hideVcsIgnoredFiles: true "webbox-color": fillColorAsBackground: false welcome: showOnStartup: false ".aem.htl": editor: commentEnd: " */-->" commentStart: "<!--/* " ".coffee.jsx.source": editor: autoIndentOnPaste: true showInvisibles: true tabLength: 4 ".css.source.twig": editor: autoIndentOnPaste: false ".diff.source": editor: scrollPastEnd: true showInvisibles: true softWrapAtPreferredLineLength: false "tree-view": hideIgnoredNames: true hideVcsIgnoredFiles: true welcome: showOnStartup: false ".js.jsx.source": editor: autoIndentOnPaste: true tabLength: 4
[ { "context": " is an existing user', ->\n createUser(name: 'bob', slackUsername: 'bob_yeah', false)\n .then (", "end": 1105, "score": 0.9849013090133667, "start": 1102, "tag": "USERNAME", "value": "bob" }, { "context": " ->\n createUser(name: 'bob', slackUsername: 'bob_yeah', false)\n .then (@bob)=>\n App.registe", "end": 1132, "score": 0.9996278882026672, "start": 1124, "tag": "USERNAME", "value": "bob_yeah" }, { "context": "ob', slackUsername: 'bob_yeah', false)\n .then (@bob)=>\n App.registerUser(@bob, {\n mes", "end": 1159, "score": 0.9931191205978394, "start": 1154, "tag": "USERNAME", "value": "(@bob" }, { "context": "lse)\n .then (@bob)=>\n App.registerUser(@bob, {\n message:\n user:\n ", "end": 1192, "score": 0.9962295889854431, "start": 1188, "tag": "USERNAME", "value": "@bob" }, { "context": " message:\n user:\n name: 'bob'\n email_address: 'bob@example.com'\n ", "end": 1257, "score": 0.6718271970748901, "start": 1254, "tag": "USERNAME", "value": "bob" }, { "context": " name: 'bob'\n email_address: 'bob@example.com'\n })\n .then => @spy.should.have.not.b", "end": 1304, "score": 0.9999163746833801, "start": 1289, "tag": "EMAIL", "value": "bob@example.com" }, { "context": "increment user count', ->\n createUser(name: 'bob', slackUsername: null)\n .then (@bob)=>\n ", "end": 1456, "score": 0.9901249408721924, "start": 1453, "tag": "USERNAME", "value": "bob" }, { "context": "User(name: 'bob', slackUsername: null)\n .then (@bob)=>\n App.registerUser(@bob, {\n nam", "end": 1497, "score": 0.9854300022125244, "start": 1492, "tag": "USERNAME", "value": "(@bob" }, { "context": "ull)\n .then (@bob)=>\n App.registerUser(@bob, {\n name: 'bob'\n email_address:", "end": 1530, "score": 0.9969857931137085, "start": 1526, "tag": "USERNAME", "value": "@bob" }, { "context": " App.registerUser(@bob, {\n name: 'bob'\n email_address: 'bob@example.com'\n ", "end": 1554, "score": 0.5294477939605713, "start": 1551, "tag": "USERNAME", "value": "bob" }, { "context": "{\n name: 'bob'\n email_address: 'bob@example.com'\n }, true)\n .then => @spy.should.have", "end": 1597, "score": 0.999915599822998, "start": 1582, "tag": "EMAIL", "value": "bob@example.com" } ]
test/integration/app-tests.coffee
citizencode/swarmbot
21
{ createUser } = require '../helpers/test-helper' sinon = require 'sinon' User = require '../../src/models/user.coffee' KeenioInfo = require '../../src/services/keenio-info.coffee' Init = require '../../src/bots/!init' describe "App", -> beforeEach -> @robot = enter: -> respond: -> adapter: customMessage: -> App.robot = @robot App.whose = (msg)-> "slack:#{msg.message.user.id}" describe ".greet", -> it "sets the user's state to the initial state", -> msg = robot: @robot message: { user: { id: "I am actually a human" } } parts: [] match: {} App.greet(msg) .then => User.find("slack:I am actually a human") .then (@createdUser)=> @createdUser.exists().should.eq true @createdUser.get('state').should.eq "projects#index" describe '.registerUser', -> beforeEach -> @spy = sinon.spy(KeenioInfo::, 'createUser') afterEach -> KeenioInfo::createUser.restore?() it 'does NOT call out to keen if it is an existing user', -> createUser(name: 'bob', slackUsername: 'bob_yeah', false) .then (@bob)=> App.registerUser(@bob, { message: user: name: 'bob' email_address: 'bob@example.com' }) .then => @spy.should.have.not.been.called it 'calls keen for a NEW user to increment user count', -> createUser(name: 'bob', slackUsername: null) .then (@bob)=> App.registerUser(@bob, { name: 'bob' email_address: 'bob@example.com' }, true) .then => @spy.should.have.been.calledWith @bob describe '.extractTextLines', -> it "makes text out of elements of different types", -> App.extractTextLines("foo").should.deep.eq ["foo"] (-> App.extractTextLines(->)).should.throw("") App.extractTextLines(3).should.deep.eq ["3"]
215865
{ createUser } = require '../helpers/test-helper' sinon = require 'sinon' User = require '../../src/models/user.coffee' KeenioInfo = require '../../src/services/keenio-info.coffee' Init = require '../../src/bots/!init' describe "App", -> beforeEach -> @robot = enter: -> respond: -> adapter: customMessage: -> App.robot = @robot App.whose = (msg)-> "slack:#{msg.message.user.id}" describe ".greet", -> it "sets the user's state to the initial state", -> msg = robot: @robot message: { user: { id: "I am actually a human" } } parts: [] match: {} App.greet(msg) .then => User.find("slack:I am actually a human") .then (@createdUser)=> @createdUser.exists().should.eq true @createdUser.get('state').should.eq "projects#index" describe '.registerUser', -> beforeEach -> @spy = sinon.spy(KeenioInfo::, 'createUser') afterEach -> KeenioInfo::createUser.restore?() it 'does NOT call out to keen if it is an existing user', -> createUser(name: 'bob', slackUsername: 'bob_yeah', false) .then (@bob)=> App.registerUser(@bob, { message: user: name: 'bob' email_address: '<EMAIL>' }) .then => @spy.should.have.not.been.called it 'calls keen for a NEW user to increment user count', -> createUser(name: 'bob', slackUsername: null) .then (@bob)=> App.registerUser(@bob, { name: 'bob' email_address: '<EMAIL>' }, true) .then => @spy.should.have.been.calledWith @bob describe '.extractTextLines', -> it "makes text out of elements of different types", -> App.extractTextLines("foo").should.deep.eq ["foo"] (-> App.extractTextLines(->)).should.throw("") App.extractTextLines(3).should.deep.eq ["3"]
true
{ createUser } = require '../helpers/test-helper' sinon = require 'sinon' User = require '../../src/models/user.coffee' KeenioInfo = require '../../src/services/keenio-info.coffee' Init = require '../../src/bots/!init' describe "App", -> beforeEach -> @robot = enter: -> respond: -> adapter: customMessage: -> App.robot = @robot App.whose = (msg)-> "slack:#{msg.message.user.id}" describe ".greet", -> it "sets the user's state to the initial state", -> msg = robot: @robot message: { user: { id: "I am actually a human" } } parts: [] match: {} App.greet(msg) .then => User.find("slack:I am actually a human") .then (@createdUser)=> @createdUser.exists().should.eq true @createdUser.get('state').should.eq "projects#index" describe '.registerUser', -> beforeEach -> @spy = sinon.spy(KeenioInfo::, 'createUser') afterEach -> KeenioInfo::createUser.restore?() it 'does NOT call out to keen if it is an existing user', -> createUser(name: 'bob', slackUsername: 'bob_yeah', false) .then (@bob)=> App.registerUser(@bob, { message: user: name: 'bob' email_address: 'PI:EMAIL:<EMAIL>END_PI' }) .then => @spy.should.have.not.been.called it 'calls keen for a NEW user to increment user count', -> createUser(name: 'bob', slackUsername: null) .then (@bob)=> App.registerUser(@bob, { name: 'bob' email_address: 'PI:EMAIL:<EMAIL>END_PI' }, true) .then => @spy.should.have.been.calledWith @bob describe '.extractTextLines', -> it "makes text out of elements of different types", -> App.extractTextLines("foo").should.deep.eq ["foo"] (-> App.extractTextLines(->)).should.throw("") App.extractTextLines(3).should.deep.eq ["3"]