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": "# The MIT License (MIT)\n\n# Copyright (c) 2015 Jacobus Meulen\n\n# Permission is hereby granted, free of charge, ", "end": 60, "score": 0.9998505711555481, "start": 46, "tag": "NAME", "value": "Jacobus Meulen" } ]
mongojs-live.coffee
sjaakiejj/mongojs-live
0
# The MIT License (MIT) # Copyright (c) 2015 Jacobus Meulen # 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. #mongohooks = require 'mongohooks' mongoquery = require 'mongo-json-query' _ = require 'lodash' EventEmitter = require('events').EventEmitter processEvent = (listenQuery, callback) -> (error, query, update, options, result) -> return if error? # Update could be an array or a single entry #if update instanceof Array # fullObject = _.map update, (upd) -> _.extend(query, upd) #else # For now just support single entries fullObject = _.extend(query.q || query, update) #console.log query.q #console.log listenQuery # Match the object mongoquery.match(fullObject, listenQuery, (matches) -> callback( result: result query: query update: update ) if matches and callback? ) # These are the supplementary functions provided by this module wrappedFind = (find, mongo, collection) -> () -> args = arguments cursor = find.apply(@, arguments) cursor.observe = (callback) -> mongo[collection].hook.on 'insert', processEvent(args[0], callback) mongo[collection].hook.on 'update', processEvent(args[0], callback) mongo[collection].hook.on 'remove', processEvent(args[0], callback) mongo[collection].hook.on 'save', processEvent(args[0], callback) cursor.observeChange = (callback) -> callback("Not currently supported") return cursor afterInsertHook = (originalInsert) -> (docOrDocs, callback) -> # Establish arguments to apply args = [docOrDocs,(err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "insert", err, docOrDocs ] # Apply the updated arguments originalInsert.apply(@,args) afterUpdateHook = (originalUpdate) -> (query, update, options, callback) -> # Modify if options is the callback callback = options if _.isFunction(options) options = {} if _.isFunction(options) # Establish arguments to apply args = [query,update,options,(err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "update", err, query, update, options, res ] # Apply the updated arguments originalUpdate.apply(@, args) afterRemoveHook = (originalRemove) -> (query, justOne, callback) -> callback = justOne if _.isFunction(justOne) justOne = false if _.isFunction(justOne) # Establish arguments to apply args = [query,justOne, (err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "remove", err, query, justOne ] originalRemove.apply(@, args) afterSaveHook = (originalSave) -> (doc, callback) -> # Establish arguments to apply args = [doc,(err,res) -> callback(err,res) if callback? process.nextTick () => @hook.emit "save", err, doc ] # Apply the updated arguments originalSave.apply(@,args) module.exports = extend: (mongo, tables) -> for collection in tables originalFind = mongo[collection].find mongo[collection].hook = new EventEmitter() mongo[collection].hook.setMaxListeners(0) mongo[collection].find = wrappedFind(originalFind, mongo, collection) mongo[collection].update = afterUpdateHook(mongo[collection].update) mongo[collection].remove = afterRemoveHook(mongo[collection].remove) return mongo
220067
# The MIT License (MIT) # Copyright (c) 2015 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #mongohooks = require 'mongohooks' mongoquery = require 'mongo-json-query' _ = require 'lodash' EventEmitter = require('events').EventEmitter processEvent = (listenQuery, callback) -> (error, query, update, options, result) -> return if error? # Update could be an array or a single entry #if update instanceof Array # fullObject = _.map update, (upd) -> _.extend(query, upd) #else # For now just support single entries fullObject = _.extend(query.q || query, update) #console.log query.q #console.log listenQuery # Match the object mongoquery.match(fullObject, listenQuery, (matches) -> callback( result: result query: query update: update ) if matches and callback? ) # These are the supplementary functions provided by this module wrappedFind = (find, mongo, collection) -> () -> args = arguments cursor = find.apply(@, arguments) cursor.observe = (callback) -> mongo[collection].hook.on 'insert', processEvent(args[0], callback) mongo[collection].hook.on 'update', processEvent(args[0], callback) mongo[collection].hook.on 'remove', processEvent(args[0], callback) mongo[collection].hook.on 'save', processEvent(args[0], callback) cursor.observeChange = (callback) -> callback("Not currently supported") return cursor afterInsertHook = (originalInsert) -> (docOrDocs, callback) -> # Establish arguments to apply args = [docOrDocs,(err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "insert", err, docOrDocs ] # Apply the updated arguments originalInsert.apply(@,args) afterUpdateHook = (originalUpdate) -> (query, update, options, callback) -> # Modify if options is the callback callback = options if _.isFunction(options) options = {} if _.isFunction(options) # Establish arguments to apply args = [query,update,options,(err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "update", err, query, update, options, res ] # Apply the updated arguments originalUpdate.apply(@, args) afterRemoveHook = (originalRemove) -> (query, justOne, callback) -> callback = justOne if _.isFunction(justOne) justOne = false if _.isFunction(justOne) # Establish arguments to apply args = [query,justOne, (err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "remove", err, query, justOne ] originalRemove.apply(@, args) afterSaveHook = (originalSave) -> (doc, callback) -> # Establish arguments to apply args = [doc,(err,res) -> callback(err,res) if callback? process.nextTick () => @hook.emit "save", err, doc ] # Apply the updated arguments originalSave.apply(@,args) module.exports = extend: (mongo, tables) -> for collection in tables originalFind = mongo[collection].find mongo[collection].hook = new EventEmitter() mongo[collection].hook.setMaxListeners(0) mongo[collection].find = wrappedFind(originalFind, mongo, collection) mongo[collection].update = afterUpdateHook(mongo[collection].update) mongo[collection].remove = afterRemoveHook(mongo[collection].remove) return mongo
true
# The MIT License (MIT) # Copyright (c) 2015 PI:NAME:<NAME>END_PI # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #mongohooks = require 'mongohooks' mongoquery = require 'mongo-json-query' _ = require 'lodash' EventEmitter = require('events').EventEmitter processEvent = (listenQuery, callback) -> (error, query, update, options, result) -> return if error? # Update could be an array or a single entry #if update instanceof Array # fullObject = _.map update, (upd) -> _.extend(query, upd) #else # For now just support single entries fullObject = _.extend(query.q || query, update) #console.log query.q #console.log listenQuery # Match the object mongoquery.match(fullObject, listenQuery, (matches) -> callback( result: result query: query update: update ) if matches and callback? ) # These are the supplementary functions provided by this module wrappedFind = (find, mongo, collection) -> () -> args = arguments cursor = find.apply(@, arguments) cursor.observe = (callback) -> mongo[collection].hook.on 'insert', processEvent(args[0], callback) mongo[collection].hook.on 'update', processEvent(args[0], callback) mongo[collection].hook.on 'remove', processEvent(args[0], callback) mongo[collection].hook.on 'save', processEvent(args[0], callback) cursor.observeChange = (callback) -> callback("Not currently supported") return cursor afterInsertHook = (originalInsert) -> (docOrDocs, callback) -> # Establish arguments to apply args = [docOrDocs,(err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "insert", err, docOrDocs ] # Apply the updated arguments originalInsert.apply(@,args) afterUpdateHook = (originalUpdate) -> (query, update, options, callback) -> # Modify if options is the callback callback = options if _.isFunction(options) options = {} if _.isFunction(options) # Establish arguments to apply args = [query,update,options,(err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "update", err, query, update, options, res ] # Apply the updated arguments originalUpdate.apply(@, args) afterRemoveHook = (originalRemove) -> (query, justOne, callback) -> callback = justOne if _.isFunction(justOne) justOne = false if _.isFunction(justOne) # Establish arguments to apply args = [query,justOne, (err,res) => callback(err,res) if callback? process.nextTick () => @hook.emit "remove", err, query, justOne ] originalRemove.apply(@, args) afterSaveHook = (originalSave) -> (doc, callback) -> # Establish arguments to apply args = [doc,(err,res) -> callback(err,res) if callback? process.nextTick () => @hook.emit "save", err, doc ] # Apply the updated arguments originalSave.apply(@,args) module.exports = extend: (mongo, tables) -> for collection in tables originalFind = mongo[collection].find mongo[collection].hook = new EventEmitter() mongo[collection].hook.setMaxListeners(0) mongo[collection].find = wrappedFind(originalFind, mongo, collection) mongo[collection].update = afterUpdateHook(mongo[collection].update) mongo[collection].remove = afterRemoveHook(mongo[collection].remove) return mongo
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9990174770355225, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-upgrade-server.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. createTestServer = -> new testServer() testServer = -> server = this http.Server.call server, -> server.on "connection", -> requests_recv++ return server.on "request", (req, res) -> res.writeHead 200, "Content-Type": "text/plain" res.write "okay" res.end() return server.on "upgrade", (req, socket, upgradeHead) -> socket.write "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n\r\n" request_upgradeHead = upgradeHead socket.on "data", (d) -> data = d.toString("utf8") if data is "kill" socket.end() else socket.write data, "utf8" return return return writeReq = (socket, data, encoding) -> requests_sent++ socket.write data return #----------------------------------------------- # connection: Upgrade with listener #----------------------------------------------- test_upgrade_with_listener = (_server) -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" state = 0 conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n" + "WjN}|M(6" return conn.on "data", (data) -> state++ assert.equal "string", typeof data if state is 1 assert.equal "HTTP/1.1 101", data.substr(0, 12) assert.equal "WjN}|M(6", request_upgradeHead.toString("utf8") conn.write "test", "utf8" else if state is 2 assert.equal "test", data conn.write "kill", "utf8" return conn.on "end", -> assert.equal 2, state conn.end() _server.removeAllListeners "upgrade" test_upgrade_no_listener() return return #----------------------------------------------- # connection: Upgrade, no listener #----------------------------------------------- test_upgrade_no_listener = -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n" return conn.on "end", -> test_upgrade_no_listener_ended = true conn.end() return conn.on "close", -> test_standard_http() return return #----------------------------------------------- # connection: normal #----------------------------------------------- test_standard_http = -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n\r\n" return conn.once "data", (data) -> assert.equal "string", typeof data assert.equal "HTTP/1.1 200", data.substr(0, 12) conn.end() return conn.on "close", -> server.close() return return common = require("../common") assert = require("assert") util = require("util") net = require("net") http = require("http") requests_recv = 0 requests_sent = 0 request_upgradeHead = null util.inherits testServer, http.Server test_upgrade_no_listener_ended = false server = createTestServer() server.listen common.PORT, -> # All tests get chained after this: test_upgrade_with_listener server return #----------------------------------------------- # Fin. #----------------------------------------------- process.on "exit", -> assert.equal 3, requests_recv assert.equal 3, requests_sent assert.ok test_upgrade_no_listener_ended return
225201
# 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. createTestServer = -> new testServer() testServer = -> server = this http.Server.call server, -> server.on "connection", -> requests_recv++ return server.on "request", (req, res) -> res.writeHead 200, "Content-Type": "text/plain" res.write "okay" res.end() return server.on "upgrade", (req, socket, upgradeHead) -> socket.write "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n\r\n" request_upgradeHead = upgradeHead socket.on "data", (d) -> data = d.toString("utf8") if data is "kill" socket.end() else socket.write data, "utf8" return return return writeReq = (socket, data, encoding) -> requests_sent++ socket.write data return #----------------------------------------------- # connection: Upgrade with listener #----------------------------------------------- test_upgrade_with_listener = (_server) -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" state = 0 conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n" + "WjN}|M(6" return conn.on "data", (data) -> state++ assert.equal "string", typeof data if state is 1 assert.equal "HTTP/1.1 101", data.substr(0, 12) assert.equal "WjN}|M(6", request_upgradeHead.toString("utf8") conn.write "test", "utf8" else if state is 2 assert.equal "test", data conn.write "kill", "utf8" return conn.on "end", -> assert.equal 2, state conn.end() _server.removeAllListeners "upgrade" test_upgrade_no_listener() return return #----------------------------------------------- # connection: Upgrade, no listener #----------------------------------------------- test_upgrade_no_listener = -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n" return conn.on "end", -> test_upgrade_no_listener_ended = true conn.end() return conn.on "close", -> test_standard_http() return return #----------------------------------------------- # connection: normal #----------------------------------------------- test_standard_http = -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n\r\n" return conn.once "data", (data) -> assert.equal "string", typeof data assert.equal "HTTP/1.1 200", data.substr(0, 12) conn.end() return conn.on "close", -> server.close() return return common = require("../common") assert = require("assert") util = require("util") net = require("net") http = require("http") requests_recv = 0 requests_sent = 0 request_upgradeHead = null util.inherits testServer, http.Server test_upgrade_no_listener_ended = false server = createTestServer() server.listen common.PORT, -> # All tests get chained after this: test_upgrade_with_listener server return #----------------------------------------------- # Fin. #----------------------------------------------- process.on "exit", -> assert.equal 3, requests_recv assert.equal 3, requests_sent assert.ok test_upgrade_no_listener_ended 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. createTestServer = -> new testServer() testServer = -> server = this http.Server.call server, -> server.on "connection", -> requests_recv++ return server.on "request", (req, res) -> res.writeHead 200, "Content-Type": "text/plain" res.write "okay" res.end() return server.on "upgrade", (req, socket, upgradeHead) -> socket.write "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n\r\n" request_upgradeHead = upgradeHead socket.on "data", (d) -> data = d.toString("utf8") if data is "kill" socket.end() else socket.write data, "utf8" return return return writeReq = (socket, data, encoding) -> requests_sent++ socket.write data return #----------------------------------------------- # connection: Upgrade with listener #----------------------------------------------- test_upgrade_with_listener = (_server) -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" state = 0 conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n" + "WjN}|M(6" return conn.on "data", (data) -> state++ assert.equal "string", typeof data if state is 1 assert.equal "HTTP/1.1 101", data.substr(0, 12) assert.equal "WjN}|M(6", request_upgradeHead.toString("utf8") conn.write "test", "utf8" else if state is 2 assert.equal "test", data conn.write "kill", "utf8" return conn.on "end", -> assert.equal 2, state conn.end() _server.removeAllListeners "upgrade" test_upgrade_no_listener() return return #----------------------------------------------- # connection: Upgrade, no listener #----------------------------------------------- test_upgrade_no_listener = -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n" return conn.on "end", -> test_upgrade_no_listener_ended = true conn.end() return conn.on "close", -> test_standard_http() return return #----------------------------------------------- # connection: normal #----------------------------------------------- test_standard_http = -> conn = net.createConnection(common.PORT) conn.setEncoding "utf8" conn.on "connect", -> writeReq conn, "GET / HTTP/1.1\r\n\r\n" return conn.once "data", (data) -> assert.equal "string", typeof data assert.equal "HTTP/1.1 200", data.substr(0, 12) conn.end() return conn.on "close", -> server.close() return return common = require("../common") assert = require("assert") util = require("util") net = require("net") http = require("http") requests_recv = 0 requests_sent = 0 request_upgradeHead = null util.inherits testServer, http.Server test_upgrade_no_listener_ended = false server = createTestServer() server.listen common.PORT, -> # All tests get chained after this: test_upgrade_with_listener server return #----------------------------------------------- # Fin. #----------------------------------------------- process.on "exit", -> assert.equal 3, requests_recv assert.equal 3, requests_sent assert.ok test_upgrade_no_listener_ended return
[ { "context": "ager \n# ---------------------\n# \n# @author : Fábio Azevedo <fabio.azevedo@unit9.com> UNIT9\n# @date : Sep", "end": 111, "score": 0.9998770952224731, "start": 98, "tag": "NAME", "value": "Fábio Azevedo" }, { "context": "---------------\n# \n# @author : F...
src/coffee/utils/MediaQueries.coffee
neilcarpenter/codedoodl.es-chrome-extension
0
# --------------------- # Media Queries Manager # --------------------- # # @author : Fábio Azevedo <fabio.azevedo@unit9.com> UNIT9 # @date : September 14 # # Instructions are on /project/sass/utils/_responsive.scss. class MediaQueries # Breakpoints @SMALL : "small" @IPAD : "ipad" @MEDIUM : "medium" @LARGE : "large" @EXTRA_LARGE : "extra-large" @setup : => MediaQueries.SMALL_BREAKPOINT = {name: "Small", breakpoints: [MediaQueries.SMALL]} MediaQueries.MEDIUM_BREAKPOINT = {name: "Medium", breakpoints: [MediaQueries.MEDIUM]} MediaQueries.LARGE_BREAKPOINT = {name: "Large", breakpoints: [MediaQueries.IPAD, MediaQueries.LARGE, MediaQueries.EXTRA_LARGE]} MediaQueries.BREAKPOINTS = [ MediaQueries.SMALL_BREAKPOINT MediaQueries.MEDIUM_BREAKPOINT MediaQueries.LARGE_BREAKPOINT ] return @getDeviceState : => return window.getComputedStyle(document.body, "after").getPropertyValue("content"); @getBreakpoint : => state = MediaQueries.getDeviceState() for i in [0...MediaQueries.BREAKPOINTS.length] if MediaQueries.BREAKPOINTS[i].breakpoints.indexOf(state) > -1 return MediaQueries.BREAKPOINTS[i].name return "" @isBreakpoint : (breakpoint) => for i in [0...breakpoint.breakpoints.length] if breakpoint.breakpoints[i] == MediaQueries.getDeviceState() return true return false module.exports = MediaQueries
181173
# --------------------- # Media Queries Manager # --------------------- # # @author : <NAME> <<EMAIL>> UNIT9 # @date : September 14 # # Instructions are on /project/sass/utils/_responsive.scss. class MediaQueries # Breakpoints @SMALL : "small" @IPAD : "ipad" @MEDIUM : "medium" @LARGE : "large" @EXTRA_LARGE : "extra-large" @setup : => MediaQueries.SMALL_BREAKPOINT = {name: "Small", breakpoints: [MediaQueries.SMALL]} MediaQueries.MEDIUM_BREAKPOINT = {name: "Medium", breakpoints: [MediaQueries.MEDIUM]} MediaQueries.LARGE_BREAKPOINT = {name: "Large", breakpoints: [MediaQueries.IPAD, MediaQueries.LARGE, MediaQueries.EXTRA_LARGE]} MediaQueries.BREAKPOINTS = [ MediaQueries.SMALL_BREAKPOINT MediaQueries.MEDIUM_BREAKPOINT MediaQueries.LARGE_BREAKPOINT ] return @getDeviceState : => return window.getComputedStyle(document.body, "after").getPropertyValue("content"); @getBreakpoint : => state = MediaQueries.getDeviceState() for i in [0...MediaQueries.BREAKPOINTS.length] if MediaQueries.BREAKPOINTS[i].breakpoints.indexOf(state) > -1 return MediaQueries.BREAKPOINTS[i].name return "" @isBreakpoint : (breakpoint) => for i in [0...breakpoint.breakpoints.length] if breakpoint.breakpoints[i] == MediaQueries.getDeviceState() return true return false module.exports = MediaQueries
true
# --------------------- # Media Queries Manager # --------------------- # # @author : PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> UNIT9 # @date : September 14 # # Instructions are on /project/sass/utils/_responsive.scss. class MediaQueries # Breakpoints @SMALL : "small" @IPAD : "ipad" @MEDIUM : "medium" @LARGE : "large" @EXTRA_LARGE : "extra-large" @setup : => MediaQueries.SMALL_BREAKPOINT = {name: "Small", breakpoints: [MediaQueries.SMALL]} MediaQueries.MEDIUM_BREAKPOINT = {name: "Medium", breakpoints: [MediaQueries.MEDIUM]} MediaQueries.LARGE_BREAKPOINT = {name: "Large", breakpoints: [MediaQueries.IPAD, MediaQueries.LARGE, MediaQueries.EXTRA_LARGE]} MediaQueries.BREAKPOINTS = [ MediaQueries.SMALL_BREAKPOINT MediaQueries.MEDIUM_BREAKPOINT MediaQueries.LARGE_BREAKPOINT ] return @getDeviceState : => return window.getComputedStyle(document.body, "after").getPropertyValue("content"); @getBreakpoint : => state = MediaQueries.getDeviceState() for i in [0...MediaQueries.BREAKPOINTS.length] if MediaQueries.BREAKPOINTS[i].breakpoints.indexOf(state) > -1 return MediaQueries.BREAKPOINTS[i].name return "" @isBreakpoint : (breakpoint) => for i in [0...breakpoint.breakpoints.length] if breakpoint.breakpoints[i] == MediaQueries.getDeviceState() return true return false module.exports = MediaQueries
[ { "context": "d process.env.MAIL_URL\n\t\t\t\t\tEmail.send\n\t\t\t\t\t\tto: 'support@steedos.com'\n\t\t\t\t\t\tfrom: 'Steedos <noreply@message.steedos.co", "end": 668, "score": 0.9999249577522278, "start": 649, "tag": "EMAIL", "value": "support@steedos.com" }, { "context": "\t\tto: '...
packages/steedos-weixin/server/routes/refresh_access_token.coffee
zonglu233/fuel-car
42
JsonRoutes.add 'get', '/api/steedos/weixin/refresh/token/:appId', (req, res, next) -> try userId = Steedos.getUserIdFromAuthToken(req, res) if !userId throw new Meteor.Error(500, "No permission") appId = req.params.appId app = Creator.getCollection("vip_apps").findOne(appId) if not app throw new Meteor.Error(500, "App not found") result = {} newToken = WXMini.getNewAccessTokenSync(app._id, app.secret) if newToken Creator.getCollection("vip_apps").update(app._id, { $set: { access_token: newToken } }) else try Email = Package.email.Email if Email and process.env.MAIL_URL Email.send to: 'support@steedos.com' from: 'Steedos <noreply@message.steedos.com>' subject: 'weixin_access_token update failed' text: JSON.stringify({'appId': app._id}) catch err console.error err JsonRoutes.sendResult res, { code: 200, data: result } return catch e console.error e.stack JsonRoutes.sendResult res, { code: e.error data: {errors: e.reason || e.message} }
141346
JsonRoutes.add 'get', '/api/steedos/weixin/refresh/token/:appId', (req, res, next) -> try userId = Steedos.getUserIdFromAuthToken(req, res) if !userId throw new Meteor.Error(500, "No permission") appId = req.params.appId app = Creator.getCollection("vip_apps").findOne(appId) if not app throw new Meteor.Error(500, "App not found") result = {} newToken = WXMini.getNewAccessTokenSync(app._id, app.secret) if newToken Creator.getCollection("vip_apps").update(app._id, { $set: { access_token: newToken } }) else try Email = Package.email.Email if Email and process.env.MAIL_URL Email.send to: '<EMAIL>' from: 'Steedos <<EMAIL>>' subject: 'weixin_access_token update failed' text: JSON.stringify({'appId': app._id}) catch err console.error err JsonRoutes.sendResult res, { code: 200, data: result } return catch e console.error e.stack JsonRoutes.sendResult res, { code: e.error data: {errors: e.reason || e.message} }
true
JsonRoutes.add 'get', '/api/steedos/weixin/refresh/token/:appId', (req, res, next) -> try userId = Steedos.getUserIdFromAuthToken(req, res) if !userId throw new Meteor.Error(500, "No permission") appId = req.params.appId app = Creator.getCollection("vip_apps").findOne(appId) if not app throw new Meteor.Error(500, "App not found") result = {} newToken = WXMini.getNewAccessTokenSync(app._id, app.secret) if newToken Creator.getCollection("vip_apps").update(app._id, { $set: { access_token: newToken } }) else try Email = Package.email.Email if Email and process.env.MAIL_URL Email.send to: 'PI:EMAIL:<EMAIL>END_PI' from: 'Steedos <PI:EMAIL:<EMAIL>END_PI>' subject: 'weixin_access_token update failed' text: JSON.stringify({'appId': app._id}) catch err console.error err JsonRoutes.sendResult res, { code: 200, data: result } return catch e console.error e.stack JsonRoutes.sendResult res, { code: e.error data: {errors: e.reason || e.message} }
[ { "context": " 'thangType', 'components']\n 'default':\n id: 'Boris'\n thangType: 'Soldier'\n components: []\n},\n ", "end": 20218, "score": 0.7909665107727051, "start": 20213, "tag": "NAME", "value": "Boris" } ]
app/schemas/models/level.coffee
FlexBlur/codecombat
1
c = require './../schemas' ThangComponentSchema = require './thang_component' SpecificArticleSchema = c.object() c.extendNamedProperties SpecificArticleSchema # name first SpecificArticleSchema.properties.body = {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} SpecificArticleSchema.properties.i18n = {type: 'object', format: 'i18n', props: ['name', 'body'], description: 'Help translate this article'} SpecificArticleSchema.displayProperty = 'name' side = {title: 'Side', description: 'A side.', type: 'string', 'enum': ['left', 'right', 'top', 'bottom']} thang = {title: 'Thang', description: 'The name of a Thang.', type: 'string', maxLength: 60, format: 'thang'} eventPrereqValueTypes = ['boolean', 'integer', 'number', 'null', 'string'] # not 'object' or 'array' EventPrereqSchema = c.object {title: 'Event Prerequisite', format: 'event-prereq', description: 'Script requires that the value of some property on the event triggering it to meet some prerequisite.', required: ['eventProps']}, eventProps: c.array {'default': ['thang'], format: 'event-value-chain', maxItems: 10, title: 'Event Property', description: 'A chain of keys in the event, like "thang.pos.x" to access event.thang.pos.x.'}, c.shortString(title: 'Property', description: 'A key in the event property key chain.') equalTo: c.object {type: eventPrereqValueTypes, title: '==', description: 'Script requires the event\'s property chain value to be equal to this value.'} notEqualTo: c.object {type: eventPrereqValueTypes, title: '!=', description: 'Script requires the event\'s property chain value to *not* be equal to this value.'} greaterThan: {type: 'number', title: '>', description: 'Script requires the event\'s property chain value to be greater than this value.'} greaterThanOrEqualTo: {type: 'number', title: '>=', description: 'Script requires the event\'s property chain value to be greater or equal to this value.'} lessThan: {type: 'number', title: '<', description: 'Script requires the event\'s property chain value to be less than this value.'} lessThanOrEqualTo: {type: 'number', title: '<=', description: 'Script requires the event\'s property chain value to be less than or equal to this value.'} containingString: c.shortString(title: 'Contains', description: 'Script requires the event\'s property chain value to be a string containing this string.') notContainingString: c.shortString(title: 'Does not contain', description: 'Script requires the event\'s property chain value to *not* be a string containing this string.') containingRegexp: c.shortString(title: 'Contains Regexp', description: 'Script requires the event\'s property chain value to be a string containing this regular expression.') notContainingRegexp: c.shortString(title: 'Does not contain regexp', description: 'Script requires the event\'s property chain value to *not* be a string containing this regular expression.') GoalSchema = c.object {title: 'Goal', description: 'A goal that the player can accomplish.', required: ['name', 'id']}, name: c.shortString(title: 'Name', description: 'Name of the goal that the player will see, like \"Defeat eighteen dragons\".') i18n: {type: 'object', format: 'i18n', props: ['name'], description: 'Help translate this goal'} id: c.shortString(title: 'ID', description: 'Unique identifier for this goal, like \"defeat-dragons\".', pattern: '^[a-z0-9-]+$') # unique somehow? worldEndsAfter: {title: 'World Ends After', description: 'When included, ends the world this many seconds after this goal succeeds or fails.', type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 300, default: 3} howMany: {title: 'How Many', description: 'When included, require only this many of the listed goal targets instead of all of them.', type: 'integer', minimum: 1} hiddenGoal: {title: 'Hidden', description: 'Hidden goals don\'t show up in the goals area for the player until they\'re failed. (Usually they\'re obvious, like "don\'t die".)', 'type': 'boolean' } optional: {title: 'Optional', description: 'Optional goals do not need to be completed for overallStatus to be success.', type: 'boolean'} team: c.shortString(title: 'Team', description: 'Name of the team this goal is for, if it is not for all of the playable teams.') killThangs: c.array {title: 'Kill Thangs', description: 'A list of Thang IDs the player should kill, or team names.', uniqueItems: true, minItems: 1, 'default': ['ogres']}, thang saveThangs: c.array {title: 'Save Thangs', description: 'A list of Thang IDs the player should save, or team names', uniqueItems: true, minItems: 1, 'default': ['Hero Placeholder']}, thang getToLocations: c.object {title: 'Get To Locations', description: 'Will be set off when any of the \"who\" touch any of the \"targets\"', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must get.', minItems: 1}, thang getAllToLocations: c.array {title: 'Get all to locations', description: 'Similar to getToLocations but now a specific \"who\" can have a specific \"target\", also must be used with the HowMany property for desired effect', required: ['getToLocation']}, c.object {title: '', description: ''}, getToLocation: c.object {title: 'Get To Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must get.', minItems: 1}, thang keepFromLocations: c.object {title: 'Keep From Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must not get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must not get.', minItems: 1}, thang keepAllFromLocations: c.array {title: 'Keep ALL From Locations', description: 'Similar to keepFromLocations but now a specific \"who\" can have a specific \"target\", also must be used with the HowMany property for desired effect', required: ['keepFromLocation']}, c.object {title: '', description: ''}, keepFromLocation: c.object {title: 'Keep From Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must not get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must not get.', minItems: 1}, thang leaveOffSides: c.object {title: 'Leave Off Sides', description: 'Sides of the level to get some Thangs to leave across.', required: ['who', 'sides']}, who: c.array {title: 'Who', description: 'The Thangs which must leave off the sides of the level.', minItems: 1}, thang sides: c.array {title: 'Sides', description: 'The sides off which the Thangs must leave.', minItems: 1}, side keepFromLeavingOffSides: c.object {title: 'Keep From Leaving Off Sides', description: 'Sides of the level to keep some Thangs from leaving across.', required: ['who', 'sides']}, who: c.array {title: 'Who', description: 'The Thangs which must not leave off the sides of the level.', minItems: 1}, thang sides: side, {title: 'Sides', description: 'The sides off which the Thangs must not leave.', minItems: 1}, side collectThangs: c.object {title: 'Collect', description: 'Thangs that other Thangs must collect.', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs which must collect the target items.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target items which the Thangs must collect.', minItems: 1}, thang keepFromCollectingThangs: c.object {title: 'Keep From Collecting', description: 'Thangs that the player must prevent other Thangs from collecting.', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs which must not collect the target items.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target items which the Thangs must not collect.', minItems: 1}, thang codeProblems: c.array {title: 'Code Problems', description: 'A list of Thang IDs that should not have any code problems, or team names.', uniqueItems: true, minItems: 1, 'default': ['humans']}, thang linesOfCode: {title: 'Lines of Code', description: 'A mapping of Thang IDs or teams to how many many lines of code should be allowed (well, statements).', type: 'object', default: {humans: 10}, additionalProperties: {type: 'integer', description: 'How many lines to allow for this Thang.'}} html: c.object {title: 'HTML', description: 'A jQuery selector and what its result should be'}, selector: {type: 'string', description: 'jQuery selector to run on the user HTML, like "h1:first-child"'} valueChecks: c.array {title: 'Value checks', description: 'Logical checks on the resulting value for this goal to pass.', format: 'event-prereqs'}, EventPrereqSchema concepts: c.array {title: 'Target Concepts', description: 'Which programming concepts this goal demonstrates.', uniqueItems: true, format: 'concepts-list'}, c.concept ResponseSchema = c.object {title: 'Dialogue Button', description: 'A button to be shown to the user with the dialogue.', required: ['text']}, text: {title: 'Title', description: 'The text that will be on the button', 'default': 'Okay', type: 'string', maxLength: 30} channel: c.shortString(title: 'Channel', format: 'event-channel', description: 'Channel that this event will be broadcast over, like "level:set-playing".') event: {type: 'object', title: 'Event', description: 'Event that will be broadcast when this button is pressed, like {playing: true}.'} buttonClass: c.shortString(title: 'Button Class', description: 'CSS class that will be added to the button, like "btn-primary".') i18n: {type: 'object', format: 'i18n', props: ['text'], description: 'Help translate this button'} PointSchema = c.object {title: 'Point', description: 'An {x, y} coordinate point.', format: 'point2d', default: { x:15, y:20 }}, x: {title: 'x', description: 'The x coordinate.', type: 'number'} y: {title: 'y', description: 'The y coordinate.', type: 'number'} SpriteCommandSchema = c.object {title: 'Thang Command', description: 'Make a target Thang move or say something, or select/deselect it.', required: ['id'], default: {id: 'Hero Placeholder'}}, id: thang select: {title: 'Select', description: 'Select or deselect this Thang.', type: 'boolean'} say: c.object {title: 'Say', description: 'Make this Thang say a message.', required: ['text'], default: { mood: 'explain' }}, blurb: c.shortString(title: 'Blurb', description: 'A very short message to display above this Thang\'s head. Plain text.', maxLength: 50) mood: c.shortString(title: 'Mood', description: 'The mood with which the Thang speaks.', 'enum': ['explain', 'debrief', 'congrats', 'attack', 'joke', 'tip', 'alarm']) text: {title: 'Text', description: 'A short message to display in the dialogue area. Markdown okay.', type: 'string', maxLength: 400} sound: c.object {title: 'Sound', description: 'A dialogue sound file to accompany the message.', required: ['mp3', 'ogg'] }, mp3: c.shortString(title: 'MP3', format: 'sound-file') ogg: c.shortString(title: 'OGG', format: 'sound-file') preload: {title: 'Preload', description: 'Whether to load this sound file before the level can begin (typically for the first dialogue of a level).', type: 'boolean' } responses: c.array {title: 'Buttons', description: 'An array of buttons to include with the dialogue, with which the user can respond.'}, ResponseSchema i18n: {type: 'object', format: 'i18n', props: ['blurb', 'text', 'sound'], description: 'Help translate this message'} move: c.object {title: 'Move', description: 'Tell the Thang to move.', required: ['target'], default: {target: {}, duration: 500}}, target: _.extend _.cloneDeep(PointSchema), {title: 'Target', description: 'Target point to which the Thang will move.', default: {x: 20, y: 20}} duration: {title: 'Duration', description: 'Number of milliseconds over which to move, or 0 for an instant move.', type: 'integer', minimum: 0, format: 'milliseconds'} NoteGroupSchema = c.object {title: 'Note Group', description: 'A group of notes that should be sent out as a result of this script triggering.', displayProperty: 'name'}, name: {title: 'Name', description: 'Short name describing the script, like \"Anya greets the player\", for your convenience.', type: 'string'} dom: c.object {title: 'DOM', description: 'Manipulate things in the play area DOM, outside of the level area canvas.'}, focus: c.shortString(title: 'Focus', description: 'Set the window focus to this DOM selector string.') showVictory: { title: 'Show Victory', description: 'Show the done button and maybe also the victory modal.', enum: [true, 'Done Button', 'Done Button And Modal'] # deprecate true, same as 'done_button_and_modal' } highlight: c.object {title: 'Highlight', description: 'Highlight the target DOM selector string with a big arrow.'}, target: c.shortString(title: 'Target', description: 'Target highlight element DOM selector string.') delay: {type: 'integer', minimum: 0, title: 'Delay', description: 'Show the highlight after this many milliseconds. Doesn\'t affect the dim shade cutout highlight method.'} offset: _.extend _.cloneDeep(PointSchema), {title: 'Offset', description: 'Pointing arrow tip offset in pixels from the default target.', format: null} rotation: {type: 'number', minimum: 0, title: 'Rotation', description: 'Rotation of the pointing arrow, in radians. PI / 2 points left, PI points up, etc.', format: 'radians'} sides: c.array {title: 'Sides', description: 'Which sides of the target element to point at.'}, {type: 'string', 'enum': ['left', 'right', 'top', 'bottom'], title: 'Side', description: 'A side of the target element to point at.'} lock: {title: 'Lock', description: 'Whether the interface should be locked so that the player\'s focus is on the script, or specific areas to lock.', type: ['boolean', 'array'], items: {type: 'string', enum: ['surface', 'editor', 'palette', 'hud', 'playback', 'playback-hover', 'level']}} letterbox: {type: 'boolean', title: 'Letterbox', description: 'Turn letterbox mode on or off. Disables surface and playback controls.'} playback: c.object {title: 'Playback', description: 'Control the playback of the level.'}, playing: {type: 'boolean', title: 'Set Playing', description: 'Set whether playback is playing or paused.'} scrub: c.object {title: 'Scrub', description: 'Scrub the level playback time to a certain point.', default: {offset: 2, duration: 1000, toRatio: 0.5}}, offset: {type: 'integer', title: 'Offset', description: 'Number of frames by which to adjust the scrub target time.'} duration: {type: 'integer', title: 'Duration', description: 'Number of milliseconds over which to scrub time.', minimum: 0, format: 'milliseconds'} toRatio: {type: 'number', title: 'To Progress Ratio', description: 'Set playback time to a target playback progress ratio.', minimum: 0, maximum: 1} toTime: {type: 'number', title: 'To Time', description: 'Set playback time to a target playback point, in seconds.', minimum: 0} toGoal: c.shortString(title: 'To Goal', description: 'Set playback time to when this goal was achieved. (TODO: not implemented.)') script: c.object {title: 'Script', description: 'Extra configuration for this action group.'}, duration: {type: 'integer', minimum: 0, title: 'Duration', description: 'How long this script should last in milliseconds. 0 for indefinite.', format: 'milliseconds'} skippable: {type: 'boolean', title: 'Skippable', description: 'Whether this script shouldn\'t bother firing when the player skips past all current scripts.'} beforeLoad: {type: 'boolean', title: 'Before Load', description: 'Whether this script should fire before the level is finished loading.'} sprites: c.array {title: 'Sprites', description: 'Commands to issue to Sprites on the Surface.'}, SpriteCommandSchema surface: c.object {title: 'Surface', description: 'Commands to issue to the Surface itself.'}, focus: c.object {title: 'Camera', description: 'Focus the camera on a specific point on the Surface.', format: 'viewport'}, target: {anyOf: [PointSchema, thang, {type: 'null'}], title: 'Target', description: 'Where to center the camera view.', default: {x: 0, y: 0}} zoom: {type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 64, title: 'Zoom', description: 'What zoom level to use.'} duration: {type: 'number', minimum: 0, title: 'Duration', description: 'in ms'} bounds: c.array {title: 'Boundary', maxItems: 2, minItems: 2, default: [{x: 0, y: 0}, {x: 46, y: 39}], format: 'bounds'}, PointSchema isNewDefault: {type: 'boolean', format: 'hidden', title: 'New Default', description: 'Set this as new default zoom once scripts end.'} # deprecated highlight: c.object {title: 'Highlight', description: 'Highlight specific Sprites on the Surface.'}, targets: c.array {title: 'Targets', description: 'Thang IDs of target Sprites to highlight.'}, thang delay: {type: 'integer', minimum: 0, title: 'Delay', description: 'Delay in milliseconds before the highlight appears.'} lockSelect: {type: 'boolean', title: 'Lock Select', description: 'Whether to lock Sprite selection so that the player can\'t select/deselect anything.'} sound: c.object {title: 'Sound', description: 'Commands to control sound playback.'}, suppressSelectionSounds: {type: 'boolean', title: 'Suppress Selection Sounds', description: 'Whether to suppress selection sounds made from clicking on Thangs.'} music: c.object {title: 'Music', description: 'Control music playing'}, play: {title: 'Play', type: 'boolean'} file: c.shortString(title: 'File', enum: ['/music/music_level_1', '/music/music_level_2', '/music/music_level_3', '/music/music_level_4', '/music/music_level_5']) ScriptSchema = c.object { title: 'Script' description: 'A script fires off a chain of notes to interact with the game when a certain event triggers it.' required: ['channel'] 'default': {channel: 'world:won', noteChain: []} }, id: c.shortString(title: 'ID', description: 'A unique ID that other scripts can rely on in their Happens After prereqs, for sequencing.', pattern: '^[a-zA-Z 0-9:\'"_!-]+$') # uniqueness? Ideally this would be just ids-like-this but we have a lot of legacy data. channel: c.shortString(title: 'Event', format: 'event-channel', description: 'Event channel this script might trigger for, like "world:won".') eventPrereqs: c.array {title: 'Event Checks', description: 'Logical checks on the event for this script to trigger.', format: 'event-prereqs'}, EventPrereqSchema repeats: {title: 'Repeats', description: 'Whether this script can trigger more than once during a level.', enum: [true, false, 'session']} scriptPrereqs: c.array {title: 'Happens After', description: 'Scripts that need to fire first.'}, c.shortString(title: 'ID', description: 'A unique ID of a script.') notAfter: c.array {title: 'Not After', description: 'Do not run this script if any of these scripts have run.'}, c.shortString(title: 'ID', description: 'A unique ID of a script.') noteChain: c.array {title: 'Actions', description: 'A list of things that happen when this script triggers.'}, NoteGroupSchema LevelThangSchema = c.object { title: 'Thang', description: 'Thangs are any units, doodads, or abstract things that you use to build the level. (\"Thing\" was too confusing to say.)', format: 'thang' required: ['id', 'thangType', 'components'] 'default': id: 'Boris' thangType: 'Soldier' components: [] }, id: thang # TODO: figure out if we can make this unique and how to set dynamic defaults thangType: c.objectId(links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], title: 'Thang Type', description: 'A reference to the original Thang template being configured.', format: 'thang-type') components: c.array {title: 'Components', description: 'Thangs are configured by changing the Components attached to them.', uniqueItems: true, format: 'thang-components-array'}, ThangComponentSchema # TODO: uniqueness should be based on 'original', not whole thing LevelSystemSchema = c.object { title: 'System' description: 'Configuration for a System that this Level uses.' format: 'level-system' required: ['original', 'majorVersion'] 'default': majorVersion: 0 config: {} links: [{rel: 'db', href: '/db/level.system/{(original)}/version/{(majorVersion)}'}] }, original: c.objectId(title: 'Original', description: 'A reference to the original System being configured.', format: 'hidden') config: c.object {title: 'Configuration', description: 'System-specific configuration properties.', additionalProperties: true, format: 'level-system-configuration'} majorVersion: {title: 'Major Version', description: 'Which major version of the System is being used.', type: 'integer', minimum: 0, format: 'hidden'} GeneralArticleSchema = c.object { title: 'Article' description: 'Reference to a general documentation article.' required: ['original'] format: 'latest-version-reference' 'default': original: null majorVersion: 0 links: [{rel: 'db', href: '/db/article/{(original)}/version/{(majorVersion)}'}] }, original: c.objectId(title: 'Original', description: 'A reference to the original Article.')#, format: 'hidden') # hidden? majorVersion: {title: 'Major Version', description: 'Which major version of the Article is being used.', type: 'integer', minimum: 0} #, format: 'hidden'} # hidden? IntroContentObject = { type: 'object', additionalProperties: false, properties: { type: { title: 'Content type', enum: ['cinematic', 'interactive', 'cutscene-video', 'avatarSelectionScreen'] } contentId: { oneOf: [ c.stringID(title: 'Content ID for all languages') { type: 'object', title: 'Content ID specific to languages', additionalProperties: c.stringID(), format: 'code-languages-object' } ] } } } LevelSchema = c.object { title: 'Level' description: 'A spectacular level which will delight and educate its stalwart players with the sorcery of coding.' required: ['name'] 'default': name: 'Ineffable Wizardry' description: 'This level is indescribably flarmy.' documentation: {} scripts: [] thangs: [] systems: [] victory: {} type: 'hero' goals: [ {id: 'ogres-die', name: 'Defeat the ogres.', killThangs: ['ogres'], worldEndsAfter: 3} {id: 'humans-survive', name: 'Your hero must survive.', saveThangs: ['Hero Placeholder'], howMany: 1, worldEndsAfter: 3, hiddenGoal: true} ] concepts: ['basic_syntax'] } c.extendNamedProperties LevelSchema # let's have the name be the first property _.extend LevelSchema.properties, description: {title: 'Description', description: 'A short explanation of what this level is about.', type: 'string', maxLength: 65536, format: 'markdown'} studentPlayInstructions: {title: 'Student Play Instructions', description: 'Instructions for game dev levels when students play them.', type: 'string', maxLength: 65536, format: 'markdown'} loadingTip: { type: 'string', title: 'Loading Tip', description: 'What to show for this level while it\'s loading.' } documentation: c.object {title: 'Documentation', description: 'Documentation articles relating to this level.', 'default': {specificArticles: [], generalArticles: []}}, specificArticles: c.array {title: 'Specific Articles', description: 'Specific documentation articles that live only in this level.', uniqueItems: true }, SpecificArticleSchema generalArticles: c.array {title: 'General Articles', description: 'General documentation articles that can be linked from multiple levels.', uniqueItems: true}, GeneralArticleSchema hints: c.array {title: 'Hints', description: 'Tips and tricks to help unstick a player for the level.', uniqueItems: true }, { type: 'object' properties: { body: {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this hint'} } } hintsB: c.array {title: 'HintsB', description: '2nd style of hints for a/b testing significant variations', uniqueItems: true }, { type: 'object' properties: { body: {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this hint'} } } nextLevel: { type: 'object', links: [{rel: 'extra', href: '/db/level/{($)}'}, {rel: 'db', href: '/db/level/{(original)}/version/{(majorVersion)}'}], format: 'latest-version-reference', title: 'Next Level', description: 'Reference to the next level players will play after beating this one.' } scripts: c.array {title: 'Scripts', description: 'An array of scripts that trigger based on what the player does and affect things outside of the core level simulation.'}, ScriptSchema thangs: c.array {title: 'Thangs', description: 'An array of Thangs that make up the level.' }, LevelThangSchema systems: c.array {title: 'Systems', description: 'Levels are configured by changing the Systems attached to them.', uniqueItems: true }, LevelSystemSchema # TODO: uniqueness should be based on 'original', not whole thing victory: c.object {title: 'Victory Screen'}, { body: {type: 'string', format: 'markdown', title: 'Body Text', description: 'Inserted into the Victory Modal once this level is complete. Tell the player they did a good job and what they accomplished!'}, i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this victory message'} } i18n: {type: 'object', format: 'i18n', props: ['name', 'description', 'loadingTip', 'studentPlayInstructions'], description: 'Help translate this level'} banner: {type: 'string', format: 'image-file', title: 'Banner'} goals: c.array {title: 'Goals', description: 'An array of goals which are visible to the player and can trigger scripts.'}, GoalSchema type: c.shortString(title: 'Type', description: 'What type of level this is.', 'enum': ['campaign', 'ladder', 'ladder-tutorial', 'hero', 'hero-ladder', 'hero-coop', 'course', 'course-ladder', 'game-dev', 'web-dev', 'intro']) kind: c.shortString(title: 'Kind', description: 'Similar to type, but just for our organization.', enum: ['demo', 'usage', 'mastery', 'advanced', 'practice', 'challenge']) ozariaType: c.shortString(title: 'Ozaria Level Type', description: 'Similar to type, specific to ozaria.', enum: ['practice', 'challenge', 'capstone']) terrain: c.terrainString requiresSubscription: {title: 'Requires Subscription', description: 'Whether this level is available to subscribers only.', type: 'boolean'} tasks: c.array {title: 'Tasks', description: 'Tasks to be completed for this level.'}, c.task helpVideos: c.array {title: 'Help Videos'}, c.object {default: {style: 'eccentric', url: '', free: false}}, style: c.shortString title: 'Style', description: 'Like: original, eccentric, scripted, edited, etc.' free: {type: 'boolean', title: 'Free', description: 'Whether this video is freely available to all players without a subscription.'} url: c.url {title: 'URL', description: 'Link to the video on Vimeo.'} replayable: {type: 'boolean', title: 'Replayable', description: 'Whether this (hero) level infinitely scales up its difficulty and can be beaten over and over for greater rewards.'} buildTime: {type: 'number', description: 'How long it has taken to build this level.'} practice: { type: 'boolean' } practiceThresholdMinutes: {type: 'number', description: 'Players with larger playtimes may be directed to a practice level.'} assessment: { type: ['boolean', 'string'], enum: [true, false, 'open-ended', 'cumulative'], description: 'Set to true if this is an assessment level.' } assessmentPlacement: { type: 'string', enum: ['middle', 'end'] } primerLanguage: { type: 'string', enum: ['javascript', 'python'], description: 'Programming language taught by this level.' } shareable: { title: 'Shareable', type: ['string', 'boolean'], enum: [false, true, 'project'], description: 'Whether the level is not shareable (false), shareable (true), or a sharing-encouraged project level ("project"). Make sure to use "project" for project levels so they show up correctly in the Teacher Dashboard.' } # Admin flags adventurer: { type: 'boolean' } adminOnly: { type: 'boolean' } disableSpaces: { type: ['boolean','integer'] } hidesSubmitUntilRun: { type: 'boolean' } hidesPlayButton: { type: 'boolean' } hidesRunShortcut: { type: 'boolean' } hidesHUD: { type: 'boolean' } hidesSay: { type: 'boolean' } hidesCodeToolbar: { type: 'boolean' } hidesRealTimePlayback: { type: 'boolean' } backspaceThrottle: { type: 'boolean' } lockDefaultCode: { type: ['boolean','integer'] } moveRightLoopSnippet: { type: 'boolean' } realTimeSpeedFactor: { type: 'number' } autocompleteFontSizePx: { type: 'number' } requiredCode: c.array {}, { type: 'string' } suspectCode: c.array {}, { type: 'object' properties: { name: { type: 'string' } pattern: { type: 'string' } } } autocompleteReplacement: c.array {}, { type: 'object' properties: { name: { type: 'string' } snippets: { type: 'object', title: 'Snippets', description: 'List of snippets for the respective programming languages', additionalProperties: c.codeSnippet, format: 'code-languages-object' } } } requiredGear: { type: 'object', title: 'Required Gear', description: 'Slots that should require one of a set array of items for that slot', additionalProperties: { type: 'array' items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' } }} restrictedGear: { type: 'object', title: 'Restricted Gear', description: 'Slots that should restrict all of a set array of items for that slot', additionalProperties: { type: 'array' items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' } }} requiredProperties: { type: 'array', items: {type: 'string'}, description: 'Names of properties a hero must have equipped to play.', format: 'solution-gear', title: 'Required Properties' } restrictedProperties: { type: 'array', items: {type: 'string'}, description: 'Names of properties a hero must not have equipped to play.', title: 'Restricted Properties' } recommendedHealth: { type: 'number', minimum: 0, exclusiveMinimum: true, description: 'If set, will show the recommended health to be able to beat this level with the intended main solution to the player when choosing equipment.', format: 'solution-stats', title: 'Recommended Health' } maximumHealth: { type: 'number', minimum: 0, exclusiveMinimum: true, description: 'If set, will enforce the maximum health of the hero.', title: 'Maximum Health'} allowedHeroes: { type: 'array', title: 'Allowed Heroes', description: 'Which heroes can play this level. For any hero, leave unset.', items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' }} campaign: c.shortString title: 'Campaign', description: 'Which campaign this level is part of (like "desert").', format: 'hidden' # Automatically set by campaign editor. campaignIndex: c.int title: 'Campaign Index', description: 'The 0-based index of this level in its campaign.', format: 'hidden' # Automatically set by campaign editor. scoreTypes: c.array {title: 'Score Types', description: 'What metric to show leaderboards for. Most important one first, not too many (2 is good).'}, { anyOf: [ c.scoreType, { type: 'object' title: 'Score Type Object' required: ['type'] additionalProperties: false properties: { type: c.scoreType thresholds: { type: 'object' properties: { bronze: { type: 'number' } silver: { type: 'number' } gold: { type: 'number' } } } } } ] } concepts: c.array {title: 'Programming Concepts', description: 'Which programming concepts this level covers.', uniqueItems: true, format: 'concepts-list'}, c.concept primaryConcepts: c.array {title: 'Primary Concepts', description: 'The main 1-3 concepts this level focuses on.', uniqueItems: true}, c.concept picoCTFProblem: { type: 'string', description: 'Associated picoCTF problem ID, if this is a picoCTF level' } password: { type: 'string', description: 'The password required to create a session for this level' } mirrorMatch: { type: 'boolean', description: 'Whether a multiplayer ladder arena is a mirror match' } introContent: { # valid for levels of type 'intro' title: 'Intro content', description: 'Intro content sequence', type: 'array', items: IntroContentObject } additionalGoals: c.array { title: 'Additional Goals', description: 'Goals that are added after the first regular goals are completed' }, c.object { title: 'Goals', description: 'Goals for this stage', minItems: 1, uniqueItems: true, properties: { stage: { type: 'integer', minimum: 2, title: 'Goal Stage', description: 'Which stage these additional goals are for (2 and onwards)' }, goals: c.array { title: 'Goals', description: 'An array of goals which are visible to the player and can trigger scripts.' }, GoalSchema } } isPlayedInStages: {type: 'boolean', title: 'Is Played in Stages', description: 'Is this level played in stages and other content(cinematics) is loaded in between stages'} methodsBankList: c.array {title: 'Methods Bank List'}, c.object { properties: { name: c.shortString(title: 'Name'), section: c.shortString(title: 'Methods Bank Section', pattern: '^[a-z]+$'), subSection: c.shortString(title: 'Methods Bank Sub-Section', pattern: '^[a-z]+$'), componentName: c.shortString(title: 'Level Component Name', description: 'Level Component to use for documentation in case there are multiple components with same property\'s documentation'), } } c.extendBasicProperties LevelSchema, 'level' c.extendSearchableProperties LevelSchema c.extendVersionedProperties LevelSchema, 'level' c.extendPermissionsProperties LevelSchema, 'level' c.extendPatchableProperties LevelSchema c.extendTranslationCoverageProperties LevelSchema module.exports = LevelSchema # To test: # 1: Copy the schema from http://localhost:3000/db/level/schema # 2. Open up the Treema demo page http://localhost:9090/demo.html # 3. tv4.addSchema(metaschema.id, metaschema) # 4. S = <paste big schema here> # 5. tv4.validateMultiple(S, metaschema) and look for errors
25060
c = require './../schemas' ThangComponentSchema = require './thang_component' SpecificArticleSchema = c.object() c.extendNamedProperties SpecificArticleSchema # name first SpecificArticleSchema.properties.body = {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} SpecificArticleSchema.properties.i18n = {type: 'object', format: 'i18n', props: ['name', 'body'], description: 'Help translate this article'} SpecificArticleSchema.displayProperty = 'name' side = {title: 'Side', description: 'A side.', type: 'string', 'enum': ['left', 'right', 'top', 'bottom']} thang = {title: 'Thang', description: 'The name of a Thang.', type: 'string', maxLength: 60, format: 'thang'} eventPrereqValueTypes = ['boolean', 'integer', 'number', 'null', 'string'] # not 'object' or 'array' EventPrereqSchema = c.object {title: 'Event Prerequisite', format: 'event-prereq', description: 'Script requires that the value of some property on the event triggering it to meet some prerequisite.', required: ['eventProps']}, eventProps: c.array {'default': ['thang'], format: 'event-value-chain', maxItems: 10, title: 'Event Property', description: 'A chain of keys in the event, like "thang.pos.x" to access event.thang.pos.x.'}, c.shortString(title: 'Property', description: 'A key in the event property key chain.') equalTo: c.object {type: eventPrereqValueTypes, title: '==', description: 'Script requires the event\'s property chain value to be equal to this value.'} notEqualTo: c.object {type: eventPrereqValueTypes, title: '!=', description: 'Script requires the event\'s property chain value to *not* be equal to this value.'} greaterThan: {type: 'number', title: '>', description: 'Script requires the event\'s property chain value to be greater than this value.'} greaterThanOrEqualTo: {type: 'number', title: '>=', description: 'Script requires the event\'s property chain value to be greater or equal to this value.'} lessThan: {type: 'number', title: '<', description: 'Script requires the event\'s property chain value to be less than this value.'} lessThanOrEqualTo: {type: 'number', title: '<=', description: 'Script requires the event\'s property chain value to be less than or equal to this value.'} containingString: c.shortString(title: 'Contains', description: 'Script requires the event\'s property chain value to be a string containing this string.') notContainingString: c.shortString(title: 'Does not contain', description: 'Script requires the event\'s property chain value to *not* be a string containing this string.') containingRegexp: c.shortString(title: 'Contains Regexp', description: 'Script requires the event\'s property chain value to be a string containing this regular expression.') notContainingRegexp: c.shortString(title: 'Does not contain regexp', description: 'Script requires the event\'s property chain value to *not* be a string containing this regular expression.') GoalSchema = c.object {title: 'Goal', description: 'A goal that the player can accomplish.', required: ['name', 'id']}, name: c.shortString(title: 'Name', description: 'Name of the goal that the player will see, like \"Defeat eighteen dragons\".') i18n: {type: 'object', format: 'i18n', props: ['name'], description: 'Help translate this goal'} id: c.shortString(title: 'ID', description: 'Unique identifier for this goal, like \"defeat-dragons\".', pattern: '^[a-z0-9-]+$') # unique somehow? worldEndsAfter: {title: 'World Ends After', description: 'When included, ends the world this many seconds after this goal succeeds or fails.', type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 300, default: 3} howMany: {title: 'How Many', description: 'When included, require only this many of the listed goal targets instead of all of them.', type: 'integer', minimum: 1} hiddenGoal: {title: 'Hidden', description: 'Hidden goals don\'t show up in the goals area for the player until they\'re failed. (Usually they\'re obvious, like "don\'t die".)', 'type': 'boolean' } optional: {title: 'Optional', description: 'Optional goals do not need to be completed for overallStatus to be success.', type: 'boolean'} team: c.shortString(title: 'Team', description: 'Name of the team this goal is for, if it is not for all of the playable teams.') killThangs: c.array {title: 'Kill Thangs', description: 'A list of Thang IDs the player should kill, or team names.', uniqueItems: true, minItems: 1, 'default': ['ogres']}, thang saveThangs: c.array {title: 'Save Thangs', description: 'A list of Thang IDs the player should save, or team names', uniqueItems: true, minItems: 1, 'default': ['Hero Placeholder']}, thang getToLocations: c.object {title: 'Get To Locations', description: 'Will be set off when any of the \"who\" touch any of the \"targets\"', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must get.', minItems: 1}, thang getAllToLocations: c.array {title: 'Get all to locations', description: 'Similar to getToLocations but now a specific \"who\" can have a specific \"target\", also must be used with the HowMany property for desired effect', required: ['getToLocation']}, c.object {title: '', description: ''}, getToLocation: c.object {title: 'Get To Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must get.', minItems: 1}, thang keepFromLocations: c.object {title: 'Keep From Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must not get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must not get.', minItems: 1}, thang keepAllFromLocations: c.array {title: 'Keep ALL From Locations', description: 'Similar to keepFromLocations but now a specific \"who\" can have a specific \"target\", also must be used with the HowMany property for desired effect', required: ['keepFromLocation']}, c.object {title: '', description: ''}, keepFromLocation: c.object {title: 'Keep From Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must not get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must not get.', minItems: 1}, thang leaveOffSides: c.object {title: 'Leave Off Sides', description: 'Sides of the level to get some Thangs to leave across.', required: ['who', 'sides']}, who: c.array {title: 'Who', description: 'The Thangs which must leave off the sides of the level.', minItems: 1}, thang sides: c.array {title: 'Sides', description: 'The sides off which the Thangs must leave.', minItems: 1}, side keepFromLeavingOffSides: c.object {title: 'Keep From Leaving Off Sides', description: 'Sides of the level to keep some Thangs from leaving across.', required: ['who', 'sides']}, who: c.array {title: 'Who', description: 'The Thangs which must not leave off the sides of the level.', minItems: 1}, thang sides: side, {title: 'Sides', description: 'The sides off which the Thangs must not leave.', minItems: 1}, side collectThangs: c.object {title: 'Collect', description: 'Thangs that other Thangs must collect.', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs which must collect the target items.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target items which the Thangs must collect.', minItems: 1}, thang keepFromCollectingThangs: c.object {title: 'Keep From Collecting', description: 'Thangs that the player must prevent other Thangs from collecting.', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs which must not collect the target items.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target items which the Thangs must not collect.', minItems: 1}, thang codeProblems: c.array {title: 'Code Problems', description: 'A list of Thang IDs that should not have any code problems, or team names.', uniqueItems: true, minItems: 1, 'default': ['humans']}, thang linesOfCode: {title: 'Lines of Code', description: 'A mapping of Thang IDs or teams to how many many lines of code should be allowed (well, statements).', type: 'object', default: {humans: 10}, additionalProperties: {type: 'integer', description: 'How many lines to allow for this Thang.'}} html: c.object {title: 'HTML', description: 'A jQuery selector and what its result should be'}, selector: {type: 'string', description: 'jQuery selector to run on the user HTML, like "h1:first-child"'} valueChecks: c.array {title: 'Value checks', description: 'Logical checks on the resulting value for this goal to pass.', format: 'event-prereqs'}, EventPrereqSchema concepts: c.array {title: 'Target Concepts', description: 'Which programming concepts this goal demonstrates.', uniqueItems: true, format: 'concepts-list'}, c.concept ResponseSchema = c.object {title: 'Dialogue Button', description: 'A button to be shown to the user with the dialogue.', required: ['text']}, text: {title: 'Title', description: 'The text that will be on the button', 'default': 'Okay', type: 'string', maxLength: 30} channel: c.shortString(title: 'Channel', format: 'event-channel', description: 'Channel that this event will be broadcast over, like "level:set-playing".') event: {type: 'object', title: 'Event', description: 'Event that will be broadcast when this button is pressed, like {playing: true}.'} buttonClass: c.shortString(title: 'Button Class', description: 'CSS class that will be added to the button, like "btn-primary".') i18n: {type: 'object', format: 'i18n', props: ['text'], description: 'Help translate this button'} PointSchema = c.object {title: 'Point', description: 'An {x, y} coordinate point.', format: 'point2d', default: { x:15, y:20 }}, x: {title: 'x', description: 'The x coordinate.', type: 'number'} y: {title: 'y', description: 'The y coordinate.', type: 'number'} SpriteCommandSchema = c.object {title: 'Thang Command', description: 'Make a target Thang move or say something, or select/deselect it.', required: ['id'], default: {id: 'Hero Placeholder'}}, id: thang select: {title: 'Select', description: 'Select or deselect this Thang.', type: 'boolean'} say: c.object {title: 'Say', description: 'Make this Thang say a message.', required: ['text'], default: { mood: 'explain' }}, blurb: c.shortString(title: 'Blurb', description: 'A very short message to display above this Thang\'s head. Plain text.', maxLength: 50) mood: c.shortString(title: 'Mood', description: 'The mood with which the Thang speaks.', 'enum': ['explain', 'debrief', 'congrats', 'attack', 'joke', 'tip', 'alarm']) text: {title: 'Text', description: 'A short message to display in the dialogue area. Markdown okay.', type: 'string', maxLength: 400} sound: c.object {title: 'Sound', description: 'A dialogue sound file to accompany the message.', required: ['mp3', 'ogg'] }, mp3: c.shortString(title: 'MP3', format: 'sound-file') ogg: c.shortString(title: 'OGG', format: 'sound-file') preload: {title: 'Preload', description: 'Whether to load this sound file before the level can begin (typically for the first dialogue of a level).', type: 'boolean' } responses: c.array {title: 'Buttons', description: 'An array of buttons to include with the dialogue, with which the user can respond.'}, ResponseSchema i18n: {type: 'object', format: 'i18n', props: ['blurb', 'text', 'sound'], description: 'Help translate this message'} move: c.object {title: 'Move', description: 'Tell the Thang to move.', required: ['target'], default: {target: {}, duration: 500}}, target: _.extend _.cloneDeep(PointSchema), {title: 'Target', description: 'Target point to which the Thang will move.', default: {x: 20, y: 20}} duration: {title: 'Duration', description: 'Number of milliseconds over which to move, or 0 for an instant move.', type: 'integer', minimum: 0, format: 'milliseconds'} NoteGroupSchema = c.object {title: 'Note Group', description: 'A group of notes that should be sent out as a result of this script triggering.', displayProperty: 'name'}, name: {title: 'Name', description: 'Short name describing the script, like \"Anya greets the player\", for your convenience.', type: 'string'} dom: c.object {title: 'DOM', description: 'Manipulate things in the play area DOM, outside of the level area canvas.'}, focus: c.shortString(title: 'Focus', description: 'Set the window focus to this DOM selector string.') showVictory: { title: 'Show Victory', description: 'Show the done button and maybe also the victory modal.', enum: [true, 'Done Button', 'Done Button And Modal'] # deprecate true, same as 'done_button_and_modal' } highlight: c.object {title: 'Highlight', description: 'Highlight the target DOM selector string with a big arrow.'}, target: c.shortString(title: 'Target', description: 'Target highlight element DOM selector string.') delay: {type: 'integer', minimum: 0, title: 'Delay', description: 'Show the highlight after this many milliseconds. Doesn\'t affect the dim shade cutout highlight method.'} offset: _.extend _.cloneDeep(PointSchema), {title: 'Offset', description: 'Pointing arrow tip offset in pixels from the default target.', format: null} rotation: {type: 'number', minimum: 0, title: 'Rotation', description: 'Rotation of the pointing arrow, in radians. PI / 2 points left, PI points up, etc.', format: 'radians'} sides: c.array {title: 'Sides', description: 'Which sides of the target element to point at.'}, {type: 'string', 'enum': ['left', 'right', 'top', 'bottom'], title: 'Side', description: 'A side of the target element to point at.'} lock: {title: 'Lock', description: 'Whether the interface should be locked so that the player\'s focus is on the script, or specific areas to lock.', type: ['boolean', 'array'], items: {type: 'string', enum: ['surface', 'editor', 'palette', 'hud', 'playback', 'playback-hover', 'level']}} letterbox: {type: 'boolean', title: 'Letterbox', description: 'Turn letterbox mode on or off. Disables surface and playback controls.'} playback: c.object {title: 'Playback', description: 'Control the playback of the level.'}, playing: {type: 'boolean', title: 'Set Playing', description: 'Set whether playback is playing or paused.'} scrub: c.object {title: 'Scrub', description: 'Scrub the level playback time to a certain point.', default: {offset: 2, duration: 1000, toRatio: 0.5}}, offset: {type: 'integer', title: 'Offset', description: 'Number of frames by which to adjust the scrub target time.'} duration: {type: 'integer', title: 'Duration', description: 'Number of milliseconds over which to scrub time.', minimum: 0, format: 'milliseconds'} toRatio: {type: 'number', title: 'To Progress Ratio', description: 'Set playback time to a target playback progress ratio.', minimum: 0, maximum: 1} toTime: {type: 'number', title: 'To Time', description: 'Set playback time to a target playback point, in seconds.', minimum: 0} toGoal: c.shortString(title: 'To Goal', description: 'Set playback time to when this goal was achieved. (TODO: not implemented.)') script: c.object {title: 'Script', description: 'Extra configuration for this action group.'}, duration: {type: 'integer', minimum: 0, title: 'Duration', description: 'How long this script should last in milliseconds. 0 for indefinite.', format: 'milliseconds'} skippable: {type: 'boolean', title: 'Skippable', description: 'Whether this script shouldn\'t bother firing when the player skips past all current scripts.'} beforeLoad: {type: 'boolean', title: 'Before Load', description: 'Whether this script should fire before the level is finished loading.'} sprites: c.array {title: 'Sprites', description: 'Commands to issue to Sprites on the Surface.'}, SpriteCommandSchema surface: c.object {title: 'Surface', description: 'Commands to issue to the Surface itself.'}, focus: c.object {title: 'Camera', description: 'Focus the camera on a specific point on the Surface.', format: 'viewport'}, target: {anyOf: [PointSchema, thang, {type: 'null'}], title: 'Target', description: 'Where to center the camera view.', default: {x: 0, y: 0}} zoom: {type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 64, title: 'Zoom', description: 'What zoom level to use.'} duration: {type: 'number', minimum: 0, title: 'Duration', description: 'in ms'} bounds: c.array {title: 'Boundary', maxItems: 2, minItems: 2, default: [{x: 0, y: 0}, {x: 46, y: 39}], format: 'bounds'}, PointSchema isNewDefault: {type: 'boolean', format: 'hidden', title: 'New Default', description: 'Set this as new default zoom once scripts end.'} # deprecated highlight: c.object {title: 'Highlight', description: 'Highlight specific Sprites on the Surface.'}, targets: c.array {title: 'Targets', description: 'Thang IDs of target Sprites to highlight.'}, thang delay: {type: 'integer', minimum: 0, title: 'Delay', description: 'Delay in milliseconds before the highlight appears.'} lockSelect: {type: 'boolean', title: 'Lock Select', description: 'Whether to lock Sprite selection so that the player can\'t select/deselect anything.'} sound: c.object {title: 'Sound', description: 'Commands to control sound playback.'}, suppressSelectionSounds: {type: 'boolean', title: 'Suppress Selection Sounds', description: 'Whether to suppress selection sounds made from clicking on Thangs.'} music: c.object {title: 'Music', description: 'Control music playing'}, play: {title: 'Play', type: 'boolean'} file: c.shortString(title: 'File', enum: ['/music/music_level_1', '/music/music_level_2', '/music/music_level_3', '/music/music_level_4', '/music/music_level_5']) ScriptSchema = c.object { title: 'Script' description: 'A script fires off a chain of notes to interact with the game when a certain event triggers it.' required: ['channel'] 'default': {channel: 'world:won', noteChain: []} }, id: c.shortString(title: 'ID', description: 'A unique ID that other scripts can rely on in their Happens After prereqs, for sequencing.', pattern: '^[a-zA-Z 0-9:\'"_!-]+$') # uniqueness? Ideally this would be just ids-like-this but we have a lot of legacy data. channel: c.shortString(title: 'Event', format: 'event-channel', description: 'Event channel this script might trigger for, like "world:won".') eventPrereqs: c.array {title: 'Event Checks', description: 'Logical checks on the event for this script to trigger.', format: 'event-prereqs'}, EventPrereqSchema repeats: {title: 'Repeats', description: 'Whether this script can trigger more than once during a level.', enum: [true, false, 'session']} scriptPrereqs: c.array {title: 'Happens After', description: 'Scripts that need to fire first.'}, c.shortString(title: 'ID', description: 'A unique ID of a script.') notAfter: c.array {title: 'Not After', description: 'Do not run this script if any of these scripts have run.'}, c.shortString(title: 'ID', description: 'A unique ID of a script.') noteChain: c.array {title: 'Actions', description: 'A list of things that happen when this script triggers.'}, NoteGroupSchema LevelThangSchema = c.object { title: 'Thang', description: 'Thangs are any units, doodads, or abstract things that you use to build the level. (\"Thing\" was too confusing to say.)', format: 'thang' required: ['id', 'thangType', 'components'] 'default': id: '<NAME>' thangType: 'Soldier' components: [] }, id: thang # TODO: figure out if we can make this unique and how to set dynamic defaults thangType: c.objectId(links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], title: 'Thang Type', description: 'A reference to the original Thang template being configured.', format: 'thang-type') components: c.array {title: 'Components', description: 'Thangs are configured by changing the Components attached to them.', uniqueItems: true, format: 'thang-components-array'}, ThangComponentSchema # TODO: uniqueness should be based on 'original', not whole thing LevelSystemSchema = c.object { title: 'System' description: 'Configuration for a System that this Level uses.' format: 'level-system' required: ['original', 'majorVersion'] 'default': majorVersion: 0 config: {} links: [{rel: 'db', href: '/db/level.system/{(original)}/version/{(majorVersion)}'}] }, original: c.objectId(title: 'Original', description: 'A reference to the original System being configured.', format: 'hidden') config: c.object {title: 'Configuration', description: 'System-specific configuration properties.', additionalProperties: true, format: 'level-system-configuration'} majorVersion: {title: 'Major Version', description: 'Which major version of the System is being used.', type: 'integer', minimum: 0, format: 'hidden'} GeneralArticleSchema = c.object { title: 'Article' description: 'Reference to a general documentation article.' required: ['original'] format: 'latest-version-reference' 'default': original: null majorVersion: 0 links: [{rel: 'db', href: '/db/article/{(original)}/version/{(majorVersion)}'}] }, original: c.objectId(title: 'Original', description: 'A reference to the original Article.')#, format: 'hidden') # hidden? majorVersion: {title: 'Major Version', description: 'Which major version of the Article is being used.', type: 'integer', minimum: 0} #, format: 'hidden'} # hidden? IntroContentObject = { type: 'object', additionalProperties: false, properties: { type: { title: 'Content type', enum: ['cinematic', 'interactive', 'cutscene-video', 'avatarSelectionScreen'] } contentId: { oneOf: [ c.stringID(title: 'Content ID for all languages') { type: 'object', title: 'Content ID specific to languages', additionalProperties: c.stringID(), format: 'code-languages-object' } ] } } } LevelSchema = c.object { title: 'Level' description: 'A spectacular level which will delight and educate its stalwart players with the sorcery of coding.' required: ['name'] 'default': name: 'Ineffable Wizardry' description: 'This level is indescribably flarmy.' documentation: {} scripts: [] thangs: [] systems: [] victory: {} type: 'hero' goals: [ {id: 'ogres-die', name: 'Defeat the ogres.', killThangs: ['ogres'], worldEndsAfter: 3} {id: 'humans-survive', name: 'Your hero must survive.', saveThangs: ['Hero Placeholder'], howMany: 1, worldEndsAfter: 3, hiddenGoal: true} ] concepts: ['basic_syntax'] } c.extendNamedProperties LevelSchema # let's have the name be the first property _.extend LevelSchema.properties, description: {title: 'Description', description: 'A short explanation of what this level is about.', type: 'string', maxLength: 65536, format: 'markdown'} studentPlayInstructions: {title: 'Student Play Instructions', description: 'Instructions for game dev levels when students play them.', type: 'string', maxLength: 65536, format: 'markdown'} loadingTip: { type: 'string', title: 'Loading Tip', description: 'What to show for this level while it\'s loading.' } documentation: c.object {title: 'Documentation', description: 'Documentation articles relating to this level.', 'default': {specificArticles: [], generalArticles: []}}, specificArticles: c.array {title: 'Specific Articles', description: 'Specific documentation articles that live only in this level.', uniqueItems: true }, SpecificArticleSchema generalArticles: c.array {title: 'General Articles', description: 'General documentation articles that can be linked from multiple levels.', uniqueItems: true}, GeneralArticleSchema hints: c.array {title: 'Hints', description: 'Tips and tricks to help unstick a player for the level.', uniqueItems: true }, { type: 'object' properties: { body: {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this hint'} } } hintsB: c.array {title: 'HintsB', description: '2nd style of hints for a/b testing significant variations', uniqueItems: true }, { type: 'object' properties: { body: {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this hint'} } } nextLevel: { type: 'object', links: [{rel: 'extra', href: '/db/level/{($)}'}, {rel: 'db', href: '/db/level/{(original)}/version/{(majorVersion)}'}], format: 'latest-version-reference', title: 'Next Level', description: 'Reference to the next level players will play after beating this one.' } scripts: c.array {title: 'Scripts', description: 'An array of scripts that trigger based on what the player does and affect things outside of the core level simulation.'}, ScriptSchema thangs: c.array {title: 'Thangs', description: 'An array of Thangs that make up the level.' }, LevelThangSchema systems: c.array {title: 'Systems', description: 'Levels are configured by changing the Systems attached to them.', uniqueItems: true }, LevelSystemSchema # TODO: uniqueness should be based on 'original', not whole thing victory: c.object {title: 'Victory Screen'}, { body: {type: 'string', format: 'markdown', title: 'Body Text', description: 'Inserted into the Victory Modal once this level is complete. Tell the player they did a good job and what they accomplished!'}, i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this victory message'} } i18n: {type: 'object', format: 'i18n', props: ['name', 'description', 'loadingTip', 'studentPlayInstructions'], description: 'Help translate this level'} banner: {type: 'string', format: 'image-file', title: 'Banner'} goals: c.array {title: 'Goals', description: 'An array of goals which are visible to the player and can trigger scripts.'}, GoalSchema type: c.shortString(title: 'Type', description: 'What type of level this is.', 'enum': ['campaign', 'ladder', 'ladder-tutorial', 'hero', 'hero-ladder', 'hero-coop', 'course', 'course-ladder', 'game-dev', 'web-dev', 'intro']) kind: c.shortString(title: 'Kind', description: 'Similar to type, but just for our organization.', enum: ['demo', 'usage', 'mastery', 'advanced', 'practice', 'challenge']) ozariaType: c.shortString(title: 'Ozaria Level Type', description: 'Similar to type, specific to ozaria.', enum: ['practice', 'challenge', 'capstone']) terrain: c.terrainString requiresSubscription: {title: 'Requires Subscription', description: 'Whether this level is available to subscribers only.', type: 'boolean'} tasks: c.array {title: 'Tasks', description: 'Tasks to be completed for this level.'}, c.task helpVideos: c.array {title: 'Help Videos'}, c.object {default: {style: 'eccentric', url: '', free: false}}, style: c.shortString title: 'Style', description: 'Like: original, eccentric, scripted, edited, etc.' free: {type: 'boolean', title: 'Free', description: 'Whether this video is freely available to all players without a subscription.'} url: c.url {title: 'URL', description: 'Link to the video on Vimeo.'} replayable: {type: 'boolean', title: 'Replayable', description: 'Whether this (hero) level infinitely scales up its difficulty and can be beaten over and over for greater rewards.'} buildTime: {type: 'number', description: 'How long it has taken to build this level.'} practice: { type: 'boolean' } practiceThresholdMinutes: {type: 'number', description: 'Players with larger playtimes may be directed to a practice level.'} assessment: { type: ['boolean', 'string'], enum: [true, false, 'open-ended', 'cumulative'], description: 'Set to true if this is an assessment level.' } assessmentPlacement: { type: 'string', enum: ['middle', 'end'] } primerLanguage: { type: 'string', enum: ['javascript', 'python'], description: 'Programming language taught by this level.' } shareable: { title: 'Shareable', type: ['string', 'boolean'], enum: [false, true, 'project'], description: 'Whether the level is not shareable (false), shareable (true), or a sharing-encouraged project level ("project"). Make sure to use "project" for project levels so they show up correctly in the Teacher Dashboard.' } # Admin flags adventurer: { type: 'boolean' } adminOnly: { type: 'boolean' } disableSpaces: { type: ['boolean','integer'] } hidesSubmitUntilRun: { type: 'boolean' } hidesPlayButton: { type: 'boolean' } hidesRunShortcut: { type: 'boolean' } hidesHUD: { type: 'boolean' } hidesSay: { type: 'boolean' } hidesCodeToolbar: { type: 'boolean' } hidesRealTimePlayback: { type: 'boolean' } backspaceThrottle: { type: 'boolean' } lockDefaultCode: { type: ['boolean','integer'] } moveRightLoopSnippet: { type: 'boolean' } realTimeSpeedFactor: { type: 'number' } autocompleteFontSizePx: { type: 'number' } requiredCode: c.array {}, { type: 'string' } suspectCode: c.array {}, { type: 'object' properties: { name: { type: 'string' } pattern: { type: 'string' } } } autocompleteReplacement: c.array {}, { type: 'object' properties: { name: { type: 'string' } snippets: { type: 'object', title: 'Snippets', description: 'List of snippets for the respective programming languages', additionalProperties: c.codeSnippet, format: 'code-languages-object' } } } requiredGear: { type: 'object', title: 'Required Gear', description: 'Slots that should require one of a set array of items for that slot', additionalProperties: { type: 'array' items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' } }} restrictedGear: { type: 'object', title: 'Restricted Gear', description: 'Slots that should restrict all of a set array of items for that slot', additionalProperties: { type: 'array' items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' } }} requiredProperties: { type: 'array', items: {type: 'string'}, description: 'Names of properties a hero must have equipped to play.', format: 'solution-gear', title: 'Required Properties' } restrictedProperties: { type: 'array', items: {type: 'string'}, description: 'Names of properties a hero must not have equipped to play.', title: 'Restricted Properties' } recommendedHealth: { type: 'number', minimum: 0, exclusiveMinimum: true, description: 'If set, will show the recommended health to be able to beat this level with the intended main solution to the player when choosing equipment.', format: 'solution-stats', title: 'Recommended Health' } maximumHealth: { type: 'number', minimum: 0, exclusiveMinimum: true, description: 'If set, will enforce the maximum health of the hero.', title: 'Maximum Health'} allowedHeroes: { type: 'array', title: 'Allowed Heroes', description: 'Which heroes can play this level. For any hero, leave unset.', items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' }} campaign: c.shortString title: 'Campaign', description: 'Which campaign this level is part of (like "desert").', format: 'hidden' # Automatically set by campaign editor. campaignIndex: c.int title: 'Campaign Index', description: 'The 0-based index of this level in its campaign.', format: 'hidden' # Automatically set by campaign editor. scoreTypes: c.array {title: 'Score Types', description: 'What metric to show leaderboards for. Most important one first, not too many (2 is good).'}, { anyOf: [ c.scoreType, { type: 'object' title: 'Score Type Object' required: ['type'] additionalProperties: false properties: { type: c.scoreType thresholds: { type: 'object' properties: { bronze: { type: 'number' } silver: { type: 'number' } gold: { type: 'number' } } } } } ] } concepts: c.array {title: 'Programming Concepts', description: 'Which programming concepts this level covers.', uniqueItems: true, format: 'concepts-list'}, c.concept primaryConcepts: c.array {title: 'Primary Concepts', description: 'The main 1-3 concepts this level focuses on.', uniqueItems: true}, c.concept picoCTFProblem: { type: 'string', description: 'Associated picoCTF problem ID, if this is a picoCTF level' } password: { type: 'string', description: 'The password required to create a session for this level' } mirrorMatch: { type: 'boolean', description: 'Whether a multiplayer ladder arena is a mirror match' } introContent: { # valid for levels of type 'intro' title: 'Intro content', description: 'Intro content sequence', type: 'array', items: IntroContentObject } additionalGoals: c.array { title: 'Additional Goals', description: 'Goals that are added after the first regular goals are completed' }, c.object { title: 'Goals', description: 'Goals for this stage', minItems: 1, uniqueItems: true, properties: { stage: { type: 'integer', minimum: 2, title: 'Goal Stage', description: 'Which stage these additional goals are for (2 and onwards)' }, goals: c.array { title: 'Goals', description: 'An array of goals which are visible to the player and can trigger scripts.' }, GoalSchema } } isPlayedInStages: {type: 'boolean', title: 'Is Played in Stages', description: 'Is this level played in stages and other content(cinematics) is loaded in between stages'} methodsBankList: c.array {title: 'Methods Bank List'}, c.object { properties: { name: c.shortString(title: 'Name'), section: c.shortString(title: 'Methods Bank Section', pattern: '^[a-z]+$'), subSection: c.shortString(title: 'Methods Bank Sub-Section', pattern: '^[a-z]+$'), componentName: c.shortString(title: 'Level Component Name', description: 'Level Component to use for documentation in case there are multiple components with same property\'s documentation'), } } c.extendBasicProperties LevelSchema, 'level' c.extendSearchableProperties LevelSchema c.extendVersionedProperties LevelSchema, 'level' c.extendPermissionsProperties LevelSchema, 'level' c.extendPatchableProperties LevelSchema c.extendTranslationCoverageProperties LevelSchema module.exports = LevelSchema # To test: # 1: Copy the schema from http://localhost:3000/db/level/schema # 2. Open up the Treema demo page http://localhost:9090/demo.html # 3. tv4.addSchema(metaschema.id, metaschema) # 4. S = <paste big schema here> # 5. tv4.validateMultiple(S, metaschema) and look for errors
true
c = require './../schemas' ThangComponentSchema = require './thang_component' SpecificArticleSchema = c.object() c.extendNamedProperties SpecificArticleSchema # name first SpecificArticleSchema.properties.body = {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} SpecificArticleSchema.properties.i18n = {type: 'object', format: 'i18n', props: ['name', 'body'], description: 'Help translate this article'} SpecificArticleSchema.displayProperty = 'name' side = {title: 'Side', description: 'A side.', type: 'string', 'enum': ['left', 'right', 'top', 'bottom']} thang = {title: 'Thang', description: 'The name of a Thang.', type: 'string', maxLength: 60, format: 'thang'} eventPrereqValueTypes = ['boolean', 'integer', 'number', 'null', 'string'] # not 'object' or 'array' EventPrereqSchema = c.object {title: 'Event Prerequisite', format: 'event-prereq', description: 'Script requires that the value of some property on the event triggering it to meet some prerequisite.', required: ['eventProps']}, eventProps: c.array {'default': ['thang'], format: 'event-value-chain', maxItems: 10, title: 'Event Property', description: 'A chain of keys in the event, like "thang.pos.x" to access event.thang.pos.x.'}, c.shortString(title: 'Property', description: 'A key in the event property key chain.') equalTo: c.object {type: eventPrereqValueTypes, title: '==', description: 'Script requires the event\'s property chain value to be equal to this value.'} notEqualTo: c.object {type: eventPrereqValueTypes, title: '!=', description: 'Script requires the event\'s property chain value to *not* be equal to this value.'} greaterThan: {type: 'number', title: '>', description: 'Script requires the event\'s property chain value to be greater than this value.'} greaterThanOrEqualTo: {type: 'number', title: '>=', description: 'Script requires the event\'s property chain value to be greater or equal to this value.'} lessThan: {type: 'number', title: '<', description: 'Script requires the event\'s property chain value to be less than this value.'} lessThanOrEqualTo: {type: 'number', title: '<=', description: 'Script requires the event\'s property chain value to be less than or equal to this value.'} containingString: c.shortString(title: 'Contains', description: 'Script requires the event\'s property chain value to be a string containing this string.') notContainingString: c.shortString(title: 'Does not contain', description: 'Script requires the event\'s property chain value to *not* be a string containing this string.') containingRegexp: c.shortString(title: 'Contains Regexp', description: 'Script requires the event\'s property chain value to be a string containing this regular expression.') notContainingRegexp: c.shortString(title: 'Does not contain regexp', description: 'Script requires the event\'s property chain value to *not* be a string containing this regular expression.') GoalSchema = c.object {title: 'Goal', description: 'A goal that the player can accomplish.', required: ['name', 'id']}, name: c.shortString(title: 'Name', description: 'Name of the goal that the player will see, like \"Defeat eighteen dragons\".') i18n: {type: 'object', format: 'i18n', props: ['name'], description: 'Help translate this goal'} id: c.shortString(title: 'ID', description: 'Unique identifier for this goal, like \"defeat-dragons\".', pattern: '^[a-z0-9-]+$') # unique somehow? worldEndsAfter: {title: 'World Ends After', description: 'When included, ends the world this many seconds after this goal succeeds or fails.', type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 300, default: 3} howMany: {title: 'How Many', description: 'When included, require only this many of the listed goal targets instead of all of them.', type: 'integer', minimum: 1} hiddenGoal: {title: 'Hidden', description: 'Hidden goals don\'t show up in the goals area for the player until they\'re failed. (Usually they\'re obvious, like "don\'t die".)', 'type': 'boolean' } optional: {title: 'Optional', description: 'Optional goals do not need to be completed for overallStatus to be success.', type: 'boolean'} team: c.shortString(title: 'Team', description: 'Name of the team this goal is for, if it is not for all of the playable teams.') killThangs: c.array {title: 'Kill Thangs', description: 'A list of Thang IDs the player should kill, or team names.', uniqueItems: true, minItems: 1, 'default': ['ogres']}, thang saveThangs: c.array {title: 'Save Thangs', description: 'A list of Thang IDs the player should save, or team names', uniqueItems: true, minItems: 1, 'default': ['Hero Placeholder']}, thang getToLocations: c.object {title: 'Get To Locations', description: 'Will be set off when any of the \"who\" touch any of the \"targets\"', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must get.', minItems: 1}, thang getAllToLocations: c.array {title: 'Get all to locations', description: 'Similar to getToLocations but now a specific \"who\" can have a specific \"target\", also must be used with the HowMany property for desired effect', required: ['getToLocation']}, c.object {title: '', description: ''}, getToLocation: c.object {title: 'Get To Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must get.', minItems: 1}, thang keepFromLocations: c.object {title: 'Keep From Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must not get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must not get.', minItems: 1}, thang keepAllFromLocations: c.array {title: 'Keep ALL From Locations', description: 'Similar to keepFromLocations but now a specific \"who\" can have a specific \"target\", also must be used with the HowMany property for desired effect', required: ['keepFromLocation']}, c.object {title: '', description: ''}, keepFromLocation: c.object {title: 'Keep From Locations', description: 'TODO: explain', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs who must not get to the target locations.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target locations to which the Thangs must not get.', minItems: 1}, thang leaveOffSides: c.object {title: 'Leave Off Sides', description: 'Sides of the level to get some Thangs to leave across.', required: ['who', 'sides']}, who: c.array {title: 'Who', description: 'The Thangs which must leave off the sides of the level.', minItems: 1}, thang sides: c.array {title: 'Sides', description: 'The sides off which the Thangs must leave.', minItems: 1}, side keepFromLeavingOffSides: c.object {title: 'Keep From Leaving Off Sides', description: 'Sides of the level to keep some Thangs from leaving across.', required: ['who', 'sides']}, who: c.array {title: 'Who', description: 'The Thangs which must not leave off the sides of the level.', minItems: 1}, thang sides: side, {title: 'Sides', description: 'The sides off which the Thangs must not leave.', minItems: 1}, side collectThangs: c.object {title: 'Collect', description: 'Thangs that other Thangs must collect.', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs which must collect the target items.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target items which the Thangs must collect.', minItems: 1}, thang keepFromCollectingThangs: c.object {title: 'Keep From Collecting', description: 'Thangs that the player must prevent other Thangs from collecting.', required: ['who', 'targets']}, who: c.array {title: 'Who', description: 'The Thangs which must not collect the target items.', minItems: 1}, thang targets: c.array {title: 'Targets', description: 'The target items which the Thangs must not collect.', minItems: 1}, thang codeProblems: c.array {title: 'Code Problems', description: 'A list of Thang IDs that should not have any code problems, or team names.', uniqueItems: true, minItems: 1, 'default': ['humans']}, thang linesOfCode: {title: 'Lines of Code', description: 'A mapping of Thang IDs or teams to how many many lines of code should be allowed (well, statements).', type: 'object', default: {humans: 10}, additionalProperties: {type: 'integer', description: 'How many lines to allow for this Thang.'}} html: c.object {title: 'HTML', description: 'A jQuery selector and what its result should be'}, selector: {type: 'string', description: 'jQuery selector to run on the user HTML, like "h1:first-child"'} valueChecks: c.array {title: 'Value checks', description: 'Logical checks on the resulting value for this goal to pass.', format: 'event-prereqs'}, EventPrereqSchema concepts: c.array {title: 'Target Concepts', description: 'Which programming concepts this goal demonstrates.', uniqueItems: true, format: 'concepts-list'}, c.concept ResponseSchema = c.object {title: 'Dialogue Button', description: 'A button to be shown to the user with the dialogue.', required: ['text']}, text: {title: 'Title', description: 'The text that will be on the button', 'default': 'Okay', type: 'string', maxLength: 30} channel: c.shortString(title: 'Channel', format: 'event-channel', description: 'Channel that this event will be broadcast over, like "level:set-playing".') event: {type: 'object', title: 'Event', description: 'Event that will be broadcast when this button is pressed, like {playing: true}.'} buttonClass: c.shortString(title: 'Button Class', description: 'CSS class that will be added to the button, like "btn-primary".') i18n: {type: 'object', format: 'i18n', props: ['text'], description: 'Help translate this button'} PointSchema = c.object {title: 'Point', description: 'An {x, y} coordinate point.', format: 'point2d', default: { x:15, y:20 }}, x: {title: 'x', description: 'The x coordinate.', type: 'number'} y: {title: 'y', description: 'The y coordinate.', type: 'number'} SpriteCommandSchema = c.object {title: 'Thang Command', description: 'Make a target Thang move or say something, or select/deselect it.', required: ['id'], default: {id: 'Hero Placeholder'}}, id: thang select: {title: 'Select', description: 'Select or deselect this Thang.', type: 'boolean'} say: c.object {title: 'Say', description: 'Make this Thang say a message.', required: ['text'], default: { mood: 'explain' }}, blurb: c.shortString(title: 'Blurb', description: 'A very short message to display above this Thang\'s head. Plain text.', maxLength: 50) mood: c.shortString(title: 'Mood', description: 'The mood with which the Thang speaks.', 'enum': ['explain', 'debrief', 'congrats', 'attack', 'joke', 'tip', 'alarm']) text: {title: 'Text', description: 'A short message to display in the dialogue area. Markdown okay.', type: 'string', maxLength: 400} sound: c.object {title: 'Sound', description: 'A dialogue sound file to accompany the message.', required: ['mp3', 'ogg'] }, mp3: c.shortString(title: 'MP3', format: 'sound-file') ogg: c.shortString(title: 'OGG', format: 'sound-file') preload: {title: 'Preload', description: 'Whether to load this sound file before the level can begin (typically for the first dialogue of a level).', type: 'boolean' } responses: c.array {title: 'Buttons', description: 'An array of buttons to include with the dialogue, with which the user can respond.'}, ResponseSchema i18n: {type: 'object', format: 'i18n', props: ['blurb', 'text', 'sound'], description: 'Help translate this message'} move: c.object {title: 'Move', description: 'Tell the Thang to move.', required: ['target'], default: {target: {}, duration: 500}}, target: _.extend _.cloneDeep(PointSchema), {title: 'Target', description: 'Target point to which the Thang will move.', default: {x: 20, y: 20}} duration: {title: 'Duration', description: 'Number of milliseconds over which to move, or 0 for an instant move.', type: 'integer', minimum: 0, format: 'milliseconds'} NoteGroupSchema = c.object {title: 'Note Group', description: 'A group of notes that should be sent out as a result of this script triggering.', displayProperty: 'name'}, name: {title: 'Name', description: 'Short name describing the script, like \"Anya greets the player\", for your convenience.', type: 'string'} dom: c.object {title: 'DOM', description: 'Manipulate things in the play area DOM, outside of the level area canvas.'}, focus: c.shortString(title: 'Focus', description: 'Set the window focus to this DOM selector string.') showVictory: { title: 'Show Victory', description: 'Show the done button and maybe also the victory modal.', enum: [true, 'Done Button', 'Done Button And Modal'] # deprecate true, same as 'done_button_and_modal' } highlight: c.object {title: 'Highlight', description: 'Highlight the target DOM selector string with a big arrow.'}, target: c.shortString(title: 'Target', description: 'Target highlight element DOM selector string.') delay: {type: 'integer', minimum: 0, title: 'Delay', description: 'Show the highlight after this many milliseconds. Doesn\'t affect the dim shade cutout highlight method.'} offset: _.extend _.cloneDeep(PointSchema), {title: 'Offset', description: 'Pointing arrow tip offset in pixels from the default target.', format: null} rotation: {type: 'number', minimum: 0, title: 'Rotation', description: 'Rotation of the pointing arrow, in radians. PI / 2 points left, PI points up, etc.', format: 'radians'} sides: c.array {title: 'Sides', description: 'Which sides of the target element to point at.'}, {type: 'string', 'enum': ['left', 'right', 'top', 'bottom'], title: 'Side', description: 'A side of the target element to point at.'} lock: {title: 'Lock', description: 'Whether the interface should be locked so that the player\'s focus is on the script, or specific areas to lock.', type: ['boolean', 'array'], items: {type: 'string', enum: ['surface', 'editor', 'palette', 'hud', 'playback', 'playback-hover', 'level']}} letterbox: {type: 'boolean', title: 'Letterbox', description: 'Turn letterbox mode on or off. Disables surface and playback controls.'} playback: c.object {title: 'Playback', description: 'Control the playback of the level.'}, playing: {type: 'boolean', title: 'Set Playing', description: 'Set whether playback is playing or paused.'} scrub: c.object {title: 'Scrub', description: 'Scrub the level playback time to a certain point.', default: {offset: 2, duration: 1000, toRatio: 0.5}}, offset: {type: 'integer', title: 'Offset', description: 'Number of frames by which to adjust the scrub target time.'} duration: {type: 'integer', title: 'Duration', description: 'Number of milliseconds over which to scrub time.', minimum: 0, format: 'milliseconds'} toRatio: {type: 'number', title: 'To Progress Ratio', description: 'Set playback time to a target playback progress ratio.', minimum: 0, maximum: 1} toTime: {type: 'number', title: 'To Time', description: 'Set playback time to a target playback point, in seconds.', minimum: 0} toGoal: c.shortString(title: 'To Goal', description: 'Set playback time to when this goal was achieved. (TODO: not implemented.)') script: c.object {title: 'Script', description: 'Extra configuration for this action group.'}, duration: {type: 'integer', minimum: 0, title: 'Duration', description: 'How long this script should last in milliseconds. 0 for indefinite.', format: 'milliseconds'} skippable: {type: 'boolean', title: 'Skippable', description: 'Whether this script shouldn\'t bother firing when the player skips past all current scripts.'} beforeLoad: {type: 'boolean', title: 'Before Load', description: 'Whether this script should fire before the level is finished loading.'} sprites: c.array {title: 'Sprites', description: 'Commands to issue to Sprites on the Surface.'}, SpriteCommandSchema surface: c.object {title: 'Surface', description: 'Commands to issue to the Surface itself.'}, focus: c.object {title: 'Camera', description: 'Focus the camera on a specific point on the Surface.', format: 'viewport'}, target: {anyOf: [PointSchema, thang, {type: 'null'}], title: 'Target', description: 'Where to center the camera view.', default: {x: 0, y: 0}} zoom: {type: 'number', minimum: 0, exclusiveMinimum: true, maximum: 64, title: 'Zoom', description: 'What zoom level to use.'} duration: {type: 'number', minimum: 0, title: 'Duration', description: 'in ms'} bounds: c.array {title: 'Boundary', maxItems: 2, minItems: 2, default: [{x: 0, y: 0}, {x: 46, y: 39}], format: 'bounds'}, PointSchema isNewDefault: {type: 'boolean', format: 'hidden', title: 'New Default', description: 'Set this as new default zoom once scripts end.'} # deprecated highlight: c.object {title: 'Highlight', description: 'Highlight specific Sprites on the Surface.'}, targets: c.array {title: 'Targets', description: 'Thang IDs of target Sprites to highlight.'}, thang delay: {type: 'integer', minimum: 0, title: 'Delay', description: 'Delay in milliseconds before the highlight appears.'} lockSelect: {type: 'boolean', title: 'Lock Select', description: 'Whether to lock Sprite selection so that the player can\'t select/deselect anything.'} sound: c.object {title: 'Sound', description: 'Commands to control sound playback.'}, suppressSelectionSounds: {type: 'boolean', title: 'Suppress Selection Sounds', description: 'Whether to suppress selection sounds made from clicking on Thangs.'} music: c.object {title: 'Music', description: 'Control music playing'}, play: {title: 'Play', type: 'boolean'} file: c.shortString(title: 'File', enum: ['/music/music_level_1', '/music/music_level_2', '/music/music_level_3', '/music/music_level_4', '/music/music_level_5']) ScriptSchema = c.object { title: 'Script' description: 'A script fires off a chain of notes to interact with the game when a certain event triggers it.' required: ['channel'] 'default': {channel: 'world:won', noteChain: []} }, id: c.shortString(title: 'ID', description: 'A unique ID that other scripts can rely on in their Happens After prereqs, for sequencing.', pattern: '^[a-zA-Z 0-9:\'"_!-]+$') # uniqueness? Ideally this would be just ids-like-this but we have a lot of legacy data. channel: c.shortString(title: 'Event', format: 'event-channel', description: 'Event channel this script might trigger for, like "world:won".') eventPrereqs: c.array {title: 'Event Checks', description: 'Logical checks on the event for this script to trigger.', format: 'event-prereqs'}, EventPrereqSchema repeats: {title: 'Repeats', description: 'Whether this script can trigger more than once during a level.', enum: [true, false, 'session']} scriptPrereqs: c.array {title: 'Happens After', description: 'Scripts that need to fire first.'}, c.shortString(title: 'ID', description: 'A unique ID of a script.') notAfter: c.array {title: 'Not After', description: 'Do not run this script if any of these scripts have run.'}, c.shortString(title: 'ID', description: 'A unique ID of a script.') noteChain: c.array {title: 'Actions', description: 'A list of things that happen when this script triggers.'}, NoteGroupSchema LevelThangSchema = c.object { title: 'Thang', description: 'Thangs are any units, doodads, or abstract things that you use to build the level. (\"Thing\" was too confusing to say.)', format: 'thang' required: ['id', 'thangType', 'components'] 'default': id: 'PI:NAME:<NAME>END_PI' thangType: 'Soldier' components: [] }, id: thang # TODO: figure out if we can make this unique and how to set dynamic defaults thangType: c.objectId(links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], title: 'Thang Type', description: 'A reference to the original Thang template being configured.', format: 'thang-type') components: c.array {title: 'Components', description: 'Thangs are configured by changing the Components attached to them.', uniqueItems: true, format: 'thang-components-array'}, ThangComponentSchema # TODO: uniqueness should be based on 'original', not whole thing LevelSystemSchema = c.object { title: 'System' description: 'Configuration for a System that this Level uses.' format: 'level-system' required: ['original', 'majorVersion'] 'default': majorVersion: 0 config: {} links: [{rel: 'db', href: '/db/level.system/{(original)}/version/{(majorVersion)}'}] }, original: c.objectId(title: 'Original', description: 'A reference to the original System being configured.', format: 'hidden') config: c.object {title: 'Configuration', description: 'System-specific configuration properties.', additionalProperties: true, format: 'level-system-configuration'} majorVersion: {title: 'Major Version', description: 'Which major version of the System is being used.', type: 'integer', minimum: 0, format: 'hidden'} GeneralArticleSchema = c.object { title: 'Article' description: 'Reference to a general documentation article.' required: ['original'] format: 'latest-version-reference' 'default': original: null majorVersion: 0 links: [{rel: 'db', href: '/db/article/{(original)}/version/{(majorVersion)}'}] }, original: c.objectId(title: 'Original', description: 'A reference to the original Article.')#, format: 'hidden') # hidden? majorVersion: {title: 'Major Version', description: 'Which major version of the Article is being used.', type: 'integer', minimum: 0} #, format: 'hidden'} # hidden? IntroContentObject = { type: 'object', additionalProperties: false, properties: { type: { title: 'Content type', enum: ['cinematic', 'interactive', 'cutscene-video', 'avatarSelectionScreen'] } contentId: { oneOf: [ c.stringID(title: 'Content ID for all languages') { type: 'object', title: 'Content ID specific to languages', additionalProperties: c.stringID(), format: 'code-languages-object' } ] } } } LevelSchema = c.object { title: 'Level' description: 'A spectacular level which will delight and educate its stalwart players with the sorcery of coding.' required: ['name'] 'default': name: 'Ineffable Wizardry' description: 'This level is indescribably flarmy.' documentation: {} scripts: [] thangs: [] systems: [] victory: {} type: 'hero' goals: [ {id: 'ogres-die', name: 'Defeat the ogres.', killThangs: ['ogres'], worldEndsAfter: 3} {id: 'humans-survive', name: 'Your hero must survive.', saveThangs: ['Hero Placeholder'], howMany: 1, worldEndsAfter: 3, hiddenGoal: true} ] concepts: ['basic_syntax'] } c.extendNamedProperties LevelSchema # let's have the name be the first property _.extend LevelSchema.properties, description: {title: 'Description', description: 'A short explanation of what this level is about.', type: 'string', maxLength: 65536, format: 'markdown'} studentPlayInstructions: {title: 'Student Play Instructions', description: 'Instructions for game dev levels when students play them.', type: 'string', maxLength: 65536, format: 'markdown'} loadingTip: { type: 'string', title: 'Loading Tip', description: 'What to show for this level while it\'s loading.' } documentation: c.object {title: 'Documentation', description: 'Documentation articles relating to this level.', 'default': {specificArticles: [], generalArticles: []}}, specificArticles: c.array {title: 'Specific Articles', description: 'Specific documentation articles that live only in this level.', uniqueItems: true }, SpecificArticleSchema generalArticles: c.array {title: 'General Articles', description: 'General documentation articles that can be linked from multiple levels.', uniqueItems: true}, GeneralArticleSchema hints: c.array {title: 'Hints', description: 'Tips and tricks to help unstick a player for the level.', uniqueItems: true }, { type: 'object' properties: { body: {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this hint'} } } hintsB: c.array {title: 'HintsB', description: '2nd style of hints for a/b testing significant variations', uniqueItems: true }, { type: 'object' properties: { body: {type: 'string', title: 'Content', description: 'The body content of the article, in Markdown.', format: 'markdown'} i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this hint'} } } nextLevel: { type: 'object', links: [{rel: 'extra', href: '/db/level/{($)}'}, {rel: 'db', href: '/db/level/{(original)}/version/{(majorVersion)}'}], format: 'latest-version-reference', title: 'Next Level', description: 'Reference to the next level players will play after beating this one.' } scripts: c.array {title: 'Scripts', description: 'An array of scripts that trigger based on what the player does and affect things outside of the core level simulation.'}, ScriptSchema thangs: c.array {title: 'Thangs', description: 'An array of Thangs that make up the level.' }, LevelThangSchema systems: c.array {title: 'Systems', description: 'Levels are configured by changing the Systems attached to them.', uniqueItems: true }, LevelSystemSchema # TODO: uniqueness should be based on 'original', not whole thing victory: c.object {title: 'Victory Screen'}, { body: {type: 'string', format: 'markdown', title: 'Body Text', description: 'Inserted into the Victory Modal once this level is complete. Tell the player they did a good job and what they accomplished!'}, i18n: {type: 'object', format: 'i18n', props: ['body'], description: 'Help translate this victory message'} } i18n: {type: 'object', format: 'i18n', props: ['name', 'description', 'loadingTip', 'studentPlayInstructions'], description: 'Help translate this level'} banner: {type: 'string', format: 'image-file', title: 'Banner'} goals: c.array {title: 'Goals', description: 'An array of goals which are visible to the player and can trigger scripts.'}, GoalSchema type: c.shortString(title: 'Type', description: 'What type of level this is.', 'enum': ['campaign', 'ladder', 'ladder-tutorial', 'hero', 'hero-ladder', 'hero-coop', 'course', 'course-ladder', 'game-dev', 'web-dev', 'intro']) kind: c.shortString(title: 'Kind', description: 'Similar to type, but just for our organization.', enum: ['demo', 'usage', 'mastery', 'advanced', 'practice', 'challenge']) ozariaType: c.shortString(title: 'Ozaria Level Type', description: 'Similar to type, specific to ozaria.', enum: ['practice', 'challenge', 'capstone']) terrain: c.terrainString requiresSubscription: {title: 'Requires Subscription', description: 'Whether this level is available to subscribers only.', type: 'boolean'} tasks: c.array {title: 'Tasks', description: 'Tasks to be completed for this level.'}, c.task helpVideos: c.array {title: 'Help Videos'}, c.object {default: {style: 'eccentric', url: '', free: false}}, style: c.shortString title: 'Style', description: 'Like: original, eccentric, scripted, edited, etc.' free: {type: 'boolean', title: 'Free', description: 'Whether this video is freely available to all players without a subscription.'} url: c.url {title: 'URL', description: 'Link to the video on Vimeo.'} replayable: {type: 'boolean', title: 'Replayable', description: 'Whether this (hero) level infinitely scales up its difficulty and can be beaten over and over for greater rewards.'} buildTime: {type: 'number', description: 'How long it has taken to build this level.'} practice: { type: 'boolean' } practiceThresholdMinutes: {type: 'number', description: 'Players with larger playtimes may be directed to a practice level.'} assessment: { type: ['boolean', 'string'], enum: [true, false, 'open-ended', 'cumulative'], description: 'Set to true if this is an assessment level.' } assessmentPlacement: { type: 'string', enum: ['middle', 'end'] } primerLanguage: { type: 'string', enum: ['javascript', 'python'], description: 'Programming language taught by this level.' } shareable: { title: 'Shareable', type: ['string', 'boolean'], enum: [false, true, 'project'], description: 'Whether the level is not shareable (false), shareable (true), or a sharing-encouraged project level ("project"). Make sure to use "project" for project levels so they show up correctly in the Teacher Dashboard.' } # Admin flags adventurer: { type: 'boolean' } adminOnly: { type: 'boolean' } disableSpaces: { type: ['boolean','integer'] } hidesSubmitUntilRun: { type: 'boolean' } hidesPlayButton: { type: 'boolean' } hidesRunShortcut: { type: 'boolean' } hidesHUD: { type: 'boolean' } hidesSay: { type: 'boolean' } hidesCodeToolbar: { type: 'boolean' } hidesRealTimePlayback: { type: 'boolean' } backspaceThrottle: { type: 'boolean' } lockDefaultCode: { type: ['boolean','integer'] } moveRightLoopSnippet: { type: 'boolean' } realTimeSpeedFactor: { type: 'number' } autocompleteFontSizePx: { type: 'number' } requiredCode: c.array {}, { type: 'string' } suspectCode: c.array {}, { type: 'object' properties: { name: { type: 'string' } pattern: { type: 'string' } } } autocompleteReplacement: c.array {}, { type: 'object' properties: { name: { type: 'string' } snippets: { type: 'object', title: 'Snippets', description: 'List of snippets for the respective programming languages', additionalProperties: c.codeSnippet, format: 'code-languages-object' } } } requiredGear: { type: 'object', title: 'Required Gear', description: 'Slots that should require one of a set array of items for that slot', additionalProperties: { type: 'array' items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' } }} restrictedGear: { type: 'object', title: 'Restricted Gear', description: 'Slots that should restrict all of a set array of items for that slot', additionalProperties: { type: 'array' items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' } }} requiredProperties: { type: 'array', items: {type: 'string'}, description: 'Names of properties a hero must have equipped to play.', format: 'solution-gear', title: 'Required Properties' } restrictedProperties: { type: 'array', items: {type: 'string'}, description: 'Names of properties a hero must not have equipped to play.', title: 'Restricted Properties' } recommendedHealth: { type: 'number', minimum: 0, exclusiveMinimum: true, description: 'If set, will show the recommended health to be able to beat this level with the intended main solution to the player when choosing equipment.', format: 'solution-stats', title: 'Recommended Health' } maximumHealth: { type: 'number', minimum: 0, exclusiveMinimum: true, description: 'If set, will enforce the maximum health of the hero.', title: 'Maximum Health'} allowedHeroes: { type: 'array', title: 'Allowed Heroes', description: 'Which heroes can play this level. For any hero, leave unset.', items: { type: 'string', links: [{rel: 'db', href: '/db/thang.type/{($)}/version'}], format: 'latest-version-original-reference' }} campaign: c.shortString title: 'Campaign', description: 'Which campaign this level is part of (like "desert").', format: 'hidden' # Automatically set by campaign editor. campaignIndex: c.int title: 'Campaign Index', description: 'The 0-based index of this level in its campaign.', format: 'hidden' # Automatically set by campaign editor. scoreTypes: c.array {title: 'Score Types', description: 'What metric to show leaderboards for. Most important one first, not too many (2 is good).'}, { anyOf: [ c.scoreType, { type: 'object' title: 'Score Type Object' required: ['type'] additionalProperties: false properties: { type: c.scoreType thresholds: { type: 'object' properties: { bronze: { type: 'number' } silver: { type: 'number' } gold: { type: 'number' } } } } } ] } concepts: c.array {title: 'Programming Concepts', description: 'Which programming concepts this level covers.', uniqueItems: true, format: 'concepts-list'}, c.concept primaryConcepts: c.array {title: 'Primary Concepts', description: 'The main 1-3 concepts this level focuses on.', uniqueItems: true}, c.concept picoCTFProblem: { type: 'string', description: 'Associated picoCTF problem ID, if this is a picoCTF level' } password: { type: 'string', description: 'The password required to create a session for this level' } mirrorMatch: { type: 'boolean', description: 'Whether a multiplayer ladder arena is a mirror match' } introContent: { # valid for levels of type 'intro' title: 'Intro content', description: 'Intro content sequence', type: 'array', items: IntroContentObject } additionalGoals: c.array { title: 'Additional Goals', description: 'Goals that are added after the first regular goals are completed' }, c.object { title: 'Goals', description: 'Goals for this stage', minItems: 1, uniqueItems: true, properties: { stage: { type: 'integer', minimum: 2, title: 'Goal Stage', description: 'Which stage these additional goals are for (2 and onwards)' }, goals: c.array { title: 'Goals', description: 'An array of goals which are visible to the player and can trigger scripts.' }, GoalSchema } } isPlayedInStages: {type: 'boolean', title: 'Is Played in Stages', description: 'Is this level played in stages and other content(cinematics) is loaded in between stages'} methodsBankList: c.array {title: 'Methods Bank List'}, c.object { properties: { name: c.shortString(title: 'Name'), section: c.shortString(title: 'Methods Bank Section', pattern: '^[a-z]+$'), subSection: c.shortString(title: 'Methods Bank Sub-Section', pattern: '^[a-z]+$'), componentName: c.shortString(title: 'Level Component Name', description: 'Level Component to use for documentation in case there are multiple components with same property\'s documentation'), } } c.extendBasicProperties LevelSchema, 'level' c.extendSearchableProperties LevelSchema c.extendVersionedProperties LevelSchema, 'level' c.extendPermissionsProperties LevelSchema, 'level' c.extendPatchableProperties LevelSchema c.extendTranslationCoverageProperties LevelSchema module.exports = LevelSchema # To test: # 1: Copy the schema from http://localhost:3000/db/level/schema # 2. Open up the Treema demo page http://localhost:9090/demo.html # 3. tv4.addSchema(metaschema.id, metaschema) # 4. S = <paste big schema here> # 5. tv4.validateMultiple(S, metaschema) and look for errors
[ { "context": "\n * @namespace KINOUT\n * @class View\n *\n * @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\nKINOUT.View = ", "end": 111, "score": 0.9998862743377686, "start": 90, "tag": "NAME", "value": "Javier Jimenez Villar" }, { "context": " @class View\n *\n ...
components/Kinout/src/Kinout.View.coffee
biojazzard/kirbout
2
### * Description or Responsability * * @namespace KINOUT * @class View * * @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi ### KINOUT.View = ((knt, $$, undefined_) -> SELECTOR = knt.Constants.SELECTOR STYLE = knt.Constants.STYLE _index = knt.index _steps = [] slide = (horizontal, vertical, next_step = true) -> unless knt.Element.steps(next_step) _saveNewIndexes horizontal, vertical _updateSlideIndexes() knt.Url.write _index.horizontal, _index.vertical return index = -> 'horizontal': _index.horizontal 'vertical': _index.vertical _saveNewIndexes = (horizontal, vertical) -> _index.horizontal = (if horizontal is `undefined` then _index.horizontal else horizontal) _index.vertical = (if vertical is `undefined` then _index.vertical else vertical) return _updateSlideIndexes = -> _index.horizontal = _updateSlides(SELECTOR.SLIDE, _index.horizontal) _index.vertical = _updateSlides(SELECTOR.SUBSLIDE, _index.vertical) _updateProgress() return _updateProgress = -> slides = knt.Element.slides(); # Horizontal horizontal = parseInt( (_index.horizontal * 100) / (slides.length - 1)) window.requestAnimationFrame -> knt.Element.progress("horizontal", horizontal) # Vertical vertical = 0 subslides = knt.Element.subslides(_index.horizontal) if subslides.length > 1 vertical = parseInt( ((_index.vertical + 1) * 100) / subslides.length) window.requestAnimationFrame -> knt.Element.progress("vertical", vertical) _updateSlides = (selector, index) -> slides = Array::slice.call(document.querySelectorAll(selector)) if slides.length index = Math.max(Math.min(index, slides.length - 1), 0) #window.requestAnimationFrame -> render(slides, index) render slides, index else index = 0 index render = (slides, index) -> slides[index].setAttribute "class", STYLE.PRESENT slides.slice(0, index).map (element) -> element.setAttribute "class", STYLE.PAST slides.slice(index + 1).map (element) -> element.setAttribute "class", STYLE.FUTURE slide: slide index: index render: render )(KINOUT, Quo)
202144
### * Description or Responsability * * @namespace KINOUT * @class View * * @author <NAME> <<EMAIL>> || @soyjavi ### KINOUT.View = ((knt, $$, undefined_) -> SELECTOR = knt.Constants.SELECTOR STYLE = knt.Constants.STYLE _index = knt.index _steps = [] slide = (horizontal, vertical, next_step = true) -> unless knt.Element.steps(next_step) _saveNewIndexes horizontal, vertical _updateSlideIndexes() knt.Url.write _index.horizontal, _index.vertical return index = -> 'horizontal': _index.horizontal 'vertical': _index.vertical _saveNewIndexes = (horizontal, vertical) -> _index.horizontal = (if horizontal is `undefined` then _index.horizontal else horizontal) _index.vertical = (if vertical is `undefined` then _index.vertical else vertical) return _updateSlideIndexes = -> _index.horizontal = _updateSlides(SELECTOR.SLIDE, _index.horizontal) _index.vertical = _updateSlides(SELECTOR.SUBSLIDE, _index.vertical) _updateProgress() return _updateProgress = -> slides = knt.Element.slides(); # Horizontal horizontal = parseInt( (_index.horizontal * 100) / (slides.length - 1)) window.requestAnimationFrame -> knt.Element.progress("horizontal", horizontal) # Vertical vertical = 0 subslides = knt.Element.subslides(_index.horizontal) if subslides.length > 1 vertical = parseInt( ((_index.vertical + 1) * 100) / subslides.length) window.requestAnimationFrame -> knt.Element.progress("vertical", vertical) _updateSlides = (selector, index) -> slides = Array::slice.call(document.querySelectorAll(selector)) if slides.length index = Math.max(Math.min(index, slides.length - 1), 0) #window.requestAnimationFrame -> render(slides, index) render slides, index else index = 0 index render = (slides, index) -> slides[index].setAttribute "class", STYLE.PRESENT slides.slice(0, index).map (element) -> element.setAttribute "class", STYLE.PAST slides.slice(index + 1).map (element) -> element.setAttribute "class", STYLE.FUTURE slide: slide index: index render: render )(KINOUT, Quo)
true
### * Description or Responsability * * @namespace KINOUT * @class View * * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi ### KINOUT.View = ((knt, $$, undefined_) -> SELECTOR = knt.Constants.SELECTOR STYLE = knt.Constants.STYLE _index = knt.index _steps = [] slide = (horizontal, vertical, next_step = true) -> unless knt.Element.steps(next_step) _saveNewIndexes horizontal, vertical _updateSlideIndexes() knt.Url.write _index.horizontal, _index.vertical return index = -> 'horizontal': _index.horizontal 'vertical': _index.vertical _saveNewIndexes = (horizontal, vertical) -> _index.horizontal = (if horizontal is `undefined` then _index.horizontal else horizontal) _index.vertical = (if vertical is `undefined` then _index.vertical else vertical) return _updateSlideIndexes = -> _index.horizontal = _updateSlides(SELECTOR.SLIDE, _index.horizontal) _index.vertical = _updateSlides(SELECTOR.SUBSLIDE, _index.vertical) _updateProgress() return _updateProgress = -> slides = knt.Element.slides(); # Horizontal horizontal = parseInt( (_index.horizontal * 100) / (slides.length - 1)) window.requestAnimationFrame -> knt.Element.progress("horizontal", horizontal) # Vertical vertical = 0 subslides = knt.Element.subslides(_index.horizontal) if subslides.length > 1 vertical = parseInt( ((_index.vertical + 1) * 100) / subslides.length) window.requestAnimationFrame -> knt.Element.progress("vertical", vertical) _updateSlides = (selector, index) -> slides = Array::slice.call(document.querySelectorAll(selector)) if slides.length index = Math.max(Math.min(index, slides.length - 1), 0) #window.requestAnimationFrame -> render(slides, index) render slides, index else index = 0 index render = (slides, index) -> slides[index].setAttribute "class", STYLE.PRESENT slides.slice(0, index).map (element) -> element.setAttribute "class", STYLE.PAST slides.slice(index + 1).map (element) -> element.setAttribute "class", STYLE.FUTURE slide: slide index: index render: render )(KINOUT, Quo)
[ { "context": "\t\t\ts += ia.html(level+1)\n\ts += \"</div>\"\n\ts\n###\n#\n# НАВИГАТОР Пирамиды\n#\nnavi[PIECHART] = (eo) ->\n\tif $txt.attr(\"content", "end": 1859, "score": 0.997076690196991, "start": 1841, "tag": "NAME", "value": "НАВИГАТОР Пирамиды" } ]
piechart.coffee
agershun/minday
0
################################################ # MINDAY 0.008BI # piechart.coffee # Процедуры для рисования диаграммы с долями ################################################ svg[PIECHART] = -> ppr[@id] = Raphael "pap"+@id,500,320 pp = $('#pap'+@id).position() # Берем координаты всей пирамиды $('#bag'+@id).height($('#txt'+@id).outerHeight(true)+$('#pap'+@id).outerHeight(true)) pie1 = [] pie2 = [] if @source? for re,ri in @source.data pie1[ri] = re[0].txt pie2[ri] = Number(re[1].txt) # pie = ppr[@id].piechart(320, 240, 100, [55, 20, 13, 32, 5, 1, 2, 10], { legend: ["%%.%% - Enterprise Users", "IE Users"], legendpos: "west", href: ["http://raphaeljs.com", "http://g.raphaeljs.com"]}) g[@id] = ppr[@id].piechart(300, 170, 130, pie2, { legend: pie1, legendpos: "west", href: ["http://minday.ru", "http://minday.ru"]}) # for ia,i in @data # svgp[ia.id] = ppr[@id].path ia.shape(1.4*400,400) # svgp[ia.id].attr # "stroke":"#888" # "stroke-opacity": 0.5 # "stroke-width":1 # "fill":"90-#FF9-#FFE" # "fill-opacity": 1 # # $("#bag"+ia.id).offset({top:pp.top+(i+1+0.25)*400/(@length+1), left:pp.left}) draw[PIECHART] = (level) -> s = @htmlIdeaTxt(level) if (level is 0) or (level > 0 and not @frame?) svga.push @ # Сохраняем текущий элемент для прорисовки s += "<div id='pap"+@id+"'></div>" s += "</div>" s ### html[LAYER] = (level) -> svga.push @ s = "" s += "<div id='bag"+@id+"' class='pyramid idea-bag"+level+"'>" s += "<div id='txt"+@id+"' class='idea-txt"+level+"'>" s += @txt if @txt? s += "</div>" # Стикеры if @sticker? and @sticker.length > 0 for sti in @sticker.data s += "<div id='sti"+sti.id+"' class='idea-sti'>" s += sti.txt s += "</div>" if (level is 0) or (level > 0 and not @frame?) for ia in @data s += ia.html(level+1) s += "</div>" s ### # # НАВИГАТОР Пирамиды # navi[PIECHART] = (eo) -> if $txt.attr("contentEditable") is "true" then return navi[IDEA](eo) switch eo.which when 40 # Down if (sidea is fidea) if sidea[0]? then sidea[0].select() else if (not sidea.frame) and sidea[0]? then sidea[0].select() else sia = sidea while sia isnt fidea and not (sia.pa[sia.ix+1]?) sia = sia.pa if sia isnt fidea then sia.pa[sia.ix+1].select() else navi[IDEA](eo) ### # Уровень пирамиды navi[LAYER] = (eo) -> if $txt.attr("contentEditable") is "true" then return navi[IDEA](eo) switch eo.which when 40 # Down if sidea.pa[sidea.ix+1]? then sidea.pa[sidea.ix+1].select() when 38 # Up if sidea.pa[sidea.ix-1]? then sidea.pa[sidea.ix-1].select() else sidea.pa.select() else navi[IDEA](eo) ###
194082
################################################ # MINDAY 0.008BI # piechart.coffee # Процедуры для рисования диаграммы с долями ################################################ svg[PIECHART] = -> ppr[@id] = Raphael "pap"+@id,500,320 pp = $('#pap'+@id).position() # Берем координаты всей пирамиды $('#bag'+@id).height($('#txt'+@id).outerHeight(true)+$('#pap'+@id).outerHeight(true)) pie1 = [] pie2 = [] if @source? for re,ri in @source.data pie1[ri] = re[0].txt pie2[ri] = Number(re[1].txt) # pie = ppr[@id].piechart(320, 240, 100, [55, 20, 13, 32, 5, 1, 2, 10], { legend: ["%%.%% - Enterprise Users", "IE Users"], legendpos: "west", href: ["http://raphaeljs.com", "http://g.raphaeljs.com"]}) g[@id] = ppr[@id].piechart(300, 170, 130, pie2, { legend: pie1, legendpos: "west", href: ["http://minday.ru", "http://minday.ru"]}) # for ia,i in @data # svgp[ia.id] = ppr[@id].path ia.shape(1.4*400,400) # svgp[ia.id].attr # "stroke":"#888" # "stroke-opacity": 0.5 # "stroke-width":1 # "fill":"90-#FF9-#FFE" # "fill-opacity": 1 # # $("#bag"+ia.id).offset({top:pp.top+(i+1+0.25)*400/(@length+1), left:pp.left}) draw[PIECHART] = (level) -> s = @htmlIdeaTxt(level) if (level is 0) or (level > 0 and not @frame?) svga.push @ # Сохраняем текущий элемент для прорисовки s += "<div id='pap"+@id+"'></div>" s += "</div>" s ### html[LAYER] = (level) -> svga.push @ s = "" s += "<div id='bag"+@id+"' class='pyramid idea-bag"+level+"'>" s += "<div id='txt"+@id+"' class='idea-txt"+level+"'>" s += @txt if @txt? s += "</div>" # Стикеры if @sticker? and @sticker.length > 0 for sti in @sticker.data s += "<div id='sti"+sti.id+"' class='idea-sti'>" s += sti.txt s += "</div>" if (level is 0) or (level > 0 and not @frame?) for ia in @data s += ia.html(level+1) s += "</div>" s ### # # <NAME> # navi[PIECHART] = (eo) -> if $txt.attr("contentEditable") is "true" then return navi[IDEA](eo) switch eo.which when 40 # Down if (sidea is fidea) if sidea[0]? then sidea[0].select() else if (not sidea.frame) and sidea[0]? then sidea[0].select() else sia = sidea while sia isnt fidea and not (sia.pa[sia.ix+1]?) sia = sia.pa if sia isnt fidea then sia.pa[sia.ix+1].select() else navi[IDEA](eo) ### # Уровень пирамиды navi[LAYER] = (eo) -> if $txt.attr("contentEditable") is "true" then return navi[IDEA](eo) switch eo.which when 40 # Down if sidea.pa[sidea.ix+1]? then sidea.pa[sidea.ix+1].select() when 38 # Up if sidea.pa[sidea.ix-1]? then sidea.pa[sidea.ix-1].select() else sidea.pa.select() else navi[IDEA](eo) ###
true
################################################ # MINDAY 0.008BI # piechart.coffee # Процедуры для рисования диаграммы с долями ################################################ svg[PIECHART] = -> ppr[@id] = Raphael "pap"+@id,500,320 pp = $('#pap'+@id).position() # Берем координаты всей пирамиды $('#bag'+@id).height($('#txt'+@id).outerHeight(true)+$('#pap'+@id).outerHeight(true)) pie1 = [] pie2 = [] if @source? for re,ri in @source.data pie1[ri] = re[0].txt pie2[ri] = Number(re[1].txt) # pie = ppr[@id].piechart(320, 240, 100, [55, 20, 13, 32, 5, 1, 2, 10], { legend: ["%%.%% - Enterprise Users", "IE Users"], legendpos: "west", href: ["http://raphaeljs.com", "http://g.raphaeljs.com"]}) g[@id] = ppr[@id].piechart(300, 170, 130, pie2, { legend: pie1, legendpos: "west", href: ["http://minday.ru", "http://minday.ru"]}) # for ia,i in @data # svgp[ia.id] = ppr[@id].path ia.shape(1.4*400,400) # svgp[ia.id].attr # "stroke":"#888" # "stroke-opacity": 0.5 # "stroke-width":1 # "fill":"90-#FF9-#FFE" # "fill-opacity": 1 # # $("#bag"+ia.id).offset({top:pp.top+(i+1+0.25)*400/(@length+1), left:pp.left}) draw[PIECHART] = (level) -> s = @htmlIdeaTxt(level) if (level is 0) or (level > 0 and not @frame?) svga.push @ # Сохраняем текущий элемент для прорисовки s += "<div id='pap"+@id+"'></div>" s += "</div>" s ### html[LAYER] = (level) -> svga.push @ s = "" s += "<div id='bag"+@id+"' class='pyramid idea-bag"+level+"'>" s += "<div id='txt"+@id+"' class='idea-txt"+level+"'>" s += @txt if @txt? s += "</div>" # Стикеры if @sticker? and @sticker.length > 0 for sti in @sticker.data s += "<div id='sti"+sti.id+"' class='idea-sti'>" s += sti.txt s += "</div>" if (level is 0) or (level > 0 and not @frame?) for ia in @data s += ia.html(level+1) s += "</div>" s ### # # PI:NAME:<NAME>END_PI # navi[PIECHART] = (eo) -> if $txt.attr("contentEditable") is "true" then return navi[IDEA](eo) switch eo.which when 40 # Down if (sidea is fidea) if sidea[0]? then sidea[0].select() else if (not sidea.frame) and sidea[0]? then sidea[0].select() else sia = sidea while sia isnt fidea and not (sia.pa[sia.ix+1]?) sia = sia.pa if sia isnt fidea then sia.pa[sia.ix+1].select() else navi[IDEA](eo) ### # Уровень пирамиды navi[LAYER] = (eo) -> if $txt.attr("contentEditable") is "true" then return navi[IDEA](eo) switch eo.which when 40 # Down if sidea.pa[sidea.ix+1]? then sidea.pa[sidea.ix+1].select() when 38 # Up if sidea.pa[sidea.ix-1]? then sidea.pa[sidea.ix-1].select() else sidea.pa.select() else navi[IDEA](eo) ###
[ { "context": "s = testData.getEditors schema.editors, [\"name\", \"username\", \"email\"]\n\t\tpjs = new PJS \".propertyEditor\", sch", "end": 455, "score": 0.9991362690925598, "start": 447, "tag": "USERNAME", "value": "username" }, { "context": "(objs[0].name).to.be.equal \"123\"\n\...
test/modules/editors/text.spec.coffee
icebob/propertiesjs
21
expect = require("chai").expect PJS = require "../../../src/js/propertiesJS" testData = require "../../test-data" describe "Test PJSTextEditor", -> pjs = null objs = null schema = null pe = null before -> testData.createDivs(@test.parent.title) pe = $ ".propertyEditor" beforeEach -> [objs, schema] = testData.clone() it "check PJSTextEditor with 1 object", -> schema.editors = testData.getEditors schema.editors, ["name", "username", "email"] pjs = new PJS ".propertyEditor", schema, objs[0] expect(pjs).to.be.exist expect(pjs.objectHandler.objs).to.be.length 1 expect(pjs.schema).to.be.equal schema expect(pjs.editors).to.be.length 3 expect(pjs.changed).to.be.false # 0. editor (name) editor = pjs.editors[0] settings = editor.settings tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # Check input classes & type expect(input.length).to.be.equal 1 expect(input.attr("type")).to.be.equal settings.type expect(input.attr("required")).to.be.equal "required" expect(input.attr("placeholder")).to.be.equal settings.placeHolder # Check input values expect(input.val()).to.be.equal objs[0][settings.field] expect(editor.getInputValue()).to.be.equal objs[0][settings.field] editor.setInputValue "222" expect(editor.getInputValue()).to.be.equal "222" # check changes flag expect(editor.changed).to.be.false editor.valueChanged "123" expect(editor.changed).to.be.true expect(pjs.changed).to.be.true expect(editor.lastValue).to.be.equal "123" expect(editor.errors).to.be.length 0 expect(objs[0].name).to.be.equal "123" # 1. editor (username) editor = pjs.editors[1] settings = editor.settings tr = pe.find "tbody tr:eq(1)" input = tr.find "input" # Check max length expect(input.attr("maxlength")).to.be.equal settings.maxLength.toString() expect(input.val()).to.be.equal objs[0][settings.field] #Check input change trigger input.val("Johnny").trigger("change") expect(pjs.workObject[editor.fieldName]).to.be.equal "Johnny" it "check editor schema validate function", (done) -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["username"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # Too short test expect(editor.valueChanged("Bob")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 # Whitespace test expect(editor.valueChanged("Ice bob")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 # Whitespace & short test expect(editor.valueChanged("I B")).to.be.false expect(editor.errors).to.be.length 2 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 2 # Good value no validation error expect(editor.valueChanged("Icebob")).to.be.true expect(editor.errors).to.be.length 0 expect(tr.hasClass("validation-error")).to.be.false expect(tr.find(".errors span")).to.be.length 0 done() it "check editor regexp validate function", -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["phone"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] settings = editor.settings tr = pe.find "tbody tr:eq(0)" input = tr.find "input" expect(input.attr("pattern")).to.be.equal settings.pattern expect(tr.find(".hint")).to.be.length 1 expect(tr.find(".hint").text()).to.be.equal settings.hint expect(pjs.checkEditorValidation()).to.be.true # not matched test expect(editor.valueChanged("Bob")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 expect(pjs.checkEditorValidation()).to.be.false # not matched test expect(editor.valueChanged("70/589-3321123")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 expect(pjs.checkEditorValidation()).to.be.false # matched test expect(editor.valueChanged("70/589-3321")).to.be.true expect(editor.errors).to.be.length 0 expect(tr.hasClass("validation-error")).to.be.false expect(tr.find(".errors span")).to.be.length 0 expect(pjs.checkEditorValidation()).to.be.true it "check editor schema validate function return false", (done) -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["name", "username", "email"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] editor = pjs.editors[2] expect(editor.valueChanged("Bob")).to.be.false expect(editor.errors).to.be.length 1 expect(editor.valueChanged("B@")).to.be.false expect(editor.errors).to.be.length 1 done() it "check PJSTextEditor with 2 object", -> schema.editors = testData.getEditors schema.editors, ["name", "username"] pjs = new PJS ".propertyEditor", schema, objs.slice 0, 2 expect(pjs).to.be.exist expect(pjs.objectHandler.objs).to.be.length 2 expect(pjs.editors).to.be.length 1 # 0. editor (name) editor = pjs.editors[0] settings = editor.settings expect(settings).to.be.equal schema.editors[0] # check input field exist tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # should undefined if object values different expect(input.val()).to.be.unDefined # check objects' value s = "Johnny" editor.valueChanged s expect(objs[0][editor.fieldName]).to.be.equal s expect(objs[1][editor.fieldName]).to.be.equal s
27011
expect = require("chai").expect PJS = require "../../../src/js/propertiesJS" testData = require "../../test-data" describe "Test PJSTextEditor", -> pjs = null objs = null schema = null pe = null before -> testData.createDivs(@test.parent.title) pe = $ ".propertyEditor" beforeEach -> [objs, schema] = testData.clone() it "check PJSTextEditor with 1 object", -> schema.editors = testData.getEditors schema.editors, ["name", "username", "email"] pjs = new PJS ".propertyEditor", schema, objs[0] expect(pjs).to.be.exist expect(pjs.objectHandler.objs).to.be.length 1 expect(pjs.schema).to.be.equal schema expect(pjs.editors).to.be.length 3 expect(pjs.changed).to.be.false # 0. editor (name) editor = pjs.editors[0] settings = editor.settings tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # Check input classes & type expect(input.length).to.be.equal 1 expect(input.attr("type")).to.be.equal settings.type expect(input.attr("required")).to.be.equal "required" expect(input.attr("placeholder")).to.be.equal settings.placeHolder # Check input values expect(input.val()).to.be.equal objs[0][settings.field] expect(editor.getInputValue()).to.be.equal objs[0][settings.field] editor.setInputValue "222" expect(editor.getInputValue()).to.be.equal "222" # check changes flag expect(editor.changed).to.be.false editor.valueChanged "123" expect(editor.changed).to.be.true expect(pjs.changed).to.be.true expect(editor.lastValue).to.be.equal "123" expect(editor.errors).to.be.length 0 expect(objs[0].name).to.be.equal "123" # 1. editor (username) editor = pjs.editors[1] settings = editor.settings tr = pe.find "tbody tr:eq(1)" input = tr.find "input" # Check max length expect(input.attr("maxlength")).to.be.equal settings.maxLength.toString() expect(input.val()).to.be.equal objs[0][settings.field] #Check input change trigger input.val("<NAME>").trigger("change") expect(pjs.workObject[editor.fieldName]).to.be.equal "Johnny" it "check editor schema validate function", (done) -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["username"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # Too short test expect(editor.valueChanged("<NAME>")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 # Whitespace test expect(editor.valueChanged("<NAME>")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 # Whitespace & short test expect(editor.valueChanged("I B")).to.be.false expect(editor.errors).to.be.length 2 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 2 # Good value no validation error expect(editor.valueChanged("<NAME>")).to.be.true expect(editor.errors).to.be.length 0 expect(tr.hasClass("validation-error")).to.be.false expect(tr.find(".errors span")).to.be.length 0 done() it "check editor regexp validate function", -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["phone"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] settings = editor.settings tr = pe.find "tbody tr:eq(0)" input = tr.find "input" expect(input.attr("pattern")).to.be.equal settings.pattern expect(tr.find(".hint")).to.be.length 1 expect(tr.find(".hint").text()).to.be.equal settings.hint expect(pjs.checkEditorValidation()).to.be.true # not matched test expect(editor.valueChanged("<NAME>")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 expect(pjs.checkEditorValidation()).to.be.false # not matched test expect(editor.valueChanged("70/589-3321123")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 expect(pjs.checkEditorValidation()).to.be.false # matched test expect(editor.valueChanged("70/589-3321")).to.be.true expect(editor.errors).to.be.length 0 expect(tr.hasClass("validation-error")).to.be.false expect(tr.find(".errors span")).to.be.length 0 expect(pjs.checkEditorValidation()).to.be.true it "check editor schema validate function return false", (done) -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["name", "username", "email"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] editor = pjs.editors[2] expect(editor.valueChanged("<NAME>")).to.be.false expect(editor.errors).to.be.length 1 expect(editor.valueChanged("B@")).to.be.false expect(editor.errors).to.be.length 1 done() it "check PJSTextEditor with 2 object", -> schema.editors = testData.getEditors schema.editors, ["name", "username"] pjs = new PJS ".propertyEditor", schema, objs.slice 0, 2 expect(pjs).to.be.exist expect(pjs.objectHandler.objs).to.be.length 2 expect(pjs.editors).to.be.length 1 # 0. editor (name) editor = pjs.editors[0] settings = editor.settings expect(settings).to.be.equal schema.editors[0] # check input field exist tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # should undefined if object values different expect(input.val()).to.be.unDefined # check objects' value s = "<NAME>" editor.valueChanged s expect(objs[0][editor.fieldName]).to.be.equal s expect(objs[1][editor.fieldName]).to.be.equal s
true
expect = require("chai").expect PJS = require "../../../src/js/propertiesJS" testData = require "../../test-data" describe "Test PJSTextEditor", -> pjs = null objs = null schema = null pe = null before -> testData.createDivs(@test.parent.title) pe = $ ".propertyEditor" beforeEach -> [objs, schema] = testData.clone() it "check PJSTextEditor with 1 object", -> schema.editors = testData.getEditors schema.editors, ["name", "username", "email"] pjs = new PJS ".propertyEditor", schema, objs[0] expect(pjs).to.be.exist expect(pjs.objectHandler.objs).to.be.length 1 expect(pjs.schema).to.be.equal schema expect(pjs.editors).to.be.length 3 expect(pjs.changed).to.be.false # 0. editor (name) editor = pjs.editors[0] settings = editor.settings tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # Check input classes & type expect(input.length).to.be.equal 1 expect(input.attr("type")).to.be.equal settings.type expect(input.attr("required")).to.be.equal "required" expect(input.attr("placeholder")).to.be.equal settings.placeHolder # Check input values expect(input.val()).to.be.equal objs[0][settings.field] expect(editor.getInputValue()).to.be.equal objs[0][settings.field] editor.setInputValue "222" expect(editor.getInputValue()).to.be.equal "222" # check changes flag expect(editor.changed).to.be.false editor.valueChanged "123" expect(editor.changed).to.be.true expect(pjs.changed).to.be.true expect(editor.lastValue).to.be.equal "123" expect(editor.errors).to.be.length 0 expect(objs[0].name).to.be.equal "123" # 1. editor (username) editor = pjs.editors[1] settings = editor.settings tr = pe.find "tbody tr:eq(1)" input = tr.find "input" # Check max length expect(input.attr("maxlength")).to.be.equal settings.maxLength.toString() expect(input.val()).to.be.equal objs[0][settings.field] #Check input change trigger input.val("PI:NAME:<NAME>END_PI").trigger("change") expect(pjs.workObject[editor.fieldName]).to.be.equal "Johnny" it "check editor schema validate function", (done) -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["username"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # Too short test expect(editor.valueChanged("PI:NAME:<NAME>END_PI")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 # Whitespace test expect(editor.valueChanged("PI:NAME:<NAME>END_PI")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 # Whitespace & short test expect(editor.valueChanged("I B")).to.be.false expect(editor.errors).to.be.length 2 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 2 # Good value no validation error expect(editor.valueChanged("PI:NAME:<NAME>END_PI")).to.be.true expect(editor.errors).to.be.length 0 expect(tr.hasClass("validation-error")).to.be.false expect(tr.find(".errors span")).to.be.length 0 done() it "check editor regexp validate function", -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["phone"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] settings = editor.settings tr = pe.find "tbody tr:eq(0)" input = tr.find "input" expect(input.attr("pattern")).to.be.equal settings.pattern expect(tr.find(".hint")).to.be.length 1 expect(tr.find(".hint").text()).to.be.equal settings.hint expect(pjs.checkEditorValidation()).to.be.true # not matched test expect(editor.valueChanged("PI:NAME:<NAME>END_PI")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 expect(pjs.checkEditorValidation()).to.be.false # not matched test expect(editor.valueChanged("70/589-3321123")).to.be.false expect(editor.errors).to.be.length 1 expect(tr.hasClass("validation-error")).to.be.true expect(tr.find(".errors span")).to.be.length 1 expect(pjs.checkEditorValidation()).to.be.false # matched test expect(editor.valueChanged("70/589-3321")).to.be.true expect(editor.errors).to.be.length 0 expect(tr.hasClass("validation-error")).to.be.false expect(tr.find(".errors span")).to.be.length 0 expect(pjs.checkEditorValidation()).to.be.true it "check editor schema validate function return false", (done) -> [objs, schema] = testData.clone() schema.editors = testData.getEditors schema.editors, ["name", "username", "email"] pjs = new PJS ".propertyEditor", schema, objs[0] editor = pjs.editors[0] editor = pjs.editors[2] expect(editor.valueChanged("PI:NAME:<NAME>END_PI")).to.be.false expect(editor.errors).to.be.length 1 expect(editor.valueChanged("B@")).to.be.false expect(editor.errors).to.be.length 1 done() it "check PJSTextEditor with 2 object", -> schema.editors = testData.getEditors schema.editors, ["name", "username"] pjs = new PJS ".propertyEditor", schema, objs.slice 0, 2 expect(pjs).to.be.exist expect(pjs.objectHandler.objs).to.be.length 2 expect(pjs.editors).to.be.length 1 # 0. editor (name) editor = pjs.editors[0] settings = editor.settings expect(settings).to.be.equal schema.editors[0] # check input field exist tr = pe.find "tbody tr:eq(0)" input = tr.find "input" # should undefined if object values different expect(input.val()).to.be.unDefined # check objects' value s = "PI:NAME:<NAME>END_PI" editor.valueChanged s expect(objs[0][editor.fieldName]).to.be.equal s expect(objs[1][editor.fieldName]).to.be.equal s
[ { "context": " 0.5 }\n ]\n\nclient = new Myna.Client\n apiKey: \"092c90f6-a8f2-11e2-a2b9-7c6d628b25f7\"\n apiRoot: testApiRoot\n experiments: [ expt ]\n", "end": 311, "score": 0.9997587203979492, "start": 275, "tag": "KEY", "value": "092c90f6-a8f2-11e2-a2b9-7c6d628b25f7" } ]
src/test/google-analytics-spec.coffee
plyfe/myna-js
2
expt = window.expt = new Myna.Experiment uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c" id: "id" settings: "myna.web.sticky": false variants: [ { id: "variant1", weight: 0.5 } { id: "variant2", weight: 0.5 } ] client = new Myna.Client apiKey: "092c90f6-a8f2-11e2-a2b9-7c6d628b25f7" apiRoot: testApiRoot experiments: [ expt ] ga = new Myna.GoogleAnalytics client initialized = (fn) -> return -> window._gaq = [] expt.off() expt.unstick() ga.off() ga.listenTo(expt) client.settings.set("myna.googleAnalytics", null) fn() describe "Myna.GoogleAnalytics.record", -> it "should record view events", initialized -> variant = null success = false error = false withSuggestion expt, (v) -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "id-view", variant.id, null, false] ] it "should record reward events", initialized -> variant = null success = false error = false withSuggestion expt, (v) -> withReward expt, 1.0, -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "id-view", variant.id, null, false] ["_trackEvent", "myna", "id-reward", variant.id, 100, true] ] it "should do nothing if disabled", initialized -> variant = null success = false error = false expt.settings.set("myna.web.googleAnalytics.enabled", false) withSuggestion expt, (v) -> withReward expt, 1.0, -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [] it "should allow the user to customise event names and reward multiplier", initialized -> variant = null success = false error = false expt.settings.set "myna.web.googleAnalytics", viewEvent: "foo" rewardEvent: "bar" rewardMultiplier: 250 client.settings.set("myna.web.googleAnalytics.rewardEvent", "bar") withSuggestion expt, (v) -> withReward expt, 0.79999999999, -> # the final reward should be rounded variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "foo", variant.id, null, false] ["_trackEvent", "myna", "bar", variant.id, 200, true] # 0.8 * 250 ]
168481
expt = window.expt = new Myna.Experiment uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c" id: "id" settings: "myna.web.sticky": false variants: [ { id: "variant1", weight: 0.5 } { id: "variant2", weight: 0.5 } ] client = new Myna.Client apiKey: "<KEY>" apiRoot: testApiRoot experiments: [ expt ] ga = new Myna.GoogleAnalytics client initialized = (fn) -> return -> window._gaq = [] expt.off() expt.unstick() ga.off() ga.listenTo(expt) client.settings.set("myna.googleAnalytics", null) fn() describe "Myna.GoogleAnalytics.record", -> it "should record view events", initialized -> variant = null success = false error = false withSuggestion expt, (v) -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "id-view", variant.id, null, false] ] it "should record reward events", initialized -> variant = null success = false error = false withSuggestion expt, (v) -> withReward expt, 1.0, -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "id-view", variant.id, null, false] ["_trackEvent", "myna", "id-reward", variant.id, 100, true] ] it "should do nothing if disabled", initialized -> variant = null success = false error = false expt.settings.set("myna.web.googleAnalytics.enabled", false) withSuggestion expt, (v) -> withReward expt, 1.0, -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [] it "should allow the user to customise event names and reward multiplier", initialized -> variant = null success = false error = false expt.settings.set "myna.web.googleAnalytics", viewEvent: "foo" rewardEvent: "bar" rewardMultiplier: 250 client.settings.set("myna.web.googleAnalytics.rewardEvent", "bar") withSuggestion expt, (v) -> withReward expt, 0.79999999999, -> # the final reward should be rounded variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "foo", variant.id, null, false] ["_trackEvent", "myna", "bar", variant.id, 200, true] # 0.8 * 250 ]
true
expt = window.expt = new Myna.Experiment uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c" id: "id" settings: "myna.web.sticky": false variants: [ { id: "variant1", weight: 0.5 } { id: "variant2", weight: 0.5 } ] client = new Myna.Client apiKey: "PI:KEY:<KEY>END_PI" apiRoot: testApiRoot experiments: [ expt ] ga = new Myna.GoogleAnalytics client initialized = (fn) -> return -> window._gaq = [] expt.off() expt.unstick() ga.off() ga.listenTo(expt) client.settings.set("myna.googleAnalytics", null) fn() describe "Myna.GoogleAnalytics.record", -> it "should record view events", initialized -> variant = null success = false error = false withSuggestion expt, (v) -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "id-view", variant.id, null, false] ] it "should record reward events", initialized -> variant = null success = false error = false withSuggestion expt, (v) -> withReward expt, 1.0, -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "id-view", variant.id, null, false] ["_trackEvent", "myna", "id-reward", variant.id, 100, true] ] it "should do nothing if disabled", initialized -> variant = null success = false error = false expt.settings.set("myna.web.googleAnalytics.enabled", false) withSuggestion expt, (v) -> withReward expt, 1.0, -> variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [] it "should allow the user to customise event names and reward multiplier", initialized -> variant = null success = false error = false expt.settings.set "myna.web.googleAnalytics", viewEvent: "foo" rewardEvent: "bar" rewardMultiplier: 250 client.settings.set("myna.web.googleAnalytics.rewardEvent", "bar") withSuggestion expt, (v) -> withReward expt, 0.79999999999, -> # the final reward should be rounded variant = v waitsFor -> variant runs -> expect(_gaq).toEqual [ ["_trackEvent", "myna", "foo", variant.id, null, false] ["_trackEvent", "myna", "bar", variant.id, 200, true] # 0.8 * 250 ]
[ { "context": " @model = new Essence.Models.Timelet\n name: 'Awesome timer'\n duration: 42\n @model.state.running = tr", "end": 125, "score": 0.96760094165802, "start": 112, "tag": "NAME", "value": "Awesome timer" }, { "context": ">\n model = new Essence.Models.Timel...
spec/javascripts/modules/timelet/views/layout/timelets_panel_spec.js.coffee
kaethorn/essence
0
describe 'Essence.Views.TimeletsPanel', -> beforeEach -> @model = new Essence.Models.Timelet name: 'Awesome timer' duration: 42 @model.state.running = true @model.state.timer = 10 @collection = new Essence.Collections.Timelets [@model] @model.collection = @collection @view = new Essence.Views.TimeletsPanel model: @model, collection: @collection @html = @view.render().$el setFixtures @html afterEach -> clearInterval @view.runner describe '#constructor', -> it 'creates a layout', -> expect(@view).toBeAnInstanceOf Backbone.Marionette.LayoutView it 'sets the model and collection', -> expect(@view.model).toBe @model expect(@view.collection).toBe @collection describe '#initialize', -> it 'loads the timelet on timelet load', -> model = new Essence.Models.Timelet name: 'Fantastic timer' @collection.add model @view.trigger 'timelet:load', model.cid expect(@view.model.get('name')).toEqual 'Fantastic timer' describe 'fetching the collection', -> describe 'with a model ID', -> beforeEach -> @view.model = new Essence.Models.Timelet { id: 123 }, collection: @collection it 'loads the model as a timelet', -> stub = sinon.stub @view, 'loadTimelet' @model.trigger 'reset' expect(stub).toHaveBeenCalledWith 123 stub.restore() describe 'without a model ID', -> it 'unloads all timelets', -> stub = sinon.stub @collection, 'unload' @model.trigger 'reset' expect(stub).toHaveBeenCalled() stub.restore() describe '#render', -> it 'shows the clock', -> expect(@html).toContain 'section.clock' expect(@html.find('section.clock')).toContainText 'Awesome timer' it 'shows the timelets list', -> expect(@html).toContain 'section.timelets' expect(@html.find('section.timelets input')).toHaveValue 'Awesome timer' describe '#loadTimelet', -> it 'stops any currently running clocks', -> spy = sinon.spy @view.clock.currentView, 'stopTimelet' @view.loadTimelet @model expect(spy).toHaveBeenCalled() spy.restore() it 'loads the timelet', -> stub = sinon.stub @model, 'load' @view.loadTimelet @model expect(stub).toHaveBeenCalled() stub.restore() it 'loads the timelets attributes into the clock', -> expect(@model.get('name')).toEqual 'Awesome timer' model = new Essence.Models.Timelet name: 'Fantasic timer' @view.collection.add model @view.loadTimelet model expect(@view.model.get('name')).toEqual 'Fantasic timer' it 'renders the timelets into the clock', -> expect(@html.find('section.clock')).toContainText 'Awesome timer' model = new Essence.Models.Timelet name: 'Fantasic timer' @view.collection.add model @view.loadTimelet model expect(@html.find('section.clock')).toContainText 'Fantasic timer'
38787
describe 'Essence.Views.TimeletsPanel', -> beforeEach -> @model = new Essence.Models.Timelet name: '<NAME>' duration: 42 @model.state.running = true @model.state.timer = 10 @collection = new Essence.Collections.Timelets [@model] @model.collection = @collection @view = new Essence.Views.TimeletsPanel model: @model, collection: @collection @html = @view.render().$el setFixtures @html afterEach -> clearInterval @view.runner describe '#constructor', -> it 'creates a layout', -> expect(@view).toBeAnInstanceOf Backbone.Marionette.LayoutView it 'sets the model and collection', -> expect(@view.model).toBe @model expect(@view.collection).toBe @collection describe '#initialize', -> it 'loads the timelet on timelet load', -> model = new Essence.Models.Timelet name: '<NAME>' @collection.add model @view.trigger 'timelet:load', model.cid expect(@view.model.get('name')).toEqual '<NAME>' describe 'fetching the collection', -> describe 'with a model ID', -> beforeEach -> @view.model = new Essence.Models.Timelet { id: 123 }, collection: @collection it 'loads the model as a timelet', -> stub = sinon.stub @view, 'loadTimelet' @model.trigger 'reset' expect(stub).toHaveBeenCalledWith 123 stub.restore() describe 'without a model ID', -> it 'unloads all timelets', -> stub = sinon.stub @collection, 'unload' @model.trigger 'reset' expect(stub).toHaveBeenCalled() stub.restore() describe '#render', -> it 'shows the clock', -> expect(@html).toContain 'section.clock' expect(@html.find('section.clock')).toContainText 'Awesome timer' it 'shows the timelets list', -> expect(@html).toContain 'section.timelets' expect(@html.find('section.timelets input')).toHaveValue 'Awesome timer' describe '#loadTimelet', -> it 'stops any currently running clocks', -> spy = sinon.spy @view.clock.currentView, 'stopTimelet' @view.loadTimelet @model expect(spy).toHaveBeenCalled() spy.restore() it 'loads the timelet', -> stub = sinon.stub @model, 'load' @view.loadTimelet @model expect(stub).toHaveBeenCalled() stub.restore() it 'loads the timelets attributes into the clock', -> expect(@model.get('name')).toEqual 'Awesome timer' model = new Essence.Models.Timelet name: 'Fantasic timer' @view.collection.add model @view.loadTimelet model expect(@view.model.get('name')).toEqual 'Fantasic timer' it 'renders the timelets into the clock', -> expect(@html.find('section.clock')).toContainText 'Awesome timer' model = new Essence.Models.Timelet name: 'Fantasic timer' @view.collection.add model @view.loadTimelet model expect(@html.find('section.clock')).toContainText 'Fantasic timer'
true
describe 'Essence.Views.TimeletsPanel', -> beforeEach -> @model = new Essence.Models.Timelet name: 'PI:NAME:<NAME>END_PI' duration: 42 @model.state.running = true @model.state.timer = 10 @collection = new Essence.Collections.Timelets [@model] @model.collection = @collection @view = new Essence.Views.TimeletsPanel model: @model, collection: @collection @html = @view.render().$el setFixtures @html afterEach -> clearInterval @view.runner describe '#constructor', -> it 'creates a layout', -> expect(@view).toBeAnInstanceOf Backbone.Marionette.LayoutView it 'sets the model and collection', -> expect(@view.model).toBe @model expect(@view.collection).toBe @collection describe '#initialize', -> it 'loads the timelet on timelet load', -> model = new Essence.Models.Timelet name: 'PI:NAME:<NAME>END_PI' @collection.add model @view.trigger 'timelet:load', model.cid expect(@view.model.get('name')).toEqual 'PI:NAME:<NAME>END_PI' describe 'fetching the collection', -> describe 'with a model ID', -> beforeEach -> @view.model = new Essence.Models.Timelet { id: 123 }, collection: @collection it 'loads the model as a timelet', -> stub = sinon.stub @view, 'loadTimelet' @model.trigger 'reset' expect(stub).toHaveBeenCalledWith 123 stub.restore() describe 'without a model ID', -> it 'unloads all timelets', -> stub = sinon.stub @collection, 'unload' @model.trigger 'reset' expect(stub).toHaveBeenCalled() stub.restore() describe '#render', -> it 'shows the clock', -> expect(@html).toContain 'section.clock' expect(@html.find('section.clock')).toContainText 'Awesome timer' it 'shows the timelets list', -> expect(@html).toContain 'section.timelets' expect(@html.find('section.timelets input')).toHaveValue 'Awesome timer' describe '#loadTimelet', -> it 'stops any currently running clocks', -> spy = sinon.spy @view.clock.currentView, 'stopTimelet' @view.loadTimelet @model expect(spy).toHaveBeenCalled() spy.restore() it 'loads the timelet', -> stub = sinon.stub @model, 'load' @view.loadTimelet @model expect(stub).toHaveBeenCalled() stub.restore() it 'loads the timelets attributes into the clock', -> expect(@model.get('name')).toEqual 'Awesome timer' model = new Essence.Models.Timelet name: 'Fantasic timer' @view.collection.add model @view.loadTimelet model expect(@view.model.get('name')).toEqual 'Fantasic timer' it 'renders the timelets into the clock', -> expect(@html.find('section.clock')).toContainText 'Awesome timer' model = new Essence.Models.Timelet name: 'Fantasic timer' @view.collection.add model @view.loadTimelet model expect(@html.find('section.clock')).toContainText 'Fantasic timer'
[ { "context": "lass=\"blue\">blue</span> line?'\n # translations by David Marin (fluent/careful but not a native speaker)\n es:\n ", "end": 1595, "score": 0.9910984635353088, "start": 1584, "tag": "NAME", "value": "David Marin" } ]
tasks/line-perception/js/line-perception.coffee
jhowe-uw/tabcat
0
### Copyright (c) 2013, Regents of the University of California All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### translations = en: translation: tap_the_longer_line_html: 'Tap the longer line<br>quickly and accurately.' which_is_parallel_html: 'Which is parallel to the <span class="blue">blue</span> line?' # translations by David Marin (fluent/careful but not a native speaker) es: translation: tap_the_longer_line_html: 'Rápidamente toque la línea más larga.' which_is_parallel_html: 'Toque la flecha <span class="orange">naranja</span> que apunta en ' + 'la misma dirección que la flecha <span class="blue">azul</span>.' zh: translation: # these are all zh-Hant tap_the_longer_line_html: '儘量選出最長的線。<br>越快越好。' which_is_parallel_html: '哪一條線跟<span class="blue">藍</span>色的平行?' # abstract base class for line perception tasks LinePerceptionTask = class # aspect ratio for the task ASPECT_RATIO: 4 / 3 # match iPad # how long a fade should take, in msec FADE_DURATION: 400 # minimum intensity for task MIN_INTENSITY: 1 # max intensity for task (set in subclasses) MAX_INTENSITY: null # task is done after this many reversals (change in direction of # intensity change). Bumping against the floor/ceiling also counts # as a reversal MAX_REVERSALS: 14 # get this many correct in a row to turn off the practice mode instructions PRACTICE_CAPTION_MAX_STREAK: 2 # get this many correct in a row to leave practice mode PRACTICE_MAX_STREAK: 4 # total number of possible practice trials PRACTICE_TRIALS_MAX: 10 # start practice mode here (set in subclasses) PRACTICE_START_INTENSITY: null # start intensity of the real task here START_INTENSITY: null # testing on-task requires a 25 percent difference in the lines ON_TASK_INTENSITY: 25 # how many on-task trials per reversal CATCH_TRIAL_MAX: 2 # decrease intensity by this much when correct STEPS_DOWN: 1 # increase intensity by this much when incorrect STEPS_UP: 3 constructor: -> @practiceStreakLength = 0 @staircase = new TabCAT.Task.Staircase( intensity: @PRACTICE_START_INTENSITY minIntensity: @MIN_INTENSITY maxIntensity: @MAX_INTENSITY stepsDown: @STEPS_DOWN stepsUp: @STEPS_UP ) @catchTrialsShown = 0 @currentReversal = 0 #used to track when on-task trial should update @intensityHasBeenReset = false @lastIntensity = @START_INTENSITY @completedCatchTrials = false @isInDebugMode = TabCAT.Task.isInDebugMode() @practiceTrialsShown = 0 # call this to show the task onscreen start: -> TabCAT.Task.start( i18n: resStore: translations trackViewport: true ) TabCAT.UI.turnOffBounce() $(=> TabCAT.UI.requireLandscapeMode($('#task')) $('#task').on('mousedown touchstart', @handleStrayTouchStart) @showNextTrial() ) # show the next trial for the task showNextTrial: -> if (@staircase.numReversals > @currentReversal) @currentReversal += 1 @catchTrialsShown = 0 # reset for new reversals if @inCatchTrialReversal() and not @inPracticeMode() if @firstTrialOfCatchTrialTest() #remember intensity for after catch trials @lastIntensity = @staircase.intensity @intensityHasBeenReset = false @completedCatchTrials = false if @shouldResetIntensity() @intensityHasBeenReset = true @staircase.intensity = @lastIntensity @staircase.lastIntensityChange = 0 else if @shouldTestCatchTrial() @staircase.intensity = @ON_TASK_INTENSITY @catchTrialsShown += 1 $nextTrialDiv = @getNextTrialDiv() $('#task').empty() $('#task').append($nextTrialDiv) TabCAT.UI.fixAspectRatio($nextTrialDiv, @ASPECT_RATIO) TabCAT.UI.linkEmToPercentOfHeight($nextTrialDiv) $nextTrialDiv.fadeIn(duration: @FADE_DURATION) # event handler for taps on lines handleLineTouchStart: (event) => event.preventDefault() event.stopPropagation() state = @getTaskState() correct = event.data.correct interpretation = @staircase.addResult( correct, ignoreReversals: @inPracticeMode(), inCatchTrial: @inCatchTrialReversal() and not @completedCatchTrials, useRefinedScoring: true) if (@catchTrialsShown >= 2 and not @completedCatchTrials) @completedCatchTrials = true if @inPracticeMode() @practiceTrialsShown += 1 if correct @practiceStreakLength += 1 else @practiceStreakLength = 0 if not @inPracticeMode() # i.e. we just left practice mode # initialize the real trial @staircase.intensity = @START_INTENSITY @staircase.lastIntensityChange = 0 TabCAT.Task.logEvent(state, event, interpretation) if @staircase.numReversals >= @MAX_REVERSALS TabCAT.Task.finish() else @showNextTrial() return # event handler for taps that miss the lines handleStrayTouchStart: (event) => event.preventDefault() TabCAT.Task.logEvent(@getTaskState(), event) return # redefine this in your subclass, to show the stimuli for the task getNextTrialDiv: -> throw new Error("not defined") # get the current state of the task (for event logging) getTaskState: -> state = intensity: @staircase.intensity stimuli: @getStimuli() trialNum: @staircase.trialNum if @inPracticeMode() state.practiceMode = true else if @inCatchTrialReversal() and not @completedCatchTrials state.catchTrial = true return state # helper for getTaskState. You'll probably want to add additional fields # in your subclass getStimuli: -> stimuli = {} $practiceCaption = $('div.practiceCaption') if $practiceCaption.is(':visible') stimuli.practiceCaption = TabCAT.Task.getElementBounds( $practiceCaption[0]) return stimuli # are we in practice mode? inPracticeMode: -> return false if @practiceTrialsShown >= @PRACTICE_TRIALS_MAX @practiceStreakLength < @PRACTICE_MAX_STREAK # should we show the practice mode caption? shouldShowPracticeCaption: -> @practiceStreakLength < @PRACTICE_CAPTION_MAX_STREAK inCatchTrialReversal: -> @staircase.numReversals == 0 or \ @staircase.numReversals == 3 or \ @staircase.numReversals == 6 or \ @staircase.numReversals == 9 or \ @staircase.numReversals == 12 shouldTestCatchTrial: -> @catchTrialsShown < @CATCH_TRIAL_MAX and \ !@inPracticeMode() and @inCatchTrialReversal() shouldResetIntensity: -> @catchTrialsShown >= @CATCH_TRIAL_MAX and \ @inCatchTrialReversal() and not @intensityHasBeenReset and \ not @inPracticeMode() firstTrialOfCatchTrialTest: -> @catchTrialsShown == 0 # abstract base class for line length tasks LineLengthTask = class extends LinePerceptionTask # width of lines, as % of height LINE_WIDTH: 7 # max % difference between line lengths MAX_INTENSITY: 50 # start practice mode here PRACTICE_START_INTENSITY: 40 # range on line length, as a % of container width SHORT_LINE_RANGE: [40, 50] # start real task here START_INTENSITY: 15 # how much wider to make invisible target around lines, as a % of height TARGET_BORDER: 3 # now with line bounding boxes! getStimuli: -> _.extend(super(), lines: ( TabCAT.Task.getElementBounds(div) for div in $('div.line:visible')) ) # LINE ORIENTATION @LineOrientationTask = class extends LinePerceptionTask # max angle difference between lines MAX_INTENSITY: 89 # max rotation of the reference line MAX_ROTATION: 60 # minimum difference in orientation between trials MIN_ORIENTATION_DIFFERENCE: 20 # min orientation in practice mode (to avoid the caption) MIN_PRACTICE_MODE_ORIENTATION: 25 # start practice mode here PRACTICE_START_INTENSITY: 45 # range on line length, as a % of container width SHORT_LINE_RANGE: [40, 50] # start real task here START_INTENSITY: 15 # set up currentStimuli and lastOrientation constructor: -> super() @currentStimuli = {} @lastOrientation = 0 # create the next trial, and return the div containing it, but don't # show it or add it to the page (showNextTrial() does this) getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $referenceLineDiv = $('<div></div>', class: 'referenceLine') $line1Div = $('<div></div>', class: 'line1') $line1Div.css(@rotationCss(trial.line1.skew)) $line1TargetAreaDiv = $('<div></div>', class: 'line1Target') $line1TargetAreaDiv.css(@rotationCss(trial.line1.skew)) $line1TargetAreaDiv.on( 'mousedown touchstart', trial.line1, @handleLineTouchStart) $line2Div = $('<div></div>', class: 'line2') $line2Div.css(@rotationCss(trial.line2.skew)) $line2TargetAreaDiv = $('<div></div>', class: 'line2Target') $line2TargetAreaDiv.css(@rotationCss(trial.line2.skew)) $line2TargetAreaDiv.on( 'mousedown touchstart', trial.line2, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $line1skew = $( '<p>line 1 skew: ' + trial.line1.skew + '</p>') $line2skew = $( '<p>line 2 skew: ' + trial.line2.skew + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown, $testingCatchTrial, $intensity, $catchTrialsShown, $line1skew, $line2skew) # put them in a container, and rotate it $stimuliDiv = $('<div></div>', class: 'lineOrientationStimuli') $stimuliDiv.css(@rotationCss(trial.referenceLine.orientation)) $stimuliDiv.append( $referenceLineDiv, $line1Div, $line1TargetAreaDiv, $line2Div, $line2TargetAreaDiv) # put them in an offscreen div $trialDiv = $('<div></div>') $trialDiv.hide() # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('which_is_parallel_html')) $trialDiv.append($practiceCaptionDiv) $trialDiv.append($stimuliDiv) if @isInDebugMode == true $trialDiv.append $stats return $trialDiv # generate data, including CSS, for the next trial getNextTrial: -> orientation = @getNextOrientation() # pick direction randomly skew = @staircase.intensity * _.sample([-1, 1]) [line1Skew, line2Skew] = _.shuffle([skew, 0]) # return this and store in currentStimuli (it's hard to query the browser # about rotations) @currentStimuli = referenceLine: orientation: orientation line1: correct: line1Skew is 0 skew: line1Skew line2: correct: line2Skew is 0 skew: line2Skew # pick a new orientation that's not too close to the last one getNextOrientation: -> while true orientation = TabCAT.Math.randomUniform(-@MAX_ROTATION, @MAX_ROTATION) if Math.abs(orientation - @lastOrientation) < @MIN_ORIENTATION_DIFFERENCE continue if @shouldShowPracticeCaption() and ( \ Math.abs(orientation) < @MIN_PRACTICE_MODE_ORIENTATION) continue @lastOrientation = orientation return orientation rotationCss: (angle) -> if angle == 0 return {} value = 'rotate(' + angle + 'deg)' return { transform: value '-moz-transform': value '-ms-transform': value '-o-transform': value '-webkit-transform': value } # now, with line orientation information! getStimuli: -> stimuli = _.extend(super(), @currentStimuli) for key in ['line1', 'line2'] if stimuli[key]? stimuli[key] = _.omit(stimuli[key], 'correct') return stimuli # PARALLEL LINE LENGTH @ParallelLineLengthTask = class extends LineLengthTask # number of positions for lines (currently, top and bottom of screen). # these work with the parallelLineLayout0 and parallelLineLayout1 CSS classes NUM_LAYOUTS: 2 # offset between line centers, as a % of the shorter line's length LINE_OFFSET_AT_CENTER: 50 getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $topLineDiv = $('<div></div>', class: 'line topLine') $topLineDiv.css(trial.topLine.css) $topLineTargetDiv = $('<div></div>', class: 'lineTarget topLineTarget') $topLineTargetDiv.css(trial.topLine.targetCss) $topLineTargetDiv.on( 'mousedown touchstart', trial.topLine, @handleLineTouchStart) $bottomLineDiv = $('<div></div>', class: 'line bottomLine') $bottomLineDiv.css(trial.bottomLine.css) $bottomLineTargetDiv = $( '<div></div>', class: 'lineTarget bottomLineTarget') $bottomLineTargetDiv.css(trial.bottomLine.targetCss) $bottomLineTargetDiv.on( 'mousedown touchstart', trial.bottomLine, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + \ @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $topLineLength = $( '<p>top line length: ' + trial.topLine.targetCss.width + '</p>') $bottomLineLength = $( '<p>bottom line length: ' + trial.bottomLine.targetCss.width + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown $testingCatchTrial, $intensity, $catchTrialsShown, $topLineLength, $bottomLineLength) # put them in an offscreen div layoutNum = @staircase.trialNum % @NUM_LAYOUTS $containerDiv = $('<div></div>', class: 'parallelLineLayout' + layoutNum) $containerDiv.hide() $containerDiv.append( $topLineDiv, $topLineTargetDiv, $bottomLineDiv, $bottomLineTargetDiv) if @isInDebugMode == true $containerDiv.append $stats # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('tap_the_longer_line_html')) $containerDiv.append($practiceCaptionDiv) return $containerDiv # generate data, including CSS, for the next trial getNextTrial: -> shortLineLength = TabCAT.Math.randomUniform(@SHORT_LINE_RANGE...) longLineLength = shortLineLength * (1 + @staircase.intensity / 100) [topLineLength, bottomLineLength] = _.shuffle( [shortLineLength, longLineLength]) centerOffset = shortLineLength * @LINE_OFFSET_AT_CENTER / 100 # make sure both lines are the same distance from the edge of the screen totalWidth = topLineLength / 2 + bottomLineLength / 2 + centerOffset margin = (100 - totalWidth) / 2 # push one line to the right, and one to the left if _.sample([true, false]) topLineLeft = margin bottomLineLeft = 100 - margin - bottomLineLength else topLineLeft = 100 - margin - topLineLength bottomLineLeft = margin targetBorderWidth = @TARGET_BORDER / @ASPECT_RATIO return { topLine: css: left: topLineLeft + '%' width: topLineLength + '%' correct: topLineLength >= bottomLineLength targetCss: left: topLineLeft - targetBorderWidth + '%' width: topLineLength + targetBorderWidth * 2 + '%' bottomLine: css: left: bottomLineLeft + '%' width: bottomLineLength + '%' correct: bottomLineLength >= topLineLength targetCss: left: bottomLineLeft - targetBorderWidth + '%' width: bottomLineLength + targetBorderWidth * 2 + '%' shortLineLength: shortLineLength intensity: @staircase.intensity } # PERPENDICULAR LINE LENGTH @PerpendicularLineLengthTask = class extends LineLengthTask # fit in a square, so all orientations work the same ASPECT_RATIO: 1 / 1 # height of practice caption, as a % of container height, so # lines can avoid it CAPTION_HEIGHT: 30 # create the next trial, and return the div containing it, but don't # show it or add it to the page (showNextTrial() does this) getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $line1Div = $('<div></div>', class: 'line') $line1Div.css(trial.line1.css) $line1TargetDiv = $('<div></div>', class: 'lineTarget') $line1TargetDiv.css(trial.line1.targetCss) $line1TargetDiv.on( 'mousedown touchstart', trial.line1, @handleLineTouchStart) $line2Div = $('<div></div>', class: 'line') $line2Div.css(trial.line2.css) $line2TargetDiv = $('<div></div>', class: 'lineTarget') $line2TargetDiv.css(trial.line2.targetCss) $line2TargetDiv.on( 'mousedown touchstart', trial.line2, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $shortLineLength = $( '<p>short line length: ' + trial.line1.lineLength + '</p>') $longLineLength = $( '<p>long line length: ' + trial.line2.lineLength + '</p>') $armLength = $( '<p>arm length: ' + trial.armLength + '</p>') $stemLength = $( '<p>stem length: ' + trial.stemLength + '</p>') $angle = $( '<p>angle: ' + trial.angle + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown, $testingCatchTrial, $intensity, $catchTrialsShown, $shortLineLength, $longLineLength, $armLength, $stemLength, $angle) # put them in an offscreen div $containerDiv = $('<div></div>') $containerDiv.hide() $containerDiv.append( $line1Div, $line1TargetDiv, $line2Div, $line2TargetDiv) if @isInDebugMode == true $containerDiv.append $stats # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('tap_the_longer_line_html')) $containerDiv.append($practiceCaptionDiv) return $containerDiv # generate data, including CSS, for the next trial getNextTrial: -> shortLineLength = TabCAT.Math.randomUniform(@SHORT_LINE_RANGE...) longLineLength = shortLineLength * (1 + @staircase.intensity / 100) # Going to make a sort of T-shaped layout, and rotate it later. # The top of the T is the "arm" and the vertical part is the "stem" # Alternate between sideways and upright, but pick orientation # randomly within that. angle = 90 * (@staircase.trialNum % 2) angle += _.sample([0, 180]) if @shouldShowPracticeCaption() # when showing the practice caption, always make the vertical # line short armIsShort = (TabCAT.Math.mod(angle, 180) == 90) else armIsShort = _.sample([true, false]) if armIsShort [armLength, stemLength] = [shortLineLength, longLineLength] else [armLength, stemLength] = [longLineLength, shortLineLength] totalHeight = stemLength + @LINE_WIDTH * 2 verticalMargin = (100 - totalHeight) / 2 arm = top: verticalMargin bottom: verticalMargin + @LINE_WIDTH height: @LINE_WIDTH left: (100 - armLength) / 2 right: (100 + armLength) / 2 width: armLength stem = top: verticalMargin + 2 * @LINE_WIDTH bottom: 100 - verticalMargin height: stemLength width: @LINE_WIDTH # offset stem to the left or right to avoid perseverative tapping # in the center of the screen if _.sample([true, false]) stem.left = arm.left + @LINE_WIDTH else stem.left = arm.right - @LINE_WIDTH * 2 stem.right = stem.left + @LINE_WIDTH # rotate the "T" shape line1Box = @rotatePercentBox(arm, angle) line2Box = @rotatePercentBox(stem, angle) # if we want to show a practice caption, shift the whole thing down if @shouldShowPracticeCaption() offset = @CAPTION_HEIGHT - Math.min(line1Box.top, line2Box.top) line1Box.top += offset line1Box.bottom += offset line2Box.top += offset line2Box.bottom += offset line1TargetBox = @makeTargetBox(line1Box) line2TargetBox = @makeTargetBox(line2Box) line1Css = @percentBoxToCss(line1Box) line1TargetCss = @percentBoxToCss(line1TargetBox) line2Css = @percentBoxToCss(line2Box) line2TargetCss = @percentBoxToCss(line2TargetBox) return { line1: correct: (armLength >= stemLength) css: line1Css targetCss: line1TargetCss lineLength: shortLineLength line2: correct: (stemLength >= armLength) css: line2Css targetCss: line2TargetCss lineLength: longLineLength angle: angle armLength: armLength stemLength: stemLength } rotatePercentBox: (box, angle) -> if (angle % 90 != 0) throw Error("angle must be a multiple of 90") angle = TabCAT.Math.mod(angle, 360) if (angle == 0) return box return @rotatePercentBox({ top: 100 - box.right bottom: 100 - box.left height: box.width left: box.top right: box.bottom width: box.height }, angle - 90) percentBoxToCss: (box) -> css = {} for own key, value of box css[key] = value + '%' return css makeTargetBox: (box, borderWidth) -> borderWidth ?= @TARGET_BORDER return { top: box.top - borderWidth bottom: box.top + borderWidth height: box.height + borderWidth * 2 left: box.left - borderWidth right: box.right + borderWidth width: box.width + borderWidth * 2 }
219651
### Copyright (c) 2013, Regents of the University of California All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### translations = en: translation: tap_the_longer_line_html: 'Tap the longer line<br>quickly and accurately.' which_is_parallel_html: 'Which is parallel to the <span class="blue">blue</span> line?' # translations by <NAME> (fluent/careful but not a native speaker) es: translation: tap_the_longer_line_html: 'Rápidamente toque la línea más larga.' which_is_parallel_html: 'Toque la flecha <span class="orange">naranja</span> que apunta en ' + 'la misma dirección que la flecha <span class="blue">azul</span>.' zh: translation: # these are all zh-Hant tap_the_longer_line_html: '儘量選出最長的線。<br>越快越好。' which_is_parallel_html: '哪一條線跟<span class="blue">藍</span>色的平行?' # abstract base class for line perception tasks LinePerceptionTask = class # aspect ratio for the task ASPECT_RATIO: 4 / 3 # match iPad # how long a fade should take, in msec FADE_DURATION: 400 # minimum intensity for task MIN_INTENSITY: 1 # max intensity for task (set in subclasses) MAX_INTENSITY: null # task is done after this many reversals (change in direction of # intensity change). Bumping against the floor/ceiling also counts # as a reversal MAX_REVERSALS: 14 # get this many correct in a row to turn off the practice mode instructions PRACTICE_CAPTION_MAX_STREAK: 2 # get this many correct in a row to leave practice mode PRACTICE_MAX_STREAK: 4 # total number of possible practice trials PRACTICE_TRIALS_MAX: 10 # start practice mode here (set in subclasses) PRACTICE_START_INTENSITY: null # start intensity of the real task here START_INTENSITY: null # testing on-task requires a 25 percent difference in the lines ON_TASK_INTENSITY: 25 # how many on-task trials per reversal CATCH_TRIAL_MAX: 2 # decrease intensity by this much when correct STEPS_DOWN: 1 # increase intensity by this much when incorrect STEPS_UP: 3 constructor: -> @practiceStreakLength = 0 @staircase = new TabCAT.Task.Staircase( intensity: @PRACTICE_START_INTENSITY minIntensity: @MIN_INTENSITY maxIntensity: @MAX_INTENSITY stepsDown: @STEPS_DOWN stepsUp: @STEPS_UP ) @catchTrialsShown = 0 @currentReversal = 0 #used to track when on-task trial should update @intensityHasBeenReset = false @lastIntensity = @START_INTENSITY @completedCatchTrials = false @isInDebugMode = TabCAT.Task.isInDebugMode() @practiceTrialsShown = 0 # call this to show the task onscreen start: -> TabCAT.Task.start( i18n: resStore: translations trackViewport: true ) TabCAT.UI.turnOffBounce() $(=> TabCAT.UI.requireLandscapeMode($('#task')) $('#task').on('mousedown touchstart', @handleStrayTouchStart) @showNextTrial() ) # show the next trial for the task showNextTrial: -> if (@staircase.numReversals > @currentReversal) @currentReversal += 1 @catchTrialsShown = 0 # reset for new reversals if @inCatchTrialReversal() and not @inPracticeMode() if @firstTrialOfCatchTrialTest() #remember intensity for after catch trials @lastIntensity = @staircase.intensity @intensityHasBeenReset = false @completedCatchTrials = false if @shouldResetIntensity() @intensityHasBeenReset = true @staircase.intensity = @lastIntensity @staircase.lastIntensityChange = 0 else if @shouldTestCatchTrial() @staircase.intensity = @ON_TASK_INTENSITY @catchTrialsShown += 1 $nextTrialDiv = @getNextTrialDiv() $('#task').empty() $('#task').append($nextTrialDiv) TabCAT.UI.fixAspectRatio($nextTrialDiv, @ASPECT_RATIO) TabCAT.UI.linkEmToPercentOfHeight($nextTrialDiv) $nextTrialDiv.fadeIn(duration: @FADE_DURATION) # event handler for taps on lines handleLineTouchStart: (event) => event.preventDefault() event.stopPropagation() state = @getTaskState() correct = event.data.correct interpretation = @staircase.addResult( correct, ignoreReversals: @inPracticeMode(), inCatchTrial: @inCatchTrialReversal() and not @completedCatchTrials, useRefinedScoring: true) if (@catchTrialsShown >= 2 and not @completedCatchTrials) @completedCatchTrials = true if @inPracticeMode() @practiceTrialsShown += 1 if correct @practiceStreakLength += 1 else @practiceStreakLength = 0 if not @inPracticeMode() # i.e. we just left practice mode # initialize the real trial @staircase.intensity = @START_INTENSITY @staircase.lastIntensityChange = 0 TabCAT.Task.logEvent(state, event, interpretation) if @staircase.numReversals >= @MAX_REVERSALS TabCAT.Task.finish() else @showNextTrial() return # event handler for taps that miss the lines handleStrayTouchStart: (event) => event.preventDefault() TabCAT.Task.logEvent(@getTaskState(), event) return # redefine this in your subclass, to show the stimuli for the task getNextTrialDiv: -> throw new Error("not defined") # get the current state of the task (for event logging) getTaskState: -> state = intensity: @staircase.intensity stimuli: @getStimuli() trialNum: @staircase.trialNum if @inPracticeMode() state.practiceMode = true else if @inCatchTrialReversal() and not @completedCatchTrials state.catchTrial = true return state # helper for getTaskState. You'll probably want to add additional fields # in your subclass getStimuli: -> stimuli = {} $practiceCaption = $('div.practiceCaption') if $practiceCaption.is(':visible') stimuli.practiceCaption = TabCAT.Task.getElementBounds( $practiceCaption[0]) return stimuli # are we in practice mode? inPracticeMode: -> return false if @practiceTrialsShown >= @PRACTICE_TRIALS_MAX @practiceStreakLength < @PRACTICE_MAX_STREAK # should we show the practice mode caption? shouldShowPracticeCaption: -> @practiceStreakLength < @PRACTICE_CAPTION_MAX_STREAK inCatchTrialReversal: -> @staircase.numReversals == 0 or \ @staircase.numReversals == 3 or \ @staircase.numReversals == 6 or \ @staircase.numReversals == 9 or \ @staircase.numReversals == 12 shouldTestCatchTrial: -> @catchTrialsShown < @CATCH_TRIAL_MAX and \ !@inPracticeMode() and @inCatchTrialReversal() shouldResetIntensity: -> @catchTrialsShown >= @CATCH_TRIAL_MAX and \ @inCatchTrialReversal() and not @intensityHasBeenReset and \ not @inPracticeMode() firstTrialOfCatchTrialTest: -> @catchTrialsShown == 0 # abstract base class for line length tasks LineLengthTask = class extends LinePerceptionTask # width of lines, as % of height LINE_WIDTH: 7 # max % difference between line lengths MAX_INTENSITY: 50 # start practice mode here PRACTICE_START_INTENSITY: 40 # range on line length, as a % of container width SHORT_LINE_RANGE: [40, 50] # start real task here START_INTENSITY: 15 # how much wider to make invisible target around lines, as a % of height TARGET_BORDER: 3 # now with line bounding boxes! getStimuli: -> _.extend(super(), lines: ( TabCAT.Task.getElementBounds(div) for div in $('div.line:visible')) ) # LINE ORIENTATION @LineOrientationTask = class extends LinePerceptionTask # max angle difference between lines MAX_INTENSITY: 89 # max rotation of the reference line MAX_ROTATION: 60 # minimum difference in orientation between trials MIN_ORIENTATION_DIFFERENCE: 20 # min orientation in practice mode (to avoid the caption) MIN_PRACTICE_MODE_ORIENTATION: 25 # start practice mode here PRACTICE_START_INTENSITY: 45 # range on line length, as a % of container width SHORT_LINE_RANGE: [40, 50] # start real task here START_INTENSITY: 15 # set up currentStimuli and lastOrientation constructor: -> super() @currentStimuli = {} @lastOrientation = 0 # create the next trial, and return the div containing it, but don't # show it or add it to the page (showNextTrial() does this) getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $referenceLineDiv = $('<div></div>', class: 'referenceLine') $line1Div = $('<div></div>', class: 'line1') $line1Div.css(@rotationCss(trial.line1.skew)) $line1TargetAreaDiv = $('<div></div>', class: 'line1Target') $line1TargetAreaDiv.css(@rotationCss(trial.line1.skew)) $line1TargetAreaDiv.on( 'mousedown touchstart', trial.line1, @handleLineTouchStart) $line2Div = $('<div></div>', class: 'line2') $line2Div.css(@rotationCss(trial.line2.skew)) $line2TargetAreaDiv = $('<div></div>', class: 'line2Target') $line2TargetAreaDiv.css(@rotationCss(trial.line2.skew)) $line2TargetAreaDiv.on( 'mousedown touchstart', trial.line2, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $line1skew = $( '<p>line 1 skew: ' + trial.line1.skew + '</p>') $line2skew = $( '<p>line 2 skew: ' + trial.line2.skew + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown, $testingCatchTrial, $intensity, $catchTrialsShown, $line1skew, $line2skew) # put them in a container, and rotate it $stimuliDiv = $('<div></div>', class: 'lineOrientationStimuli') $stimuliDiv.css(@rotationCss(trial.referenceLine.orientation)) $stimuliDiv.append( $referenceLineDiv, $line1Div, $line1TargetAreaDiv, $line2Div, $line2TargetAreaDiv) # put them in an offscreen div $trialDiv = $('<div></div>') $trialDiv.hide() # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('which_is_parallel_html')) $trialDiv.append($practiceCaptionDiv) $trialDiv.append($stimuliDiv) if @isInDebugMode == true $trialDiv.append $stats return $trialDiv # generate data, including CSS, for the next trial getNextTrial: -> orientation = @getNextOrientation() # pick direction randomly skew = @staircase.intensity * _.sample([-1, 1]) [line1Skew, line2Skew] = _.shuffle([skew, 0]) # return this and store in currentStimuli (it's hard to query the browser # about rotations) @currentStimuli = referenceLine: orientation: orientation line1: correct: line1Skew is 0 skew: line1Skew line2: correct: line2Skew is 0 skew: line2Skew # pick a new orientation that's not too close to the last one getNextOrientation: -> while true orientation = TabCAT.Math.randomUniform(-@MAX_ROTATION, @MAX_ROTATION) if Math.abs(orientation - @lastOrientation) < @MIN_ORIENTATION_DIFFERENCE continue if @shouldShowPracticeCaption() and ( \ Math.abs(orientation) < @MIN_PRACTICE_MODE_ORIENTATION) continue @lastOrientation = orientation return orientation rotationCss: (angle) -> if angle == 0 return {} value = 'rotate(' + angle + 'deg)' return { transform: value '-moz-transform': value '-ms-transform': value '-o-transform': value '-webkit-transform': value } # now, with line orientation information! getStimuli: -> stimuli = _.extend(super(), @currentStimuli) for key in ['line1', 'line2'] if stimuli[key]? stimuli[key] = _.omit(stimuli[key], 'correct') return stimuli # PARALLEL LINE LENGTH @ParallelLineLengthTask = class extends LineLengthTask # number of positions for lines (currently, top and bottom of screen). # these work with the parallelLineLayout0 and parallelLineLayout1 CSS classes NUM_LAYOUTS: 2 # offset between line centers, as a % of the shorter line's length LINE_OFFSET_AT_CENTER: 50 getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $topLineDiv = $('<div></div>', class: 'line topLine') $topLineDiv.css(trial.topLine.css) $topLineTargetDiv = $('<div></div>', class: 'lineTarget topLineTarget') $topLineTargetDiv.css(trial.topLine.targetCss) $topLineTargetDiv.on( 'mousedown touchstart', trial.topLine, @handleLineTouchStart) $bottomLineDiv = $('<div></div>', class: 'line bottomLine') $bottomLineDiv.css(trial.bottomLine.css) $bottomLineTargetDiv = $( '<div></div>', class: 'lineTarget bottomLineTarget') $bottomLineTargetDiv.css(trial.bottomLine.targetCss) $bottomLineTargetDiv.on( 'mousedown touchstart', trial.bottomLine, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + \ @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $topLineLength = $( '<p>top line length: ' + trial.topLine.targetCss.width + '</p>') $bottomLineLength = $( '<p>bottom line length: ' + trial.bottomLine.targetCss.width + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown $testingCatchTrial, $intensity, $catchTrialsShown, $topLineLength, $bottomLineLength) # put them in an offscreen div layoutNum = @staircase.trialNum % @NUM_LAYOUTS $containerDiv = $('<div></div>', class: 'parallelLineLayout' + layoutNum) $containerDiv.hide() $containerDiv.append( $topLineDiv, $topLineTargetDiv, $bottomLineDiv, $bottomLineTargetDiv) if @isInDebugMode == true $containerDiv.append $stats # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('tap_the_longer_line_html')) $containerDiv.append($practiceCaptionDiv) return $containerDiv # generate data, including CSS, for the next trial getNextTrial: -> shortLineLength = TabCAT.Math.randomUniform(@SHORT_LINE_RANGE...) longLineLength = shortLineLength * (1 + @staircase.intensity / 100) [topLineLength, bottomLineLength] = _.shuffle( [shortLineLength, longLineLength]) centerOffset = shortLineLength * @LINE_OFFSET_AT_CENTER / 100 # make sure both lines are the same distance from the edge of the screen totalWidth = topLineLength / 2 + bottomLineLength / 2 + centerOffset margin = (100 - totalWidth) / 2 # push one line to the right, and one to the left if _.sample([true, false]) topLineLeft = margin bottomLineLeft = 100 - margin - bottomLineLength else topLineLeft = 100 - margin - topLineLength bottomLineLeft = margin targetBorderWidth = @TARGET_BORDER / @ASPECT_RATIO return { topLine: css: left: topLineLeft + '%' width: topLineLength + '%' correct: topLineLength >= bottomLineLength targetCss: left: topLineLeft - targetBorderWidth + '%' width: topLineLength + targetBorderWidth * 2 + '%' bottomLine: css: left: bottomLineLeft + '%' width: bottomLineLength + '%' correct: bottomLineLength >= topLineLength targetCss: left: bottomLineLeft - targetBorderWidth + '%' width: bottomLineLength + targetBorderWidth * 2 + '%' shortLineLength: shortLineLength intensity: @staircase.intensity } # PERPENDICULAR LINE LENGTH @PerpendicularLineLengthTask = class extends LineLengthTask # fit in a square, so all orientations work the same ASPECT_RATIO: 1 / 1 # height of practice caption, as a % of container height, so # lines can avoid it CAPTION_HEIGHT: 30 # create the next trial, and return the div containing it, but don't # show it or add it to the page (showNextTrial() does this) getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $line1Div = $('<div></div>', class: 'line') $line1Div.css(trial.line1.css) $line1TargetDiv = $('<div></div>', class: 'lineTarget') $line1TargetDiv.css(trial.line1.targetCss) $line1TargetDiv.on( 'mousedown touchstart', trial.line1, @handleLineTouchStart) $line2Div = $('<div></div>', class: 'line') $line2Div.css(trial.line2.css) $line2TargetDiv = $('<div></div>', class: 'lineTarget') $line2TargetDiv.css(trial.line2.targetCss) $line2TargetDiv.on( 'mousedown touchstart', trial.line2, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $shortLineLength = $( '<p>short line length: ' + trial.line1.lineLength + '</p>') $longLineLength = $( '<p>long line length: ' + trial.line2.lineLength + '</p>') $armLength = $( '<p>arm length: ' + trial.armLength + '</p>') $stemLength = $( '<p>stem length: ' + trial.stemLength + '</p>') $angle = $( '<p>angle: ' + trial.angle + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown, $testingCatchTrial, $intensity, $catchTrialsShown, $shortLineLength, $longLineLength, $armLength, $stemLength, $angle) # put them in an offscreen div $containerDiv = $('<div></div>') $containerDiv.hide() $containerDiv.append( $line1Div, $line1TargetDiv, $line2Div, $line2TargetDiv) if @isInDebugMode == true $containerDiv.append $stats # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('tap_the_longer_line_html')) $containerDiv.append($practiceCaptionDiv) return $containerDiv # generate data, including CSS, for the next trial getNextTrial: -> shortLineLength = TabCAT.Math.randomUniform(@SHORT_LINE_RANGE...) longLineLength = shortLineLength * (1 + @staircase.intensity / 100) # Going to make a sort of T-shaped layout, and rotate it later. # The top of the T is the "arm" and the vertical part is the "stem" # Alternate between sideways and upright, but pick orientation # randomly within that. angle = 90 * (@staircase.trialNum % 2) angle += _.sample([0, 180]) if @shouldShowPracticeCaption() # when showing the practice caption, always make the vertical # line short armIsShort = (TabCAT.Math.mod(angle, 180) == 90) else armIsShort = _.sample([true, false]) if armIsShort [armLength, stemLength] = [shortLineLength, longLineLength] else [armLength, stemLength] = [longLineLength, shortLineLength] totalHeight = stemLength + @LINE_WIDTH * 2 verticalMargin = (100 - totalHeight) / 2 arm = top: verticalMargin bottom: verticalMargin + @LINE_WIDTH height: @LINE_WIDTH left: (100 - armLength) / 2 right: (100 + armLength) / 2 width: armLength stem = top: verticalMargin + 2 * @LINE_WIDTH bottom: 100 - verticalMargin height: stemLength width: @LINE_WIDTH # offset stem to the left or right to avoid perseverative tapping # in the center of the screen if _.sample([true, false]) stem.left = arm.left + @LINE_WIDTH else stem.left = arm.right - @LINE_WIDTH * 2 stem.right = stem.left + @LINE_WIDTH # rotate the "T" shape line1Box = @rotatePercentBox(arm, angle) line2Box = @rotatePercentBox(stem, angle) # if we want to show a practice caption, shift the whole thing down if @shouldShowPracticeCaption() offset = @CAPTION_HEIGHT - Math.min(line1Box.top, line2Box.top) line1Box.top += offset line1Box.bottom += offset line2Box.top += offset line2Box.bottom += offset line1TargetBox = @makeTargetBox(line1Box) line2TargetBox = @makeTargetBox(line2Box) line1Css = @percentBoxToCss(line1Box) line1TargetCss = @percentBoxToCss(line1TargetBox) line2Css = @percentBoxToCss(line2Box) line2TargetCss = @percentBoxToCss(line2TargetBox) return { line1: correct: (armLength >= stemLength) css: line1Css targetCss: line1TargetCss lineLength: shortLineLength line2: correct: (stemLength >= armLength) css: line2Css targetCss: line2TargetCss lineLength: longLineLength angle: angle armLength: armLength stemLength: stemLength } rotatePercentBox: (box, angle) -> if (angle % 90 != 0) throw Error("angle must be a multiple of 90") angle = TabCAT.Math.mod(angle, 360) if (angle == 0) return box return @rotatePercentBox({ top: 100 - box.right bottom: 100 - box.left height: box.width left: box.top right: box.bottom width: box.height }, angle - 90) percentBoxToCss: (box) -> css = {} for own key, value of box css[key] = value + '%' return css makeTargetBox: (box, borderWidth) -> borderWidth ?= @TARGET_BORDER return { top: box.top - borderWidth bottom: box.top + borderWidth height: box.height + borderWidth * 2 left: box.left - borderWidth right: box.right + borderWidth width: box.width + borderWidth * 2 }
true
### Copyright (c) 2013, Regents of the University of California All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### translations = en: translation: tap_the_longer_line_html: 'Tap the longer line<br>quickly and accurately.' which_is_parallel_html: 'Which is parallel to the <span class="blue">blue</span> line?' # translations by PI:NAME:<NAME>END_PI (fluent/careful but not a native speaker) es: translation: tap_the_longer_line_html: 'Rápidamente toque la línea más larga.' which_is_parallel_html: 'Toque la flecha <span class="orange">naranja</span> que apunta en ' + 'la misma dirección que la flecha <span class="blue">azul</span>.' zh: translation: # these are all zh-Hant tap_the_longer_line_html: '儘量選出最長的線。<br>越快越好。' which_is_parallel_html: '哪一條線跟<span class="blue">藍</span>色的平行?' # abstract base class for line perception tasks LinePerceptionTask = class # aspect ratio for the task ASPECT_RATIO: 4 / 3 # match iPad # how long a fade should take, in msec FADE_DURATION: 400 # minimum intensity for task MIN_INTENSITY: 1 # max intensity for task (set in subclasses) MAX_INTENSITY: null # task is done after this many reversals (change in direction of # intensity change). Bumping against the floor/ceiling also counts # as a reversal MAX_REVERSALS: 14 # get this many correct in a row to turn off the practice mode instructions PRACTICE_CAPTION_MAX_STREAK: 2 # get this many correct in a row to leave practice mode PRACTICE_MAX_STREAK: 4 # total number of possible practice trials PRACTICE_TRIALS_MAX: 10 # start practice mode here (set in subclasses) PRACTICE_START_INTENSITY: null # start intensity of the real task here START_INTENSITY: null # testing on-task requires a 25 percent difference in the lines ON_TASK_INTENSITY: 25 # how many on-task trials per reversal CATCH_TRIAL_MAX: 2 # decrease intensity by this much when correct STEPS_DOWN: 1 # increase intensity by this much when incorrect STEPS_UP: 3 constructor: -> @practiceStreakLength = 0 @staircase = new TabCAT.Task.Staircase( intensity: @PRACTICE_START_INTENSITY minIntensity: @MIN_INTENSITY maxIntensity: @MAX_INTENSITY stepsDown: @STEPS_DOWN stepsUp: @STEPS_UP ) @catchTrialsShown = 0 @currentReversal = 0 #used to track when on-task trial should update @intensityHasBeenReset = false @lastIntensity = @START_INTENSITY @completedCatchTrials = false @isInDebugMode = TabCAT.Task.isInDebugMode() @practiceTrialsShown = 0 # call this to show the task onscreen start: -> TabCAT.Task.start( i18n: resStore: translations trackViewport: true ) TabCAT.UI.turnOffBounce() $(=> TabCAT.UI.requireLandscapeMode($('#task')) $('#task').on('mousedown touchstart', @handleStrayTouchStart) @showNextTrial() ) # show the next trial for the task showNextTrial: -> if (@staircase.numReversals > @currentReversal) @currentReversal += 1 @catchTrialsShown = 0 # reset for new reversals if @inCatchTrialReversal() and not @inPracticeMode() if @firstTrialOfCatchTrialTest() #remember intensity for after catch trials @lastIntensity = @staircase.intensity @intensityHasBeenReset = false @completedCatchTrials = false if @shouldResetIntensity() @intensityHasBeenReset = true @staircase.intensity = @lastIntensity @staircase.lastIntensityChange = 0 else if @shouldTestCatchTrial() @staircase.intensity = @ON_TASK_INTENSITY @catchTrialsShown += 1 $nextTrialDiv = @getNextTrialDiv() $('#task').empty() $('#task').append($nextTrialDiv) TabCAT.UI.fixAspectRatio($nextTrialDiv, @ASPECT_RATIO) TabCAT.UI.linkEmToPercentOfHeight($nextTrialDiv) $nextTrialDiv.fadeIn(duration: @FADE_DURATION) # event handler for taps on lines handleLineTouchStart: (event) => event.preventDefault() event.stopPropagation() state = @getTaskState() correct = event.data.correct interpretation = @staircase.addResult( correct, ignoreReversals: @inPracticeMode(), inCatchTrial: @inCatchTrialReversal() and not @completedCatchTrials, useRefinedScoring: true) if (@catchTrialsShown >= 2 and not @completedCatchTrials) @completedCatchTrials = true if @inPracticeMode() @practiceTrialsShown += 1 if correct @practiceStreakLength += 1 else @practiceStreakLength = 0 if not @inPracticeMode() # i.e. we just left practice mode # initialize the real trial @staircase.intensity = @START_INTENSITY @staircase.lastIntensityChange = 0 TabCAT.Task.logEvent(state, event, interpretation) if @staircase.numReversals >= @MAX_REVERSALS TabCAT.Task.finish() else @showNextTrial() return # event handler for taps that miss the lines handleStrayTouchStart: (event) => event.preventDefault() TabCAT.Task.logEvent(@getTaskState(), event) return # redefine this in your subclass, to show the stimuli for the task getNextTrialDiv: -> throw new Error("not defined") # get the current state of the task (for event logging) getTaskState: -> state = intensity: @staircase.intensity stimuli: @getStimuli() trialNum: @staircase.trialNum if @inPracticeMode() state.practiceMode = true else if @inCatchTrialReversal() and not @completedCatchTrials state.catchTrial = true return state # helper for getTaskState. You'll probably want to add additional fields # in your subclass getStimuli: -> stimuli = {} $practiceCaption = $('div.practiceCaption') if $practiceCaption.is(':visible') stimuli.practiceCaption = TabCAT.Task.getElementBounds( $practiceCaption[0]) return stimuli # are we in practice mode? inPracticeMode: -> return false if @practiceTrialsShown >= @PRACTICE_TRIALS_MAX @practiceStreakLength < @PRACTICE_MAX_STREAK # should we show the practice mode caption? shouldShowPracticeCaption: -> @practiceStreakLength < @PRACTICE_CAPTION_MAX_STREAK inCatchTrialReversal: -> @staircase.numReversals == 0 or \ @staircase.numReversals == 3 or \ @staircase.numReversals == 6 or \ @staircase.numReversals == 9 or \ @staircase.numReversals == 12 shouldTestCatchTrial: -> @catchTrialsShown < @CATCH_TRIAL_MAX and \ !@inPracticeMode() and @inCatchTrialReversal() shouldResetIntensity: -> @catchTrialsShown >= @CATCH_TRIAL_MAX and \ @inCatchTrialReversal() and not @intensityHasBeenReset and \ not @inPracticeMode() firstTrialOfCatchTrialTest: -> @catchTrialsShown == 0 # abstract base class for line length tasks LineLengthTask = class extends LinePerceptionTask # width of lines, as % of height LINE_WIDTH: 7 # max % difference between line lengths MAX_INTENSITY: 50 # start practice mode here PRACTICE_START_INTENSITY: 40 # range on line length, as a % of container width SHORT_LINE_RANGE: [40, 50] # start real task here START_INTENSITY: 15 # how much wider to make invisible target around lines, as a % of height TARGET_BORDER: 3 # now with line bounding boxes! getStimuli: -> _.extend(super(), lines: ( TabCAT.Task.getElementBounds(div) for div in $('div.line:visible')) ) # LINE ORIENTATION @LineOrientationTask = class extends LinePerceptionTask # max angle difference between lines MAX_INTENSITY: 89 # max rotation of the reference line MAX_ROTATION: 60 # minimum difference in orientation between trials MIN_ORIENTATION_DIFFERENCE: 20 # min orientation in practice mode (to avoid the caption) MIN_PRACTICE_MODE_ORIENTATION: 25 # start practice mode here PRACTICE_START_INTENSITY: 45 # range on line length, as a % of container width SHORT_LINE_RANGE: [40, 50] # start real task here START_INTENSITY: 15 # set up currentStimuli and lastOrientation constructor: -> super() @currentStimuli = {} @lastOrientation = 0 # create the next trial, and return the div containing it, but don't # show it or add it to the page (showNextTrial() does this) getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $referenceLineDiv = $('<div></div>', class: 'referenceLine') $line1Div = $('<div></div>', class: 'line1') $line1Div.css(@rotationCss(trial.line1.skew)) $line1TargetAreaDiv = $('<div></div>', class: 'line1Target') $line1TargetAreaDiv.css(@rotationCss(trial.line1.skew)) $line1TargetAreaDiv.on( 'mousedown touchstart', trial.line1, @handleLineTouchStart) $line2Div = $('<div></div>', class: 'line2') $line2Div.css(@rotationCss(trial.line2.skew)) $line2TargetAreaDiv = $('<div></div>', class: 'line2Target') $line2TargetAreaDiv.css(@rotationCss(trial.line2.skew)) $line2TargetAreaDiv.on( 'mousedown touchstart', trial.line2, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $line1skew = $( '<p>line 1 skew: ' + trial.line1.skew + '</p>') $line2skew = $( '<p>line 2 skew: ' + trial.line2.skew + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown, $testingCatchTrial, $intensity, $catchTrialsShown, $line1skew, $line2skew) # put them in a container, and rotate it $stimuliDiv = $('<div></div>', class: 'lineOrientationStimuli') $stimuliDiv.css(@rotationCss(trial.referenceLine.orientation)) $stimuliDiv.append( $referenceLineDiv, $line1Div, $line1TargetAreaDiv, $line2Div, $line2TargetAreaDiv) # put them in an offscreen div $trialDiv = $('<div></div>') $trialDiv.hide() # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('which_is_parallel_html')) $trialDiv.append($practiceCaptionDiv) $trialDiv.append($stimuliDiv) if @isInDebugMode == true $trialDiv.append $stats return $trialDiv # generate data, including CSS, for the next trial getNextTrial: -> orientation = @getNextOrientation() # pick direction randomly skew = @staircase.intensity * _.sample([-1, 1]) [line1Skew, line2Skew] = _.shuffle([skew, 0]) # return this and store in currentStimuli (it's hard to query the browser # about rotations) @currentStimuli = referenceLine: orientation: orientation line1: correct: line1Skew is 0 skew: line1Skew line2: correct: line2Skew is 0 skew: line2Skew # pick a new orientation that's not too close to the last one getNextOrientation: -> while true orientation = TabCAT.Math.randomUniform(-@MAX_ROTATION, @MAX_ROTATION) if Math.abs(orientation - @lastOrientation) < @MIN_ORIENTATION_DIFFERENCE continue if @shouldShowPracticeCaption() and ( \ Math.abs(orientation) < @MIN_PRACTICE_MODE_ORIENTATION) continue @lastOrientation = orientation return orientation rotationCss: (angle) -> if angle == 0 return {} value = 'rotate(' + angle + 'deg)' return { transform: value '-moz-transform': value '-ms-transform': value '-o-transform': value '-webkit-transform': value } # now, with line orientation information! getStimuli: -> stimuli = _.extend(super(), @currentStimuli) for key in ['line1', 'line2'] if stimuli[key]? stimuli[key] = _.omit(stimuli[key], 'correct') return stimuli # PARALLEL LINE LENGTH @ParallelLineLengthTask = class extends LineLengthTask # number of positions for lines (currently, top and bottom of screen). # these work with the parallelLineLayout0 and parallelLineLayout1 CSS classes NUM_LAYOUTS: 2 # offset between line centers, as a % of the shorter line's length LINE_OFFSET_AT_CENTER: 50 getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $topLineDiv = $('<div></div>', class: 'line topLine') $topLineDiv.css(trial.topLine.css) $topLineTargetDiv = $('<div></div>', class: 'lineTarget topLineTarget') $topLineTargetDiv.css(trial.topLine.targetCss) $topLineTargetDiv.on( 'mousedown touchstart', trial.topLine, @handleLineTouchStart) $bottomLineDiv = $('<div></div>', class: 'line bottomLine') $bottomLineDiv.css(trial.bottomLine.css) $bottomLineTargetDiv = $( '<div></div>', class: 'lineTarget bottomLineTarget') $bottomLineTargetDiv.css(trial.bottomLine.targetCss) $bottomLineTargetDiv.on( 'mousedown touchstart', trial.bottomLine, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + \ @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $topLineLength = $( '<p>top line length: ' + trial.topLine.targetCss.width + '</p>') $bottomLineLength = $( '<p>bottom line length: ' + trial.bottomLine.targetCss.width + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown $testingCatchTrial, $intensity, $catchTrialsShown, $topLineLength, $bottomLineLength) # put them in an offscreen div layoutNum = @staircase.trialNum % @NUM_LAYOUTS $containerDiv = $('<div></div>', class: 'parallelLineLayout' + layoutNum) $containerDiv.hide() $containerDiv.append( $topLineDiv, $topLineTargetDiv, $bottomLineDiv, $bottomLineTargetDiv) if @isInDebugMode == true $containerDiv.append $stats # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('tap_the_longer_line_html')) $containerDiv.append($practiceCaptionDiv) return $containerDiv # generate data, including CSS, for the next trial getNextTrial: -> shortLineLength = TabCAT.Math.randomUniform(@SHORT_LINE_RANGE...) longLineLength = shortLineLength * (1 + @staircase.intensity / 100) [topLineLength, bottomLineLength] = _.shuffle( [shortLineLength, longLineLength]) centerOffset = shortLineLength * @LINE_OFFSET_AT_CENTER / 100 # make sure both lines are the same distance from the edge of the screen totalWidth = topLineLength / 2 + bottomLineLength / 2 + centerOffset margin = (100 - totalWidth) / 2 # push one line to the right, and one to the left if _.sample([true, false]) topLineLeft = margin bottomLineLeft = 100 - margin - bottomLineLength else topLineLeft = 100 - margin - topLineLength bottomLineLeft = margin targetBorderWidth = @TARGET_BORDER / @ASPECT_RATIO return { topLine: css: left: topLineLeft + '%' width: topLineLength + '%' correct: topLineLength >= bottomLineLength targetCss: left: topLineLeft - targetBorderWidth + '%' width: topLineLength + targetBorderWidth * 2 + '%' bottomLine: css: left: bottomLineLeft + '%' width: bottomLineLength + '%' correct: bottomLineLength >= topLineLength targetCss: left: bottomLineLeft - targetBorderWidth + '%' width: bottomLineLength + targetBorderWidth * 2 + '%' shortLineLength: shortLineLength intensity: @staircase.intensity } # PERPENDICULAR LINE LENGTH @PerpendicularLineLengthTask = class extends LineLengthTask # fit in a square, so all orientations work the same ASPECT_RATIO: 1 / 1 # height of practice caption, as a % of container height, so # lines can avoid it CAPTION_HEIGHT: 30 # create the next trial, and return the div containing it, but don't # show it or add it to the page (showNextTrial() does this) getNextTrialDiv: -> # get line offsets and widths for next trial trial = @getNextTrial() # construct divs for these lines $line1Div = $('<div></div>', class: 'line') $line1Div.css(trial.line1.css) $line1TargetDiv = $('<div></div>', class: 'lineTarget') $line1TargetDiv.css(trial.line1.targetCss) $line1TargetDiv.on( 'mousedown touchstart', trial.line1, @handleLineTouchStart) $line2Div = $('<div></div>', class: 'line') $line2Div.css(trial.line2.css) $line2TargetDiv = $('<div></div>', class: 'lineTarget') $line2TargetDiv.css(trial.line2.targetCss) $line2TargetDiv.on( 'mousedown touchstart', trial.line2, @handleLineTouchStart) #stats for debugging, will remove for production $currentReversal = $('<p>current reversal: ' + @currentReversal + '</p>') $numReversals = $('<p>reversal: ' + @staircase.numReversals + '</p>') $practiceTrialsShown = $('<p>practice trials shown: ' + @practiceTrialsShown + '</p>') $testingCatchTrial = $( '<p>testing on task: ' + @shouldTestCatchTrial() + '</p>') $intensity = $('<p>intensity: ' + @staircase.intensity + '</p>') $catchTrialsShown = $( '<p>on task trials shown: ' + @catchTrialsShown + '</p>') $shortLineLength = $( '<p>short line length: ' + trial.line1.lineLength + '</p>') $longLineLength = $( '<p>long line length: ' + trial.line2.lineLength + '</p>') $armLength = $( '<p>arm length: ' + trial.armLength + '</p>') $stemLength = $( '<p>stem length: ' + trial.stemLength + '</p>') $angle = $( '<p>angle: ' + trial.angle + '</p>') $stats = $('<div></div>', class: 'testStats') $stats.append($currentReversal, $numReversals, $practiceTrialsShown, $testingCatchTrial, $intensity, $catchTrialsShown, $shortLineLength, $longLineLength, $armLength, $stemLength, $angle) # put them in an offscreen div $containerDiv = $('<div></div>') $containerDiv.hide() $containerDiv.append( $line1Div, $line1TargetDiv, $line2Div, $line2TargetDiv) if @isInDebugMode == true $containerDiv.append $stats # show practice caption, if required if @shouldShowPracticeCaption() $practiceCaptionDiv = $('<div></div>', class: 'practiceCaption') $practiceCaptionDiv.html($.t('tap_the_longer_line_html')) $containerDiv.append($practiceCaptionDiv) return $containerDiv # generate data, including CSS, for the next trial getNextTrial: -> shortLineLength = TabCAT.Math.randomUniform(@SHORT_LINE_RANGE...) longLineLength = shortLineLength * (1 + @staircase.intensity / 100) # Going to make a sort of T-shaped layout, and rotate it later. # The top of the T is the "arm" and the vertical part is the "stem" # Alternate between sideways and upright, but pick orientation # randomly within that. angle = 90 * (@staircase.trialNum % 2) angle += _.sample([0, 180]) if @shouldShowPracticeCaption() # when showing the practice caption, always make the vertical # line short armIsShort = (TabCAT.Math.mod(angle, 180) == 90) else armIsShort = _.sample([true, false]) if armIsShort [armLength, stemLength] = [shortLineLength, longLineLength] else [armLength, stemLength] = [longLineLength, shortLineLength] totalHeight = stemLength + @LINE_WIDTH * 2 verticalMargin = (100 - totalHeight) / 2 arm = top: verticalMargin bottom: verticalMargin + @LINE_WIDTH height: @LINE_WIDTH left: (100 - armLength) / 2 right: (100 + armLength) / 2 width: armLength stem = top: verticalMargin + 2 * @LINE_WIDTH bottom: 100 - verticalMargin height: stemLength width: @LINE_WIDTH # offset stem to the left or right to avoid perseverative tapping # in the center of the screen if _.sample([true, false]) stem.left = arm.left + @LINE_WIDTH else stem.left = arm.right - @LINE_WIDTH * 2 stem.right = stem.left + @LINE_WIDTH # rotate the "T" shape line1Box = @rotatePercentBox(arm, angle) line2Box = @rotatePercentBox(stem, angle) # if we want to show a practice caption, shift the whole thing down if @shouldShowPracticeCaption() offset = @CAPTION_HEIGHT - Math.min(line1Box.top, line2Box.top) line1Box.top += offset line1Box.bottom += offset line2Box.top += offset line2Box.bottom += offset line1TargetBox = @makeTargetBox(line1Box) line2TargetBox = @makeTargetBox(line2Box) line1Css = @percentBoxToCss(line1Box) line1TargetCss = @percentBoxToCss(line1TargetBox) line2Css = @percentBoxToCss(line2Box) line2TargetCss = @percentBoxToCss(line2TargetBox) return { line1: correct: (armLength >= stemLength) css: line1Css targetCss: line1TargetCss lineLength: shortLineLength line2: correct: (stemLength >= armLength) css: line2Css targetCss: line2TargetCss lineLength: longLineLength angle: angle armLength: armLength stemLength: stemLength } rotatePercentBox: (box, angle) -> if (angle % 90 != 0) throw Error("angle must be a multiple of 90") angle = TabCAT.Math.mod(angle, 360) if (angle == 0) return box return @rotatePercentBox({ top: 100 - box.right bottom: 100 - box.left height: box.width left: box.top right: box.bottom width: box.height }, angle - 90) percentBoxToCss: (box) -> css = {} for own key, value of box css[key] = value + '%' return css makeTargetBox: (box, borderWidth) -> borderWidth ?= @TARGET_BORDER return { top: box.top - borderWidth bottom: box.top + borderWidth height: box.height + borderWidth * 2 left: box.left - borderWidth right: box.right + borderWidth width: box.width + borderWidth * 2 }
[ { "context": " * Maple.css\n * Copyright 2013 Koji Ishimoto\n * Licensed under the MIT License\n ", "end": 1190, "score": 0.9997862577438354, "start": 1177, "tag": "NAME", "value": "Koji Ishimoto" } ]
app/templates/src/Gruntfile.coffee
t32k/generator-maple
1
module.exports = (grunt) -> 'use strict' # Project configuration. grunt.initConfig # Metadata. pkg: grunt.file.readJSON 'package.json' # Parse CSS and add vendor-prefixed CSS properties using the Can I Use database. autoprefixer: options: browsers: ['ios >= 5', 'android >= 2.3'] dist: src: 'build/files/css/maple.css' # Start a static web server. # Reload assets live in the browser connect: app: options: port: 8080 base: 'build/' open: 'http://localhost:8080/' doc: options: port: 8081 base: 'doc/' open: 'http://localhost:8081/' # Sort CSS properties in specific order. csscomb: dist: options: config: '.csscombrc' files: 'build/files/css/maple.css': ['build/files/css/maple.css'] # Lint CSS files. csslint: dist: options: csslintrc: '.csslintrc' src: ['build/files/css/maple.css'] # Minify CSS files with CSSO. csso: dist: options: banner: """ /* * Maple.css * Copyright 2013 Koji Ishimoto * Licensed under the MIT License */ """ files: 'build/files/css/maple.min.css': ['build/files/css/maple.css'] # Optimize PNG, JPEG, GIF images with grunt task. image: options: optimizationLevel: 3 dist: files: [ expand: true cwd: "build/files/img/sprite/" src: ["**/*.{png,jpg,gif}"] dest: "build/files/img/sprite/" ] # KSS styleguide generator for grunt. kss: options: includeType: 'css' includePath: 'build/files/css/maple.css' template: 'doc/template' dist: files: # dest : src 'doc/': ['src/stylesheets/'] # Grunt task to compile Sass SCSS to CSS sass: dist: files: 'build/files/css/maple.css': 'src/stylesheets/maple.scss' # Grunt task for creating spritesheets and their coordinates sprite: dist: src: 'build/files/img/sprite/tabs/*.png' destImg: 'build/files/img/sprite/tabs.png' imgPath: '/files/img/sprite/tabs.png' destCSS: 'build/files/css/sass/lib/_sprite.scss' algorithm: 'binary-tree' padding: 2 cssTemplate: 'build/files/img/sprite/spritesmith.mustache' # cssOpts: { functions: false } # Run tasks whenever watched files change. watch: options: livereload: true css: files: ['src/stylesheets/**/*.scss', 'build/**/*.html'] tasks: ['stylesheet'] sprite: files: ['build/files/img/sprite/*/*.png'] tasks: ['sprite'] # SVG to webfont converter for Grunt. webfont: dist: src: 'src/svg/*.svg' dest: 'build/files/font/' destCss: 'src/stylesheets/lib/' options: font: 'myfont' types: ['woff', 'ttf'] stylesheet: 'scss' htmlDemo: false syntax: 'bootstrap' relativeFontPath: '/files/font/' # Load the plugins. grunt.loadNpmTasks 'grunt-kss' grunt.loadNpmTasks 'grunt-sass' grunt.loadNpmTasks 'grunt-csso' grunt.loadNpmTasks 'grunt-image' grunt.loadNpmTasks 'grunt-csscomb' grunt.loadNpmTasks 'grunt-webfont' grunt.loadNpmTasks 'grunt-spritesmith' grunt.loadNpmTasks 'grunt-autoprefixer' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-connect' grunt.loadNpmTasks 'grunt-contrib-csslint' # Tasks. grunt.registerTask 'default', ['develop'] grunt.registerTask 'stylesheet', ['sass', 'autoprefixer', 'csscomb', 'csslint'] grunt.registerTask 'develop', ['connect:app', 'watch'] grunt.registerTask 'typeset', ['webfont', 'stylesheet'] grunt.registerTask 'publish', ['stylesheet', 'kss','connect:doc', 'watch'] grunt.registerTask 'build', ['stylesheet', 'csso', 'image']
61527
module.exports = (grunt) -> 'use strict' # Project configuration. grunt.initConfig # Metadata. pkg: grunt.file.readJSON 'package.json' # Parse CSS and add vendor-prefixed CSS properties using the Can I Use database. autoprefixer: options: browsers: ['ios >= 5', 'android >= 2.3'] dist: src: 'build/files/css/maple.css' # Start a static web server. # Reload assets live in the browser connect: app: options: port: 8080 base: 'build/' open: 'http://localhost:8080/' doc: options: port: 8081 base: 'doc/' open: 'http://localhost:8081/' # Sort CSS properties in specific order. csscomb: dist: options: config: '.csscombrc' files: 'build/files/css/maple.css': ['build/files/css/maple.css'] # Lint CSS files. csslint: dist: options: csslintrc: '.csslintrc' src: ['build/files/css/maple.css'] # Minify CSS files with CSSO. csso: dist: options: banner: """ /* * Maple.css * Copyright 2013 <NAME> * Licensed under the MIT License */ """ files: 'build/files/css/maple.min.css': ['build/files/css/maple.css'] # Optimize PNG, JPEG, GIF images with grunt task. image: options: optimizationLevel: 3 dist: files: [ expand: true cwd: "build/files/img/sprite/" src: ["**/*.{png,jpg,gif}"] dest: "build/files/img/sprite/" ] # KSS styleguide generator for grunt. kss: options: includeType: 'css' includePath: 'build/files/css/maple.css' template: 'doc/template' dist: files: # dest : src 'doc/': ['src/stylesheets/'] # Grunt task to compile Sass SCSS to CSS sass: dist: files: 'build/files/css/maple.css': 'src/stylesheets/maple.scss' # Grunt task for creating spritesheets and their coordinates sprite: dist: src: 'build/files/img/sprite/tabs/*.png' destImg: 'build/files/img/sprite/tabs.png' imgPath: '/files/img/sprite/tabs.png' destCSS: 'build/files/css/sass/lib/_sprite.scss' algorithm: 'binary-tree' padding: 2 cssTemplate: 'build/files/img/sprite/spritesmith.mustache' # cssOpts: { functions: false } # Run tasks whenever watched files change. watch: options: livereload: true css: files: ['src/stylesheets/**/*.scss', 'build/**/*.html'] tasks: ['stylesheet'] sprite: files: ['build/files/img/sprite/*/*.png'] tasks: ['sprite'] # SVG to webfont converter for Grunt. webfont: dist: src: 'src/svg/*.svg' dest: 'build/files/font/' destCss: 'src/stylesheets/lib/' options: font: 'myfont' types: ['woff', 'ttf'] stylesheet: 'scss' htmlDemo: false syntax: 'bootstrap' relativeFontPath: '/files/font/' # Load the plugins. grunt.loadNpmTasks 'grunt-kss' grunt.loadNpmTasks 'grunt-sass' grunt.loadNpmTasks 'grunt-csso' grunt.loadNpmTasks 'grunt-image' grunt.loadNpmTasks 'grunt-csscomb' grunt.loadNpmTasks 'grunt-webfont' grunt.loadNpmTasks 'grunt-spritesmith' grunt.loadNpmTasks 'grunt-autoprefixer' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-connect' grunt.loadNpmTasks 'grunt-contrib-csslint' # Tasks. grunt.registerTask 'default', ['develop'] grunt.registerTask 'stylesheet', ['sass', 'autoprefixer', 'csscomb', 'csslint'] grunt.registerTask 'develop', ['connect:app', 'watch'] grunt.registerTask 'typeset', ['webfont', 'stylesheet'] grunt.registerTask 'publish', ['stylesheet', 'kss','connect:doc', 'watch'] grunt.registerTask 'build', ['stylesheet', 'csso', 'image']
true
module.exports = (grunt) -> 'use strict' # Project configuration. grunt.initConfig # Metadata. pkg: grunt.file.readJSON 'package.json' # Parse CSS and add vendor-prefixed CSS properties using the Can I Use database. autoprefixer: options: browsers: ['ios >= 5', 'android >= 2.3'] dist: src: 'build/files/css/maple.css' # Start a static web server. # Reload assets live in the browser connect: app: options: port: 8080 base: 'build/' open: 'http://localhost:8080/' doc: options: port: 8081 base: 'doc/' open: 'http://localhost:8081/' # Sort CSS properties in specific order. csscomb: dist: options: config: '.csscombrc' files: 'build/files/css/maple.css': ['build/files/css/maple.css'] # Lint CSS files. csslint: dist: options: csslintrc: '.csslintrc' src: ['build/files/css/maple.css'] # Minify CSS files with CSSO. csso: dist: options: banner: """ /* * Maple.css * Copyright 2013 PI:NAME:<NAME>END_PI * Licensed under the MIT License */ """ files: 'build/files/css/maple.min.css': ['build/files/css/maple.css'] # Optimize PNG, JPEG, GIF images with grunt task. image: options: optimizationLevel: 3 dist: files: [ expand: true cwd: "build/files/img/sprite/" src: ["**/*.{png,jpg,gif}"] dest: "build/files/img/sprite/" ] # KSS styleguide generator for grunt. kss: options: includeType: 'css' includePath: 'build/files/css/maple.css' template: 'doc/template' dist: files: # dest : src 'doc/': ['src/stylesheets/'] # Grunt task to compile Sass SCSS to CSS sass: dist: files: 'build/files/css/maple.css': 'src/stylesheets/maple.scss' # Grunt task for creating spritesheets and their coordinates sprite: dist: src: 'build/files/img/sprite/tabs/*.png' destImg: 'build/files/img/sprite/tabs.png' imgPath: '/files/img/sprite/tabs.png' destCSS: 'build/files/css/sass/lib/_sprite.scss' algorithm: 'binary-tree' padding: 2 cssTemplate: 'build/files/img/sprite/spritesmith.mustache' # cssOpts: { functions: false } # Run tasks whenever watched files change. watch: options: livereload: true css: files: ['src/stylesheets/**/*.scss', 'build/**/*.html'] tasks: ['stylesheet'] sprite: files: ['build/files/img/sprite/*/*.png'] tasks: ['sprite'] # SVG to webfont converter for Grunt. webfont: dist: src: 'src/svg/*.svg' dest: 'build/files/font/' destCss: 'src/stylesheets/lib/' options: font: 'myfont' types: ['woff', 'ttf'] stylesheet: 'scss' htmlDemo: false syntax: 'bootstrap' relativeFontPath: '/files/font/' # Load the plugins. grunt.loadNpmTasks 'grunt-kss' grunt.loadNpmTasks 'grunt-sass' grunt.loadNpmTasks 'grunt-csso' grunt.loadNpmTasks 'grunt-image' grunt.loadNpmTasks 'grunt-csscomb' grunt.loadNpmTasks 'grunt-webfont' grunt.loadNpmTasks 'grunt-spritesmith' grunt.loadNpmTasks 'grunt-autoprefixer' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-connect' grunt.loadNpmTasks 'grunt-contrib-csslint' # Tasks. grunt.registerTask 'default', ['develop'] grunt.registerTask 'stylesheet', ['sass', 'autoprefixer', 'csscomb', 'csslint'] grunt.registerTask 'develop', ['connect:app', 'watch'] grunt.registerTask 'typeset', ['webfont', 'stylesheet'] grunt.registerTask 'publish', ['stylesheet', 'kss','connect:doc', 'watch'] grunt.registerTask 'build', ['stylesheet', 'csso', 'image']
[ { "context": "[\n \"ěščřžýáí\"\n \"\\u011b\\u0161\\u010d\\u0159\\u017e\\u00fd\\u00e1\\", "end": 15, "score": 0.6472693085670471, "start": 7, "tag": "NAME", "value": "ěščřžýáí" } ]
test/parser/unicode.cson
asellappen/pycson
634
[ "ěščřžýáí" "\u011b\u0161\u010d\u0159\u017e\u00fd\u00e1\u00ed" "ě\u0161č\u0159ž\u00fdá\u00ed" "\u011bš\u010dř\u017eý\u00e1í" ]
211965
[ "<NAME>" "\u011b\u0161\u010d\u0159\u017e\u00fd\u00e1\u00ed" "ě\u0161č\u0159ž\u00fdá\u00ed" "\u011bš\u010dř\u017eý\u00e1í" ]
true
[ "PI:NAME:<NAME>END_PI" "\u011b\u0161\u010d\u0159\u017e\u00fd\u00e1\u00ed" "ě\u0161č\u0159ž\u00fdá\u00ed" "\u011bš\u010dř\u017eý\u00e1í" ]
[ { "context": "', =>\n it 'should pass', =>\n test = new Test 'Peter'\n expect(test.sayHello()).to.equal 'Hello, Pet", "end": 139, "score": 0.992812991142273, "start": 134, "tag": "NAME", "value": "Peter" }, { "context": "eter'\n expect(test.sayHello()).to.equal 'Hello, Pete...
chapter2/node_modules/grunt-mocha-test/test/scenarios/requireCompilersOption/test.coffee
pipihei/phptest
3
expect = require('chai').expect Test = require './lib' describe 'test coffee-script', => it 'should pass', => test = new Test 'Peter' expect(test.sayHello()).to.equal 'Hello, Peter' expect(testVar).to.equal 'test'
23243
expect = require('chai').expect Test = require './lib' describe 'test coffee-script', => it 'should pass', => test = new Test '<NAME>' expect(test.sayHello()).to.equal 'Hello, <NAME>' expect(testVar).to.equal 'test'
true
expect = require('chai').expect Test = require './lib' describe 'test coffee-script', => it 'should pass', => test = new Test 'PI:NAME:<NAME>END_PI' expect(test.sayHello()).to.equal 'Hello, PI:NAME:<NAME>END_PI' expect(testVar).to.equal 'test'
[ { "context": "\t\tusername\t:\tsettings.username\n\t\t\t\t\t\t\t\tpassword\t:\tpassword\n\t\t\t\t\t\t\t\tactive\t\t:\ttrue \n\t\t\t\t\t\t\t\tcreated\t\t:\tnew Da", "end": 495, "score": 0.9993351101875305, "start": 487, "tag": "PASSWORD", "value": "password" }, { "context": "sername =...
applications/lighter/modules/user.coffee
nodebenchmark/benchmarks
13
module.exports = (settings)-> class User constructor:(settings)-> @settings = settings @user = settings.mongoose.model 'user' @crypto = require('crypto') # initializes the user from settings. init:(callback)-> @user.findOne username : settings.username, (err, data)=> password = @crypto.createHash('md5').update(settings.password.trim()).digest('hex') if data is null user = new @user username : settings.username password : password active : true created : new Date() user.save (err, data)-> if err isnt null throw err callback(data) else data.username = settings.username data.password = password data.save (err, data)-> callback(data) find:(username, password, callback)-> password = password.trim() password = @crypto.createHash('md5').update(password).digest('hex') @user.findOne username : username.trim() password : password, (err, data)-> callback(data) delete: (callback)-> @user.remove ()-> callback() new User(settings)
122202
module.exports = (settings)-> class User constructor:(settings)-> @settings = settings @user = settings.mongoose.model 'user' @crypto = require('crypto') # initializes the user from settings. init:(callback)-> @user.findOne username : settings.username, (err, data)=> password = @crypto.createHash('md5').update(settings.password.trim()).digest('hex') if data is null user = new @user username : settings.username password : <PASSWORD> active : true created : new Date() user.save (err, data)-> if err isnt null throw err callback(data) else data.username = settings.username data.password = <PASSWORD> data.save (err, data)-> callback(data) find:(username, password, callback)-> password = <PASSWORD>() password = @crypto.createHash('md5').update(password).digest('hex') @user.findOne username : username.trim() password : <PASSWORD>, (err, data)-> callback(data) delete: (callback)-> @user.remove ()-> callback() new User(settings)
true
module.exports = (settings)-> class User constructor:(settings)-> @settings = settings @user = settings.mongoose.model 'user' @crypto = require('crypto') # initializes the user from settings. init:(callback)-> @user.findOne username : settings.username, (err, data)=> password = @crypto.createHash('md5').update(settings.password.trim()).digest('hex') if data is null user = new @user username : settings.username password : PI:PASSWORD:<PASSWORD>END_PI active : true created : new Date() user.save (err, data)-> if err isnt null throw err callback(data) else data.username = settings.username data.password = PI:PASSWORD:<PASSWORD>END_PI data.save (err, data)-> callback(data) find:(username, password, callback)-> password = PI:PASSWORD:<PASSWORD>END_PI() password = @crypto.createHash('md5').update(password).digest('hex') @user.findOne username : username.trim() password : PI:PASSWORD:<PASSWORD>END_PI, (err, data)-> callback(data) delete: (callback)-> @user.remove ()-> callback() new User(settings)
[ { "context": "ame.trim().replace /\\s/gm, ' '\r\n\t\t\t\t\tkeyName = new Jaco(keyName).toNarrow().toWideKatakana().toString()\r\n", "end": 3798, "score": 0.8397259712219238, "start": 3794, "tag": "KEY", "value": "Jaco" }, { "context": "place /\\s/gm, ' '\r\n\t\t\t\t\tkeyName = new Ja...
src/typed-table.coffee
YusukeHirao/typed-table
0
'use strict' fs = require 'fs' path = require 'path' xlsx = require 'xlsx' jaco = require 'jaco' Jaco = jaco.Jaco PARENT = module.parent BASE_DIR = path.dirname PARENT.filename CHAR_CODE_A = 64 CHAR_CODE_Z = 90 NAME_COLUMN_VALUES = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('') NAME_COLUMN_VALUES_LENGTH = NAME_COLUMN_VALUES.length # アルファベット形式の列番号を数値に変換 _getNumberOfCol = (r1c1) -> num = 0 s = r1c1.toUpperCase().split '' for c, i in s n = NAME_COLUMN_VALUES.indexOf(c) if 1 isnt 0 or i < s.length - 1 n++ num = num * 26 + n num # 整数値の列番号をアルファベット形式に変換 _getColFormNumber = (num) -> s = '' col = 0 if 1 isnt 0 or col > 0 num-- mod = num % NAME_COLUMN_VALUES_LENGTH s = NAME_COLUMN_VALUES[mod] + s num = Math.floor num / NAME_COLUMN_VALUES_LENGTH col++ while num > 0 if 1 isnt 0 or col > 0 num-- mod = num % NAME_COLUMN_VALUES_LENGTH s = NAME_COLUMN_VALUES[mod] + s num = Math.floor num / NAME_COLUMN_VALUES_LENGTH col++ s # #RRGGBB形式のカラーコードを数値に変換する _colorCodeToNumber = (code) -> parseInt code.replace(/#/, ''), 16 class Range startCol: null startRow: null endCol: null endRow: null startNCol: 0 startNRow: 0 endNCol: 0 endNRow: 0 constructor: (@ref) -> refSplit =/^([a-z]+)([0-9]+):([a-z]+)([0-9]+)/ig.exec @ref @startCol = refSplit[1] @startRow = refSplit[2] @endCol = refSplit[3] @endRow = refSplit[4] @startNCol = _getNumberOfCol refSplit[1] @startNRow = +refSplit[2] @endNCol = _getNumberOfCol refSplit[3] @endNRow = +refSplit[4] toString: () -> "#{@startCol}#{@startRow}:#{@endCol}#{@endRow}" class Cell value: null type: null format: '' color: 0x000000 bgColor: -1 constructor: (@value, @type, @format, @color = 0x000000, @bgColor = -1) -> class Sheet range: null rows: null constructor: (sheetData) -> @rows = [] @range = new Range sheetData['!ref'] # Repeat Rows r = @range.startNRow rl = @range.endNRow while r <= rl c = @range.startNCol cl = @range.endNCol cols = [] while c <= cl id = "#{_getColFormNumber c}#{r}" cellData = sheetData[id] if cellData cellValue = new Cell cellData.v, cellData.t, cellData.f if cellData.s cellValue.bgColor = parseInt cellData.s.fgColor.rgb, 16 else cellValue = null cols[c - 1] = cellValue c++ @rows[r - 1] = cols r++ class TypedTable rows: null header: null types: null constructor: (rows, rowOption) -> rowOption = rowOption || {} LABEL_ROW_NUM = if rowOption.label isnt undefined then rowOption.label else 0 # ignore row HEADER_ROW_NUM = if rowOption.header isnt undefined then rowOption.header else 1 # field name TYPE_ROW_NUM = if rowOption.type isnt undefined then rowOption.type else 2 # field type DESC_ROW_NUM = if rowOption.description isnt undefined then rowOption.description else null # ignore row # console.log # LABEL_ROW_NUM: LABEL_ROW_NUM # HEADER_ROW_NUM: HEADER_ROW_NUM # TYPE_ROW_NUM: TYPE_ROW_NUM # DESC_ROW_NUM: DESC_ROW_NUM @rows = [] @header = [] @types = [] for cols, rowNum in rows switch rowNum when LABEL_ROW_NUM, DESC_ROW_NUM continue when HEADER_ROW_NUM @header = cols.slice(0) when TYPE_ROW_NUM @types = cols.slice(0) else @rows.push cols.slice(0) cols = null rows = null toJSON: () -> data = [] allNull = true for row, i in @rows cellValues = {} for cell, j in row headerName = @header[j].value type = @types[j].value if @types and @types[j] if headerName # ヘッダからキー名を取得する keyName = headerName.trim().replace /\s/gm, ' ' keyName = new Jaco(keyName).toNarrow().toWideKatakana().toString() # データ型を参照して から value = if cell switch String(type).toLowerCase() when 'c', 'color', 'colour' if /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test cell.value _colorCodeToNumber cell.value else cell.bgColor when 'd', 'date', 't', 'time' new Date((+cell.value - 25569) * 86400 * 1000 or 0) when 'a', 'arr', 'ary', 'array' arr = for item in (('' + cell.value).split ',') when item isnt '' item.trim() when 'b', 'bool', 'boolean' !!cell.value when 'n', 'num', 'number' +cell.value else ('' + cell.value).replace /\r/, '' else null # --繋ぎのツリー型 if keyName.match /^[a-z][a-z0-9_-]+--/ig keyNameSplit = keyName.split /--/ parentName = keyNameSplit[0] + 's' # 複数形のsのアルゴリズムをいずれ入れたい childName = keyNameSplit[1] cellValues[parentName] ?= {} cellValues[parentName][childName] = value else cellValues[keyName] = value if value isnt null and allNull is true allNull = false if not allNull data.push cellValues allNull = true data toJSONStringify: (replacer, space = ' ') -> JSON.stringify @toJSON(), replacer, space saveJSONFile: (fileName, space = ' ') -> json = @toJSONStringify null, ' ' fs.writeFileSync fileName, json return @readExcel = (xlsxFile, rowOption) -> if path.isAbsolute xlsxFile filePath = xlsxFile else filePath = path.join process.cwd(), xlsxFile file = xlsx.readFile filePath, cellStyles: on cellNF: on sheets = [] tables = [] for name in file.SheetNames sheet = new Sheet file.Sheets[name] table = new TypedTable(sheet.rows, rowOption) sheets.push sheet tables.push table tables module.exports = TypedTable
107116
'use strict' fs = require 'fs' path = require 'path' xlsx = require 'xlsx' jaco = require 'jaco' Jaco = jaco.Jaco PARENT = module.parent BASE_DIR = path.dirname PARENT.filename CHAR_CODE_A = 64 CHAR_CODE_Z = 90 NAME_COLUMN_VALUES = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('') NAME_COLUMN_VALUES_LENGTH = NAME_COLUMN_VALUES.length # アルファベット形式の列番号を数値に変換 _getNumberOfCol = (r1c1) -> num = 0 s = r1c1.toUpperCase().split '' for c, i in s n = NAME_COLUMN_VALUES.indexOf(c) if 1 isnt 0 or i < s.length - 1 n++ num = num * 26 + n num # 整数値の列番号をアルファベット形式に変換 _getColFormNumber = (num) -> s = '' col = 0 if 1 isnt 0 or col > 0 num-- mod = num % NAME_COLUMN_VALUES_LENGTH s = NAME_COLUMN_VALUES[mod] + s num = Math.floor num / NAME_COLUMN_VALUES_LENGTH col++ while num > 0 if 1 isnt 0 or col > 0 num-- mod = num % NAME_COLUMN_VALUES_LENGTH s = NAME_COLUMN_VALUES[mod] + s num = Math.floor num / NAME_COLUMN_VALUES_LENGTH col++ s # #RRGGBB形式のカラーコードを数値に変換する _colorCodeToNumber = (code) -> parseInt code.replace(/#/, ''), 16 class Range startCol: null startRow: null endCol: null endRow: null startNCol: 0 startNRow: 0 endNCol: 0 endNRow: 0 constructor: (@ref) -> refSplit =/^([a-z]+)([0-9]+):([a-z]+)([0-9]+)/ig.exec @ref @startCol = refSplit[1] @startRow = refSplit[2] @endCol = refSplit[3] @endRow = refSplit[4] @startNCol = _getNumberOfCol refSplit[1] @startNRow = +refSplit[2] @endNCol = _getNumberOfCol refSplit[3] @endNRow = +refSplit[4] toString: () -> "#{@startCol}#{@startRow}:#{@endCol}#{@endRow}" class Cell value: null type: null format: '' color: 0x000000 bgColor: -1 constructor: (@value, @type, @format, @color = 0x000000, @bgColor = -1) -> class Sheet range: null rows: null constructor: (sheetData) -> @rows = [] @range = new Range sheetData['!ref'] # Repeat Rows r = @range.startNRow rl = @range.endNRow while r <= rl c = @range.startNCol cl = @range.endNCol cols = [] while c <= cl id = "#{_getColFormNumber c}#{r}" cellData = sheetData[id] if cellData cellValue = new Cell cellData.v, cellData.t, cellData.f if cellData.s cellValue.bgColor = parseInt cellData.s.fgColor.rgb, 16 else cellValue = null cols[c - 1] = cellValue c++ @rows[r - 1] = cols r++ class TypedTable rows: null header: null types: null constructor: (rows, rowOption) -> rowOption = rowOption || {} LABEL_ROW_NUM = if rowOption.label isnt undefined then rowOption.label else 0 # ignore row HEADER_ROW_NUM = if rowOption.header isnt undefined then rowOption.header else 1 # field name TYPE_ROW_NUM = if rowOption.type isnt undefined then rowOption.type else 2 # field type DESC_ROW_NUM = if rowOption.description isnt undefined then rowOption.description else null # ignore row # console.log # LABEL_ROW_NUM: LABEL_ROW_NUM # HEADER_ROW_NUM: HEADER_ROW_NUM # TYPE_ROW_NUM: TYPE_ROW_NUM # DESC_ROW_NUM: DESC_ROW_NUM @rows = [] @header = [] @types = [] for cols, rowNum in rows switch rowNum when LABEL_ROW_NUM, DESC_ROW_NUM continue when HEADER_ROW_NUM @header = cols.slice(0) when TYPE_ROW_NUM @types = cols.slice(0) else @rows.push cols.slice(0) cols = null rows = null toJSON: () -> data = [] allNull = true for row, i in @rows cellValues = {} for cell, j in row headerName = @header[j].value type = @types[j].value if @types and @types[j] if headerName # ヘッダからキー名を取得する keyName = headerName.trim().replace /\s/gm, ' ' keyName = new <KEY>(keyName).<KEY> # データ型を参照して から value = if cell switch String(type).toLowerCase() when 'c', 'color', 'colour' if /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test cell.value _colorCodeToNumber cell.value else cell.bgColor when 'd', 'date', 't', 'time' new Date((+cell.value - 25569) * 86400 * 1000 or 0) when 'a', 'arr', 'ary', 'array' arr = for item in (('' + cell.value).split ',') when item isnt '' item.trim() when 'b', 'bool', 'boolean' !!cell.value when 'n', 'num', 'number' +cell.value else ('' + cell.value).replace /\r/, '' else null # --繋ぎのツリー型 if keyName.match /^[a-<KEY>ig keyNameSplit = keyName.split /--/ parentName = keyNameSplit[0] + 's' # 複数形のsのアルゴリズムをいずれ入れたい childName = keyNameSplit[1] cellValues[parentName] ?= {} cellValues[parentName][childName] = value else cellValues[keyName] = value if value isnt null and allNull is true allNull = false if not allNull data.push cellValues allNull = true data toJSONStringify: (replacer, space = ' ') -> JSON.stringify @toJSON(), replacer, space saveJSONFile: (fileName, space = ' ') -> json = @toJSONStringify null, ' ' fs.writeFileSync fileName, json return @readExcel = (xlsxFile, rowOption) -> if path.isAbsolute xlsxFile filePath = xlsxFile else filePath = path.join process.cwd(), xlsxFile file = xlsx.readFile filePath, cellStyles: on cellNF: on sheets = [] tables = [] for name in file.SheetNames sheet = new Sheet file.Sheets[name] table = new TypedTable(sheet.rows, rowOption) sheets.push sheet tables.push table tables module.exports = TypedTable
true
'use strict' fs = require 'fs' path = require 'path' xlsx = require 'xlsx' jaco = require 'jaco' Jaco = jaco.Jaco PARENT = module.parent BASE_DIR = path.dirname PARENT.filename CHAR_CODE_A = 64 CHAR_CODE_Z = 90 NAME_COLUMN_VALUES = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('') NAME_COLUMN_VALUES_LENGTH = NAME_COLUMN_VALUES.length # アルファベット形式の列番号を数値に変換 _getNumberOfCol = (r1c1) -> num = 0 s = r1c1.toUpperCase().split '' for c, i in s n = NAME_COLUMN_VALUES.indexOf(c) if 1 isnt 0 or i < s.length - 1 n++ num = num * 26 + n num # 整数値の列番号をアルファベット形式に変換 _getColFormNumber = (num) -> s = '' col = 0 if 1 isnt 0 or col > 0 num-- mod = num % NAME_COLUMN_VALUES_LENGTH s = NAME_COLUMN_VALUES[mod] + s num = Math.floor num / NAME_COLUMN_VALUES_LENGTH col++ while num > 0 if 1 isnt 0 or col > 0 num-- mod = num % NAME_COLUMN_VALUES_LENGTH s = NAME_COLUMN_VALUES[mod] + s num = Math.floor num / NAME_COLUMN_VALUES_LENGTH col++ s # #RRGGBB形式のカラーコードを数値に変換する _colorCodeToNumber = (code) -> parseInt code.replace(/#/, ''), 16 class Range startCol: null startRow: null endCol: null endRow: null startNCol: 0 startNRow: 0 endNCol: 0 endNRow: 0 constructor: (@ref) -> refSplit =/^([a-z]+)([0-9]+):([a-z]+)([0-9]+)/ig.exec @ref @startCol = refSplit[1] @startRow = refSplit[2] @endCol = refSplit[3] @endRow = refSplit[4] @startNCol = _getNumberOfCol refSplit[1] @startNRow = +refSplit[2] @endNCol = _getNumberOfCol refSplit[3] @endNRow = +refSplit[4] toString: () -> "#{@startCol}#{@startRow}:#{@endCol}#{@endRow}" class Cell value: null type: null format: '' color: 0x000000 bgColor: -1 constructor: (@value, @type, @format, @color = 0x000000, @bgColor = -1) -> class Sheet range: null rows: null constructor: (sheetData) -> @rows = [] @range = new Range sheetData['!ref'] # Repeat Rows r = @range.startNRow rl = @range.endNRow while r <= rl c = @range.startNCol cl = @range.endNCol cols = [] while c <= cl id = "#{_getColFormNumber c}#{r}" cellData = sheetData[id] if cellData cellValue = new Cell cellData.v, cellData.t, cellData.f if cellData.s cellValue.bgColor = parseInt cellData.s.fgColor.rgb, 16 else cellValue = null cols[c - 1] = cellValue c++ @rows[r - 1] = cols r++ class TypedTable rows: null header: null types: null constructor: (rows, rowOption) -> rowOption = rowOption || {} LABEL_ROW_NUM = if rowOption.label isnt undefined then rowOption.label else 0 # ignore row HEADER_ROW_NUM = if rowOption.header isnt undefined then rowOption.header else 1 # field name TYPE_ROW_NUM = if rowOption.type isnt undefined then rowOption.type else 2 # field type DESC_ROW_NUM = if rowOption.description isnt undefined then rowOption.description else null # ignore row # console.log # LABEL_ROW_NUM: LABEL_ROW_NUM # HEADER_ROW_NUM: HEADER_ROW_NUM # TYPE_ROW_NUM: TYPE_ROW_NUM # DESC_ROW_NUM: DESC_ROW_NUM @rows = [] @header = [] @types = [] for cols, rowNum in rows switch rowNum when LABEL_ROW_NUM, DESC_ROW_NUM continue when HEADER_ROW_NUM @header = cols.slice(0) when TYPE_ROW_NUM @types = cols.slice(0) else @rows.push cols.slice(0) cols = null rows = null toJSON: () -> data = [] allNull = true for row, i in @rows cellValues = {} for cell, j in row headerName = @header[j].value type = @types[j].value if @types and @types[j] if headerName # ヘッダからキー名を取得する keyName = headerName.trim().replace /\s/gm, ' ' keyName = new PI:KEY:<KEY>END_PI(keyName).PI:KEY:<KEY>END_PI # データ型を参照して から value = if cell switch String(type).toLowerCase() when 'c', 'color', 'colour' if /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test cell.value _colorCodeToNumber cell.value else cell.bgColor when 'd', 'date', 't', 'time' new Date((+cell.value - 25569) * 86400 * 1000 or 0) when 'a', 'arr', 'ary', 'array' arr = for item in (('' + cell.value).split ',') when item isnt '' item.trim() when 'b', 'bool', 'boolean' !!cell.value when 'n', 'num', 'number' +cell.value else ('' + cell.value).replace /\r/, '' else null # --繋ぎのツリー型 if keyName.match /^[a-PI:KEY:<KEY>END_PIig keyNameSplit = keyName.split /--/ parentName = keyNameSplit[0] + 's' # 複数形のsのアルゴリズムをいずれ入れたい childName = keyNameSplit[1] cellValues[parentName] ?= {} cellValues[parentName][childName] = value else cellValues[keyName] = value if value isnt null and allNull is true allNull = false if not allNull data.push cellValues allNull = true data toJSONStringify: (replacer, space = ' ') -> JSON.stringify @toJSON(), replacer, space saveJSONFile: (fileName, space = ' ') -> json = @toJSONStringify null, ' ' fs.writeFileSync fileName, json return @readExcel = (xlsxFile, rowOption) -> if path.isAbsolute xlsxFile filePath = xlsxFile else filePath = path.join process.cwd(), xlsxFile file = xlsx.readFile filePath, cellStyles: on cellNF: on sheets = [] tables = [] for name in file.SheetNames sheet = new Sheet file.Sheets[name] table = new TypedTable(sheet.rows, rowOption) sheets.push sheet tables.push table tables module.exports = TypedTable
[ { "context": "an_educator: \"I'm an Educator\"\n im_a_teacher: \"Sunt Profesor\"\n im_a_student: \"Sunt Student\"\n learn_more:", "end": 9496, "score": 0.8706863522529602, "start": 9483, "tag": "NAME", "value": "Sunt Profesor" }, { "context": "pact\"\n contact: \"Contact\...
app/locale/ro.coffee
suwijakza/codecombat
0
module.exports = nativeDescription: "limba română", englishDescription: "Romanian", 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: "Un joc de programare dezvoltat cu gandul la profesori." # 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: "Informatică" built_for_teachers_subblurb1: "Începând cu cursul nostru gratuit de Introducere în Informatică, studenții însușesc concepte de baza în programare, cum ar fi bucle while/for, funcții și algoritmi." built_for_teachers_subtitle2: "Dezvoltare de jocuri" # 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: "Dezvoltare Web" # 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: "Gândire critică" # 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: "Creativitate" # 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: "Partener oficial Code.org" # 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: "Implementare ușoară" # 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: "Cel mai interesant mod de a învăța codul 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: "Classroom Edition:" # learn_to_code: "Learn to code:" # play_now: "Play Now" # im_an_educator: "I'm an Educator" im_a_teacher: "Sunt Profesor" im_a_student: "Sunt Student" learn_more: "Aflați mai multe" # classroom_in_a_box: "A classroom in-a-box for teaching computer science." # codecombat_is: "CodeCombat is a platform <strong>for students</strong> to learn computer science while playing through a real game." # our_courses: "Our courses have been specifically playtested <strong>to excel in the classroom</strong>, even for teachers with little to no prior programming experience." # watch_how: "Watch how CodeCombat is transforming the way people learn computer science." # top_screenshots_hint: "Students write code and see their changes update in real-time" # designed_with: "Designed with teachers in mind" # real_code: "Real, typed code" from_the_first_level: "de la primul nivel" # getting_students: "Getting students to typed code as quickly as possible is critical to learning programming syntax and proper structure." # educator_resources: "Educator resources" course_guides: "și ghiduri de curs" # teaching_computer_science: "Teaching computer science does not require a costly degree, because we provide tools to support educators of all backgrounds." accessible_to: "Accesibil la" everyone: "toţi" # democratizing: "Democratizing the process of learning coding is at the core of our philosophy. Everyone should be able to learn to code." # forgot_learning: "I think they actually forgot that they were learning something." # wanted_to_do: " Coding is something I've always wanted to do, and I never thought I would be able to learn it in school." # builds_concepts_up: "I like how CodeCombat builds the concepts up. It's really easy to understand and fun to figure it out." why_games: "De ce este importantă învățarea prin jocuri?" # games_reward: "Games reward the productive struggle." # encourage: "Gaming is a medium that encourages interaction, discovery, and trial-and-error. A good game challenges the player to master skills over time, which is the same critical process students go through as they learn." # excel: "Games excel at rewarding" # struggle: "productive struggle" # kind_of_struggle: "the kind of struggle that results in learning that’s engaging and" motivating: "motivând" # not_tedious: "not tedious." gaming_is_good: "Studiile sugerează că jocurile sunt bune pentru creierul copiilor. (e adevarat!)" # 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: "A real game, played with real coding." # 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: "Request a Demo" # request_quote: "Request a Quote" # setup_a_class: "Set Up a Class" have_an_account: "Aveți un cont?" logged_in_as: "În prezent sunteți conectat(ă) ca" # computer_science: "Our self-paced courses cover basic syntax to advanced concepts" ffa: "Gratuit pentru toți elevii" # coming_soon: "More coming soon!" # courses_available_in: "Courses are available in JavaScript and Python. Web Development courses utilize HTML, CSS, and 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: "Everything you need to run a computer science class in your school today, no CS background required." # goto_classes: "Go to My Classes" # view_profile: "View My Profile" # view_progress: "View Progress" # go_to_courses: "Go to My Courses" # want_coco: "Want CodeCombat at your school?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" # map: "Map" play: "Nivele" # The top nav bar entry where players choose which levels to play community: "Communitate" courses: "Cursuri" blog: "Blog" forum: "Forum" account: "Cont" my_account: "Contul meu" profile: "Profil" home: "Acasă" contribute: "Contribuie" legal: "Confidențialitate și termeni" # privacy: "Privacy Notice" about: "Despre" # impact: "Impact" contact: "Contact" twitter_follow: "Urmărește" # my_classrooms: "My Classes" my_courses: "Cursurile mele" # my_teachers: "My Teachers" # careers: "Careers" facebook: "Facebook" twitter: "Twitter" # create_a_class: "Create a Class" # other: "Other" # learn_to_code: "Learn to Code!" # toggle_nav: "Toggle navigation" # schools: "Schools" # get_involved: "Get Involved" # open_source: "Open source (GitHub)" # support: "Support" # faqs: "FAQs" # copyright_prefix: "Copyright" # copyright_suffix: "All Rights Reserved." # help_pref: "Need help? Email" # help_suff: "and we'll get in touch!" # resource_hub: "Resource Hub" # apcsp: "AP CS Principles" # parent: "Parents" # browser_recommendation: "For the best experience we recommend using the latest version of Chrome. Download the browser here!" modal: close: "Inchide" okay: "Okay" # cancel: "Cancel" not_found: page_not_found: "Pagina nu a fost gasită" diplomat_suggestion: title: "Ajută-ne să traducem CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat in limba engleza , dar deja avem jucatări din toate colțurile lumii. Mulți dintre ei vor să joace in română și nu vorbesc engleză. Dacă poți vorbi ambele te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți sa traducem atât jocul cât și site-ul." missing_translations: "Until we can translate everything into Romanian, you'll see English when Romanian isn't available." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" 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: "CodeCombat has a" # anon_signup_title_2: "Classroom Version!" # anon_signup_enter_code: "Enter Class Code:" # anon_signup_ask_teacher: "Don't have one? Ask your teacher!" # anon_signup_create_class: "Want to create a class?" # anon_signup_setup_class: "Set up a class, add your students, and monitor progress!" # anon_signup_create_teacher: "Create free teacher account" play_as: "Alege-ți echipa" # Ladder page # get_course_for_class: "Assign Game Development and more to your classes!" # request_licenses: "Contact our school specialists for details." # compete: "Compete!" # Course details page spectate: "Spectator" # Ladder page players: "jucători" # Hover over a level on /play hours_played: "ore jucate" # Hover over a level on /play items: "Iteme" # Tooltip on item shop button from /play unlock: "Deblochează" # For purchasing items and heroes confirm: "Confirmă" owned: "Deținute" # For items you own locked: "Blocate" available: "Valabile" skills_granted: "Skill-uri acordate" # Property documentation details heroes: "Eroi" # Tooltip on hero shop button from /play achievements: "Realizări" # Tooltip on achievement list button from /play settings: "Setări" # Tooltip on settings button from /play poll: "Sondaj" # Tooltip on poll button from /play next: "Următorul" # Go from choose hero to choose inventory before playing a level change_hero: "Schimbă eroul" # Go back from choose inventory to choose hero # change_hero_or_language: "Change Hero or Language" buy_gems: "Cumpără Pietre Prețioase" # subscribers_only: "Subscribers Only!" # subscribe_unlock: "Subscribe to Unlock!" # subscriber_heroes: "Subscribe today to immediately unlock Amara, Hushbaum, and Hattori!" # subscriber_gems: "Subscribe today to purchase this hero with gems!" anonymous: "Jucător Anonim" level_difficulty: "Dificultate: " awaiting_levels_adventurer_prefix: "Lansăm niveluri noi în fiecare săptămână." awaiting_levels_adventurer: "Înscrie-te ca un aventurier " awaiting_levels_adventurer_suffix: "pentru a fi primul care joacă nivele noi." adjust_volume: "Reglează volumul" campaign_multiplayer: "Arene Multiplayer" campaign_multiplayer_description: "... în care te lupți cap-la-cap contra alți jucători." # 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: "Back to Classroom" # teacher_button: "For Teachers" # get_more_codecombat: "Get More CodeCombat" code: # if: "if" # 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: "else" # elif: "else if" # while: "while" # loop: "loop" # for: "for" # break: "break" # continue: "continue" # pass: "pass" # return: "return" # then: "then" # do: "do" # end: "end" # function: "function" # def: "define" # var: "variable" # self: "self" # hero: "hero" # this: "this" # or: "or" # "||": "or" # and: "and" # "&&": "and" # not: "not" # "!": "not" # "=": "assign" # "==": "equals" # "===": "strictly equals" # "!=": "does not equal" # "!==": "does not strictly equal" # ">": "is greater than" # ">=": "is greater than or equal" # "<": "is less than" # "<=": "is less than or equal" # "*": "multiplied by" # "/": "divided by" "+": "plus" "-": "minus" "+=": "adaugă și atribuie" "-=": "scade și atribuie" True: "Adevărat" true: "adevărat" False: "Fals" false: "fals" undefined: "nedefinit" # null: "null" # nil: "nil" # None: "None" share_progress_modal: blurb: "Faci progrese mari! Spune-le părinților cât de mult ai învățat cu CodeCombat." email_invalid: "Adresă Email invalidă." form_blurb: "Introduceți adresa e-mail al unui părinte mai jos și le vom arăta!" form_label: "Adresă Email" placeholder: "adresă email" title: "Excelentă treabă, Ucenicule" login: sign_up: "Crează cont" email_or_username: "Email sau nume de utilizator" log_in: "Log In" logging_in: "Se conectează" log_out: "Log Out" forgot_password: "Ai uitat parola?" finishing: "Terminare" sign_in_with_facebook: "Conectați-vă cu Facebook" sign_in_with_gplus: "Conectați-vă cu G+" signup_switch: "Doriți să creați un cont?" signup: complete_subscription: "Completează abonamentul" create_student_header: "Creează cont student" create_teacher_header: "Creează cont profesor" create_individual_header: "Creează cont profesor un cont individual" email_announcements: "Primește notificări prin email" # {change} sign_in_to_continue: "Conecteaza-te sau creează un cont pentru a continua" # teacher_email_announcements: "Keep me updated on new teacher resources, curriculum, and courses!" creating: "Se creează contul..." sign_up: "Înscrie-te" log_in: "loghează-te cu parola" # login: "Login" required: "Trebuie să te înregistrezi înaite să parcurgi acest drum." login_switch: "Ai deja un cont?" optional: "opțional" # 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: "Students, enter the class code from your teacher." # birthday: "Birthday" # 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: "Checking..." # account_exists: "This email is already in use:" # sign_in: "Sign in" # email_good: "Email looks good!" # name_taken: "Username already taken! Try {{suggestedName}}?" # name_available: "Username available!" # name_is_email: "Username may not be an email" # choose_type: "Choose your account type:" # teacher_type_1: "Teach programming using CodeCombat!" # teacher_type_2: "Set up your class" # teacher_type_3: "Access Course Guides" # teacher_type_4: "View student progress" # signup_as_teacher: "Sign up as a Teacher" # student_type_1: "Learn to program while playing an engaging game!" # student_type_2: "Play with your class" # student_type_3: "Compete in arenas" student_type_4: "Alege-ți eroul!" # student_type_5: "Have your Class Code ready!" # signup_as_student: "Sign up as a Student" # individuals_or_parents: "Individuals & Parents" # individual_type: "For players learning to code outside of a class. Parents should sign up for an account here." # signup_as_individual: "Sign up as an Individual" # enter_class_code: "Enter your Class Code" # enter_birthdate: "Enter your birthdate:" # parent_use_birthdate: "Parents, use your own birthdate." # ask_teacher_1: "Ask your teacher for your Class Code." # ask_teacher_2: "Not part of a class? Create an " # ask_teacher_3: "Individual Account" # ask_teacher_4: " instead." # about_to_join: "You're about to join:" enter_parent_email: "Introduceți adresa de e-mail a părintelui dvs .:" # 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: "Account Created!" # confirm_student_blurb: "Write down your information so that you don't forget it. Your teacher can also help you reset your password at any time." # confirm_individual_blurb: "Write down your login information in case you need it later. Verify your email so you can recover your account if you ever forget your password - check your inbox!" write_this_down: "Notează asta:" start_playing: "Începe jocul!" # sso_connected: "Successfully connected with:" # select_your_starting_hero: "Select Your Starting Hero:" # you_can_always_change_your_hero_later: "You can always change your hero later." # 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: "Află mai multe despre riscuri posibile." eu_confirmation_student: "Dacă nu ești sigur, întreabă-ți profesorul." # 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: "Recuperează Cont" send_password: "Trimite parolă de recuperare" recovery_sent: "Email de recuperare trimis." items: primary: "Primar" secondary: "Secundar" armor: "Armură" accessories: "Accesorii" misc: "Diverse" books: "Cărti" 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: "Inapoi" # When used as an action verb, like "Navigate backward" coming_soon: "In curand!" continue: "Continuă" # When used as an action verb, like "Continue forward" next: "Urmator" default_code: "Cod implicit" loading: "Se încarcă..." overview: "Prezentare generală" processing: "Procesare..." solution: "Soluţie" table_of_contents: "Cuprins" intro: "Introducere" saving: "Se salvează..." sending: "Se trimite..." send: "Trimite" sent: "Trimis" cancel: "Anulează" save: "Salvează" publish: "Publică" create: "Creează" fork: "Fork" play: "Joacă" # When used as an action verb, like "Play next level" retry: "Reîncearca" actions: "Acţiuni" info: "Info" help: "Ajutor" watch: "Watch" unwatch: "Unwatch" submit_patch: "Înainteaza Patch" submit_changes: "Trimite modificări" save_changes: "Salveaza modificări" required_field: "obligatoriu" # submit: "Submit" # replay: "Replay" # complete: "Complete" general: and: "și" name: "Nume" date: "Dată" body: "Corp" version: "Versiune" pending: "În așteptare" accepted: "Acceptat" rejected: "Respins" withdrawn: "Retrage" accept: "Accepta" accept_and_save: "Acceptă și Salvează" reject: "Respinge" withdraw: "Retrage" submitter: "Expeditor" submitted: "Expediat" commit_msg: "Înregistrează Mesajul" version_history: "Istoricul versiunilor" version_history_for: "Istoricul versiunilor pentru: " select_changes: "Selectați două schimbări de mai jos pentru a vedea diferenţa." undo_prefix: "Undo" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Redo" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Joaca previzualizarea nivelului actual" result: "Rezultat" results: "Rezultate" description: "Descriere" or: "sau" subject: "Subiect" email: "Email" password: "Parola" confirm_password: "Confirmă parola" message: "Mesaj" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rang" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" player: "Jucător" player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Războinic" ranger: "Arcaș" wizard: "Vrăjitor" first_name: "Prenume" last_name: "Nume" last_initial: "Inițiala nume" username: "Nume de utilizator" contact_us: "Contacteaza-ne" close_window: "Închide fereastra" learn_more: "Află mai mult" more: "Mai mult" fewer: "Mai putin" with: "cu" units: second: "secundă" seconds: "secunde" # sec: "sec" minute: "minut" minutes: "minute" hour: "oră" hours: "ore" day: "zi" days: "zile" week: "săptămână" weeks: "săptămâni" month: "lună" months: "luni" year: "an" years: "ani" play_level: # back_to_map: "Back to Map" # directions: "Directions" # edit_level: "Edit Level" # keep_learning: "Keep Learning" # explore_codecombat: "Explore CodeCombat" # finished_hoc: "I'm finished with my Hour of Code" # get_certificate: "Get your certificate!" # level_complete: "Level Complete" # completed_level: "Completed Level:" # course: "Course:" done: "Gata" # next_level: "Next Level" # 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__ Concepts Used" # 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: "Start Challenge" # next_game: "Next game" languages: "Limbi" programming_language: "Limbaj de programare" # show_menu: "Show game menu" home: "Acasă" # Not used any more, will be removed soon. level: "Nivel" # Like "Level: Dungeons of Kithgard" skip: "Sari peste" game_menu: "Meniul Jocului" restart: "Restart" goals: "Obiective" goal: "Obiectiv" # 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: "Rulează..." success: "Success!" incomplete: "Incomplet" timed_out: "Ai rămas fără timp" failing: "Eşec" reload: "Reîncarca" reload_title: "Reîncarcă tot codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reîncarca Tot" # 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: "Test Level" victory: "Victorie" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Crează un cont gratis!" victory_rate_the_level: "Apreciază nivelul: " # {change} victory_return_to_ladder: "Înapoi la jocurile de clasament" victory_saving_progress: "Salvează Progresul" victory_go_home: "Acasă" victory_review: "Spune-ne mai multe!" # victory_review_placeholder: "How was the level?" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" victory_experience_gained: "Ai câștigat XP" victory_gems_gained: "Ai câștigat Pietre Prețioase" victory_new_item: "Item nou" # victory_new_hero: "New Hero" victory_viking_code_school: "Wow, ăla a fost un nivel greu! Daca nu ești deja un dezvoltator de software, ar trebui să fi. Tocmai ai fost selectat pentru acceptare in Viking Code School, unde poți sa iți dezvolți abilitățile la nivelul următor și să devi un dezvoltator web profesionist în 14 săptămâni." victory_become_a_viking: "Devino Viking" # victory_no_progress_for_teachers: "Progress is not saved for teachers. But, you can add a student account to your classroom for yourself." tome_cast_button_run: "Ruleaza" tome_cast_button_running: "In Derulare" tome_cast_button_ran: "A rulat" # tome_cast_button_update: "Update" tome_submit_button: "Trimite" tome_reload_method: "Reîncarcă cod original, pentru această metodă" # {change} tome_available_spells: "Vrăji disponibile" tome_your_skills: "Skillurile tale" # hints: "Hints" # videos: "Videos" # hints_title: "Hint {{number}}" code_saved: "Cod Salvat" skip_tutorial: "Sari peste (esc)" keyboard_shortcuts: "Scurtături Keyboard" loading_start: "Începe Level" # loading_start_combo: "Start Combo Challenge" # loading_start_concept: "Start Concept Challenge" problem_alert_title: "Repară codul" time_current: "Acum:" time_total: "Max:" time_goto: "Dute la:" non_user_code_problem_title: "Imposibil de încărcat Nivel" infinite_loop_title: "Buclă infinită detectată" infinite_loop_description: "Codul initial pentru a construi lumea nu a terminat de rulat. Este, probabil, foarte lent sau are o buclă infinită. Sau ar putea fi un bug. Puteți încerca acest cod nou sau resetați codul la starea implicită. Dacă nu-l repara, vă rugăm să ne anunțați." check_dev_console: "Puteți deschide, de asemenea, consola de dezvoltator pentru a vedea ce ar putea merge gresit." check_dev_console_link: "(instrucțiuni)" infinite_loop_try_again: "Încearcă din nou" infinite_loop_reset_level: "Resetează Nivelul" infinite_loop_comment_out: "Comentează Codul" tip_toggle_play: "Pune sau scoate pauza cu Ctrl+P." tip_scrub_shortcut: "Înapoi și derulare rapidă cu Ctrl+[ and Ctrl+]." # {change} tip_guide_exists: "Apasă pe ghidul din partea de sus a pagini pentru informații utile." tip_open_source: "CodeCombat este 100% open source!" # {change} # tip_tell_friends: "Enjoying CodeCombat? Tell your friends about us!" tip_beta_launch: "CodeCombat a fost lansat beta in Octombrie 2013." tip_think_solution: "Gândește-te la soluție, nu la problemă." tip_theory_practice: "Teoretic nu este nici o diferență înte teorie și practică. Dar practic este. - Yogi Berra" tip_error_free: "Există doar două metode de a scrie un program fără erori; numai a treia funcționează. - Alan Perlis" tip_debugging_program: "Dacă a face debuggin este procesul de a scoate bug-uri, atunci a programa este procesul de a introduce bug-uri. - Edsger W. Dijkstra" tip_forums: "Intră pe forum și spune-ți părerea!" tip_baby_coders: "În vitor până și bebelușii vor fi Archmage." tip_morale_improves: "Se va încărca până până când va crește moralul." tip_all_species: "Noi credem în șanse egale de a învăța programare pentru toate speciile." tip_reticulating: "Reticulăm coloane vertebrale." tip_harry: "Ha un Wizard, " tip_great_responsibility: "Cu o mare abilitate mare de programare vine o mare responsabilitate de debugging." tip_munchkin: "Daca nu iți mananci legumele, un munchkin va veni după tine cand dormi." tip_binary: "Sunt doar 10 tipuri de oameni in lume: cei ce îteleg sistemul binar, si ceilalți." tip_commitment_yoda: "Un programator trebuie să aiba cel mai profund angajament, si mintea cea mai serioasă. ~Yoda" tip_no_try: "Fă. Sau nu mai face. Nu exista voi încerca. ~Yoda" tip_patience: "Să ai rabdare trebuie, tinere Padawan. ~Yoda" tip_documented_bug: "Un bug documentat nu e chiar un bug; este o caracteristica." tip_impossible: "Mereu pare imposibil până e gata. ~Nelson Mandela" tip_talk_is_cheap: "Vorbele sunt ieftine. Arată-mi codul. ~Linus Torvalds" tip_first_language: "Cel mai dezastruos lucru pe care poți să îl înveți este primul limbaj de programare. ~Alan Kay" tip_hardware_problem: "Î: De cați programatori ai nevoie ca să schimbi un bec? R: Niciunul, e o problemă hardware." tip_hofstadters_law: "Legea lui Hofstadter: Mereu dureaza mai mult decât te aștepți, chiar dacă iei în considerare Legea lui Hofstadter." tip_premature_optimization: "Optimizarea prematură este rădăcina tuturor răutăților. ~Donald Knuth" tip_brute_force: "Atunci cănd ești în dubii, folosește brute force. ~Ken Thompson" tip_extrapolation: "Există două feluri de oameni: cei care pot extrapola din date incomplete..." tip_superpower: "Programarea este cel mai apropiat lucru de o superputere." tip_control_destiny: "In open source, ai dreptul de a-ți controla propiul destin. ~Linus Torvalds" tip_no_code: "Nici-un cod nu e mai rapid decat niciun cod." tip_code_never_lies: "Codul nu minte niciodată, commenturile mai mint. ~Ron Jeffries" tip_reusable_software: "Înainte ca un software să fie reutilizabil, trebuie să fie mai întâi utilizabil." tip_optimization_operator: "Fiecare limbaj are un operator de optimizare. La majoritatea acela este '//'" tip_lines_of_code: "Măsurarea progresului în lini de cod este ca și măsurarea progresului de construcție a aeronavelor în greutate. ~Bill Gates" tip_source_code: "Vreau să schimb lumea dar nu îmi dă nimeni codul sursă." tip_javascript_java: "Java e pentru JavaScript exact ce e o Mașina pentru o Carpetă. ~Chris Heilmann" tip_move_forward: "Orice ai face, dăi înainte. ~Martin Luther King Jr." tip_google: "Ai o problemă care nu o poți rezolva? Folosește Google!" tip_adding_evil: "Adaugăm un strop de răutate." tip_hate_computers: "Tocmai aia e problema celor ce urăsc calulatoarele, ei defapt urăsc programatorii nepricepuți. ~Larry Niven" tip_open_source_contribute: "Poți ajuta la îmbunătățirea jocului CodeCombat!" tip_recurse: "A itera este uman, recursiv este divin. ~L. Peter Deutsch" tip_free_your_mind: "Trebuie sa lași totul, Neo. Frica, Îndoiala și necredința. Eliberează-ți mintea. ~Morpheus" tip_strong_opponents: "Și cei mai puternici dintre oponenți întodeauna au o slăbiciune. ~Itachi Uchiha" # tip_paper_and_pen: "Before you start coding, you can always plan with a sheet of paper and a pen." # tip_solve_then_write: "First, solve the problem. Then, write the code. - John Johnson" # tip_compiler_ignores_comments: "Sometimes I think that the compiler ignores my comments." # tip_understand_recursion: "The only way to understand recursion is to understand recursion." # 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: "Project Complete!" # share_this_project: "Share this project with friends or family:" # ready_to_share: "Ready to publish your project?" # 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: "View Gallery" # project_published_noty: "Your level has been published!" # keep_editing: "Keep Editing" # 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: "Methods" # events: "Events" # handlers: "Handlers" # properties: "Properties" # snippets: "Snippets" # spawnable: "Spawnable" # html: "HTML" # math: "Math" # array: "Array" # object: "Object" # string: "String" # function: "Function" # vector: "Vector" # date: "Date" # jquery: "jQuery" # json: "JSON" # number: "Number" # 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: "Creat de {{name}}" # created_during_hoc: "Created during Hour of Code" # restart: "Restart Level" # play: "Play Level" # play_more_codecombat: "Play More CodeCombat" # default_student_instructions: "Click to control your hero and win your game!" # goal_survive: "Survive." # goal_survive_time: "Survive for __seconds__ seconds." # goal_defeat: "Defeat all enemies." # goal_defeat_amount: "Defeat __amount__ enemies." # 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: "Inventar" save_load_tab: "Salvează/Încarcă" options_tab: "Opțiuni" guide_tab: "Ghid" guide_video_tutorial: "Tutorial Video" guide_tips: "Sfaturi" multiplayer_tab: "Multiplayer" auth_tab: "Înscriete" inventory_caption: "Echipeazăți Eroul" choose_hero_caption: "Alege Eroul, limbajul" options_caption: "Configurarea setărilor" guide_caption: "Documentație si sfaturi" multiplayer_caption: "Joaca cu prieteni!" auth_caption: "Salvează progresul." leaderboard: view_other_solutions: "Vizualizează Tabelul de Clasificare" scores: "Scoruri" top_players: "Top Jucători" day: "Astăzi" week: "Săptămâna Aceasta" all: "Tot Timpul" latest: "Ultimul" time: "Timp" damage_taken: "Damage Primit" damage_dealt: "Damage Oferit" difficulty: "Dificultate" gold_collected: "Aur Colectat" survival_time: "Supravietuit" defeated: "Inamici înfrânți" code_length: "Linii de cod" score_display: "__scoreType__: __score__" inventory: equipped_item: "Echipat" required_purchase_title: "Necesar" available_item: "Valabil" restricted_title: "Restricționat" should_equip: "(dublu-click pentru echipare)" equipped: "(echipat)" locked: "(blocat)" restricted: "(în acest nivel)" equip: "Echipează" unequip: "Dezechipează" # warrior_only: "Warrior Only" # ranger_only: "Ranger Only" # wizard_only: "Wizard Only" buy_gems: few_gems: "Căteva Pietre Prețioase" pile_gems: "Un morman de Pietre Prețioase" chest_gems: "Un cufăr de Pietre Prețioase" purchasing: "Cumpărare..." declined: "Cardul tău a fost refuzat." retrying: "Eroare de server, reîncerc." prompt_title: "Nu sunt destule Pietre Prețioase." prompt_body: "Vrei mai multe?" prompt_button: "Intră în magazin." recovered: "Pietre Prețioase cumpărate anterior recuperate.Va rugăm să dați refresh la pagină." price: "x{{gems}} / mo" buy_premium: "Cumpara Premium" # purchase: "Purchase" # purchased: "Purchased" subscribe_for_gems: prompt_title: "Pietre prețioase insuficiente!" prompt_body: "Abonează-te la Premium pentru a obține pietre prețioase și pentru a accesa chiar mai multe nivele!" earn_gems: prompt_title: "Pietre prețioase insuficiente" prompt_body: "Continuă să joci pentru a câștiga mai mult!" subscribe: best_deal: "Cea mai bună afacere!" confirmation: "Felicitări! Acum ai abonament CodeCombat Premium!" premium_already_subscribed: "Esti deja abonat la Premium!" subscribe_modal_title: "CodeCombat Premium" comparison_blurb: "Îmbunătățește-ți abilitățile cu abonamentul CodeCombat" must_be_logged: "Trebuie să te conectezi mai întâi. Te rugăm să creezi un cont sau să te conectezi din meniul de mai sus." subscribe_title: "Abonează-te" # Actually used in subscribe buttons, too unsubscribe: "Dezabonează-te" confirm_unsubscribe: "Confirmă Dezabonarea" never_mind: "Nu contează, eu tot te iubesc!" thank_you_months_prefix: "Mulțumesc pentru sprijinul acordat în aceste" thank_you_months_suffix: "luni." thank_you: "Mulțumim pentru susținerea jocului CodeCombat!" sorry_to_see_you_go: "Ne pare rău că pleci! Te rugăm să ne spui ce am fi putut face mai bine." unsubscribe_feedback_placeholder: "O, ce am făcut?" stripe_description: "Abonament Lunar" buy_now: "Cumpără acum" subscription_required_to_play: "Ai nevoie de abonament ca să joci acest nivel." unlock_help_videos: "Abonează-te pentru deblocarea tuturor tutorialelor video." personal_sub: "Abonament Personal" # Accounts Subscription View below loading_info: "Se încarcă informațile despre abonament..." managed_by: "Gestionat de" will_be_cancelled: "Va fi anulat pe" currently_free: "Ai un abonament gratuit" currently_free_until: "Ai un abonament gratuit până pe" free_subscription: "Abonament gratuit" was_free_until: "Ai avut un abonament gratuit până pe" managed_subs: "Abonamente Gestionate" subscribing: "Te abonăm..." current_recipients: "Recipienți curenți" unsubscribing: "Dezabonare..." subscribe_prepaid: "Dă Click pe Abonare pentru a folosi un cod prepaid" using_prepaid: "Foloseste codul prepaid pentru un abonament lunar" feature_level_access: "Accesează peste 300 de nivele disponibile" feature_heroes: "Deblochează eroi exclusivi și personaje" feature_learn: "Învață să creezi jocuri și site-uri web" month_price: "$__price__" first_month_price: "Doar $__price__ pentru prima luna!" lifetime: "Acces pe viață" lifetime_price: "$__price__" year_subscription: "Abonament anual" year_price: "$__price__/an" support_part1: "Ai nevoie de ajutor cu plata sau preferi PayPal? E-mail" 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: "Alege Eroul" programming_language: "Limbaj de Programare" programming_language_description: "Ce limbaj de programare vrei să folosești?" default: "Implicit" experimental: "Experimental" python_blurb: "Simplu dar puternic, Python este un limbaj de uz general extraordinar!" javascript_blurb: "Limbajul web-ului." coffeescript_blurb: "JavaScript cu o syntaxă mai placută!" lua_blurb: "Limbaj de scripting pentru jocuri." # java_blurb: "(Subscriber Only) Android and enterprise." # cpp_blurb: "(Subscriber Only) Game development and high performance computing." status: "Stare" weapons: "Armament" weapons_warrior: "Săbii - Distanță Scurtă, Fără Magie" weapons_ranger: "Arbalete, Arme - Distanță Mare, Fără Magie" weapons_wizard: "Baghete, Toiage, - Distanță Mare, Și Magie" attack: "Attack" # Can also translate as "Attack" health: "Viață" speed: "Viteză" regeneration: "Regenerare" range: "Rază" # As in "attack or visual range" blocks: "Blochează" # As in "this shield blocks this much damage" backstab: "Înjunghiere" # As in "this dagger does this much backstab damage" skills: "Skilluri" attack_1: "Oferă" attack_2: "of listed" attack_3: "Damage cu arma." health_1: "Primește" health_2: "of listed" health_3: "Armură." speed_1: "Se mișcă cu" speed_2: "metri pe secundă." available_for_purchase: "Disponibil pentru cumpărare" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Pentru deblocare termină nivelul:" # 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: "Numai anumiți eroi pot juca acest nivel" # 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: "function" # skill types # method: "method" # snippet: "snippet" # number: "number" # array: "array" # object: "object" # string: "string" writable: "permisiuni de scriere" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "permisiuni doar de citire" # action: "Action" # spell: "Spell" action_name: "nume" action_cooldown: "Ține" action_specific_cooldown: "Cooldown" action_damage: "Damage" action_range: "Rază de acțiune" action_radius: "Rază" action_duration: "Durată" example: "Exemplu" ex: "ex" # Abbreviation of "example" current_value: "Valoare Curentă" default_value: "Valoare Implicită" parameters: "Parametrii" # required_parameters: "Required Parameters" # optional_parameters: "Optional Parameters" returns: "Întoarce" granted_by: "Acordat de" # still_undocumented: "Still undocumented, sorry." save_load: granularity_saved_games: "Salvate" granularity_change_history: "Istoric" options: general_options: "Opțiuni Generale" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Muzică" music_description: "Oprește Muzica din fundal." editor_config_title: "Configurare Editor" editor_config_livecompletion_label: "Autocompletare Live" editor_config_livecompletion_description: "Afișează sugesti de autocompletare în timp ce scri." editor_config_invisibles_label: "Arată etichetele invizibile" editor_config_invisibles_description: "Arată spațiile și taburile invizibile." editor_config_indentguides_label: "Arată ghidul de indentare" editor_config_indentguides_description: "Arată linii verticale pentru a vedea mai bine indentarea." editor_config_behaviors_label: "Comportamente inteligente" editor_config_behaviors_description: "Completează automat parantezele, ghilimele etc." # 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: "Learn More" # main_title: "If you want to learn to program, you need to write (a lot of) code." # main_description: "At CodeCombat, our job is to make sure you're doing that with a smile on your face." # mission_link: "Mission" # team_link: "Team" # story_link: "Story" # press_link: "Press" # mission_title: "Our mission: make programming accessible to every student on Earth." # mission_description_1: "<strong>Programming is magic</strong>. It's the ability to create things from pure imagination. We started CodeCombat to give learners the feeling of wizardly power at their fingertips by using <strong>typed code</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: "Meet the CodeCombat team" # 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: "Cofounder, CEO" # matt_title: "Cofounder, CTO" # cat_title: "Game Designer" # scott_title: "Cofounder, Software Engineer" # maka_title: "Customer Advocate" # robin_title: "Senior Product Manager" # nolan_title: "Sales Manager" # david_title: "Marketing Lead" # titles_csm: "Customer Success Manager" # titles_territory_manager: "Territory Manager" # 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: "Illustration" # retrostyle_blurb: "RetroStyle Games" # bryukh_title: "Gameplay Developer" # bryukh_blurb: "Constructs puzzles" # community_title: "...and our open-source community" # community_subtitle: "Over 500 contributors have helped build CodeCombat, with more joining every week!" # community_description_3: "CodeCombat is a" # community_description_link_2: "community project" # 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: "contribute page" # community_description_2: "for more info." # number_contributors: "Over 450 contributors have lent their support and time to this project." # story_title: "Our story so far" # story_subtitle: "Since 2013, CodeCombat has grown from a mere set of sketches to a living, thriving game." # story_statistic_1a: "5,000,000+" # story_statistic_1b: "total players" # story_statistic_1c: "have started their programming journey through CodeCombat" # story_statistic_2a: "We’ve been translated into over 50 languages — our players hail from" # story_statistic_2b: "190+ countries" # story_statistic_3a: "Together, they have written" # story_statistic_3b: "1 billion lines of code and counting" # story_statistic_3c: "across many different programming languages" # 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: "Employee Benefits" # jobs_benefit_4: "Unlimited vacation" # 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: "Create Your Own" # 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: "Press & Contact" # contact_subtitle: "Need more information? Get in touch with us at" # screenshots_title: "Game Screenshots" # screenshots_hint: "(click to view full size)" # downloads_title: "Download Assets & Information" # about_codecombat: "About CodeCombat" # logo: "Logo" # screenshots: "Screenshots" # character_art: "Character Art" # download_all: "Download All" # previous: "Previous" # location_title: "We're located in downtown SF:" # teachers: # licenses_needed: "Licenses needed" # special_offer: # special_offer: "Special Offer" # 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: "Phone number" # phone_number_help: "What's the best number to reach you?" # primary_role_label: "Your Primary Role" # role_default: "Select Role" # primary_role_default: "Select Primary Role" # purchaser_role_default: "Select Purchaser Role" # tech_coordinator: "Technology coordinator" # advisor: "Curriculum Specialist/Advisor" # principal: "Principal" # superintendent: "Superintendent" # parent: "Parent" # 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: "District" # district_name: "District Name" # district_na: "Enter N/A if not applicable" # organization_label: "School" # school_name: "School Name" # city: "City" # state: "State / Region" # country: "Country" # num_students_help: "How many students will use CodeCombat?" # num_students_default: "Select Range" # education_level_label: "Education Level of Students" # education_level_help: "Choose as many as apply." # elementary_school: "Elementary School" # high_school: "High School" # please_explain: "(please explain)" # middle_school: "Middle School" # college_plus: "College or higher" # referrer: "How did you hear about us?" # referrer_help: "For example: from another teacher, a conference, your students, Code.org, etc." # referrer_default: "Select One" # referrer_conference: "Conference (e.g. ISTE)" # referrer_hoc: "Code.org/Hour of Code" # referrer_teacher: "A teacher" # referrer_admin: "An administrator" # referrer_student: "A student" # referrer_pd: "Professional trainings/workshops" # referrer_web: "Google" # referrer_other: "Other" # anything_else: "What kind of class do you anticipate using CodeCombat for?" # anything_else_helper: "" # thanks_header: "Request Received!" # 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: "Back to Classes" # 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: "Connect with:" # 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: "Create a Teacher Account" # create_account_subtitle: "Get access to teacher-only tools for using CodeCombat in the classroom. <strong>Set up a class</strong>, add your students, and <strong>monitor their progress</strong>!" # convert_account_title: "Update to Teacher Account" # not: "Not" # full_name_required: "First and last name required" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" submitting_patch: "Trimitere Patch..." cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" # owner_approve: "An owner will need to approve it before your changes will become visible." contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " forum_prefix: "Pentru orice altceva vă rugăm sa incercați " forum_page: "forumul nostru" forum_suffix: " în schimb." faq_prefix: "Există si un" faq: "FAQ" subscribe_prefix: "Daca ai nevoie de ajutor ca să termini un nivel te rugăm să" subscribe: "cumperi un abonament CodeCombat" subscribe_suffix: "si vom fi bucuroși să te ajutăm cu codul." subscriber_support: "Din moment ce ești un abonat CodeCombat, adresa ta de email va primi sprijinul nostru prioritar." screenshot_included: "Screenshot-uri incluse." where_reply: "Unde ar trebui să răspundem?" send: "Trimite Feedback" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau crează un cont nou pentru a schimba setările." me_tab: "Eu" picture_tab: "Poză" delete_account_tab: "Șterge Contul" wrong_email: "Email Greșit" # wrong_password: "Wrong Password" delete_this_account: "Ștergere permanetă a acestui cont" # reset_progress_tab: "Reset All Progress" # reset_your_progress: "Clear all your progress and start over" # god_mode: "God Mode" emails_tab: "Email-uri" admin: "Admin" # manage_subscription: "Click here to manage your subscription." new_password: "Parolă nouă" new_password_verify: "Verifică" type_in_email: "Scrie adresa de email ca să confirmi ștergerea" # type_in_email_progress: "Type in your email to confirm deleting your progress." # type_in_password: "Also, type in your password." email_subscriptions: "Subscripție Email" email_subscriptions_none: "Nu ai subscripții Email." email_announcements: "Anunțuri" email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." email_notifications: "Notificări" email_notifications_summary: "Control pentru notificări email personalizate, legate de activitatea CodeCombat." email_any_notes: "Orice Notificări" email_any_notes_description: "Dezactivați pentru a opri toate e-mailurile de notificare a activității." email_news: "Noutăți" email_recruit_notes: "Oportunități de job-uri" email_recruit_notes_description: "Daca joci foarte bine, este posibil sa te contactăm pentru obținerea unui loc (mai bun) de muncă." contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "Parola nu se potrivește." password_repeat: "Te rugăm sa repeți parola." keyboard_shortcuts: keyboard_shortcuts: "Scurtături Keyboard" space: "Space" enter: "Enter" # press_enter: "press enter" escape: "Escape" shift: "Shift" run_code: "Rulează codul." run_real_time: "Rulează în timp real." continue_script: "Continue past current script." skip_scripts: "Treci peste toate script-urile ce pot fi sărite." toggle_playback: "Comută play/pause." scrub_playback: "Mergi înainte si înapoi in timp." single_scrub_playback: "Mergi înainte si înapoi in timp cu un singur cadru." scrub_execution: "Mergi prin lista curentă de vrăji executate." toggle_debug: "Comută afișaj debug." toggle_grid: "Comută afișaj grilă." toggle_pathfinding: "Comută afișaj pathfinding." beautify: "Înfrumusețează codul standardizând formatarea lui." maximize_editor: "Mărește/Micește editorul." # cinematic: # click_anywhere_continue: "click anywhere to continue" community: main_title: "Comunitatea CodeCombat" introduction: "Vezi metode prin care poți să te implici și tu mai jos și decide să alegi ce ți se pare cel mai distractiv. Deabia așteptăm să lucrăm împreună!" level_editor_prefix: "Folosește CodeCombat" level_editor_suffix: "Pentru a crea și a edita nivele. Useri au creat nivele pentru clasele lor, prieteni, hackathonuri, studenți si rude. Dacă crearea unui nivel nou ți se pare intimidant poți sa modifici un nivel creat de noi!" thang_editor_prefix: "Numim unitățile din joc 'thangs'. Folosește" thang_editor_suffix: "pentru a modifica ilustrațile sursă CodeCombat. Permitele unitătilor sa arunce proiectile, schimbă direcția unei animații, schimbă viața unei unități, sau uploadează propiile sprite-uri vectoriale." article_editor_prefix: "Vezi o greșală in documentația noastă? Vrei să documentezi instrucțiuni pentru propiile creații? Vezi" article_editor_suffix: "si ajută jucători CodeCombat să obțină căt mai multe din playtime-ul lor." find_us: "Ne găsești pe aceste site-uri" # social_github: "Check out all our code on GitHub" social_blog: "Citește blogul CodeCombat pe Sett" social_discource: "Alăturăte discuțiilor pe forumul Discourse" social_facebook: "Lasă un Like pentru CodeCombat pe facebook" social_twitter: "Urmărește CodeCombat pe Twitter" # social_slack: "Chat with us in the public CodeCombat Slack channel" contribute_to_the_project: "Contribuie la proiect" 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: "Clan" clans: "Clanuri" new_name: "Nume nou de clan" new_description: "Descrierea clanului nou" make_private: "Fă clanul privat" subs_only: "numai abonați" create_clan: "Creează un clan Nou" # private_preview: "Preview" # private_clans: "Private Clans" public_clans: "Clanuri Publice" my_clans: "Clanurile mele" clan_name: "Numele Clanului" name: "Nume" chieftain: "Chieftain" edit_clan_name: "Editează numele clanului" edit_clan_description: "Editează descrierea clanului" edit_name: "editează nume" edit_description: "editează descriere" private: "(privat)" summary: "Sumar" average_level: "Medie Level" average_achievements: "Medie Achievements" delete_clan: "Șterge Clan" leave_clan: "Pleacă din Clan" join_clan: "Intră în Clan" invite_1: "Invitație:" invite_2: "*Invită jucători in acest clan trimițându-le acest link." members: "Membrii" progress: "Progres" not_started_1: "neînceput" started_1: "început" complete_1: "complet" exp_levels: "Extinde nivele" rem_hero: "Șterge Eroul" status: "Stare" complete_2: "Complet" started_2: "Început" not_started_2: "Neînceput" view_solution: "Click pentru a vedea soluția." # view_attempt: "Click to view attempt." latest_achievement: "Ultimile Achievement-uri" playtime: "Timp Jucat" last_played: "Ultima oară cănd ai jucat" # leagues_explanation: "Play in a league against other clan members in these multiplayer arena instances." # track_concepts1: "Track concepts" # track_concepts2a: "learned by each student" # track_concepts2b: "learned by each member" # track_concepts3a: "Track levels completed for each student" # track_concepts3b: "Track levels completed for each member" # track_concepts4a: "See your students'" # track_concepts4b: "See your members'" # track_concepts5: "solutions" # track_concepts6a: "Sort students by name or progress" # track_concepts6b: "Sort members by name or progress" # track_concepts7: "Requires invitation" # track_concepts8: "to join" # private_require_sub: "Private clans require a subscription to create or join." # courses: # create_new_class: "Create New Class" # 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: "Level solutions are available for teachers who have licenses." # unnamed_class: "Unnamed Class" # edit_settings1: "Edit Class Settings" # add_students: "Add Students" # stats: "Statistics" # student_email_invite_blurb: "Your students can also use class code <strong>__classCode__</strong> when creating a Student Account, no email required." # total_students: "Total students:" # average_time: "Average level play time:" # total_time: "Total play time:" # average_levels: "Average levels completed:" # total_levels: "Total levels completed:" # students: "Students" # concepts: "Concepts" # play_time: "Play time:" # completed: "Completed:" # enter_emails: "Separate each email address by a line break or commas" # send_invites: "Invite Students" # number_programming_students: "Number of Programming Students" # number_total_students: "Total Students in School/District" # enroll: "Enroll" # enroll_paid: "Enroll Students in Paid Courses" # get_enrollments: "Get More Licenses" # change_language: "Change Course Language" # keep_using: "Keep Using" # switch_to: "Switch To" # greetings: "Greetings!" # back_classrooms: "Back to my classrooms" # back_classroom: "Back to classroom" # back_courses: "Back to my courses" # edit_details: "Edit class details" # purchase_enrollments: "Purchase Student Licenses" # remove_student: "remove student" # assign: "Assign" # to_assign: "to assign paid courses." # student: "Student" # teacher: "Teacher" # arena: "Arena" # available_levels: "Available Levels" # started: "started" # complete: "complete" # practice: "practice" # required: "required" # welcome_to_courses: "Adventurers, welcome to Courses!" # ready_to_play: "Ready to play?" # start_new_game: "Start New Game" # play_now_learn_header: "Play now to learn" # 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: "My Student Dashboard" # my_classes: "Current Classes" # class_added: "Class successfully added!" # view_map: "view map" # view_videos: "view videos" # view_project_gallery: "view my classmates' projects" # join_class: "Join A Class" # join_class_2: "Join class" # ask_teacher_for_code: "Ask your teacher if you have a CodeCombat class code! If so, enter it below:" # enter_c_code: "<Enter Class Code>" # join: "Join" # joining: "Joining class" # course_complete: "Course Complete" # play_arena: "Play Arena" # view_project: "View Project" # start: "Start" # last_level: "Last level played" # not_you: "Not you?" # continue_playing: "Continue Playing" # option1_header: "Invite Students by Email" # remove_student1: "Remove Student" # are_you_sure: "Are you sure you want to remove this student from this class?" # 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: "Keep Student" # removing_user: "Removing user" # subtitle: "Review course overviews and levels" # Flat style redesign # changelog: "View latest changes to course levels." # select_language: "Select language" # select_level: "Select level" # play_level: "Play Level" # concepts_covered: "Concepts covered" # view_guide_online: "Level Overviews and Solutions" # grants_lifetime_access: "Grants access to all Courses." # enrollment_credits_available: "Licenses Available:" # language_select: "Select a language" # ClassroomSettingsModal # language_cannot_change: "Language cannot be changed once students join a class." # avg_student_exp_label: "Average Student Programming Experience" # avg_student_exp_desc: "This will help us understand how to pace courses better." # avg_student_exp_select: "Select the best option" # avg_student_exp_none: "No Experience - little to no experience" # avg_student_exp_beginner: "Beginner - some exposure or block-based" # avg_student_exp_intermediate: "Intermediate - some experience with typed code" # avg_student_exp_advanced: "Advanced - extensive experience with typed code" # avg_student_exp_varied: "Varied Levels of Experience" # student_age_range_label: "Student Age Range" # student_age_range_younger: "Younger than 6" # student_age_range_older: "Older than 18" # student_age_range_to: "to" # 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: "Create Class" # class_name: "Class Name" # teacher_account_restricted: "Your account is a teacher account and cannot access student content." # account_restricted: "A student account is required to access this page." # update_account_login_title: "Log in to update your account" # update_account_title: "Your account needs attention!" # 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: "I am a teacher" # 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: "I am a student" # 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: "Select Your Hero" # select_your_hero_description: "You can always change your hero by going to your Courses page and clicking \"Change Hero\"" # select_this_hero: "Select this Hero" # current_hero: "Current Hero:" # current_hero_female: "Current Hero:" # 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: "You'll need to join a course to play this level." # 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: "Status:" # assessments: "Assessments" # challenges: "Challenges" # level_name: "Level Name:" # keep_trying: "Keep Trying" # start_challenge: "Start Challenge" # locked: "Locked" # concepts_used: "Concepts Used:" # 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: "Be the first to publish a project in this course!" # view_project: "View Project" # edit_project: "Edit Project" # teacher: # assigning_course: "Assigning course" # back_to_top: "Back to Top" # click_student_code: "Click on any level that the student has started or completed below to view the code they wrote." # code: "__name__'s Code" # complete_solution: "Complete Solution" # 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: "Partial Solution" # capstone_solution: "Capstone Solution" # removing_course: "Removing course" # 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: "__name__'s Student Code" # teacher_dashboard: "Teacher Dashboard" # Navbar # my_classes: "My Classes" # courses: "Course Guides" # enrollments: "Student Licenses" # resources: "Resources" # help: "Help" # language: "Language" # edit_class_settings: "edit class settings" # access_restricted: "Account Update Required" # teacher_account_required: "A teacher account is required to access this content." # create_teacher_account: "Create Teacher Account" # what_is_a_teacher_account: "What's a Teacher Account?" # 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: "Current Classes" # archived_classes: "Archived Classes" # archived_classes_blurb: "Classes can be archived for future reference. Unarchive a class to view it in the Current Classes list again." # view_class: "view class" # archive_class: "archive class" # unarchive_class: "unarchive class" # unarchive_this_class: "Unarchive this class" # no_students_yet: "This class has no students yet." # no_students_yet_view_class: "View class to add students." # try_refreshing: "(You may need to refresh the page)" # create_new_class: "Create a New Class" # class_overview: "Class Overview" # View Class page # avg_playtime: "Average level playtime" # total_playtime: "Total play time" # avg_completed: "Average levels completed" # total_completed: "Total levels completed" # created: "Created" # concepts_covered: "Concepts covered" # earliest_incomplete: "Earliest incomplete level" # latest_complete: "Latest completed level" # enroll_student: "Enroll student" # apply_license: "Apply License" # revoke_license: "Revoke License" # revoke_licenses: "Revoke All Licenses" # course_progress: "Course Progress" # not_applicable: "N/A" # edit: "edit" # edit_2: "Edit" # remove: "remove" # latest_completed: "Latest completed:" # sort_by: "Sort by" # progress: "Progress" # concepts_used: "Concepts used by Student:" # concept_checked: "Concept checked:" # completed: "Completed" # practice: "Practice" # started: "Started" # no_progress: "No progress" # not_required: "Not required" # view_student_code: "Click to view student code" # select_course: "Select course to view" # progress_color_key: "Progress color key:" # level_in_progress: "Level in Progress" # level_not_started: "Level Not Started" # project_or_arena: "Project or Arena" # students_not_assigned: "Students who have not been assigned {{courseName}}" # course_overview: "Course Overview" # copy_class_code: "Copy Class Code" # class_code_blurb: "Students can join your class using this Class Code. No email address is required when creating a Student account with this Class Code." # copy_class_url: "Copy Class URL" # class_join_url_blurb: "You can also post this unique class URL to a shared webpage." # add_students_manually: "Invite Students by Email" # bulk_assign: "Select course" # assigned_msg_1: "{{numberAssigned}} students were assigned {{courseName}}." # assigned_msg_2: "{{numberEnrolled}} licenses were applied." # assigned_msg_3: "You now have {{remainingSpots}} available licenses remaining." # assign_course: "Assign Course" # removed_course_msg: "{{numberRemoved}} students were removed from {{courseName}}." # remove_course: "Remove Course" # not_assigned_modal_title: "Courses were not assigned" # 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: "Enroll Selected Students" # no_students_selected: "No students were selected." # show_students_from: "Show students from" # Enroll students modal # apply_licenses_to_the_following_students: "Apply Licenses to the Following Students" # students_have_licenses: "The following students already have licenses applied:" # all_students: "All Students" # apply_licenses: "Apply Licenses" # not_enough_enrollments: "Not enough licenses available." # enrollments_blurb: "Students are required to have a license to access any content after the first course." # how_to_apply_licenses: "How to Apply Licenses" # export_student_progress: "Export Student Progress (CSV)" # send_email_to: "Send Recover Password Email to:" # email_sent: "Email sent" # send_recovery_email: "Send recovery email" # enter_new_password_below: "Enter new password below:" # change_password: "Change Password" # changed: "Changed" # available_credits: "Available Licenses" # pending_credits: "Pending Licenses" # empty_credits: "Exhausted Licenses" # license_remaining: "license remaining" # licenses_remaining: "licenses remaining" # one_license_used: "1 out of __totalLicenses__ licenses has been used" # num_licenses_used: "__numLicensesUsed__ out of __totalLicenses__ licenses have been used" # starter_licenses: "starter licenses" # start_date: "start date:" # end_date: "end date:" # get_enrollments_blurb: " We'll help you build a solution that meets the needs of your class, school or district." # 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: "Request Sent!" # assessments: "Assessments" # license_status: "License Status" # status_expired: "Expired on {{date}}" # status_not_enrolled: "Not Enrolled" # status_enrolled: "Expires on {{date}}" # select_all: "Select All" # project: "Project" # project_gallery: "Project Gallery" # view_project: "View Project" # unpublished: "(unpublished)" # view_arena_ladder: "View Arena Ladder" # resource_hub: "Resource Hub" # 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: "Additional guides coming soon!" # 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: "Overview" # student_details: "Student Details" # student_name: "Student Name" # no_name: "No name provided." # no_username: "No username provided." # no_email: "Student has no email address set." # student_profile: "Student Profile" # playtime_detail: "Playtime Detail" # student_completed: "Student Completed" # student_in_progress: "Student in Progress" # class_average: "Class Average" # not_assigned: "has not been assigned the following courses" # playtime_axis: "Playtime in Seconds" # levels_axis: "Levels in" # student_state: "How is" # student_state_2: "doing?" # 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: "Revoking..." # 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: "More Info" # 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: "Add Students" # 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: "Level:" # time_played_label: "Time Played:" # back_to_resource_hub: "Back to Resource Hub" # back_to_course_guides: "Back to Course Guides" # print_guide: "Print this guide" # 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: "Concept" # 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: "Share Licenses" # shared_by: "Shared By:" # add_teacher_label: "Enter exact teacher email:" # add_teacher_button: "Add Teacher" # 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." # have_not_shared: "You've not 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: "(you)" # one_license_used: "(1 license used)" # licenses_used: "(__licensesUsed__ licenses used)" # more_info: "More info" # sharing: # game: "Game" # webpage: "Webpage" # 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: "Share This Game" # share_web: "Share This Webpage" # victory_share_prefix: "Share this link to invite your friends & family to" # victory_share_prefix_short: "Invite people to" # victory_share_game: "play your game level" # victory_share_web: "view your webpage" # victory_share_suffix: "." # victory_course_share_prefix: "This link will let your friends & family" # victory_course_share_game: "play the game" # victory_course_share_web: "view the webpage" # victory_course_share_suffix: "you just created." # copy_url: "Copy URL" # share_with_teacher_email: "Send to your teacher" # game_dev: # creator: "Creator" # web_dev: # image_gallery_title: "Image Gallery" # select_an_image: "Select an image you want to use" # scroll_down_for_more_images: "(Scroll down for more images)" # copy_the_url: "Copy the URL below" # copy_the_url_description: "Useful if you want to replace an existing image." # copy_the_img_tag: "Copy the <img> tag" # copy_the_img_tag_description: "Useful if you want to insert a new image." # copy_url: "Copy URL" # copy_img: "Copy <img>" # how_to_copy_paste: "How to Copy/Paste" # copy: "Copy" # paste: "Paste" # back_to_editing: "Back to Editing" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" archmage_summary: "Dacă ești un dezvoltator interesat să programezi jocuri educaționale, devino Archmage si ajută-ne să construim CodeCombat!" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" artisan_summary: "Construiește si oferă nivele pentru tine si pentru prieteni tăi, ca să se joace. Devino Artisan si învață arta de a împărți cunoștințe despre programare." adventurer_title: "Aventurier" adventurer_title_description: "(Playtester de nivele)" adventurer_summary: "Primește nivelele noastre noi (chiar si cele pentru abonați) gratis cu o săptămână înainte si ajută-ne să reparăm bug-uri până la lansare." scribe_title: "Scrib" scribe_title_description: "(Editor de articole)" scribe_summary: "Un cod bun are nevoie de o documentație bună. Scrie, editează, si improvizează documentația citită de milioane de jucători în întreaga lume." diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" diplomat_summary: "CodeCombat e localizat în 45+ de limbi de Diplomații noștri. Ajută-ne și contribuie la traducere." ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" ambassador_summary: "Îmblânzește useri de pe forumul nostru si oferă direcți pentru cei cu întrebări. Ambasadori noștri reprezintă CodeCombat în fața lumii." # teacher_title: "Teacher" editor: main_title: "Editori CodeCombat" article_title: "Editor Articol" thang_title: "Editor Thang" level_title: "Editor Nivele" # course_title: "Course Editor" achievement_title: "Editor Achievement" poll_title: "Editor Sondaje" back: "Înapoi" revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" pick_a_terrain: "Alege Terenul" dungeon: "Temniță" indoor: "Interior" desert: "Deșert" grassy: "Ierbos" # mountain: "Mountain" # glacier: "Glacier" small: "Mic" large: "Mare" fork_title: "Fork Versiune Nouă" fork_creating: "Creare Fork..." generate_terrain: "Generează Teren" more: "Mai Multe" wiki: "Wiki" live_chat: "Chat Live" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Culori" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "Script-uri" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_docs: "Documentație" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_all: "Toate" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă Thangs" # level_tab_thangs_search: "Search thangs" add_components: "Adaugă Componente" component_configs: "Configurarea Componentelor" config_thang: "Dublu click pentru a configura un thang" delete: "Șterge" duplicate: "Duplică" stop_duplicate: "Oprește Duplicarea" rotate: "Rotește" level_component_tab_title: "Componente actuale" level_component_btn_new: "Crează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Crează sistem nou" level_systems_btn_add: "Adaugă Sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează Componentă" level_component_config_schema: "Schema Config" level_system_edit_title: "Editează Sistem" create_system_title: "Crează sistem nou" new_component_title: "Crează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Crează un articol nou" new_thang_title: "Crează un nou tip de Thang" new_level_title: "Crează un nivel nou" new_article_title_login: "Loghează-te pentru a crea un Articol Nou" new_thang_title_login: "Loghează-te pentru a crea un Thang de Tip Nou" new_level_title_login: "Loghează-te pentru a crea un Nivel Nou" new_achievement_title: "Crează un Achivement Nou" new_achievement_title_login: "Loghează-te pentru a crea un Achivement Nou" new_poll_title: "Crează un Sondaj Nou" new_poll_title_login: "Loghează-te pentru a crea un Sondaj Nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută nivele aici" achievement_search_title: "Caută Achievements" poll_search_title: "Caută Sondaje" read_only_warning2: "Notă: nu poți salva editările aici, pentru că nu ești logat." no_achievements: "Nici-un achivement adăugat acestui nivel până acum." achievement_query_misc: "Key achievement din diverse" achievement_query_goals: "Key achievement din obiectivele nivelelor" level_completion: "Finalizare Nivel" pop_i18n: "Populează I18N" tasks: "Sarcini" clear_storage: "Șterge schimbările locale" # add_system_title: "Add Systems to Level" # done_adding: "Done Adding" article: edit_btn_preview: "Preview" edit_article_title: "Editează Articol" polls: priority: "Prioritate" contribute: page_title: "Contribuțtii" intro_blurb: "CodeCombat este 100% open source! Sute de jucători dedicați ne-au ajutat sa construim jocul în cea ce este astăzi. Alătură-te si scrie următorul capitol în aventura CodeCombat de a ajuta lumea să învețe cod!" # {change} alert_account_message_intro: "Salutare!" alert_account_message: "Pentru a te abona la mailurile clasei trebuie să fi logat." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, Sunet, Networking în timp real, Social Networking, și desigur multe dintre aspectele comune ale programării, de la gestiune low-level a bazelor de date, și administrare server până la construirea de interfețe. Este mult de muncă, și dacă ești un programator cu experiență, cu un dor de a se arunca cu capul înainte îm CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este JavaScript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" # join_url_slack: "public Slack channel" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_introduction_suf: ", atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să testați pe mai mulți oameni și să obțineți feedback, și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebui să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași, mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Crează un nivel nou și explorează nivelele deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelele tale pe forum pentru feedback." artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de Nivele și anunțuri." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura, atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucrează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi nivele de testat. De asemenea vom posta despre nivele care trebuie revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri, înscrie-te acolo!" adventurer_subscribe_desc: "Primește email-uri când sunt noi nivele de testat." scribe_introduction_pref: "CodeCombat nu o să fie doar o colecție de nivele. Vor fi incluse resurse de cunoaștere, un wiki despre concepte de programare legate de fiecare nivel. În felul acesta fiecare Arisan nu trebuie să mai descrie în detaliu ce este un operator de comparație, ei pot să pună un link la un Articol mai bine documentat. Ceva asemănător cu ce " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a construit. Dacă idea ta de distracție este să articulezi conceptele de programare în formă Markdown, această clasă ți s-ar potrivi." scribe_attribute_1: "Un talent în cuvinte este tot ce îți trebuie. Nu numai gramatică și ortografie, trebuie să poți să explici ideii complicate celorlați." contact_us_url: "Contactați-ne" # {change} scribe_join_description: "spune-ne câte ceva despre tine, experiențele tale despre programare și ce fel de lucruri ți-ar place să scri despre. Vom începe de acolo!." scribe_subscribe_desc: "Primește mailuri despre scrisul de articole." diplomat_introduction_pref: "Dacă ar fi un lucru care l-am învățat din " diplomat_launch_url: "lansarea din Octombire" diplomat_introduction_suf: "acesta ar fi că: există un interes mare pentru CodeCombat și în alte țări! Încercăm sa adunăm cât mai mulți translatori care sunt pregătiți să transforme un set de cuvinte intr-un alt set de cuvinte ca să facă CodeCombat cât mai accesibil în toată lumea. Dacă vrei să tragi cu ochiul la conțintul ce va apărea și să aduci nivele cât mai repede pentru conaționali tăi, această clasă ți se potriveste." diplomat_attribute_1: "Fluență în Engleză și limba în care vrei să traduci. Când explici ideii complicate este important să întelegi bine ambele limbi!" diplomat_i18n_page_prefix: "Poți începe să traduci nivele accesând" diplomat_i18n_page: "Pagina de traduceri" diplomat_i18n_page_suffix: ", sau interfața si website-ul pe GitHub." diplomat_join_pref_github: "Găsește fișierul pentru limba ta " diplomat_github_url: "pe GitHub" diplomat_join_suf_github: ", editeazăl online si trimite un pull request. Bifează căsuța de mai jos ca să fi up-to-date cu dezvoltările noastre internaționale!" diplomat_subscribe_desc: "Primește mail-uri despre dezvoltările i18n si niveluri de tradus." ambassador_introduction: "Aceasta este o comunitate pe care o construim, iar voi sunteți conexiunile. Avem forumui, email-uri, si rețele sociale cu mulți oameni cu care se poate vorbi despre joc și de la care se poate învața. Dacă vrei să ajuți oameni să se implice și să se distreze această clasă este potrivită pentru tine." ambassador_attribute_1: "Abilități de comunicare. Abilitatea de a indentifica problemele pe care jucătorii le au si șa îi poti ajuta. De asemenea, trebuie să ne informezi cu părerile jucătoriilor, ce le place și ce vor mai mult!" ambassador_join_desc: "spune-ne câte ceva despre tine, ce ai făcut si ce te interesează să faci. Vom porni de acolo!." ambassador_join_note_strong: "Notă" ambassador_join_note_desc: "Una din prioritățile noaste este să constrruim un joc multiplayer unde jucători noștri, dacă au probleme pot să cheme un wizard cu un nivel ridicat să îi ajute." ambassador_subscribe_desc: "Primește mailuri despre support updates și dezvoltări multiplayer." # teacher_subscribe_desc: "Get emails on updates and announcements for teachers." changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "Scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" # simulation_explanation_leagues: "You will mainly help simulate games for allied players in your clans and courses." simulate_games: "Simulează Jocuri!" games_simulated_by: "Jocuri simulate de tine:" games_simulated_for: "Jocuri simulate pentru tine:" # games_in_queue: "Games currently in the queue:" games_simulated: "Jocuri simulate" games_played: "Jocuri jucate" ratio: "Rație" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un Cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul in Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea in clasament" rank_being_ranked: "Jocul se plasează in Clasament" rank_last_submitted: "trimis " help_simulate: "Ne ajuți simulând jocuri?" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Nici un meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentru a-ți plasa meciul in clasament." choose_opponent: "Alege un adversar" select_your_language: "Alege limbă!" tutorial_play: "Joacă Tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sări peste Tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă Tutorial-ul mai întâi." simple_ai: "AI simplu" # {change} warmup: "Încălzire" friends_playing: "Prieteni ce se Joacă" log_in_for_friends: "Loghează-te ca să joci cu prieteni tăi!" social_connect_blurb: "Conectează-te și joacă împotriva prietenilor tăi!" invite_friends_to_battle: "Invită-ți prieteni să se alăture bătăliei" fight: "Luptă!" watch_victory: "Vizualizează victoria" defeat_the: "Învinge" # watch_battle: "Watch the battle" tournament_started: ", a început" tournament_ends: "Turneul se termină" tournament_ended: "Turneul s-a terminat" tournament_rules: "Regulile Turneului" tournament_blurb: "Scrie cod, colectează aur, construiește armate, distruge inamici, câștigă premii, si îmbunătățeșteți cariera în turneul Lăcomiei de $40,000! Află detalii" tournament_blurb_criss_cross: "Caștigă pariuri, creează căi, păcălește-ți oponenți, strâange Pietre Prețioase, si îmbunătățeșteți cariera in turneul Criss-Cross! Află detalii" tournament_blurb_zero_sum: "Dezlănțuie creativitatea de programare în strângerea de aur sau în tactici de bătălie în alpine mirror match dintre vrăitori roșii și cei albaștrii.Turneul începe Vineri, 27 Martie și se va desfăsura până Luni, 6 Aprilie la 5PM PDT. Află detalii" # tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details" tournament_blurb_blog: "pe blogul nostru" rules: "Reguli" winners: "Învingători" # league: "League" # red_ai: "Red CPU" # "Red AI Wins", at end of multiplayer match playback # blue_ai: "Blue CPU" # wins: "Wins" # At end of multiplayer match playback # humans: "Red" # Ladder page display team name # ogres: "Blue" # 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: "Statistici" singleplayer_title: "Nivele Singleplayer" multiplayer_title: "Nivele Multiplayer" achievements_title: "Achievement-uri" last_played: "Ultima oară jucat" status: "Stare" status_completed: "Complet" status_unfinished: "Neterminat" no_singleplayer: "Nici-un joc Singleplayer jucat." no_multiplayer: "Nici-un joc Multiplayer jucat." no_achievements: "Nici-un Achivement câștigat." favorite_prefix: "Limbaj preferat" favorite_postfix: "." not_member_of_clans: "Nu ești membrul unui clan." # 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: "Ultimul câstigat" amount_achieved: "Sumă" achievement: "Achievement" current_xp_prefix: "" current_xp_postfix: " în total" new_xp_prefix: "" new_xp_postfix: " câștigat" left_xp_prefix: "" left_xp_infix: " până la level" 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: "Plăți" # prepaid_codes: "Prepaid Codes" purchased: "Cumpărate" # subscribe_for_gems: "Subscribe for gems" subscription: "Abonament" invoices: "Invoice-uri" service_apple: "Apple" service_web: "Web" paid_on: "Plătit pe" service: "Service" price: "Preț" gems: "Pietre Prețioase" active: "Activ" subscribed: "Abonat" unsubscribed: "Dezabonat" active_until: "Activ până" cost: "Cost" next_payment: "Următoarea Plată" card: "Card" status_unsubscribed_active: "Nu ești abonat si nu vei fi facturat, contul tău este activ deocamdată." status_unsubscribed: "Primește access la nivele noi, eroi, iteme, și Pietre Prețioase bonus cu un abonament CodeCombat!" # not_yet_verified: "Not yet verified." # resend_email: "Resend email" # email_sent: "Email sent! Check your inbox." # verifying_email: "Verifying your email address..." # successfully_verified: "You've successfully verified your email address!" # verify_error: "Something went wrong when verifying your email :(" # unsubscribe_from_marketing: "Unsubscribe __email__ from all CodeCombat marketing emails?" # unsubscribe_button: "Yes, unsubscribe" # unsubscribe_failed: "Failed" # unsubscribe_success: "Success" account_invoices: amount: "Sumă in dolari US" declined: "Cardul tău a fost refuzat" invalid_amount: "Introdu o sumă in dolari US." not_logged_in: "Logheazăte sau crează un cont pentru a accesa invoice-uri." pay: "Plată Invoice" purchasing: "Cumpăr..." retrying: "Eroare server, reîncerc." success: "Plătit cu success. Mulțumim!" # account_prepaid: # purchase_code: "Purchase a Subscription Code" # 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: "Users" # months: "Months" # purchase_total: "Total" # purchase_button: "Submit Purchase" # your_codes: "Your Codes" # redeem_codes: "Redeem a Subscription Code" # prepaid_code: "Prepaid Code" # lookup_code: "Lookup prepaid code" # apply_account: "Apply to your account" # copy_link: "You can copy the code's link and send it to someone." # quantity: "Quantity" # redeemed: "Redeemed" # no_codes: "No codes yet!" # you_can1: "You can" # you_can2: "purchase a prepaid code" # you_can3: "that can be applied to your own account or given to others." # 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: "Eroare la încărcarea pe server" # {change} connection_failure: "Conexiune eșuată." # connection_failure_desc: "It doesn’t look like you’re connected to the internet! Check your network connection and then reload this page." # login_required: "Login Required" # login_required_desc: "You need to be logged in to access this page." unauthorized: "Este nevoie să te loghezi. Ai cookies dezactivate?" forbidden: "Nu ai permisiune." # forbidden_desc: "Oh no, there’s nothing we can show you here! Make sure you’re logged into the correct account, or visit one of the links below to get back to programming!" # user_not_found: "User Not Found" not_found: "Nu a fost găsit." # not_found_desc: "Hm, there’s nothing here. Visit one of the following links to get back to programming!" not_allowed: "Metodă nepermisă." timeout: "Timeout Server." # {change} conflict: "Conflict resurse." bad_input: "Date greșite." server_error: "Eroare Server." unknown: "Eroare Necunoscută." # {change} # error: "ERROR" # general_desc: "Something went wrong, and it’s probably our fault. Try waiting a bit and then refreshing the page, or visit one of the following links to get back to programming!" resources: level: "Nivel" patch: "Patch" patches: "Patch-uri" system: "Sistem" systems: "Sisteme" component: "Componentă" components: "Componente" hero: "Erou" campaigns: "Campanii" # 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: "Arguments" # arithmetic: "Arithmetic" # 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: "Basic Syntax" # binary: "Binary" # 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: "Break Statements" # classes: "Classes" # continue_statements: "Continue Statements" # dom_events: "DOM Events" # dynamic_styling: "Dynamic Styling" # events: "Events" # 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: "Functions" # functions_parameters: "Parameters" # functions_multiple_parameters: "Multiple Parameters" # game_ai: "Game AI" # game_goals: "Game Goals" # game_spawn: "Game Spawn" # graphics: "Graphics" # graphs: "Graphs" # heaps: "Heaps" # if_condition: "Conditional If Statements" # if_else_if: "If/Else If Statements" # if_else_statements: "If/Else Statements" # if_statements: "If Statements" # 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: "Geometry" # math_operations: "Math Library Operations" # math_proportions: "Proportion Math" # math_trigonometry: "Trigonometry" # object_literals: "Object Literals" # parameters: "Parameters" # programs: "Programs" # properties: "Properties" # property_access: "Accessing Properties" # property_assignment: "Assigning Properties" # property_coordinate: "Coordinate Property" # queues: "Data Structures - Queues" # reading_docs: "Reading the Docs" # recursion: "Recursion" # return_statements: "Return Statements" # stacks: "Data Structures - Stacks" # strings: "Strings" # strings_concatenation: "String Concatenation" # strings_substrings: "Substring" # trees: "Data Structures - Trees" # variables: "Variables" # vectors: "Vectors" # while_condition_loops: "While Loops with Conditionals" # while_loops_simple: "While Loops" # while_loops_nested: "Nested While Loops" # xy_coordinates: "Coordinate Pairs" # advanced_strings: "Advanced Strings" # Rest of concepts are deprecated # algorithms: "Algorithms" # boolean_logic: "Boolean Logic" # basic_html: "Basic HTML" # basic_css: "Basic CSS" # basic_web_scripting: "Basic Web Scripting" # intermediate_html: "Intermediate HTML" # intermediate_css: "Intermediate CSS" # intermediate_web_scripting: "Intermediate Web Scripting" # advanced_html: "Advanced HTML" # advanced_css: "Advanced CSS" # advanced_web_scripting: "Advanced Web Scripting" # input_handling: "Input Handling" # while_loops: "While Loops" # place_game_objects: "Place game objects" # construct_mazes: "Construct mazes" # 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: "Basic JavaScript" # 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: "Your name:" # enter_teacher_email: "Your teacher's email:" # teacher_email_placeholder: "teacher.email@example.com" # student_name_placeholder: "type your name here" # teachers_section: "Teachers:" # students_section: "Students:" # teacher_notified: "We've notified your teacher that you want to play more CodeCombat in your classroom!" delta: added: "Adăugat" modified: "Modificat" # not_modified: "Not Modified" deleted: "Șters" moved_index: "Index Mutat" text_diff: "Diff Text" merge_conflict_with: "ÎBINĂ CONFLICTUL CU" no_changes: "Fară Schimbări" legal: page_title: "Aspecte Legale" # opensource_introduction: "CodeCombat is part of the open source community." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit peste o mulțime de proiecte open source, care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu software-ul care fac acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Nu o să iți vindem datele personale." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" # cost_description: "CodeCombat is free to play for all of its core levels, with a ${{price}} USD/mo subscription for access to extra level branches and {{gems}} bonus gems per month. You can cancel with a click, and we offer a 100% money-back guarantee." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" # {change} # 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: "MIT license" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a crea nivele." art_title: "Artă/Muzică - Conținut Comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea nivele. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice si toate celelalte creații non-cod care sunt disponibile când se crează nivele." art_access: "Momentan nu există nici un sistem universal,ușor pentru preluarea acestor bunuri. În general, preluați-le precum site-ul din URL-urile folosite, contactați-ne pentru asistență, sau ajutați-ne sa extindem site-ul pentru a face aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm numiți și lăsați referire link la codecombat.com unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link in apropiere, de exemplu sub o imagine, sau in pagina generală de atribuiri unde menționați și alte Bunuri Creative și software open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să se facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către ei, și urmăriți indicațiile de atribuire prevăzute în descrierea resursei dacă există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru Nivele în sine. Asta include" rights_scripts: "Script-uri" rights_unit: "Configurații de unități" rights_writings: "Scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru acel nivel care nu este valabil în mod normal pentru creat nivele." rights_clarification: "Pentru a clarifica, orice este valabil in Editorul de Nivele pentru scopul de a crea nivele se află sub CC, pe când conținutul creat cu Editorul de Nivele sau încărcat pentru a face nivelul nu se află." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Nivele puteți folosi liber cum vreți pentru a crea nivele. Dar ne rezervăm dreptul de a rezerva distribuția de nivele în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." # nutshell_see_also: "See also:" canonical: "Versiunea in engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între traduceri, documentul in engleză are prioritate." # third_party_title: "Third Party Services" # third_party_description: "CodeCombat uses the following third party services (among others):" # cookies_message: "CodeCombat uses a few essential and non-essential cookies." # cookies_deny: "Decline non-essential cookies" ladder_prizes: title: "Premii Turnee" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Aceste premii se acordă în funcție de" blurb_2: "Regulile Turneului" blurb_3: "la jucători umani sau ogre de top." blurb_4: "Două echipe înseamnă dublul premiilor!" blurb_5: "(O să fie 2 câștigători pe primul loc, 2 pe locul 2, etc.)" rank: "Rank" prizes: "Premii" total_value: "Valoare Totala" in_cash: "în cash" custom_wizard: "Wizard CodeCombat personalizat" custom_avatar: "Avatar CodeCombat personalizat" heap: "pentru 6 luni de acces \"Startup\"" credits: "credite" one_month_coupon: "coupon: alege Rails sau HTML" one_month_discount: "discount, 30% off: choose either Rails or HTML" license: "licență" oreilly: "ebook la alegere" calendar: year: "An" day: "Zi" # month: "Month" january: "Ianuarie" # february: "February" # march: "March" # april: "April" # may: "May" # june: "June" # july: "July" # august: "August" # september: "September" # october: "October" # november: "November" # december: "December" # 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: "Email already taken" # username_taken: "Username already taken" # esper: # line_no: "Line $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: "Error: " # x_not_a_function: "$1 is not a function" # x_not_defined: "$1 is not defined" # 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: "Unexpected token" # unexpected_number: "Unexpected number" # 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: "Try `$1`" # there_is_no_function: "There is no function `$1`, but `$2` has a method `$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` has no method `$2`." # there_is_a_problem: "There is a problem with your code." # 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"
220540
module.exports = nativeDescription: "limba română", englishDescription: "Romanian", 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: "Un joc de programare dezvoltat cu gandul la profesori." # 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: "Informatică" built_for_teachers_subblurb1: "Începând cu cursul nostru gratuit de Introducere în Informatică, studenții însușesc concepte de baza în programare, cum ar fi bucle while/for, funcții și algoritmi." built_for_teachers_subtitle2: "Dezvoltare de jocuri" # 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: "Dezvoltare Web" # 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: "Gândire critică" # 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: "Creativitate" # 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: "Partener oficial Code.org" # 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: "Implementare ușoară" # 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: "Cel mai interesant mod de a învăța codul 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: "Classroom Edition:" # learn_to_code: "Learn to code:" # play_now: "Play Now" # im_an_educator: "I'm an Educator" im_a_teacher: "<NAME>" im_a_student: "Sunt Student" learn_more: "Aflați mai multe" # classroom_in_a_box: "A classroom in-a-box for teaching computer science." # codecombat_is: "CodeCombat is a platform <strong>for students</strong> to learn computer science while playing through a real game." # our_courses: "Our courses have been specifically playtested <strong>to excel in the classroom</strong>, even for teachers with little to no prior programming experience." # watch_how: "Watch how CodeCombat is transforming the way people learn computer science." # top_screenshots_hint: "Students write code and see their changes update in real-time" # designed_with: "Designed with teachers in mind" # real_code: "Real, typed code" from_the_first_level: "de la primul nivel" # getting_students: "Getting students to typed code as quickly as possible is critical to learning programming syntax and proper structure." # educator_resources: "Educator resources" course_guides: "și ghiduri de curs" # teaching_computer_science: "Teaching computer science does not require a costly degree, because we provide tools to support educators of all backgrounds." accessible_to: "Accesibil la" everyone: "toţi" # democratizing: "Democratizing the process of learning coding is at the core of our philosophy. Everyone should be able to learn to code." # forgot_learning: "I think they actually forgot that they were learning something." # wanted_to_do: " Coding is something I've always wanted to do, and I never thought I would be able to learn it in school." # builds_concepts_up: "I like how CodeCombat builds the concepts up. It's really easy to understand and fun to figure it out." why_games: "De ce este importantă învățarea prin jocuri?" # games_reward: "Games reward the productive struggle." # encourage: "Gaming is a medium that encourages interaction, discovery, and trial-and-error. A good game challenges the player to master skills over time, which is the same critical process students go through as they learn." # excel: "Games excel at rewarding" # struggle: "productive struggle" # kind_of_struggle: "the kind of struggle that results in learning that’s engaging and" motivating: "motivând" # not_tedious: "not tedious." gaming_is_good: "Studiile sugerează că jocurile sunt bune pentru creierul copiilor. (e adevarat!)" # 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: "A real game, played with real coding." # 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: "Request a Demo" # request_quote: "Request a Quote" # setup_a_class: "Set Up a Class" have_an_account: "Aveți un cont?" logged_in_as: "În prezent sunteți conectat(ă) ca" # computer_science: "Our self-paced courses cover basic syntax to advanced concepts" ffa: "Gratuit pentru toți elevii" # coming_soon: "More coming soon!" # courses_available_in: "Courses are available in JavaScript and Python. Web Development courses utilize HTML, CSS, and 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: "Everything you need to run a computer science class in your school today, no CS background required." # goto_classes: "Go to My Classes" # view_profile: "View My Profile" # view_progress: "View Progress" # go_to_courses: "Go to My Courses" # want_coco: "Want CodeCombat at your school?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" # map: "Map" play: "Nivele" # The top nav bar entry where players choose which levels to play community: "Communitate" courses: "Cursuri" blog: "Blog" forum: "Forum" account: "Cont" my_account: "Contul meu" profile: "Profil" home: "Acasă" contribute: "Contribuie" legal: "Confidențialitate și termeni" # privacy: "Privacy Notice" about: "Despre" # impact: "Impact" contact: "Contact" twitter_follow: "Urmărește" # my_classrooms: "My Classes" my_courses: "Cursurile mele" # my_teachers: "My Teachers" # careers: "Careers" facebook: "Facebook" twitter: "Twitter" # create_a_class: "Create a Class" # other: "Other" # learn_to_code: "Learn to Code!" # toggle_nav: "Toggle navigation" # schools: "Schools" # get_involved: "Get Involved" # open_source: "Open source (GitHub)" # support: "Support" # faqs: "FAQs" # copyright_prefix: "Copyright" # copyright_suffix: "All Rights Reserved." # help_pref: "Need help? Email" # help_suff: "and we'll get in touch!" # resource_hub: "Resource Hub" # apcsp: "AP CS Principles" # parent: "Parents" # browser_recommendation: "For the best experience we recommend using the latest version of Chrome. Download the browser here!" modal: close: "Inchide" okay: "Okay" # cancel: "Cancel" not_found: page_not_found: "Pagina nu a fost gasită" diplomat_suggestion: title: "Ajută-ne să traducem CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat in limba engleza , dar deja avem jucatări din toate colțurile lumii. Mulți dintre ei vor să joace in română și nu vorbesc engleză. Dacă poți vorbi ambele te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți sa traducem atât jocul cât și site-ul." missing_translations: "Until we can translate everything into Romanian, you'll see English when Romanian isn't available." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" 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: "CodeCombat has a" # anon_signup_title_2: "Classroom Version!" # anon_signup_enter_code: "Enter Class Code:" # anon_signup_ask_teacher: "Don't have one? Ask your teacher!" # anon_signup_create_class: "Want to create a class?" # anon_signup_setup_class: "Set up a class, add your students, and monitor progress!" # anon_signup_create_teacher: "Create free teacher account" play_as: "Alege-ți echipa" # Ladder page # get_course_for_class: "Assign Game Development and more to your classes!" # request_licenses: "Contact our school specialists for details." # compete: "Compete!" # Course details page spectate: "Spectator" # Ladder page players: "jucători" # Hover over a level on /play hours_played: "ore jucate" # Hover over a level on /play items: "Iteme" # Tooltip on item shop button from /play unlock: "Deblochează" # For purchasing items and heroes confirm: "Confirmă" owned: "Deținute" # For items you own locked: "Blocate" available: "Valabile" skills_granted: "Skill-uri acordate" # Property documentation details heroes: "Eroi" # Tooltip on hero shop button from /play achievements: "Realizări" # Tooltip on achievement list button from /play settings: "Setări" # Tooltip on settings button from /play poll: "Sondaj" # Tooltip on poll button from /play next: "Următorul" # Go from choose hero to choose inventory before playing a level change_hero: "Schimbă eroul" # Go back from choose inventory to choose hero # change_hero_or_language: "Change Hero or Language" buy_gems: "Cumpără Pietre Prețioase" # subscribers_only: "Subscribers Only!" # subscribe_unlock: "Subscribe to Unlock!" # subscriber_heroes: "Subscribe today to immediately unlock Amara, Hushbaum, and Hattori!" # subscriber_gems: "Subscribe today to purchase this hero with gems!" anonymous: "<NAME>" level_difficulty: "Dificultate: " awaiting_levels_adventurer_prefix: "Lansăm niveluri noi în fiecare săptămână." awaiting_levels_adventurer: "Înscrie-te ca un aventurier " awaiting_levels_adventurer_suffix: "pentru a fi primul care joacă nivele noi." adjust_volume: "Reglează volumul" campaign_multiplayer: "Arene Multiplayer" campaign_multiplayer_description: "... în care te lupți cap-la-cap contra alți jucători." # 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: "Back to Classroom" # teacher_button: "For Teachers" # get_more_codecombat: "Get More CodeCombat" code: # if: "if" # 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: "else" # elif: "else if" # while: "while" # loop: "loop" # for: "for" # break: "break" # continue: "continue" # pass: "pass" # return: "return" # then: "then" # do: "do" # end: "end" # function: "function" # def: "define" # var: "variable" # self: "self" # hero: "hero" # this: "this" # or: "or" # "||": "or" # and: "and" # "&&": "and" # not: "not" # "!": "not" # "=": "assign" # "==": "equals" # "===": "strictly equals" # "!=": "does not equal" # "!==": "does not strictly equal" # ">": "is greater than" # ">=": "is greater than or equal" # "<": "is less than" # "<=": "is less than or equal" # "*": "multiplied by" # "/": "divided by" "+": "plus" "-": "minus" "+=": "adaugă și atribuie" "-=": "scade și atribuie" True: "Adevărat" true: "adevărat" False: "Fals" false: "fals" undefined: "nedefinit" # null: "null" # nil: "nil" # None: "None" share_progress_modal: blurb: "Faci progrese mari! Spune-le părinților cât de mult ai învățat cu CodeCombat." email_invalid: "Adresă Email invalidă." form_blurb: "Introduceți adresa e-mail al unui părinte mai jos și le vom arăta!" form_label: "Adresă Email" placeholder: "adresă email" title: "Excelentă treabă, Ucenicule" login: sign_up: "Crează cont" email_or_username: "Email sau nume de utilizator" log_in: "Log In" logging_in: "Se conectează" log_out: "Log Out" forgot_password: "<PASSWORD>?" finishing: "Terminare" sign_in_with_facebook: "Conectați-vă cu Facebook" sign_in_with_gplus: "Conectați-vă cu G+" signup_switch: "Doriți să creați un cont?" signup: complete_subscription: "Completează abonamentul" create_student_header: "Creează cont student" create_teacher_header: "Creează cont profesor" create_individual_header: "Creează cont profesor un cont individual" email_announcements: "Primește notificări prin email" # {change} sign_in_to_continue: "Conecteaza-te sau creează un cont pentru a continua" # teacher_email_announcements: "Keep me updated on new teacher resources, curriculum, and courses!" creating: "Se creează contul..." sign_up: "Înscrie-te" log_in: "loghează-te cu parola" # login: "Login" required: "Trebuie să te înregistrezi înaite să parcurgi acest drum." login_switch: "Ai deja un cont?" optional: "opțional" # 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: "Students, enter the class code from your teacher." # birthday: "Birthday" # 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: "Checking..." # account_exists: "This email is already in use:" # sign_in: "Sign in" # email_good: "Email looks good!" # name_taken: "Username already taken! Try {{suggestedName}}?" # name_available: "Username available!" # name_is_email: "Username may not be an email" # choose_type: "Choose your account type:" # teacher_type_1: "Teach programming using CodeCombat!" # teacher_type_2: "Set up your class" # teacher_type_3: "Access Course Guides" # teacher_type_4: "View student progress" # signup_as_teacher: "Sign up as a Teacher" # student_type_1: "Learn to program while playing an engaging game!" # student_type_2: "Play with your class" # student_type_3: "Compete in arenas" student_type_4: "Alege-ți eroul!" # student_type_5: "Have your Class Code ready!" # signup_as_student: "Sign up as a Student" # individuals_or_parents: "Individuals & Parents" # individual_type: "For players learning to code outside of a class. Parents should sign up for an account here." # signup_as_individual: "Sign up as an Individual" # enter_class_code: "Enter your Class Code" # enter_birthdate: "Enter your birthdate:" # parent_use_birthdate: "Parents, use your own birthdate." # ask_teacher_1: "Ask your teacher for your Class Code." # ask_teacher_2: "Not part of a class? Create an " # ask_teacher_3: "Individual Account" # ask_teacher_4: " instead." # about_to_join: "You're about to join:" enter_parent_email: "Introduceți adresa de e-mail a părintelui dvs .:" # 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: "Account Created!" # confirm_student_blurb: "Write down your information so that you don't forget it. Your teacher can also help you reset your password at any time." # confirm_individual_blurb: "Write down your login information in case you need it later. Verify your email so you can recover your account if you ever forget your password - check your inbox!" write_this_down: "Notează asta:" start_playing: "Începe jocul!" # sso_connected: "Successfully connected with:" # select_your_starting_hero: "Select Your Starting Hero:" # you_can_always_change_your_hero_later: "You can always change your hero later." # 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: "Află mai multe despre riscuri posibile." eu_confirmation_student: "Dacă nu ești sigur, întreabă-ți profesorul." # 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: "Recuperează Cont" send_password: "<PASSWORD>" recovery_sent: "Email de recuperare trimis." items: primary: "Primar" secondary: "Secundar" armor: "Armură" accessories: "Accesorii" misc: "Diverse" books: "Cărti" 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: "Inapoi" # When used as an action verb, like "Navigate backward" coming_soon: "In curand!" continue: "Continuă" # When used as an action verb, like "Continue forward" next: "Urmator" default_code: "Cod implicit" loading: "Se încarcă..." overview: "Prezentare generală" processing: "Procesare..." solution: "Soluţie" table_of_contents: "Cuprins" intro: "Introducere" saving: "Se salvează..." sending: "Se trimite..." send: "Trimite" sent: "Trimis" cancel: "Anulează" save: "Salvează" publish: "Publică" create: "Creează" fork: "Fork" play: "Joacă" # When used as an action verb, like "Play next level" retry: "Reîncearca" actions: "Acţiuni" info: "Info" help: "Ajutor" watch: "Watch" unwatch: "Unwatch" submit_patch: "Înainteaza Patch" submit_changes: "Trimite modificări" save_changes: "Salveaza modificări" required_field: "obligatoriu" # submit: "Submit" # replay: "Replay" # complete: "Complete" general: and: "și" name: "<NAME>" date: "Dată" body: "Corp" version: "Versiune" pending: "În așteptare" accepted: "Acceptat" rejected: "Respins" withdrawn: "Retrage" accept: "Accepta" accept_and_save: "Acceptă și Salvează" reject: "Respinge" withdraw: "Retrage" submitter: "<NAME>" submitted: "Expediat" commit_msg: "Înregistrează Mesajul" version_history: "Istoricul versiunilor" version_history_for: "Istoricul versiunilor pentru: " select_changes: "Selectați două schimbări de mai jos pentru a vedea diferenţa." undo_prefix: "Undo" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Redo" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Joaca previzualizarea nivelului actual" result: "Rezultat" results: "Rezultate" description: "Descriere" or: "sau" subject: "Subiect" email: "Email" password: "<PASSWORD>" confirm_password: "<PASSWORD>" message: "Mes<NAME>" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rang" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" player: "<NAME>" player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard warrior: "<NAME>" ranger: "Arcaș" wizard: "Vrăjitor" first_name: "<NAME>" last_name: "<NAME>" last_initial: "Inițiala nume" username: "Nume de utilizator" contact_us: "Contacteaza-ne" close_window: "Închide fereastra" learn_more: "Află mai mult" more: "Mai mult" fewer: "Mai putin" with: "cu" units: second: "secundă" seconds: "secunde" # sec: "sec" minute: "minut" minutes: "minute" hour: "oră" hours: "ore" day: "zi" days: "zile" week: "săptămână" weeks: "săptămâni" month: "lună" months: "luni" year: "an" years: "ani" play_level: # back_to_map: "Back to Map" # directions: "Directions" # edit_level: "Edit Level" # keep_learning: "Keep Learning" # explore_codecombat: "Explore CodeCombat" # finished_hoc: "I'm finished with my Hour of Code" # get_certificate: "Get your certificate!" # level_complete: "Level Complete" # completed_level: "Completed Level:" # course: "Course:" done: "Gata" # next_level: "Next Level" # 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__ Concepts Used" # 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: "Start Challenge" # next_game: "Next game" languages: "Limbi" programming_language: "Limbaj de programare" # show_menu: "Show game menu" home: "Acasă" # Not used any more, will be removed soon. level: "Nivel" # Like "Level: Dungeons of Kithgard" skip: "Sari peste" game_menu: "Meniul Jocului" restart: "Restart" goals: "Obiective" goal: "Obiectiv" # 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: "Rulează..." success: "Success!" incomplete: "Incomplet" timed_out: "Ai rămas fără timp" failing: "Eşec" reload: "Reîncarca" reload_title: "Reîncarcă tot codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reîncarca Tot" # 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: "Test Level" victory: "Victorie" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Crează un cont gratis!" victory_rate_the_level: "Apreciază nivelul: " # {change} victory_return_to_ladder: "Înapoi la jocurile de clasament" victory_saving_progress: "Salvează Progresul" victory_go_home: "Acasă" victory_review: "Spune-ne mai multe!" # victory_review_placeholder: "How was the level?" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" victory_experience_gained: "Ai câștigat XP" victory_gems_gained: "Ai câștigat Pietre Prețioase" victory_new_item: "Item nou" # victory_new_hero: "New Hero" victory_viking_code_school: "Wow, ăla a fost un nivel greu! Daca nu ești deja un dezvoltator de software, ar trebui să fi. Tocmai ai fost selectat pentru acceptare in Viking Code School, unde poți sa iți dezvolți abilitățile la nivelul următor și să devi un dezvoltator web profesionist în 14 săptămâni." victory_become_a_viking: "<NAME>" # victory_no_progress_for_teachers: "Progress is not saved for teachers. But, you can add a student account to your classroom for yourself." tome_cast_button_run: "Ruleaza" tome_cast_button_running: "In Derulare" tome_cast_button_ran: "A rulat" # tome_cast_button_update: "Update" tome_submit_button: "Trimite" tome_reload_method: "Reîncarcă cod original, pentru această metodă" # {change} tome_available_spells: "Vrăji disponibile" tome_your_skills: "Skillurile tale" # hints: "Hints" # videos: "Videos" # hints_title: "Hint {{number}}" code_saved: "Cod Salvat" skip_tutorial: "Sari peste (esc)" keyboard_shortcuts: "Scurtături Keyboard" loading_start: "Începe Level" # loading_start_combo: "Start Combo Challenge" # loading_start_concept: "Start Concept Challenge" problem_alert_title: "Repară codul" time_current: "Acum:" time_total: "Max:" time_goto: "Dute la:" non_user_code_problem_title: "Imposibil de încărcat Nivel" infinite_loop_title: "Buclă infinită detectată" infinite_loop_description: "Codul initial pentru a construi lumea nu a terminat de rulat. Este, probabil, foarte lent sau are o buclă infinită. Sau ar putea fi un bug. Puteți încerca acest cod nou sau resetați codul la starea implicită. Dacă nu-l repara, vă rugăm să ne anunțați." check_dev_console: "Puteți deschide, de asemenea, consola de dezvoltator pentru a vedea ce ar putea merge gresit." check_dev_console_link: "(instrucțiuni)" infinite_loop_try_again: "Încearcă din nou" infinite_loop_reset_level: "Resetează Nivelul" infinite_loop_comment_out: "Comentează Codul" tip_toggle_play: "Pune sau scoate pauza cu Ctrl+P." tip_scrub_shortcut: "Înapoi și derulare rapidă cu Ctrl+[ and Ctrl+]." # {change} tip_guide_exists: "Apasă pe ghidul din partea de sus a pagini pentru informații utile." tip_open_source: "CodeCombat este 100% open source!" # {change} # tip_tell_friends: "Enjoying CodeCombat? Tell your friends about us!" tip_beta_launch: "CodeCombat a fost lansat beta in Octombrie 2013." tip_think_solution: "Gândește-te la soluție, nu la problemă." tip_theory_practice: "Teoretic nu este nici o diferență înte teorie și practică. Dar practic este. - <NAME>" tip_error_free: "Există doar două metode de a scrie un program fără erori; numai a treia funcționează. - <NAME>" tip_debugging_program: "Dacă a face debuggin este procesul de a scoate bug-uri, atunci a programa este procesul de a introduce bug-uri. - <NAME>" tip_forums: "Intră pe forum și spune-ți părerea!" tip_baby_coders: "În vitor până și bebelușii vor fi Archmage." tip_morale_improves: "Se va încărca până până când va crește moralul." tip_all_species: "Noi credem în șanse egale de a învăța programare pentru toate speciile." tip_reticulating: "Reticulăm coloane vertebrale." tip_harry: "Ha un Wizard, " tip_great_responsibility: "Cu o mare abilitate mare de programare vine o mare responsabilitate de debugging." tip_munchkin: "Daca nu iți mananci legumele, un munchkin va veni după tine cand dormi." tip_binary: "Sunt doar 10 tipuri de oameni in lume: cei ce îteleg sistemul binar, si ceilalți." tip_commitment_yoda: "Un programator trebuie să aiba cel mai profund angajament, si mintea cea mai serioasă. ~Yoda" tip_no_try: "Fă. Sau nu mai face. Nu exista voi încerca. ~Yoda" tip_patience: "Să ai rabdare trebuie, tinere Padawan. ~Yoda" tip_documented_bug: "Un bug documentat nu e chiar un bug; este o caracteristica." tip_impossible: "Mereu pare imposibil până e gata. ~<NAME>" tip_talk_is_cheap: "Vorbele sunt ieftine. Arată-mi codul. ~<NAME>" tip_first_language: "Cel mai dezastruos lucru pe care poți să îl înveți este primul limbaj de programare. ~<NAME>" tip_hardware_problem: "Î: De cați programatori ai nevoie ca să schimbi un bec? R: Niciunul, e o problemă hardware." tip_hofstadters_law: "Legea lui Hofstadter: Mereu dureaza mai mult decât te aștepți, chiar dacă iei în considerare Legea lui Hofstadter." tip_premature_optimization: "Optimizarea prematură este rădăcina tuturor răutăților. ~<NAME>" tip_brute_force: "Atunci cănd ești în dubii, folosește brute force. ~<NAME>" tip_extrapolation: "Există două feluri de oameni: cei care pot extrapola din date incomplete..." tip_superpower: "Programarea este cel mai apropiat lucru de o superputere." tip_control_destiny: "In open source, ai dreptul de a-ți controla propiul destin. ~<NAME>" tip_no_code: "Nici-un cod nu e mai rapid decat niciun cod." tip_code_never_lies: "Codul nu minte niciodată, commenturile mai mint. ~<NAME>" tip_reusable_software: "Înainte ca un software să fie reutilizabil, trebuie să fie mai întâi utilizabil." tip_optimization_operator: "Fiecare limbaj are un operator de optimizare. La majoritatea acela este '//'" tip_lines_of_code: "Măsurarea progresului în lini de cod este ca și măsurarea progresului de construcție a aeronavelor în greutate. ~<NAME>" tip_source_code: "Vreau să schimb lumea dar nu îmi dă nimeni codul sursă." tip_javascript_java: "Java e pentru JavaScript exact ce e o Mașina pentru o Carpetă. ~<NAME>" tip_move_forward: "Orice ai face, dăi înainte. ~<NAME> Jr." tip_google: "Ai o problemă care nu o poți rezolva? Folosește Google!" tip_adding_evil: "Adaugăm un strop de răutate." tip_hate_computers: "Tocmai aia e problema celor ce urăsc calulatoarele, ei defapt urăsc programatorii nepricepuți. ~<NAME>" tip_open_source_contribute: "Poți ajuta la îmbunătățirea jocului CodeCombat!" tip_recurse: "A itera este uman, recursiv este divin. ~<NAME>. <NAME>" tip_free_your_mind: "Trebuie sa lași totul, <NAME>, Îndoiala și necredința. Eliberează-ți mintea. ~Morpheus" tip_strong_opponents: "Și cei mai puternici dintre oponenți întodeauna au o slăbiciune. ~Itachi Uchiha" # tip_paper_and_pen: "Before you start coding, you can always plan with a sheet of paper and a pen." # tip_solve_then_write: "First, solve the problem. Then, write the code. - <NAME>" # tip_compiler_ignores_comments: "Sometimes I think that the compiler ignores my comments." # tip_understand_recursion: "The only way to understand recursion is to understand recursion." # 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>" # tip_nemo: "When life gets you down, want to know what you've gotta do? Just keep swimming, just keep swimming. - <NAME>, 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. - <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. - <NAME>" # tip_mulan: "Believe you can, then you will. - <NAME>" # project_complete: "Project Complete!" # share_this_project: "Share this project with friends or family:" # ready_to_share: "Ready to publish your project?" # 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: "View Gallery" # project_published_noty: "Your level has been published!" # keep_editing: "Keep Editing" # 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: "Methods" # events: "Events" # handlers: "Handlers" # properties: "Properties" # snippets: "Snippets" # spawnable: "Spawnable" # html: "HTML" # math: "Math" # array: "Array" # object: "Object" # string: "String" # function: "Function" # vector: "Vector" # date: "Date" # jquery: "jQuery" # json: "JSON" # number: "Number" # 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: "<NAME> {{name}}" # created_during_hoc: "Created during Hour of Code" # restart: "Restart Level" # play: "Play Level" # play_more_codecombat: "Play More CodeCombat" # default_student_instructions: "Click to control your hero and win your game!" # goal_survive: "Survive." # goal_survive_time: "Survive for __seconds__ seconds." # goal_defeat: "Defeat all enemies." # goal_defeat_amount: "Defeat __amount__ enemies." # 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: "Inventar" save_load_tab: "Salvează/Încarcă" options_tab: "Opțiuni" guide_tab: "Ghid" guide_video_tutorial: "Tutorial Video" guide_tips: "Sfaturi" multiplayer_tab: "Multiplayer" auth_tab: "Înscriete" inventory_caption: "Echipeazăți Eroul" choose_hero_caption: "Alege Eroul, limbajul" options_caption: "Configurarea setărilor" guide_caption: "Documentație si sfaturi" multiplayer_caption: "Joaca cu prieteni!" auth_caption: "Salvează progresul." leaderboard: view_other_solutions: "Vizualizează Tabelul de Clasificare" scores: "Scoruri" top_players: "Top Jucători" day: "Astăzi" week: "Săptămâna Aceasta" all: "Tot Timpul" latest: "Ultimul" time: "Timp" damage_taken: "Damage Primit" damage_dealt: "Damage Oferit" difficulty: "Dificultate" gold_collected: "Aur Colectat" survival_time: "Supravietuit" defeated: "Inamici înfrânți" code_length: "Linii de cod" score_display: "__scoreType__: __score__" inventory: equipped_item: "Echipat" required_purchase_title: "Necesar" available_item: "Valabil" restricted_title: "Restricționat" should_equip: "(dublu-click pentru echipare)" equipped: "(echipat)" locked: "(blocat)" restricted: "(în acest nivel)" equip: "Echipează" unequip: "Dezechipează" # warrior_only: "Warrior Only" # ranger_only: "Ranger Only" # wizard_only: "Wizard Only" buy_gems: few_gems: "Căteva Pietre Prețioase" pile_gems: "Un morman de Pietre Prețioase" chest_gems: "Un cufăr de Pietre Prețioase" purchasing: "Cumpărare..." declined: "Cardul tău a fost refuzat." retrying: "Eroare de server, reîncerc." prompt_title: "Nu sunt destule Pietre Prețioase." prompt_body: "Vrei mai multe?" prompt_button: "Intră în magazin." recovered: "Pietre Prețioase cumpărate anterior recuperate.Va rugăm să dați refresh la pagină." price: "x{{gems}} / mo" buy_premium: "Cumpara Premium" # purchase: "Purchase" # purchased: "Purchased" subscribe_for_gems: prompt_title: "Pietre prețioase insuficiente!" prompt_body: "Abonează-te la Premium pentru a obține pietre prețioase și pentru a accesa chiar mai multe nivele!" earn_gems: prompt_title: "Pietre prețioase insuficiente" prompt_body: "Continuă să joci pentru a câștiga mai mult!" subscribe: best_deal: "Cea mai bună afacere!" confirmation: "Felicitări! Acum ai abonament CodeCombat Premium!" premium_already_subscribed: "Esti deja abonat la Premium!" subscribe_modal_title: "CodeCombat Premium" comparison_blurb: "Îmbunătățește-ți abilitățile cu abonamentul CodeCombat" must_be_logged: "Trebuie să te conectezi mai întâi. Te rugăm să creezi un cont sau să te conectezi din meniul de mai sus." subscribe_title: "Abonează-te" # Actually used in subscribe buttons, too unsubscribe: "Dezabonează-te" confirm_unsubscribe: "Confirmă Dezabonarea" never_mind: "Nu contează, eu tot te iubesc!" thank_you_months_prefix: "Mulțumesc pentru sprijinul acordat în aceste" thank_you_months_suffix: "luni." thank_you: "Mulțumim pentru susținerea jocului CodeCombat!" sorry_to_see_you_go: "Ne pare rău că pleci! Te rugăm să ne spui ce am fi putut face mai bine." unsubscribe_feedback_placeholder: "O, ce am făcut?" stripe_description: "Abonament Lunar" buy_now: "Cumpără acum" subscription_required_to_play: "Ai nevoie de abonament ca să joci acest nivel." unlock_help_videos: "Abonează-te pentru deblocarea tuturor tutorialelor video." personal_sub: "Abonament Personal" # Accounts Subscription View below loading_info: "Se încarcă informațile despre abonament..." managed_by: "Gestionat de" will_be_cancelled: "Va fi anulat pe" currently_free: "Ai un abonament gratuit" currently_free_until: "Ai un abonament gratuit până pe" free_subscription: "Abonament gratuit" was_free_until: "Ai avut un abonament gratuit până pe" managed_subs: "Abonamente Gestionate" subscribing: "Te abonăm..." current_recipients: "Recipienți curenți" unsubscribing: "Dezabonare..." subscribe_prepaid: "Dă Click pe Abonare pentru a folosi un cod prepaid" using_prepaid: "Foloseste codul prepaid pentru un abonament lunar" feature_level_access: "Accesează peste 300 de nivele disponibile" feature_heroes: "Deblochează eroi exclusivi și personaje" feature_learn: "Învață să creezi jocuri și site-uri web" month_price: "$__price__" first_month_price: "Doar $__price__ pentru prima luna!" lifetime: "Acces pe viață" lifetime_price: "$__price__" year_subscription: "Abonament anual" year_price: "$__price__/an" support_part1: "Ai nevoie de ajutor cu plata sau preferi PayPal? E-mail" 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: "Mimic" # 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: "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 Gl<NAME>ier 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: "Alege Eroul" programming_language: "Limbaj de Programare" programming_language_description: "Ce limbaj de programare vrei să folosești?" default: "Implicit" experimental: "Experimental" python_blurb: "Simplu dar puternic, Python este un limbaj de uz general extraordinar!" javascript_blurb: "Limbajul web-ului." coffeescript_blurb: "JavaScript cu o syntaxă mai placută!" lua_blurb: "Limbaj de scripting pentru jocuri." # java_blurb: "(Subscriber Only) Android and enterprise." # cpp_blurb: "(Subscriber Only) Game development and high performance computing." status: "Stare" weapons: "Armament" weapons_warrior: "Săbii - Distanță Scurtă, Fără Magie" weapons_ranger: "Arbalete, Arme - Distanță Mare, Fără Magie" weapons_wizard: "Baghete, Toiage, - Distanță Mare, Și Magie" attack: "Attack" # Can also translate as "Attack" health: "Viață" speed: "Viteză" regeneration: "Regenerare" range: "Rază" # As in "attack or visual range" blocks: "Blochează" # As in "this shield blocks this much damage" backstab: "Înjunghiere" # As in "this dagger does this much backstab damage" skills: "Skilluri" attack_1: "Oferă" attack_2: "of listed" attack_3: "Damage cu arma." health_1: "Primește" health_2: "of listed" health_3: "Armură." speed_1: "Se mișcă cu" speed_2: "metri pe secundă." available_for_purchase: "Disponibil pentru cumpărare" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Pentru deblocare termină nivelul:" # 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: "Numai anumiți eroi pot juca acest nivel" # 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: "function" # skill types # method: "method" # snippet: "snippet" # number: "number" # array: "array" # object: "object" # string: "string" writable: "permisiuni de scriere" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "permisiuni doar de citire" # action: "Action" # spell: "Spell" action_name: "nume" action_cooldown: "Ține" action_specific_cooldown: "Cooldown" action_damage: "Damage" action_range: "Rază de acțiune" action_radius: "Rază" action_duration: "Durată" example: "Exemplu" ex: "ex" # Abbreviation of "example" current_value: "Valoare Curentă" default_value: "Valoare Implicită" parameters: "Parametrii" # required_parameters: "Required Parameters" # optional_parameters: "Optional Parameters" returns: "Întoarce" granted_by: "Acordat de" # still_undocumented: "Still undocumented, sorry." save_load: granularity_saved_games: "Salvate" granularity_change_history: "Istoric" options: general_options: "Opțiuni Generale" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Muzică" music_description: "Oprește Muzica din fundal." editor_config_title: "Configurare Editor" editor_config_livecompletion_label: "Autocompletare Live" editor_config_livecompletion_description: "Afișează sugesti de autocompletare în timp ce scri." editor_config_invisibles_label: "Arată etichetele invizibile" editor_config_invisibles_description: "Arată spațiile și taburile invizibile." editor_config_indentguides_label: "Arată ghidul de indentare" editor_config_indentguides_description: "Arată linii verticale pentru a vedea mai bine indentarea." editor_config_behaviors_label: "Comportamente inteligente" editor_config_behaviors_description: "Completează automat parantezele, ghilimele etc." # 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: "Learn More" # main_title: "If you want to learn to program, you need to write (a lot of) code." # main_description: "At CodeCombat, our job is to make sure you're doing that with a smile on your face." # mission_link: "Mission" # team_link: "Team" # story_link: "Story" # press_link: "Press" # mission_title: "Our mission: make programming accessible to every student on Earth." # mission_description_1: "<strong>Programming is magic</strong>. It's the ability to create things from pure imagination. We started CodeCombat to give learners the feeling of wizardly power at their fingertips by using <strong>typed code</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: "Meet the CodeCombat team" # 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: "Cofounder, CEO" # matt_title: "Cofounder, CTO" # cat_title: "Game Designer" # scott_title: "Cofounder, Software Engineer" # maka_title: "Customer Advocate" # robin_title: "Senior Product Manager" # nolan_title: "Sales Manager" # david_title: "Marketing Lead" # titles_csm: "Customer Success Manager" # titles_territory_manager: "Territory Manager" # 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: "Illustration" # retrostyle_blurb: "RetroStyle Games" # bryukh_title: "Gameplay Developer" # bryukh_blurb: "Constructs puzzles" # community_title: "...and our open-source community" # community_subtitle: "Over 500 contributors have helped build CodeCombat, with more joining every week!" # community_description_3: "CodeCombat is a" # community_description_link_2: "community project" # 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: "contribute page" # community_description_2: "for more info." # number_contributors: "Over 450 contributors have lent their support and time to this project." # story_title: "Our story so far" # story_subtitle: "Since 2013, CodeCombat has grown from a mere set of sketches to a living, thriving game." # story_statistic_1a: "5,000,000+" # story_statistic_1b: "total players" # story_statistic_1c: "have started their programming journey through CodeCombat" # story_statistic_2a: "We’ve been translated into over 50 languages — our players hail from" # story_statistic_2b: "190+ countries" # story_statistic_3a: "Together, they have written" # story_statistic_3b: "1 billion lines of code and counting" # story_statistic_3c: "across many different programming languages" # 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: "Employee Benefits" # jobs_benefit_4: "Unlimited vacation" # 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: "Create Your Own" # 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: "Press & Contact" # contact_subtitle: "Need more information? Get in touch with us at" # screenshots_title: "Game Screenshots" # screenshots_hint: "(click to view full size)" # downloads_title: "Download Assets & Information" # about_codecombat: "About CodeCombat" # logo: "Logo" # screenshots: "Screenshots" # character_art: "Character Art" # download_all: "Download All" # previous: "Previous" # location_title: "We're located in downtown SF:" # teachers: # licenses_needed: "Licenses needed" # special_offer: # special_offer: "Special Offer" # 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: "Phone number" # phone_number_help: "What's the best number to reach you?" # primary_role_label: "Your Primary Role" # role_default: "Select Role" # primary_role_default: "Select Primary Role" # purchaser_role_default: "Select Purchaser Role" # tech_coordinator: "Technology coordinator" # advisor: "Curriculum Specialist/Advisor" # principal: "Principal" # superintendent: "Superintendent" # parent: "Parent" # 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: "District" # district_name: "District Name" # district_na: "Enter N/A if not applicable" # organization_label: "School" # school_name: "School Name" # city: "City" # state: "State / Region" # country: "Country" # num_students_help: "How many students will use CodeCombat?" # num_students_default: "Select Range" # education_level_label: "Education Level of Students" # education_level_help: "Choose as many as apply." # elementary_school: "Elementary School" # high_school: "High School" # please_explain: "(please explain)" # middle_school: "Middle School" # college_plus: "College or higher" # referrer: "How did you hear about us?" # referrer_help: "For example: from another teacher, a conference, your students, Code.org, etc." # referrer_default: "Select One" # referrer_conference: "Conference (e.g. ISTE)" # referrer_hoc: "Code.org/Hour of Code" # referrer_teacher: "A teacher" # referrer_admin: "An administrator" # referrer_student: "A student" # referrer_pd: "Professional trainings/workshops" # referrer_web: "Google" # referrer_other: "Other" # anything_else: "What kind of class do you anticipate using CodeCombat for?" # anything_else_helper: "" # thanks_header: "Request Received!" # 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: "Back to Classes" # 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: "Connect with:" # 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: "Create a Teacher Account" # create_account_subtitle: "Get access to teacher-only tools for using CodeCombat in the classroom. <strong>Set up a class</strong>, add your students, and <strong>monitor their progress</strong>!" # convert_account_title: "Update to Teacher Account" # not: "Not" # full_name_required: "First and last name required" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" submitting_patch: "Trimitere Patch..." cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" # owner_approve: "An owner will need to approve it before your changes will become visible." contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " forum_prefix: "Pentru orice altceva vă rugăm sa incercați " forum_page: "forumul nostru" forum_suffix: " în schimb." faq_prefix: "Există si un" faq: "FAQ" subscribe_prefix: "Daca ai nevoie de ajutor ca să termini un nivel te rugăm să" subscribe: "cumperi un abonament CodeCombat" subscribe_suffix: "si vom fi bucuroși să te ajutăm cu codul." subscriber_support: "Din moment ce ești un abonat CodeCombat, adresa ta de email va primi sprijinul nostru prioritar." screenshot_included: "Screenshot-uri incluse." where_reply: "Unde ar trebui să răspundem?" send: "Trimite Feedback" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau crează un cont nou pentru a schimba setările." me_tab: "Eu" picture_tab: "Poză" delete_account_tab: "Șterge Contul" wrong_email: "Email Greșit" # wrong_password: "<PASSWORD>" delete_this_account: "Ștergere permanetă a acestui cont" # reset_progress_tab: "Reset All Progress" # reset_your_progress: "Clear all your progress and start over" # god_mode: "God Mode" emails_tab: "Email-uri" admin: "Admin" # manage_subscription: "Click here to manage your subscription." new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" type_in_email: "Scrie adresa de email ca să confirmi ștergerea" # type_in_email_progress: "Type in your email to confirm deleting your progress." # type_in_password: "Also, type in your password." email_subscriptions: "Subscripție Email" email_subscriptions_none: "Nu ai subscripții Email." email_announcements: "Anunțuri" email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." email_notifications: "Notificări" email_notifications_summary: "Control pentru notificări email personalizate, legate de activitatea CodeCombat." email_any_notes: "Orice Notificări" email_any_notes_description: "Dezactivați pentru a opri toate e-mailurile de notificare a activității." email_news: "Noutăți" email_recruit_notes: "Oportunități de job-uri" email_recruit_notes_description: "Daca joci foarte bine, este posibil sa te contactăm pentru obținerea unui loc (mai bun) de muncă." contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "<PASSWORD>ște." password_repeat: "Te <PASSWORD>m sa repeți par<PASSWORD>." keyboard_shortcuts: keyboard_shortcuts: "Scurtături Keyboard" space: "Space" enter: "Enter" # press_enter: "press enter" escape: "Escape" shift: "Shift" run_code: "Rulează codul." run_real_time: "Rulează în timp real." continue_script: "Continue past current script." skip_scripts: "Treci peste toate script-urile ce pot fi sărite." toggle_playback: "Comută play/pause." scrub_playback: "Mergi înainte si înapoi in timp." single_scrub_playback: "Mergi înainte si înapoi in timp cu un singur cadru." scrub_execution: "Mergi prin lista curentă de vrăji executate." toggle_debug: "Comută afișaj debug." toggle_grid: "Comută afișaj grilă." toggle_pathfinding: "Comută afișaj pathfinding." beautify: "Înfrumusețează codul standardizând formatarea lui." maximize_editor: "Mărește/Micește editorul." # cinematic: # click_anywhere_continue: "click anywhere to continue" community: main_title: "Comunitatea CodeCombat" introduction: "Vezi metode prin care poți să te implici și tu mai jos și decide să alegi ce ți se pare cel mai distractiv. Deabia așteptăm să lucrăm împreună!" level_editor_prefix: "Folosește CodeCombat" level_editor_suffix: "Pentru a crea și a edita nivele. Useri au creat nivele pentru clasele lor, prieteni, hackathonuri, studenți si rude. Dacă crearea unui nivel nou ți se pare intimidant poți sa modifici un nivel creat de noi!" thang_editor_prefix: "Numim unitățile din joc 'thangs'. Folosește" thang_editor_suffix: "pentru a modifica ilustrațile sursă CodeCombat. Permitele unitătilor sa arunce proiectile, schimbă direcția unei animații, schimbă viața unei unități, sau uploadează propiile sprite-uri vectoriale." article_editor_prefix: "Vezi o greșală in documentația noastă? Vrei să documentezi instrucțiuni pentru propiile creații? Vezi" article_editor_suffix: "si ajută jucători CodeCombat să obțină căt mai multe din playtime-ul lor." find_us: "Ne găsești pe aceste site-uri" # social_github: "Check out all our code on GitHub" social_blog: "Citește blogul CodeCombat pe Sett" social_discource: "Alăturăte discuțiilor pe forumul Discourse" social_facebook: "Lasă un Like pentru CodeCombat pe facebook" social_twitter: "Urmărește CodeCombat pe Twitter" # social_slack: "Chat with us in the public CodeCombat Slack channel" contribute_to_the_project: "Contribuie la proiect" 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: "Clan" clans: "Clanuri" new_name: "<NAME>" new_description: "Descrierea clanului nou" make_private: "Fă clanul privat" subs_only: "numai abonați" create_clan: "Creează un clan Nou" # private_preview: "Preview" # private_clans: "Private Clans" public_clans: "Clanuri Publice" my_clans: "Clanurile mele" clan_name: "<NAME>ului" name: "<NAME>" chieftain: "Chieftain" edit_clan_name: "Editează numele clanului" edit_clan_description: "Editează descrierea clanului" edit_name: "editează <NAME>" edit_description: "editează descriere" private: "(privat)" summary: "Sumar" average_level: "Medie Level" average_achievements: "Medie Achievements" delete_clan: "Șterge Clan" leave_clan: "Pleacă din Clan" join_clan: "Intră în Clan" invite_1: "Invitație:" invite_2: "*Invită jucători in acest clan trimițându-le acest link." members: "Mem<NAME>" progress: "Progres" not_started_1: "neînceput" started_1: "început" complete_1: "complet" exp_levels: "Extinde nivele" rem_hero: "Șterge Eroul" status: "Stare" complete_2: "Complet" started_2: "Început" not_started_2: "Neînceput" view_solution: "Click pentru a vedea soluția." # view_attempt: "Click to view attempt." latest_achievement: "Ultimile Achievement-uri" playtime: "Timp Jucat" last_played: "Ultima oară cănd ai jucat" # leagues_explanation: "Play in a league against other clan members in these multiplayer arena instances." # track_concepts1: "Track concepts" # track_concepts2a: "learned by each student" # track_concepts2b: "learned by each member" # track_concepts3a: "Track levels completed for each student" # track_concepts3b: "Track levels completed for each member" # track_concepts4a: "See your students'" # track_concepts4b: "See your members'" # track_concepts5: "solutions" # track_concepts6a: "Sort students by name or progress" # track_concepts6b: "Sort members by name or progress" # track_concepts7: "Requires invitation" # track_concepts8: "to join" # private_require_sub: "Private clans require a subscription to create or join." # courses: # create_new_class: "Create New Class" # 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: "Level solutions are available for teachers who have licenses." # unnamed_class: "Unnamed Class" # edit_settings1: "Edit Class Settings" # add_students: "Add Students" # stats: "Statistics" # student_email_invite_blurb: "Your students can also use class code <strong>__classCode__</strong> when creating a Student Account, no email required." # total_students: "Total students:" # average_time: "Average level play time:" # total_time: "Total play time:" # average_levels: "Average levels completed:" # total_levels: "Total levels completed:" # students: "Students" # concepts: "Concepts" # play_time: "Play time:" # completed: "Completed:" # enter_emails: "Separate each email address by a line break or commas" # send_invites: "Invite Students" # number_programming_students: "Number of Programming Students" # number_total_students: "Total Students in School/District" # enroll: "Enroll" # enroll_paid: "Enroll Students in Paid Courses" # get_enrollments: "Get More Licenses" # change_language: "Change Course Language" # keep_using: "Keep Using" # switch_to: "Switch To" # greetings: "Greetings!" # back_classrooms: "Back to my classrooms" # back_classroom: "Back to classroom" # back_courses: "Back to my courses" # edit_details: "Edit class details" # purchase_enrollments: "Purchase Student Licenses" # remove_student: "remove student" # assign: "Assign" # to_assign: "to assign paid courses." # student: "Student" # teacher: "Teacher" # arena: "Arena" # available_levels: "Available Levels" # started: "started" # complete: "complete" # practice: "practice" # required: "required" # welcome_to_courses: "Adventurers, welcome to Courses!" # ready_to_play: "Ready to play?" # start_new_game: "Start New Game" # play_now_learn_header: "Play now to learn" # 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: "My Student Dashboard" # my_classes: "Current Classes" # class_added: "Class successfully added!" # view_map: "view map" # view_videos: "view videos" # view_project_gallery: "view my classmates' projects" # join_class: "Join A Class" # join_class_2: "Join class" # ask_teacher_for_code: "Ask your teacher if you have a CodeCombat class code! If so, enter it below:" # enter_c_code: "<Enter Class Code>" # join: "Join" # joining: "Joining class" # course_complete: "Course Complete" # play_arena: "Play Arena" # view_project: "View Project" # start: "Start" # last_level: "Last level played" # not_you: "Not you?" # continue_playing: "Continue Playing" # option1_header: "Invite Students by Email" # remove_student1: "Remove Student" # are_you_sure: "Are you sure you want to remove this student from this class?" # 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: "Keep Student" # removing_user: "Removing user" # subtitle: "Review course overviews and levels" # Flat style redesign # changelog: "View latest changes to course levels." # select_language: "Select language" # select_level: "Select level" # play_level: "Play Level" # concepts_covered: "Concepts covered" # view_guide_online: "Level Overviews and Solutions" # grants_lifetime_access: "Grants access to all Courses." # enrollment_credits_available: "Licenses Available:" # language_select: "Select a language" # ClassroomSettingsModal # language_cannot_change: "Language cannot be changed once students join a class." # avg_student_exp_label: "Average Student Programming Experience" # avg_student_exp_desc: "This will help us understand how to pace courses better." # avg_student_exp_select: "Select the best option" # avg_student_exp_none: "No Experience - little to no experience" # avg_student_exp_beginner: "Beginner - some exposure or block-based" # avg_student_exp_intermediate: "Intermediate - some experience with typed code" # avg_student_exp_advanced: "Advanced - extensive experience with typed code" # avg_student_exp_varied: "Varied Levels of Experience" # student_age_range_label: "Student Age Range" # student_age_range_younger: "Younger than 6" # student_age_range_older: "Older than 18" # student_age_range_to: "to" # 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: "Create Class" # class_name: "Class Name" # teacher_account_restricted: "Your account is a teacher account and cannot access student content." # account_restricted: "A student account is required to access this page." # update_account_login_title: "Log in to update your account" # update_account_title: "Your account needs attention!" # 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: "I am a teacher" # 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: "I am a student" # 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: "Select Your Hero" # select_your_hero_description: "You can always change your hero by going to your Courses page and clicking \"Change Hero\"" # select_this_hero: "Select this Hero" # current_hero: "Current Hero:" # current_hero_female: "Current Hero:" # 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: "You'll need to join a course to play this level." # 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: "Status:" # assessments: "Assessments" # challenges: "Challenges" # level_name: "Level Name:" # keep_trying: "Keep Trying" # start_challenge: "Start Challenge" # locked: "Locked" # concepts_used: "Concepts Used:" # 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: "Be the first to publish a project in this course!" # view_project: "View Project" # edit_project: "Edit Project" # teacher: # assigning_course: "Assigning course" # back_to_top: "Back to Top" # click_student_code: "Click on any level that the student has started or completed below to view the code they wrote." # code: "__name__'s Code" # complete_solution: "Complete Solution" # 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: "Partial Solution" # capstone_solution: "Capstone Solution" # removing_course: "Removing course" # 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: "__name__'s Student Code" # teacher_dashboard: "Teacher Dashboard" # Navbar # my_classes: "My Classes" # courses: "Course Guides" # enrollments: "Student Licenses" # resources: "Resources" # help: "Help" # language: "Language" # edit_class_settings: "edit class settings" # access_restricted: "Account Update Required" # teacher_account_required: "A teacher account is required to access this content." # create_teacher_account: "Create Teacher Account" # what_is_a_teacher_account: "What's a Teacher Account?" # 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: "Current Classes" # archived_classes: "Archived Classes" # archived_classes_blurb: "Classes can be archived for future reference. Unarchive a class to view it in the Current Classes list again." # view_class: "view class" # archive_class: "archive class" # unarchive_class: "unarchive class" # unarchive_this_class: "Unarchive this class" # no_students_yet: "This class has no students yet." # no_students_yet_view_class: "View class to add students." # try_refreshing: "(You may need to refresh the page)" # create_new_class: "Create a New Class" # class_overview: "Class Overview" # View Class page # avg_playtime: "Average level playtime" # total_playtime: "Total play time" # avg_completed: "Average levels completed" # total_completed: "Total levels completed" # created: "Created" # concepts_covered: "Concepts covered" # earliest_incomplete: "Earliest incomplete level" # latest_complete: "Latest completed level" # enroll_student: "Enroll student" # apply_license: "Apply License" # revoke_license: "Revoke License" # revoke_licenses: "Revoke All Licenses" # course_progress: "Course Progress" # not_applicable: "N/A" # edit: "edit" # edit_2: "Edit" # remove: "remove" # latest_completed: "Latest completed:" # sort_by: "Sort by" # progress: "Progress" # concepts_used: "Concepts used by Student:" # concept_checked: "Concept checked:" # completed: "Completed" # practice: "Practice" # started: "Started" # no_progress: "No progress" # not_required: "Not required" # view_student_code: "Click to view student code" # select_course: "Select course to view" # progress_color_key: "Progress color key:" # level_in_progress: "Level in Progress" # level_not_started: "Level Not Started" # project_or_arena: "Project or Arena" # students_not_assigned: "Students who have not been assigned {{courseName}}" # course_overview: "Course Overview" # copy_class_code: "Copy Class Code" # class_code_blurb: "Students can join your class using this Class Code. No email address is required when creating a Student account with this Class Code." # copy_class_url: "Copy Class URL" # class_join_url_blurb: "You can also post this unique class URL to a shared webpage." # add_students_manually: "Invite Students by Email" # bulk_assign: "Select course" # assigned_msg_1: "{{numberAssigned}} students were assigned {{courseName}}." # assigned_msg_2: "{{numberEnrolled}} licenses were applied." # assigned_msg_3: "You now have {{remainingSpots}} available licenses remaining." # assign_course: "Assign Course" # removed_course_msg: "{{numberRemoved}} students were removed from {{courseName}}." # remove_course: "Remove Course" # not_assigned_modal_title: "Courses were not assigned" # 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: "Enroll Selected Students" # no_students_selected: "No students were selected." # show_students_from: "Show students from" # Enroll students modal # apply_licenses_to_the_following_students: "Apply Licenses to the Following Students" # students_have_licenses: "The following students already have licenses applied:" # all_students: "All Students" # apply_licenses: "Apply Licenses" # not_enough_enrollments: "Not enough licenses available." # enrollments_blurb: "Students are required to have a license to access any content after the first course." # how_to_apply_licenses: "How to Apply Licenses" # export_student_progress: "Export Student Progress (CSV)" # send_email_to: "Send Recover Password Email to:" # email_sent: "Email sent" # send_recovery_email: "Send recovery email" # enter_new_password_below: "Enter new password below:" # change_password: "<PASSWORD>" # changed: "Changed" # available_credits: "Available Licenses" # pending_credits: "Pending Licenses" # empty_credits: "Exhausted Licenses" # license_remaining: "license remaining" # licenses_remaining: "licenses remaining" # one_license_used: "1 out of __totalLicenses__ licenses has been used" # num_licenses_used: "__numLicensesUsed__ out of __totalLicenses__ licenses have been used" # starter_licenses: "starter licenses" # start_date: "start date:" # end_date: "end date:" # get_enrollments_blurb: " We'll help you build a solution that meets the needs of your class, school or district." # 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: "Request Sent!" # assessments: "Assessments" # license_status: "License Status" # status_expired: "Expired on {{date}}" # status_not_enrolled: "Not Enrolled" # status_enrolled: "Expires on {{date}}" # select_all: "Select All" # project: "Project" # project_gallery: "Project Gallery" # view_project: "View Project" # unpublished: "(unpublished)" # view_arena_ladder: "View Arena Ladder" # resource_hub: "Resource Hub" # 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: "Additional guides coming soon!" # 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: "Overview" # student_details: "Student Details" # student_name: "<NAME>" # no_name: "No name provided." # no_username: "No username provided." # no_email: "Student has no email address set." # student_profile: "Student Profile" # playtime_detail: "Playtime Detail" # student_completed: "Student Completed" # student_in_progress: "Student in Progress" # class_average: "Class Average" # not_assigned: "has not been assigned the following courses" # playtime_axis: "Playtime in Seconds" # levels_axis: "Levels in" # student_state: "How is" # student_state_2: "doing?" # 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: "Revoking..." # 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: "More Info" # 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: "Add Students" # 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: "Level:" # time_played_label: "Time Played:" # back_to_resource_hub: "Back to Resource Hub" # back_to_course_guides: "Back to Course Guides" # print_guide: "Print this guide" # 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: "Concept" # 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: "Share Licenses" # shared_by: "Shared By:" # add_teacher_label: "Enter exact teacher email:" # add_teacher_button: "Add Teacher" # 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." # have_not_shared: "You've not 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: "(you)" # one_license_used: "(1 license used)" # licenses_used: "(__licensesUsed__ licenses used)" # more_info: "More info" # sharing: # game: "Game" # webpage: "Webpage" # 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: "Share This Game" # share_web: "Share This Webpage" # victory_share_prefix: "Share this link to invite your friends & family to" # victory_share_prefix_short: "Invite people to" # victory_share_game: "play your game level" # victory_share_web: "view your webpage" # victory_share_suffix: "." # victory_course_share_prefix: "This link will let your friends & family" # victory_course_share_game: "play the game" # victory_course_share_web: "view the webpage" # victory_course_share_suffix: "you just created." # copy_url: "Copy URL" # share_with_teacher_email: "Send to your teacher" # game_dev: # creator: "<NAME>" # web_dev: # image_gallery_title: "Image Gallery" # select_an_image: "Select an image you want to use" # scroll_down_for_more_images: "(Scroll down for more images)" # copy_the_url: "Copy the URL below" # copy_the_url_description: "Useful if you want to replace an existing image." # copy_the_img_tag: "Copy the <img> tag" # copy_the_img_tag_description: "Useful if you want to insert a new image." # copy_url: "Copy URL" # copy_img: "Copy <img>" # how_to_copy_paste: "How to Copy/Paste" # copy: "Copy" # paste: "Paste" # back_to_editing: "Back to Editing" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" archmage_summary: "Dacă ești un dezvoltator interesat să programezi jocuri educaționale, devino Archmage si ajută-ne să construim CodeCombat!" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" artisan_summary: "Construiește si oferă nivele pentru tine si pentru prieteni tăi, ca să se joace. Devino Artisan si învață arta de a împărți cunoștințe despre programare." adventurer_title: "Aventurier" adventurer_title_description: "(Playtester de nivele)" adventurer_summary: "Primește nivelele noastre noi (chiar si cele pentru abonați) gratis cu o săptămână înainte si ajută-ne să reparăm bug-uri până la lansare." scribe_title: "<NAME>" scribe_title_description: "(Editor de articole)" scribe_summary: "Un cod bun are nevoie de o documentație bună. Scrie, editează, si improvizează documentația citită de milioane de jucători în întreaga lume." diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" diplomat_summary: "CodeCombat e localizat în 45+ de limbi de Diplomații noștri. Ajută-ne și contribuie la traducere." ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" ambassador_summary: "Îmblânzește useri de pe forumul nostru si oferă direcți pentru cei cu întrebări. Ambasadori noștri reprezintă CodeCombat în fața lumii." # teacher_title: "Teacher" editor: main_title: "Editori CodeCombat" article_title: "Editor Articol" thang_title: "Editor Thang" level_title: "Editor Nivele" # course_title: "Course Editor" achievement_title: "Editor Achievement" poll_title: "Editor Sondaje" back: "Înapoi" revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" pick_a_terrain: "Alege Terenul" dungeon: "Temniță" indoor: "Interior" desert: "Deșert" grassy: "Ierbos" # mountain: "Mountain" # glacier: "Glacier" small: "Mic" large: "Mare" fork_title: "Fork Versiune Nouă" fork_creating: "Creare Fork..." generate_terrain: "Generează Teren" more: "Mai Multe" wiki: "Wiki" live_chat: "Chat Live" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Culori" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "Script-uri" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_docs: "Documentație" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_all: "Toate" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă Thangs" # level_tab_thangs_search: "Search thangs" add_components: "Adaugă Componente" component_configs: "Configurarea Componentelor" config_thang: "Dublu click pentru a configura un thang" delete: "Șterge" duplicate: "Duplică" stop_duplicate: "Oprește Duplicarea" rotate: "Rotește" level_component_tab_title: "Componente actuale" level_component_btn_new: "Crează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Crează sistem nou" level_systems_btn_add: "Adaugă Sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează Componentă" level_component_config_schema: "Schema Config" level_system_edit_title: "Editează Sistem" create_system_title: "Crează sistem nou" new_component_title: "Crează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Crează un articol nou" new_thang_title: "Crează un nou tip de Thang" new_level_title: "Crează un nivel nou" new_article_title_login: "Loghează-te pentru a crea un Articol Nou" new_thang_title_login: "Loghează-te pentru a crea un Thang de Tip Nou" new_level_title_login: "Loghează-te pentru a crea un Nivel Nou" new_achievement_title: "Crează un Achivement Nou" new_achievement_title_login: "Loghează-te pentru a crea un Achivement Nou" new_poll_title: "Crează un Sondaj Nou" new_poll_title_login: "Loghează-te pentru a crea un Sondaj Nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută nivele aici" achievement_search_title: "Caută Achievements" poll_search_title: "Caută Sondaje" read_only_warning2: "Notă: nu poți salva editările aici, pentru că nu ești logat." no_achievements: "Nici-un achivement adăugat acestui nivel până acum." achievement_query_misc: "Key achievement din diverse" achievement_query_goals: "Key achievement din obiectivele nivelelor" level_completion: "Finalizare Nivel" pop_i18n: "Populează I18N" tasks: "Sarcini" clear_storage: "Șterge schimbările locale" # add_system_title: "Add Systems to Level" # done_adding: "Done Adding" article: edit_btn_preview: "Preview" edit_article_title: "Editează Articol" polls: priority: "Prioritate" contribute: page_title: "Contribuțtii" intro_blurb: "CodeCombat este 100% open source! Sute de jucători dedicați ne-au ajutat sa construim jocul în cea ce este astăzi. Alătură-te si scrie următorul capitol în aventura CodeCombat de a ajuta lumea să învețe cod!" # {change} alert_account_message_intro: "Salutare!" alert_account_message: "Pentru a te abona la mailurile clasei trebuie să fi logat." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, Sunet, Networking în timp real, Social Networking, și desigur multe dintre aspectele comune ale programării, de la gestiune low-level a bazelor de date, și administrare server până la construirea de interfețe. Este mult de muncă, și dacă ești un programator cu experiență, cu un dor de a se arunca cu capul înainte îm CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este JavaScript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" # join_url_slack: "public Slack channel" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_introduction_suf: ", atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să testați pe mai mulți oameni și să obțineți feedback, și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebui să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași, mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Crează un nivel nou și explorează nivelele deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelele tale pe forum pentru feedback." artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de Nivele și anunțuri." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura, atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucrează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi nivele de testat. De asemenea vom posta despre nivele care trebuie revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri, înscrie-te acolo!" adventurer_subscribe_desc: "Primește email-uri când sunt noi nivele de testat." scribe_introduction_pref: "CodeCombat nu o să fie doar o colecție de nivele. Vor fi incluse resurse de cunoaștere, un wiki despre concepte de programare legate de fiecare nivel. În felul acesta fiecare Arisan nu trebuie să mai descrie în detaliu ce este un operator de comparație, ei pot să pună un link la un Articol mai bine documentat. Ceva asemănător cu ce " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a construit. Dacă idea ta de distracție este să articulezi conceptele de programare în formă Markdown, această clasă ți s-ar potrivi." scribe_attribute_1: "Un talent în cuvinte este tot ce îți trebuie. Nu numai gramatică și ortografie, trebuie să poți să explici ideii complicate celorlați." contact_us_url: "Contactați-ne" # {change} scribe_join_description: "spune-ne câte ceva despre tine, experiențele tale despre programare și ce fel de lucruri ți-ar place să scri despre. Vom începe de acolo!." scribe_subscribe_desc: "Primește mailuri despre scrisul de articole." diplomat_introduction_pref: "Dacă ar fi un lucru care l-am învățat din " diplomat_launch_url: "lansarea din Octombire" diplomat_introduction_suf: "acesta ar fi că: există un interes mare pentru CodeCombat și în alte țări! Încercăm sa adunăm cât mai mulți translatori care sunt pregătiți să transforme un set de cuvinte intr-un alt set de cuvinte ca să facă CodeCombat cât mai accesibil în toată lumea. Dacă vrei să tragi cu ochiul la conțintul ce va apărea și să aduci nivele cât mai repede pentru conaționali tăi, această clasă ți se potriveste." diplomat_attribute_1: "Fluență în Engleză și limba în care vrei să traduci. Când explici ideii complicate este important să întelegi bine ambele limbi!" diplomat_i18n_page_prefix: "Poți începe să traduci nivele accesând" diplomat_i18n_page: "Pagina de traduceri" diplomat_i18n_page_suffix: ", sau interfața si website-ul pe GitHub." diplomat_join_pref_github: "Găsește fișierul pentru limba ta " diplomat_github_url: "pe GitHub" diplomat_join_suf_github: ", editeazăl online si trimite un pull request. Bifează căsuța de mai jos ca să fi up-to-date cu dezvoltările noastre internaționale!" diplomat_subscribe_desc: "Primește mail-uri despre dezvoltările i18n si niveluri de tradus." ambassador_introduction: "Aceasta este o comunitate pe care o construim, iar voi sunteți conexiunile. Avem forumui, email-uri, si rețele sociale cu mulți oameni cu care se poate vorbi despre joc și de la care se poate învața. Dacă vrei să ajuți oameni să se implice și să se distreze această clasă este potrivită pentru tine." ambassador_attribute_1: "Abilități de comunicare. Abilitatea de a indentifica problemele pe care jucătorii le au si șa îi poti ajuta. De asemenea, trebuie să ne informezi cu părerile jucătoriilor, ce le place și ce vor mai mult!" ambassador_join_desc: "spune-ne câte ceva despre tine, ce ai făcut si ce te interesează să faci. Vom porni de acolo!." ambassador_join_note_strong: "Notă" ambassador_join_note_desc: "Una din prioritățile noaste este să constrruim un joc multiplayer unde jucători noștri, dacă au probleme pot să cheme un wizard cu un nivel ridicat să îi ajute." ambassador_subscribe_desc: "Primește mailuri despre support updates și dezvoltări multiplayer." # teacher_subscribe_desc: "Get emails on updates and announcements for teachers." changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "Scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" # simulation_explanation_leagues: "You will mainly help simulate games for allied players in your clans and courses." simulate_games: "Simulează Jocuri!" games_simulated_by: "Jocuri simulate de tine:" games_simulated_for: "Jocuri simulate pentru tine:" # games_in_queue: "Games currently in the queue:" games_simulated: "Jocuri simulate" games_played: "Jocuri jucate" ratio: "Rație" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un Cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul in Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea in clasament" rank_being_ranked: "Jocul se plasează in Clasament" rank_last_submitted: "trimis " help_simulate: "Ne ajuți simulând jocuri?" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Nici un meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentru a-ți plasa meciul in clasament." choose_opponent: "Alege un adversar" select_your_language: "Alege limbă!" tutorial_play: "Joacă Tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sări peste Tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă Tutorial-ul mai întâi." simple_ai: "AI simplu" # {change} warmup: "Încălzire" friends_playing: "Prieteni ce se Joacă" log_in_for_friends: "Loghează-te ca să joci cu prieteni tăi!" social_connect_blurb: "Conectează-te și joacă împotriva prietenilor tăi!" invite_friends_to_battle: "Invită-ți prieteni să se alăture bătăliei" fight: "Luptă!" watch_victory: "Vizualizează victoria" defeat_the: "Învinge" # watch_battle: "Watch the battle" tournament_started: ", a început" tournament_ends: "Turneul se termină" tournament_ended: "Turneul s-a terminat" tournament_rules: "Regulile Turneului" tournament_blurb: "Scrie cod, colectează aur, construiește armate, distruge inamici, câștigă premii, si îmbunătățeșteți cariera în turneul Lăcomiei de $40,000! Află detalii" tournament_blurb_criss_cross: "Caștigă pariuri, creează căi, păcălește-ți oponenți, strâange Pietre Prețioase, si îmbunătățeșteți cariera in turneul Criss-Cross! Află detalii" tournament_blurb_zero_sum: "Dezlănțuie creativitatea de programare în strângerea de aur sau în tactici de bătălie în alpine mirror match dintre vrăitori roșii și cei albaștrii.Turneul începe Vineri, 27 Martie și se va desfăsura până Luni, 6 Aprilie la 5PM PDT. Află detalii" # tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details" tournament_blurb_blog: "pe blogul nostru" rules: "Reguli" winners: "Învingători" # league: "League" # red_ai: "Red CPU" # "Red AI Wins", at end of multiplayer match playback # blue_ai: "Blue CPU" # wins: "Wins" # At end of multiplayer match playback # humans: "Red" # Ladder page display team name # ogres: "Blue" # 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: "Statistici" singleplayer_title: "Nivele Singleplayer" multiplayer_title: "Nivele Multiplayer" achievements_title: "Achievement-uri" last_played: "Ultima oară jucat" status: "Stare" status_completed: "Complet" status_unfinished: "Neterminat" no_singleplayer: "Nici-un joc Singleplayer jucat." no_multiplayer: "Nici-un joc Multiplayer jucat." no_achievements: "Nici-un Achivement câștigat." favorite_prefix: "Limbaj preferat" favorite_postfix: "." not_member_of_clans: "Nu ești membrul unui clan." # 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: "Ultimul câstigat" amount_achieved: "Sumă" achievement: "Achievement" current_xp_prefix: "" current_xp_postfix: " în total" new_xp_prefix: "" new_xp_postfix: " câștigat" left_xp_prefix: "" left_xp_infix: " până la level" 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: "Plăți" # prepaid_codes: "Prepaid Codes" purchased: "Cumpărate" # subscribe_for_gems: "Subscribe for gems" subscription: "Abonament" invoices: "Invoice-uri" service_apple: "Apple" service_web: "Web" paid_on: "Plătit pe" service: "Service" price: "Preț" gems: "Pietre Prețioase" active: "Activ" subscribed: "Abonat" unsubscribed: "Dezabonat" active_until: "Activ p<NAME>" cost: "Cost" next_payment: "Următoarea Plată" card: "Card" status_unsubscribed_active: "Nu ești abonat si nu vei fi facturat, contul tău este activ deocamdată." status_unsubscribed: "Primește access la nivele noi, eroi, iteme, și Pietre Prețioase bonus cu un abonament CodeCombat!" # not_yet_verified: "Not yet verified." # resend_email: "Resend email" # email_sent: "Email sent! Check your inbox." # verifying_email: "Verifying your email address..." # successfully_verified: "You've successfully verified your email address!" # verify_error: "Something went wrong when verifying your email :(" # unsubscribe_from_marketing: "Unsubscribe __email__ from all CodeCombat marketing emails?" # unsubscribe_button: "Yes, unsubscribe" # unsubscribe_failed: "Failed" # unsubscribe_success: "Success" account_invoices: amount: "Sumă in dolari US" declined: "Cardul tău a fost refuzat" invalid_amount: "Introdu o sumă in dolari US." not_logged_in: "Logheazăte sau crează un cont pentru a accesa invoice-uri." pay: "Plată Invoice" purchasing: "Cumpăr..." retrying: "Eroare server, reîncerc." success: "Plătit cu success. Mulțumim!" # account_prepaid: # purchase_code: "Purchase a Subscription Code" # 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: "Users" # months: "Months" # purchase_total: "Total" # purchase_button: "Submit Purchase" # your_codes: "Your Codes" # redeem_codes: "Redeem a Subscription Code" # prepaid_code: "Prepaid Code" # lookup_code: "Lookup prepaid code" # apply_account: "Apply to your account" # copy_link: "You can copy the code's link and send it to someone." # quantity: "Quantity" # redeemed: "Redeemed" # no_codes: "No codes yet!" # you_can1: "You can" # you_can2: "purchase a prepaid code" # you_can3: "that can be applied to your own account or given to others." # 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 Bobby Duke 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: "Eroare la încărcarea pe server" # {change} connection_failure: "Conexiune eșuată." # connection_failure_desc: "It doesn’t look like you’re connected to the internet! Check your network connection and then reload this page." # login_required: "Login Required" # login_required_desc: "You need to be logged in to access this page." unauthorized: "Este nevoie să te loghezi. Ai cookies dezactivate?" forbidden: "Nu ai permisiune." # forbidden_desc: "Oh no, there’s nothing we can show you here! Make sure you’re logged into the correct account, or visit one of the links below to get back to programming!" # user_not_found: "User Not Found" not_found: "Nu a fost găsit." # not_found_desc: "Hm, there’s nothing here. Visit one of the following links to get back to programming!" not_allowed: "Metodă nepermisă." timeout: "Timeout Server." # {change} conflict: "Conflict resurse." bad_input: "Date greșite." server_error: "Eroare Server." unknown: "Eroare Necunoscută." # {change} # error: "ERROR" # general_desc: "Something went wrong, and it’s probably our fault. Try waiting a bit and then refreshing the page, or visit one of the following links to get back to programming!" resources: level: "Nivel" patch: "Patch" patches: "Patch-uri" system: "Sistem" systems: "Sisteme" component: "Componentă" components: "Componente" hero: "Erou" campaigns: "Campanii" # 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: "Arguments" # arithmetic: "Arithmetic" # 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: "Basic Syntax" # binary: "Binary" # 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: "Break Statements" # classes: "Classes" # continue_statements: "Continue Statements" # dom_events: "DOM Events" # dynamic_styling: "Dynamic Styling" # events: "Events" # 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: "Functions" # functions_parameters: "Parameters" # functions_multiple_parameters: "Multiple Parameters" # game_ai: "Game AI" # game_goals: "Game Goals" # game_spawn: "Game Spawn" # graphics: "Graphics" # graphs: "Graphs" # heaps: "Heaps" # if_condition: "Conditional If Statements" # if_else_if: "If/Else If Statements" # if_else_statements: "If/Else Statements" # if_statements: "If Statements" # 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: "Geometry" # math_operations: "Math Library Operations" # math_proportions: "Proportion Math" # math_trigonometry: "Trigonometry" # object_literals: "Object Literals" # parameters: "Parameters" # programs: "Programs" # properties: "Properties" # property_access: "Accessing Properties" # property_assignment: "Assigning Properties" # property_coordinate: "Coordinate Property" # queues: "Data Structures - Queues" # reading_docs: "Reading the Docs" # recursion: "Recursion" # return_statements: "Return Statements" # stacks: "Data Structures - Stacks" # strings: "Strings" # strings_concatenation: "String Concatenation" # strings_substrings: "Substring" # trees: "Data Structures - Trees" # variables: "Variables" # vectors: "Vectors" # while_condition_loops: "While Loops with Conditionals" # while_loops_simple: "While Loops" # while_loops_nested: "Nested While Loops" # xy_coordinates: "Coordinate Pairs" # advanced_strings: "Advanced Strings" # Rest of concepts are deprecated # algorithms: "Algorithms" # boolean_logic: "Boolean Logic" # basic_html: "Basic HTML" # basic_css: "Basic CSS" # basic_web_scripting: "Basic Web Scripting" # intermediate_html: "Intermediate HTML" # intermediate_css: "Intermediate CSS" # intermediate_web_scripting: "Intermediate Web Scripting" # advanced_html: "Advanced HTML" # advanced_css: "Advanced CSS" # advanced_web_scripting: "Advanced Web Scripting" # input_handling: "Input Handling" # while_loops: "While Loops" # place_game_objects: "Place game objects" # construct_mazes: "Construct mazes" # 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: "Basic JavaScript" # 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: "<NAME>:" # enter_teacher_email: "Your teacher's email:" # teacher_email_placeholder: "<EMAIL>" # student_name_placeholder: "type your name here" # teachers_section: "Teachers:" # students_section: "Students:" # teacher_notified: "We've notified your teacher that you want to play more CodeCombat in your classroom!" delta: added: "Adăugat" modified: "Modificat" # not_modified: "Not Modified" deleted: "Șters" moved_index: "Index Mutat" text_diff: "Diff Text" merge_conflict_with: "ÎBINĂ CONFLICTUL CU" no_changes: "<NAME>" legal: page_title: "Aspecte Legale" # opensource_introduction: "CodeCombat is part of the open source community." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit peste o mulțime de proiecte open source, care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu software-ul care fac acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Nu o să iți vindem datele personale." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" # cost_description: "CodeCombat is free to play for all of its core levels, with a ${{price}} USD/mo subscription for access to extra level branches and {{gems}} bonus gems per month. You can cancel with a click, and we offer a 100% money-back guarantee." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" # {change} # 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: "MIT license" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a crea nivele." art_title: "Artă/Muzică - Conținut Comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea nivele. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice si toate celelalte creații non-cod care sunt disponibile când se crează nivele." art_access: "Momentan nu există nici un sistem universal,ușor pentru preluarea acestor bunuri. În general, preluați-le precum site-ul din URL-urile folosite, contactați-ne pentru asistență, sau ajutați-ne sa extindem site-ul pentru a face aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm numiți și lăsați referire link la codecombat.com unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link in apropiere, de exemplu sub o imagine, sau in pagina generală de atribuiri unde menționați și alte Bunuri Creative și software open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să se facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către ei, și urmăriți indicațiile de atribuire prevăzute în descrierea resursei dacă există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru Nivele în sine. Asta include" rights_scripts: "Script-uri" rights_unit: "Configurații de unități" rights_writings: "Scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru acel nivel care nu este valabil în mod normal pentru creat nivele." rights_clarification: "Pentru a clarifica, orice este valabil in Editorul de Nivele pentru scopul de a crea nivele se află sub CC, pe când conținutul creat cu Editorul de Nivele sau încărcat pentru a face nivelul nu se află." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Nivele puteți folosi liber cum vreți pentru a crea nivele. Dar ne rezervăm dreptul de a rezerva distribuția de nivele în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." # nutshell_see_also: "See also:" canonical: "Versiunea in engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între traduceri, documentul in engleză are prioritate." # third_party_title: "Third Party Services" # third_party_description: "CodeCombat uses the following third party services (among others):" # cookies_message: "CodeCombat uses a few essential and non-essential cookies." # cookies_deny: "Decline non-essential cookies" ladder_prizes: title: "Premii Turnee" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Aceste premii se acordă în funcție de" blurb_2: "Regulile Turneului" blurb_3: "la jucători umani sau ogre de top." blurb_4: "Două echipe înseamnă dublul premiilor!" blurb_5: "(O să fie 2 câștigători pe primul loc, 2 pe locul 2, etc.)" rank: "Rank" prizes: "Premii" total_value: "Valoare Totala" in_cash: "în cash" custom_wizard: "Wizard CodeCombat personalizat" custom_avatar: "Avatar CodeCombat personalizat" heap: "pentru 6 luni de acces \"Startup\"" credits: "credite" one_month_coupon: "coupon: alege Rails sau HTML" one_month_discount: "discount, 30% off: choose either Rails or HTML" license: "licență" oreilly: "ebook la alegere" calendar: year: "An" day: "Zi" # month: "Month" january: "Ianuarie" # february: "February" # march: "March" # april: "April" # may: "May" # june: "June" # july: "July" # august: "August" # september: "September" # october: "October" # november: "November" # december: "December" # 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: "Email already taken" # username_taken: "Username already taken" # esper: # line_no: "Line $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: "Error: " # x_not_a_function: "$1 is not a function" # x_not_defined: "$1 is not defined" # 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: "Unexpected token" # unexpected_number: "Unexpected number" # 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: "Try `$1`" # there_is_no_function: "There is no function `$1`, but `$2` has a method `$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` has no method `$2`." # there_is_a_problem: "There is a problem with your code." # 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: "<NAME>" # 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: "limba română", englishDescription: "Romanian", 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: "Un joc de programare dezvoltat cu gandul la profesori." # 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: "Informatică" built_for_teachers_subblurb1: "Începând cu cursul nostru gratuit de Introducere în Informatică, studenții însușesc concepte de baza în programare, cum ar fi bucle while/for, funcții și algoritmi." built_for_teachers_subtitle2: "Dezvoltare de jocuri" # 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: "Dezvoltare Web" # 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: "Gândire critică" # 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: "Creativitate" # 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: "Partener oficial Code.org" # 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: "Implementare ușoară" # 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: "Cel mai interesant mod de a învăța codul 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: "Classroom Edition:" # learn_to_code: "Learn to code:" # play_now: "Play Now" # im_an_educator: "I'm an Educator" im_a_teacher: "PI:NAME:<NAME>END_PI" im_a_student: "Sunt Student" learn_more: "Aflați mai multe" # classroom_in_a_box: "A classroom in-a-box for teaching computer science." # codecombat_is: "CodeCombat is a platform <strong>for students</strong> to learn computer science while playing through a real game." # our_courses: "Our courses have been specifically playtested <strong>to excel in the classroom</strong>, even for teachers with little to no prior programming experience." # watch_how: "Watch how CodeCombat is transforming the way people learn computer science." # top_screenshots_hint: "Students write code and see their changes update in real-time" # designed_with: "Designed with teachers in mind" # real_code: "Real, typed code" from_the_first_level: "de la primul nivel" # getting_students: "Getting students to typed code as quickly as possible is critical to learning programming syntax and proper structure." # educator_resources: "Educator resources" course_guides: "și ghiduri de curs" # teaching_computer_science: "Teaching computer science does not require a costly degree, because we provide tools to support educators of all backgrounds." accessible_to: "Accesibil la" everyone: "toţi" # democratizing: "Democratizing the process of learning coding is at the core of our philosophy. Everyone should be able to learn to code." # forgot_learning: "I think they actually forgot that they were learning something." # wanted_to_do: " Coding is something I've always wanted to do, and I never thought I would be able to learn it in school." # builds_concepts_up: "I like how CodeCombat builds the concepts up. It's really easy to understand and fun to figure it out." why_games: "De ce este importantă învățarea prin jocuri?" # games_reward: "Games reward the productive struggle." # encourage: "Gaming is a medium that encourages interaction, discovery, and trial-and-error. A good game challenges the player to master skills over time, which is the same critical process students go through as they learn." # excel: "Games excel at rewarding" # struggle: "productive struggle" # kind_of_struggle: "the kind of struggle that results in learning that’s engaging and" motivating: "motivând" # not_tedious: "not tedious." gaming_is_good: "Studiile sugerează că jocurile sunt bune pentru creierul copiilor. (e adevarat!)" # 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: "A real game, played with real coding." # 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: "Request a Demo" # request_quote: "Request a Quote" # setup_a_class: "Set Up a Class" have_an_account: "Aveți un cont?" logged_in_as: "În prezent sunteți conectat(ă) ca" # computer_science: "Our self-paced courses cover basic syntax to advanced concepts" ffa: "Gratuit pentru toți elevii" # coming_soon: "More coming soon!" # courses_available_in: "Courses are available in JavaScript and Python. Web Development courses utilize HTML, CSS, and 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: "Everything you need to run a computer science class in your school today, no CS background required." # goto_classes: "Go to My Classes" # view_profile: "View My Profile" # view_progress: "View Progress" # go_to_courses: "Go to My Courses" # want_coco: "Want CodeCombat at your school?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" # map: "Map" play: "Nivele" # The top nav bar entry where players choose which levels to play community: "Communitate" courses: "Cursuri" blog: "Blog" forum: "Forum" account: "Cont" my_account: "Contul meu" profile: "Profil" home: "Acasă" contribute: "Contribuie" legal: "Confidențialitate și termeni" # privacy: "Privacy Notice" about: "Despre" # impact: "Impact" contact: "Contact" twitter_follow: "Urmărește" # my_classrooms: "My Classes" my_courses: "Cursurile mele" # my_teachers: "My Teachers" # careers: "Careers" facebook: "Facebook" twitter: "Twitter" # create_a_class: "Create a Class" # other: "Other" # learn_to_code: "Learn to Code!" # toggle_nav: "Toggle navigation" # schools: "Schools" # get_involved: "Get Involved" # open_source: "Open source (GitHub)" # support: "Support" # faqs: "FAQs" # copyright_prefix: "Copyright" # copyright_suffix: "All Rights Reserved." # help_pref: "Need help? Email" # help_suff: "and we'll get in touch!" # resource_hub: "Resource Hub" # apcsp: "AP CS Principles" # parent: "Parents" # browser_recommendation: "For the best experience we recommend using the latest version of Chrome. Download the browser here!" modal: close: "Inchide" okay: "Okay" # cancel: "Cancel" not_found: page_not_found: "Pagina nu a fost gasită" diplomat_suggestion: title: "Ajută-ne să traducem CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Avem nevoie de abilitățile tale lingvistice." pitch_body: "CodeCombat este dezvoltat in limba engleza , dar deja avem jucatări din toate colțurile lumii. Mulți dintre ei vor să joace in română și nu vorbesc engleză. Dacă poți vorbi ambele te rugăm să te gândești dacă ai dori să devi un Diplomat și să ne ajuți sa traducem atât jocul cât și site-ul." missing_translations: "Until we can translate everything into Romanian, you'll see English when Romanian isn't available." learn_more: "Află mai multe despre cum să fi un Diplomat" subscribe_as_diplomat: "Înscrie-te ca Diplomat" 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: "CodeCombat has a" # anon_signup_title_2: "Classroom Version!" # anon_signup_enter_code: "Enter Class Code:" # anon_signup_ask_teacher: "Don't have one? Ask your teacher!" # anon_signup_create_class: "Want to create a class?" # anon_signup_setup_class: "Set up a class, add your students, and monitor progress!" # anon_signup_create_teacher: "Create free teacher account" play_as: "Alege-ți echipa" # Ladder page # get_course_for_class: "Assign Game Development and more to your classes!" # request_licenses: "Contact our school specialists for details." # compete: "Compete!" # Course details page spectate: "Spectator" # Ladder page players: "jucători" # Hover over a level on /play hours_played: "ore jucate" # Hover over a level on /play items: "Iteme" # Tooltip on item shop button from /play unlock: "Deblochează" # For purchasing items and heroes confirm: "Confirmă" owned: "Deținute" # For items you own locked: "Blocate" available: "Valabile" skills_granted: "Skill-uri acordate" # Property documentation details heroes: "Eroi" # Tooltip on hero shop button from /play achievements: "Realizări" # Tooltip on achievement list button from /play settings: "Setări" # Tooltip on settings button from /play poll: "Sondaj" # Tooltip on poll button from /play next: "Următorul" # Go from choose hero to choose inventory before playing a level change_hero: "Schimbă eroul" # Go back from choose inventory to choose hero # change_hero_or_language: "Change Hero or Language" buy_gems: "Cumpără Pietre Prețioase" # subscribers_only: "Subscribers Only!" # subscribe_unlock: "Subscribe to Unlock!" # subscriber_heroes: "Subscribe today to immediately unlock Amara, Hushbaum, and Hattori!" # subscriber_gems: "Subscribe today to purchase this hero with gems!" anonymous: "PI:NAME:<NAME>END_PI" level_difficulty: "Dificultate: " awaiting_levels_adventurer_prefix: "Lansăm niveluri noi în fiecare săptămână." awaiting_levels_adventurer: "Înscrie-te ca un aventurier " awaiting_levels_adventurer_suffix: "pentru a fi primul care joacă nivele noi." adjust_volume: "Reglează volumul" campaign_multiplayer: "Arene Multiplayer" campaign_multiplayer_description: "... în care te lupți cap-la-cap contra alți jucători." # 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: "Back to Classroom" # teacher_button: "For Teachers" # get_more_codecombat: "Get More CodeCombat" code: # if: "if" # 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: "else" # elif: "else if" # while: "while" # loop: "loop" # for: "for" # break: "break" # continue: "continue" # pass: "pass" # return: "return" # then: "then" # do: "do" # end: "end" # function: "function" # def: "define" # var: "variable" # self: "self" # hero: "hero" # this: "this" # or: "or" # "||": "or" # and: "and" # "&&": "and" # not: "not" # "!": "not" # "=": "assign" # "==": "equals" # "===": "strictly equals" # "!=": "does not equal" # "!==": "does not strictly equal" # ">": "is greater than" # ">=": "is greater than or equal" # "<": "is less than" # "<=": "is less than or equal" # "*": "multiplied by" # "/": "divided by" "+": "plus" "-": "minus" "+=": "adaugă și atribuie" "-=": "scade și atribuie" True: "Adevărat" true: "adevărat" False: "Fals" false: "fals" undefined: "nedefinit" # null: "null" # nil: "nil" # None: "None" share_progress_modal: blurb: "Faci progrese mari! Spune-le părinților cât de mult ai învățat cu CodeCombat." email_invalid: "Adresă Email invalidă." form_blurb: "Introduceți adresa e-mail al unui părinte mai jos și le vom arăta!" form_label: "Adresă Email" placeholder: "adresă email" title: "Excelentă treabă, Ucenicule" login: sign_up: "Crează cont" email_or_username: "Email sau nume de utilizator" log_in: "Log In" logging_in: "Se conectează" log_out: "Log Out" forgot_password: "PI:PASSWORD:<PASSWORD>END_PI?" finishing: "Terminare" sign_in_with_facebook: "Conectați-vă cu Facebook" sign_in_with_gplus: "Conectați-vă cu G+" signup_switch: "Doriți să creați un cont?" signup: complete_subscription: "Completează abonamentul" create_student_header: "Creează cont student" create_teacher_header: "Creează cont profesor" create_individual_header: "Creează cont profesor un cont individual" email_announcements: "Primește notificări prin email" # {change} sign_in_to_continue: "Conecteaza-te sau creează un cont pentru a continua" # teacher_email_announcements: "Keep me updated on new teacher resources, curriculum, and courses!" creating: "Se creează contul..." sign_up: "Înscrie-te" log_in: "loghează-te cu parola" # login: "Login" required: "Trebuie să te înregistrezi înaite să parcurgi acest drum." login_switch: "Ai deja un cont?" optional: "opțional" # 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: "Students, enter the class code from your teacher." # birthday: "Birthday" # 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: "Checking..." # account_exists: "This email is already in use:" # sign_in: "Sign in" # email_good: "Email looks good!" # name_taken: "Username already taken! Try {{suggestedName}}?" # name_available: "Username available!" # name_is_email: "Username may not be an email" # choose_type: "Choose your account type:" # teacher_type_1: "Teach programming using CodeCombat!" # teacher_type_2: "Set up your class" # teacher_type_3: "Access Course Guides" # teacher_type_4: "View student progress" # signup_as_teacher: "Sign up as a Teacher" # student_type_1: "Learn to program while playing an engaging game!" # student_type_2: "Play with your class" # student_type_3: "Compete in arenas" student_type_4: "Alege-ți eroul!" # student_type_5: "Have your Class Code ready!" # signup_as_student: "Sign up as a Student" # individuals_or_parents: "Individuals & Parents" # individual_type: "For players learning to code outside of a class. Parents should sign up for an account here." # signup_as_individual: "Sign up as an Individual" # enter_class_code: "Enter your Class Code" # enter_birthdate: "Enter your birthdate:" # parent_use_birthdate: "Parents, use your own birthdate." # ask_teacher_1: "Ask your teacher for your Class Code." # ask_teacher_2: "Not part of a class? Create an " # ask_teacher_3: "Individual Account" # ask_teacher_4: " instead." # about_to_join: "You're about to join:" enter_parent_email: "Introduceți adresa de e-mail a părintelui dvs .:" # 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: "Account Created!" # confirm_student_blurb: "Write down your information so that you don't forget it. Your teacher can also help you reset your password at any time." # confirm_individual_blurb: "Write down your login information in case you need it later. Verify your email so you can recover your account if you ever forget your password - check your inbox!" write_this_down: "Notează asta:" start_playing: "Începe jocul!" # sso_connected: "Successfully connected with:" # select_your_starting_hero: "Select Your Starting Hero:" # you_can_always_change_your_hero_later: "You can always change your hero later." # 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: "Află mai multe despre riscuri posibile." eu_confirmation_student: "Dacă nu ești sigur, întreabă-ți profesorul." # 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: "Recuperează Cont" send_password: "PI:PASSWORD:<PASSWORD>END_PI" recovery_sent: "Email de recuperare trimis." items: primary: "Primar" secondary: "Secundar" armor: "Armură" accessories: "Accesorii" misc: "Diverse" books: "Cărti" 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: "Inapoi" # When used as an action verb, like "Navigate backward" coming_soon: "In curand!" continue: "Continuă" # When used as an action verb, like "Continue forward" next: "Urmator" default_code: "Cod implicit" loading: "Se încarcă..." overview: "Prezentare generală" processing: "Procesare..." solution: "Soluţie" table_of_contents: "Cuprins" intro: "Introducere" saving: "Se salvează..." sending: "Se trimite..." send: "Trimite" sent: "Trimis" cancel: "Anulează" save: "Salvează" publish: "Publică" create: "Creează" fork: "Fork" play: "Joacă" # When used as an action verb, like "Play next level" retry: "Reîncearca" actions: "Acţiuni" info: "Info" help: "Ajutor" watch: "Watch" unwatch: "Unwatch" submit_patch: "Înainteaza Patch" submit_changes: "Trimite modificări" save_changes: "Salveaza modificări" required_field: "obligatoriu" # submit: "Submit" # replay: "Replay" # complete: "Complete" general: and: "și" name: "PI:NAME:<NAME>END_PI" date: "Dată" body: "Corp" version: "Versiune" pending: "În așteptare" accepted: "Acceptat" rejected: "Respins" withdrawn: "Retrage" accept: "Accepta" accept_and_save: "Acceptă și Salvează" reject: "Respinge" withdraw: "Retrage" submitter: "PI:NAME:<NAME>END_PI" submitted: "Expediat" commit_msg: "Înregistrează Mesajul" version_history: "Istoricul versiunilor" version_history_for: "Istoricul versiunilor pentru: " select_changes: "Selectați două schimbări de mai jos pentru a vedea diferenţa." undo_prefix: "Undo" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Redo" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Joaca previzualizarea nivelului actual" result: "Rezultat" results: "Rezultate" description: "Descriere" or: "sau" subject: "Subiect" email: "Email" password: "PI:PASSWORD:<PASSWORD>END_PI" confirm_password: "PI:PASSWORD:<PASSWORD>END_PI" message: "MesPI:NAME:<NAME>END_PI" code: "Cod" ladder: "Clasament" when: "când" opponent: "oponent" rank: "Rang" score: "Scor" win: "Victorie" loss: "Înfrângere" tie: "Remiză" easy: "Ușor" medium: "Mediu" hard: "Greu" player: "PI:NAME:<NAME>END_PI" player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard warrior: "PI:NAME:<NAME>END_PI" ranger: "Arcaș" wizard: "Vrăjitor" first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" last_initial: "Inițiala nume" username: "Nume de utilizator" contact_us: "Contacteaza-ne" close_window: "Închide fereastra" learn_more: "Află mai mult" more: "Mai mult" fewer: "Mai putin" with: "cu" units: second: "secundă" seconds: "secunde" # sec: "sec" minute: "minut" minutes: "minute" hour: "oră" hours: "ore" day: "zi" days: "zile" week: "săptămână" weeks: "săptămâni" month: "lună" months: "luni" year: "an" years: "ani" play_level: # back_to_map: "Back to Map" # directions: "Directions" # edit_level: "Edit Level" # keep_learning: "Keep Learning" # explore_codecombat: "Explore CodeCombat" # finished_hoc: "I'm finished with my Hour of Code" # get_certificate: "Get your certificate!" # level_complete: "Level Complete" # completed_level: "Completed Level:" # course: "Course:" done: "Gata" # next_level: "Next Level" # 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__ Concepts Used" # 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: "Start Challenge" # next_game: "Next game" languages: "Limbi" programming_language: "Limbaj de programare" # show_menu: "Show game menu" home: "Acasă" # Not used any more, will be removed soon. level: "Nivel" # Like "Level: Dungeons of Kithgard" skip: "Sari peste" game_menu: "Meniul Jocului" restart: "Restart" goals: "Obiective" goal: "Obiectiv" # 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: "Rulează..." success: "Success!" incomplete: "Incomplet" timed_out: "Ai rămas fără timp" failing: "Eşec" reload: "Reîncarca" reload_title: "Reîncarcă tot codul?" reload_really: "Ești sigur că vrei să reîncarci nivelul de la început?" reload_confirm: "Reîncarca Tot" # 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: "Test Level" victory: "Victorie" victory_title_prefix: "" victory_title_suffix: " Terminat" victory_sign_up: "Înscrie-te pentru a salva progresul" victory_sign_up_poke: "Vrei să-ți salvezi codul? Crează un cont gratis!" victory_rate_the_level: "Apreciază nivelul: " # {change} victory_return_to_ladder: "Înapoi la jocurile de clasament" victory_saving_progress: "Salvează Progresul" victory_go_home: "Acasă" victory_review: "Spune-ne mai multe!" # victory_review_placeholder: "How was the level?" victory_hour_of_code_done: "Ai terminat?" victory_hour_of_code_done_yes: "Da, am terminat Hour of Code™!" victory_experience_gained: "Ai câștigat XP" victory_gems_gained: "Ai câștigat Pietre Prețioase" victory_new_item: "Item nou" # victory_new_hero: "New Hero" victory_viking_code_school: "Wow, ăla a fost un nivel greu! Daca nu ești deja un dezvoltator de software, ar trebui să fi. Tocmai ai fost selectat pentru acceptare in Viking Code School, unde poți sa iți dezvolți abilitățile la nivelul următor și să devi un dezvoltator web profesionist în 14 săptămâni." victory_become_a_viking: "PI:NAME:<NAME>END_PI" # victory_no_progress_for_teachers: "Progress is not saved for teachers. But, you can add a student account to your classroom for yourself." tome_cast_button_run: "Ruleaza" tome_cast_button_running: "In Derulare" tome_cast_button_ran: "A rulat" # tome_cast_button_update: "Update" tome_submit_button: "Trimite" tome_reload_method: "Reîncarcă cod original, pentru această metodă" # {change} tome_available_spells: "Vrăji disponibile" tome_your_skills: "Skillurile tale" # hints: "Hints" # videos: "Videos" # hints_title: "Hint {{number}}" code_saved: "Cod Salvat" skip_tutorial: "Sari peste (esc)" keyboard_shortcuts: "Scurtături Keyboard" loading_start: "Începe Level" # loading_start_combo: "Start Combo Challenge" # loading_start_concept: "Start Concept Challenge" problem_alert_title: "Repară codul" time_current: "Acum:" time_total: "Max:" time_goto: "Dute la:" non_user_code_problem_title: "Imposibil de încărcat Nivel" infinite_loop_title: "Buclă infinită detectată" infinite_loop_description: "Codul initial pentru a construi lumea nu a terminat de rulat. Este, probabil, foarte lent sau are o buclă infinită. Sau ar putea fi un bug. Puteți încerca acest cod nou sau resetați codul la starea implicită. Dacă nu-l repara, vă rugăm să ne anunțați." check_dev_console: "Puteți deschide, de asemenea, consola de dezvoltator pentru a vedea ce ar putea merge gresit." check_dev_console_link: "(instrucțiuni)" infinite_loop_try_again: "Încearcă din nou" infinite_loop_reset_level: "Resetează Nivelul" infinite_loop_comment_out: "Comentează Codul" tip_toggle_play: "Pune sau scoate pauza cu Ctrl+P." tip_scrub_shortcut: "Înapoi și derulare rapidă cu Ctrl+[ and Ctrl+]." # {change} tip_guide_exists: "Apasă pe ghidul din partea de sus a pagini pentru informații utile." tip_open_source: "CodeCombat este 100% open source!" # {change} # tip_tell_friends: "Enjoying CodeCombat? Tell your friends about us!" tip_beta_launch: "CodeCombat a fost lansat beta in Octombrie 2013." tip_think_solution: "Gândește-te la soluție, nu la problemă." tip_theory_practice: "Teoretic nu este nici o diferență înte teorie și practică. Dar practic este. - PI:NAME:<NAME>END_PI" tip_error_free: "Există doar două metode de a scrie un program fără erori; numai a treia funcționează. - PI:NAME:<NAME>END_PI" tip_debugging_program: "Dacă a face debuggin este procesul de a scoate bug-uri, atunci a programa este procesul de a introduce bug-uri. - PI:NAME:<NAME>END_PI" tip_forums: "Intră pe forum și spune-ți părerea!" tip_baby_coders: "În vitor până și bebelușii vor fi Archmage." tip_morale_improves: "Se va încărca până până când va crește moralul." tip_all_species: "Noi credem în șanse egale de a învăța programare pentru toate speciile." tip_reticulating: "Reticulăm coloane vertebrale." tip_harry: "Ha un Wizard, " tip_great_responsibility: "Cu o mare abilitate mare de programare vine o mare responsabilitate de debugging." tip_munchkin: "Daca nu iți mananci legumele, un munchkin va veni după tine cand dormi." tip_binary: "Sunt doar 10 tipuri de oameni in lume: cei ce îteleg sistemul binar, si ceilalți." tip_commitment_yoda: "Un programator trebuie să aiba cel mai profund angajament, si mintea cea mai serioasă. ~Yoda" tip_no_try: "Fă. Sau nu mai face. Nu exista voi încerca. ~Yoda" tip_patience: "Să ai rabdare trebuie, tinere Padawan. ~Yoda" tip_documented_bug: "Un bug documentat nu e chiar un bug; este o caracteristica." tip_impossible: "Mereu pare imposibil până e gata. ~PI:NAME:<NAME>END_PI" tip_talk_is_cheap: "Vorbele sunt ieftine. Arată-mi codul. ~PI:NAME:<NAME>END_PI" tip_first_language: "Cel mai dezastruos lucru pe care poți să îl înveți este primul limbaj de programare. ~PI:NAME:<NAME>END_PI" tip_hardware_problem: "Î: De cați programatori ai nevoie ca să schimbi un bec? R: Niciunul, e o problemă hardware." tip_hofstadters_law: "Legea lui Hofstadter: Mereu dureaza mai mult decât te aștepți, chiar dacă iei în considerare Legea lui Hofstadter." tip_premature_optimization: "Optimizarea prematură este rădăcina tuturor răutăților. ~PI:NAME:<NAME>END_PI" tip_brute_force: "Atunci cănd ești în dubii, folosește brute force. ~PI:NAME:<NAME>END_PI" tip_extrapolation: "Există două feluri de oameni: cei care pot extrapola din date incomplete..." tip_superpower: "Programarea este cel mai apropiat lucru de o superputere." tip_control_destiny: "In open source, ai dreptul de a-ți controla propiul destin. ~PI:NAME:<NAME>END_PI" tip_no_code: "Nici-un cod nu e mai rapid decat niciun cod." tip_code_never_lies: "Codul nu minte niciodată, commenturile mai mint. ~PI:NAME:<NAME>END_PI" tip_reusable_software: "Înainte ca un software să fie reutilizabil, trebuie să fie mai întâi utilizabil." tip_optimization_operator: "Fiecare limbaj are un operator de optimizare. La majoritatea acela este '//'" tip_lines_of_code: "Măsurarea progresului în lini de cod este ca și măsurarea progresului de construcție a aeronavelor în greutate. ~PI:NAME:<NAME>END_PI" tip_source_code: "Vreau să schimb lumea dar nu îmi dă nimeni codul sursă." tip_javascript_java: "Java e pentru JavaScript exact ce e o Mașina pentru o Carpetă. ~PI:NAME:<NAME>END_PI" tip_move_forward: "Orice ai face, dăi înainte. ~PI:NAME:<NAME>END_PI Jr." tip_google: "Ai o problemă care nu o poți rezolva? Folosește Google!" tip_adding_evil: "Adaugăm un strop de răutate." tip_hate_computers: "Tocmai aia e problema celor ce urăsc calulatoarele, ei defapt urăsc programatorii nepricepuți. ~PI:NAME:<NAME>END_PI" tip_open_source_contribute: "Poți ajuta la îmbunătățirea jocului CodeCombat!" tip_recurse: "A itera este uman, recursiv este divin. ~PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI" tip_free_your_mind: "Trebuie sa lași totul, PI:NAME:<NAME>END_PI, Îndoiala și necredința. Eliberează-ți mintea. ~Morpheus" tip_strong_opponents: "Și cei mai puternici dintre oponenți întodeauna au o slăbiciune. ~Itachi Uchiha" # tip_paper_and_pen: "Before you start coding, you can always plan with a sheet of paper and a pen." # tip_solve_then_write: "First, solve the problem. Then, write the code. - PI:NAME:<NAME>END_PI" # tip_compiler_ignores_comments: "Sometimes I think that the compiler ignores my comments." # tip_understand_recursion: "The only way to understand recursion is to understand recursion." # 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" # 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, 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. - 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. - PI:NAME:<NAME>END_PI" # tip_mulan: "Believe you can, then you will. - PI:NAME:<NAME>END_PI" # project_complete: "Project Complete!" # share_this_project: "Share this project with friends or family:" # ready_to_share: "Ready to publish your project?" # 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: "View Gallery" # project_published_noty: "Your level has been published!" # keep_editing: "Keep Editing" # 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: "Methods" # events: "Events" # handlers: "Handlers" # properties: "Properties" # snippets: "Snippets" # spawnable: "Spawnable" # html: "HTML" # math: "Math" # array: "Array" # object: "Object" # string: "String" # function: "Function" # vector: "Vector" # date: "Date" # jquery: "jQuery" # json: "JSON" # number: "Number" # 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: "PI:NAME:<NAME>END_PI {{name}}" # created_during_hoc: "Created during Hour of Code" # restart: "Restart Level" # play: "Play Level" # play_more_codecombat: "Play More CodeCombat" # default_student_instructions: "Click to control your hero and win your game!" # goal_survive: "Survive." # goal_survive_time: "Survive for __seconds__ seconds." # goal_defeat: "Defeat all enemies." # goal_defeat_amount: "Defeat __amount__ enemies." # 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: "Inventar" save_load_tab: "Salvează/Încarcă" options_tab: "Opțiuni" guide_tab: "Ghid" guide_video_tutorial: "Tutorial Video" guide_tips: "Sfaturi" multiplayer_tab: "Multiplayer" auth_tab: "Înscriete" inventory_caption: "Echipeazăți Eroul" choose_hero_caption: "Alege Eroul, limbajul" options_caption: "Configurarea setărilor" guide_caption: "Documentație si sfaturi" multiplayer_caption: "Joaca cu prieteni!" auth_caption: "Salvează progresul." leaderboard: view_other_solutions: "Vizualizează Tabelul de Clasificare" scores: "Scoruri" top_players: "Top Jucători" day: "Astăzi" week: "Săptămâna Aceasta" all: "Tot Timpul" latest: "Ultimul" time: "Timp" damage_taken: "Damage Primit" damage_dealt: "Damage Oferit" difficulty: "Dificultate" gold_collected: "Aur Colectat" survival_time: "Supravietuit" defeated: "Inamici înfrânți" code_length: "Linii de cod" score_display: "__scoreType__: __score__" inventory: equipped_item: "Echipat" required_purchase_title: "Necesar" available_item: "Valabil" restricted_title: "Restricționat" should_equip: "(dublu-click pentru echipare)" equipped: "(echipat)" locked: "(blocat)" restricted: "(în acest nivel)" equip: "Echipează" unequip: "Dezechipează" # warrior_only: "Warrior Only" # ranger_only: "Ranger Only" # wizard_only: "Wizard Only" buy_gems: few_gems: "Căteva Pietre Prețioase" pile_gems: "Un morman de Pietre Prețioase" chest_gems: "Un cufăr de Pietre Prețioase" purchasing: "Cumpărare..." declined: "Cardul tău a fost refuzat." retrying: "Eroare de server, reîncerc." prompt_title: "Nu sunt destule Pietre Prețioase." prompt_body: "Vrei mai multe?" prompt_button: "Intră în magazin." recovered: "Pietre Prețioase cumpărate anterior recuperate.Va rugăm să dați refresh la pagină." price: "x{{gems}} / mo" buy_premium: "Cumpara Premium" # purchase: "Purchase" # purchased: "Purchased" subscribe_for_gems: prompt_title: "Pietre prețioase insuficiente!" prompt_body: "Abonează-te la Premium pentru a obține pietre prețioase și pentru a accesa chiar mai multe nivele!" earn_gems: prompt_title: "Pietre prețioase insuficiente" prompt_body: "Continuă să joci pentru a câștiga mai mult!" subscribe: best_deal: "Cea mai bună afacere!" confirmation: "Felicitări! Acum ai abonament CodeCombat Premium!" premium_already_subscribed: "Esti deja abonat la Premium!" subscribe_modal_title: "CodeCombat Premium" comparison_blurb: "Îmbunătățește-ți abilitățile cu abonamentul CodeCombat" must_be_logged: "Trebuie să te conectezi mai întâi. Te rugăm să creezi un cont sau să te conectezi din meniul de mai sus." subscribe_title: "Abonează-te" # Actually used in subscribe buttons, too unsubscribe: "Dezabonează-te" confirm_unsubscribe: "Confirmă Dezabonarea" never_mind: "Nu contează, eu tot te iubesc!" thank_you_months_prefix: "Mulțumesc pentru sprijinul acordat în aceste" thank_you_months_suffix: "luni." thank_you: "Mulțumim pentru susținerea jocului CodeCombat!" sorry_to_see_you_go: "Ne pare rău că pleci! Te rugăm să ne spui ce am fi putut face mai bine." unsubscribe_feedback_placeholder: "O, ce am făcut?" stripe_description: "Abonament Lunar" buy_now: "Cumpără acum" subscription_required_to_play: "Ai nevoie de abonament ca să joci acest nivel." unlock_help_videos: "Abonează-te pentru deblocarea tuturor tutorialelor video." personal_sub: "Abonament Personal" # Accounts Subscription View below loading_info: "Se încarcă informațile despre abonament..." managed_by: "Gestionat de" will_be_cancelled: "Va fi anulat pe" currently_free: "Ai un abonament gratuit" currently_free_until: "Ai un abonament gratuit până pe" free_subscription: "Abonament gratuit" was_free_until: "Ai avut un abonament gratuit până pe" managed_subs: "Abonamente Gestionate" subscribing: "Te abonăm..." current_recipients: "Recipienți curenți" unsubscribing: "Dezabonare..." subscribe_prepaid: "Dă Click pe Abonare pentru a folosi un cod prepaid" using_prepaid: "Foloseste codul prepaid pentru un abonament lunar" feature_level_access: "Accesează peste 300 de nivele disponibile" feature_heroes: "Deblochează eroi exclusivi și personaje" feature_learn: "Învață să creezi jocuri și site-uri web" month_price: "$__price__" first_month_price: "Doar $__price__ pentru prima luna!" lifetime: "Acces pe viață" lifetime_price: "$__price__" year_subscription: "Abonament anual" year_price: "$__price__/an" support_part1: "Ai nevoie de ajutor cu plata sau preferi PayPal? E-mail" 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: "Mimic" # 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: "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 GlPI:NAME:<NAME>END_PIier 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: "Alege Eroul" programming_language: "Limbaj de Programare" programming_language_description: "Ce limbaj de programare vrei să folosești?" default: "Implicit" experimental: "Experimental" python_blurb: "Simplu dar puternic, Python este un limbaj de uz general extraordinar!" javascript_blurb: "Limbajul web-ului." coffeescript_blurb: "JavaScript cu o syntaxă mai placută!" lua_blurb: "Limbaj de scripting pentru jocuri." # java_blurb: "(Subscriber Only) Android and enterprise." # cpp_blurb: "(Subscriber Only) Game development and high performance computing." status: "Stare" weapons: "Armament" weapons_warrior: "Săbii - Distanță Scurtă, Fără Magie" weapons_ranger: "Arbalete, Arme - Distanță Mare, Fără Magie" weapons_wizard: "Baghete, Toiage, - Distanță Mare, Și Magie" attack: "Attack" # Can also translate as "Attack" health: "Viață" speed: "Viteză" regeneration: "Regenerare" range: "Rază" # As in "attack or visual range" blocks: "Blochează" # As in "this shield blocks this much damage" backstab: "Înjunghiere" # As in "this dagger does this much backstab damage" skills: "Skilluri" attack_1: "Oferă" attack_2: "of listed" attack_3: "Damage cu arma." health_1: "Primește" health_2: "of listed" health_3: "Armură." speed_1: "Se mișcă cu" speed_2: "metri pe secundă." available_for_purchase: "Disponibil pentru cumpărare" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Pentru deblocare termină nivelul:" # 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: "Numai anumiți eroi pot juca acest nivel" # 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: "function" # skill types # method: "method" # snippet: "snippet" # number: "number" # array: "array" # object: "object" # string: "string" writable: "permisiuni de scriere" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "permisiuni doar de citire" # action: "Action" # spell: "Spell" action_name: "nume" action_cooldown: "Ține" action_specific_cooldown: "Cooldown" action_damage: "Damage" action_range: "Rază de acțiune" action_radius: "Rază" action_duration: "Durată" example: "Exemplu" ex: "ex" # Abbreviation of "example" current_value: "Valoare Curentă" default_value: "Valoare Implicită" parameters: "Parametrii" # required_parameters: "Required Parameters" # optional_parameters: "Optional Parameters" returns: "Întoarce" granted_by: "Acordat de" # still_undocumented: "Still undocumented, sorry." save_load: granularity_saved_games: "Salvate" granularity_change_history: "Istoric" options: general_options: "Opțiuni Generale" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Muzică" music_description: "Oprește Muzica din fundal." editor_config_title: "Configurare Editor" editor_config_livecompletion_label: "Autocompletare Live" editor_config_livecompletion_description: "Afișează sugesti de autocompletare în timp ce scri." editor_config_invisibles_label: "Arată etichetele invizibile" editor_config_invisibles_description: "Arată spațiile și taburile invizibile." editor_config_indentguides_label: "Arată ghidul de indentare" editor_config_indentguides_description: "Arată linii verticale pentru a vedea mai bine indentarea." editor_config_behaviors_label: "Comportamente inteligente" editor_config_behaviors_description: "Completează automat parantezele, ghilimele etc." # 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: "Learn More" # main_title: "If you want to learn to program, you need to write (a lot of) code." # main_description: "At CodeCombat, our job is to make sure you're doing that with a smile on your face." # mission_link: "Mission" # team_link: "Team" # story_link: "Story" # press_link: "Press" # mission_title: "Our mission: make programming accessible to every student on Earth." # mission_description_1: "<strong>Programming is magic</strong>. It's the ability to create things from pure imagination. We started CodeCombat to give learners the feeling of wizardly power at their fingertips by using <strong>typed code</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: "Meet the CodeCombat team" # 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: "Cofounder, CEO" # matt_title: "Cofounder, CTO" # cat_title: "Game Designer" # scott_title: "Cofounder, Software Engineer" # maka_title: "Customer Advocate" # robin_title: "Senior Product Manager" # nolan_title: "Sales Manager" # david_title: "Marketing Lead" # titles_csm: "Customer Success Manager" # titles_territory_manager: "Territory Manager" # 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: "Illustration" # retrostyle_blurb: "RetroStyle Games" # bryukh_title: "Gameplay Developer" # bryukh_blurb: "Constructs puzzles" # community_title: "...and our open-source community" # community_subtitle: "Over 500 contributors have helped build CodeCombat, with more joining every week!" # community_description_3: "CodeCombat is a" # community_description_link_2: "community project" # 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: "contribute page" # community_description_2: "for more info." # number_contributors: "Over 450 contributors have lent their support and time to this project." # story_title: "Our story so far" # story_subtitle: "Since 2013, CodeCombat has grown from a mere set of sketches to a living, thriving game." # story_statistic_1a: "5,000,000+" # story_statistic_1b: "total players" # story_statistic_1c: "have started their programming journey through CodeCombat" # story_statistic_2a: "We’ve been translated into over 50 languages — our players hail from" # story_statistic_2b: "190+ countries" # story_statistic_3a: "Together, they have written" # story_statistic_3b: "1 billion lines of code and counting" # story_statistic_3c: "across many different programming languages" # 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: "Employee Benefits" # jobs_benefit_4: "Unlimited vacation" # 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: "Create Your Own" # 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: "Press & Contact" # contact_subtitle: "Need more information? Get in touch with us at" # screenshots_title: "Game Screenshots" # screenshots_hint: "(click to view full size)" # downloads_title: "Download Assets & Information" # about_codecombat: "About CodeCombat" # logo: "Logo" # screenshots: "Screenshots" # character_art: "Character Art" # download_all: "Download All" # previous: "Previous" # location_title: "We're located in downtown SF:" # teachers: # licenses_needed: "Licenses needed" # special_offer: # special_offer: "Special Offer" # 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: "Phone number" # phone_number_help: "What's the best number to reach you?" # primary_role_label: "Your Primary Role" # role_default: "Select Role" # primary_role_default: "Select Primary Role" # purchaser_role_default: "Select Purchaser Role" # tech_coordinator: "Technology coordinator" # advisor: "Curriculum Specialist/Advisor" # principal: "Principal" # superintendent: "Superintendent" # parent: "Parent" # 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: "District" # district_name: "District Name" # district_na: "Enter N/A if not applicable" # organization_label: "School" # school_name: "School Name" # city: "City" # state: "State / Region" # country: "Country" # num_students_help: "How many students will use CodeCombat?" # num_students_default: "Select Range" # education_level_label: "Education Level of Students" # education_level_help: "Choose as many as apply." # elementary_school: "Elementary School" # high_school: "High School" # please_explain: "(please explain)" # middle_school: "Middle School" # college_plus: "College or higher" # referrer: "How did you hear about us?" # referrer_help: "For example: from another teacher, a conference, your students, Code.org, etc." # referrer_default: "Select One" # referrer_conference: "Conference (e.g. ISTE)" # referrer_hoc: "Code.org/Hour of Code" # referrer_teacher: "A teacher" # referrer_admin: "An administrator" # referrer_student: "A student" # referrer_pd: "Professional trainings/workshops" # referrer_web: "Google" # referrer_other: "Other" # anything_else: "What kind of class do you anticipate using CodeCombat for?" # anything_else_helper: "" # thanks_header: "Request Received!" # 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: "Back to Classes" # 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: "Connect with:" # 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: "Create a Teacher Account" # create_account_subtitle: "Get access to teacher-only tools for using CodeCombat in the classroom. <strong>Set up a class</strong>, add your students, and <strong>monitor their progress</strong>!" # convert_account_title: "Update to Teacher Account" # not: "Not" # full_name_required: "First and last name required" versions: save_version_title: "Salvează noua versiune" new_major_version: "Versiune nouă majoră" submitting_patch: "Trimitere Patch..." cla_prefix: "Pentru a salva modificările mai intâi trebuie sa fiți de acord cu" cla_url: "CLA" cla_suffix: "." cla_agree: "SUNT DE ACORD" # owner_approve: "An owner will need to approve it before your changes will become visible." contact: contact_us: "Contact CodeCombat" welcome: "Folosiți acest formular pentru a ne trimite email. " forum_prefix: "Pentru orice altceva vă rugăm sa incercați " forum_page: "forumul nostru" forum_suffix: " în schimb." faq_prefix: "Există si un" faq: "FAQ" subscribe_prefix: "Daca ai nevoie de ajutor ca să termini un nivel te rugăm să" subscribe: "cumperi un abonament CodeCombat" subscribe_suffix: "si vom fi bucuroși să te ajutăm cu codul." subscriber_support: "Din moment ce ești un abonat CodeCombat, adresa ta de email va primi sprijinul nostru prioritar." screenshot_included: "Screenshot-uri incluse." where_reply: "Unde ar trebui să răspundem?" send: "Trimite Feedback" account_settings: title: "Setări Cont" not_logged_in: "Loghează-te sau crează un cont nou pentru a schimba setările." me_tab: "Eu" picture_tab: "Poză" delete_account_tab: "Șterge Contul" wrong_email: "Email Greșit" # wrong_password: "PI:PASSWORD:<PASSWORD>END_PI" delete_this_account: "Ștergere permanetă a acestui cont" # reset_progress_tab: "Reset All Progress" # reset_your_progress: "Clear all your progress and start over" # god_mode: "God Mode" emails_tab: "Email-uri" admin: "Admin" # manage_subscription: "Click here to manage your subscription." new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" type_in_email: "Scrie adresa de email ca să confirmi ștergerea" # type_in_email_progress: "Type in your email to confirm deleting your progress." # type_in_password: "Also, type in your password." email_subscriptions: "Subscripție Email" email_subscriptions_none: "Nu ai subscripții Email." email_announcements: "Anunțuri" email_announcements_description: "Primește email-uri cu ultimele știri despre CodeCombat." email_notifications: "Notificări" email_notifications_summary: "Control pentru notificări email personalizate, legate de activitatea CodeCombat." email_any_notes: "Orice Notificări" email_any_notes_description: "Dezactivați pentru a opri toate e-mailurile de notificare a activității." email_news: "Noutăți" email_recruit_notes: "Oportunități de job-uri" email_recruit_notes_description: "Daca joci foarte bine, este posibil sa te contactăm pentru obținerea unui loc (mai bun) de muncă." contributor_emails: "Contributor Class Emails" contribute_prefix: "Căutăm oameni să se alăture distracției! Intră pe " contribute_page: "pagina de contribuție" contribute_suffix: " pentru a afla mai multe." email_toggle: "Alege tot" error_saving: "Salvare erori" saved: "Modificări salvate" password_mismatch: "PI:PASSWORD:<PASSWORD>END_PIște." password_repeat: "Te PI:PASSWORD:<PASSWORD>END_PIm sa repeți parPI:PASSWORD:<PASSWORD>END_PI." keyboard_shortcuts: keyboard_shortcuts: "Scurtături Keyboard" space: "Space" enter: "Enter" # press_enter: "press enter" escape: "Escape" shift: "Shift" run_code: "Rulează codul." run_real_time: "Rulează în timp real." continue_script: "Continue past current script." skip_scripts: "Treci peste toate script-urile ce pot fi sărite." toggle_playback: "Comută play/pause." scrub_playback: "Mergi înainte si înapoi in timp." single_scrub_playback: "Mergi înainte si înapoi in timp cu un singur cadru." scrub_execution: "Mergi prin lista curentă de vrăji executate." toggle_debug: "Comută afișaj debug." toggle_grid: "Comută afișaj grilă." toggle_pathfinding: "Comută afișaj pathfinding." beautify: "Înfrumusețează codul standardizând formatarea lui." maximize_editor: "Mărește/Micește editorul." # cinematic: # click_anywhere_continue: "click anywhere to continue" community: main_title: "Comunitatea CodeCombat" introduction: "Vezi metode prin care poți să te implici și tu mai jos și decide să alegi ce ți se pare cel mai distractiv. Deabia așteptăm să lucrăm împreună!" level_editor_prefix: "Folosește CodeCombat" level_editor_suffix: "Pentru a crea și a edita nivele. Useri au creat nivele pentru clasele lor, prieteni, hackathonuri, studenți si rude. Dacă crearea unui nivel nou ți se pare intimidant poți sa modifici un nivel creat de noi!" thang_editor_prefix: "Numim unitățile din joc 'thangs'. Folosește" thang_editor_suffix: "pentru a modifica ilustrațile sursă CodeCombat. Permitele unitătilor sa arunce proiectile, schimbă direcția unei animații, schimbă viața unei unități, sau uploadează propiile sprite-uri vectoriale." article_editor_prefix: "Vezi o greșală in documentația noastă? Vrei să documentezi instrucțiuni pentru propiile creații? Vezi" article_editor_suffix: "si ajută jucători CodeCombat să obțină căt mai multe din playtime-ul lor." find_us: "Ne găsești pe aceste site-uri" # social_github: "Check out all our code on GitHub" social_blog: "Citește blogul CodeCombat pe Sett" social_discource: "Alăturăte discuțiilor pe forumul Discourse" social_facebook: "Lasă un Like pentru CodeCombat pe facebook" social_twitter: "Urmărește CodeCombat pe Twitter" # social_slack: "Chat with us in the public CodeCombat Slack channel" contribute_to_the_project: "Contribuie la proiect" 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: "Clan" clans: "Clanuri" new_name: "PI:NAME:<NAME>END_PI" new_description: "Descrierea clanului nou" make_private: "Fă clanul privat" subs_only: "numai abonați" create_clan: "Creează un clan Nou" # private_preview: "Preview" # private_clans: "Private Clans" public_clans: "Clanuri Publice" my_clans: "Clanurile mele" clan_name: "PI:NAME:<NAME>END_PIului" name: "PI:NAME:<NAME>END_PI" chieftain: "Chieftain" edit_clan_name: "Editează numele clanului" edit_clan_description: "Editează descrierea clanului" edit_name: "editează PI:NAME:<NAME>END_PI" edit_description: "editează descriere" private: "(privat)" summary: "Sumar" average_level: "Medie Level" average_achievements: "Medie Achievements" delete_clan: "Șterge Clan" leave_clan: "Pleacă din Clan" join_clan: "Intră în Clan" invite_1: "Invitație:" invite_2: "*Invită jucători in acest clan trimițându-le acest link." members: "MemPI:NAME:<NAME>END_PI" progress: "Progres" not_started_1: "neînceput" started_1: "început" complete_1: "complet" exp_levels: "Extinde nivele" rem_hero: "Șterge Eroul" status: "Stare" complete_2: "Complet" started_2: "Început" not_started_2: "Neînceput" view_solution: "Click pentru a vedea soluția." # view_attempt: "Click to view attempt." latest_achievement: "Ultimile Achievement-uri" playtime: "Timp Jucat" last_played: "Ultima oară cănd ai jucat" # leagues_explanation: "Play in a league against other clan members in these multiplayer arena instances." # track_concepts1: "Track concepts" # track_concepts2a: "learned by each student" # track_concepts2b: "learned by each member" # track_concepts3a: "Track levels completed for each student" # track_concepts3b: "Track levels completed for each member" # track_concepts4a: "See your students'" # track_concepts4b: "See your members'" # track_concepts5: "solutions" # track_concepts6a: "Sort students by name or progress" # track_concepts6b: "Sort members by name or progress" # track_concepts7: "Requires invitation" # track_concepts8: "to join" # private_require_sub: "Private clans require a subscription to create or join." # courses: # create_new_class: "Create New Class" # 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: "Level solutions are available for teachers who have licenses." # unnamed_class: "Unnamed Class" # edit_settings1: "Edit Class Settings" # add_students: "Add Students" # stats: "Statistics" # student_email_invite_blurb: "Your students can also use class code <strong>__classCode__</strong> when creating a Student Account, no email required." # total_students: "Total students:" # average_time: "Average level play time:" # total_time: "Total play time:" # average_levels: "Average levels completed:" # total_levels: "Total levels completed:" # students: "Students" # concepts: "Concepts" # play_time: "Play time:" # completed: "Completed:" # enter_emails: "Separate each email address by a line break or commas" # send_invites: "Invite Students" # number_programming_students: "Number of Programming Students" # number_total_students: "Total Students in School/District" # enroll: "Enroll" # enroll_paid: "Enroll Students in Paid Courses" # get_enrollments: "Get More Licenses" # change_language: "Change Course Language" # keep_using: "Keep Using" # switch_to: "Switch To" # greetings: "Greetings!" # back_classrooms: "Back to my classrooms" # back_classroom: "Back to classroom" # back_courses: "Back to my courses" # edit_details: "Edit class details" # purchase_enrollments: "Purchase Student Licenses" # remove_student: "remove student" # assign: "Assign" # to_assign: "to assign paid courses." # student: "Student" # teacher: "Teacher" # arena: "Arena" # available_levels: "Available Levels" # started: "started" # complete: "complete" # practice: "practice" # required: "required" # welcome_to_courses: "Adventurers, welcome to Courses!" # ready_to_play: "Ready to play?" # start_new_game: "Start New Game" # play_now_learn_header: "Play now to learn" # 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: "My Student Dashboard" # my_classes: "Current Classes" # class_added: "Class successfully added!" # view_map: "view map" # view_videos: "view videos" # view_project_gallery: "view my classmates' projects" # join_class: "Join A Class" # join_class_2: "Join class" # ask_teacher_for_code: "Ask your teacher if you have a CodeCombat class code! If so, enter it below:" # enter_c_code: "<Enter Class Code>" # join: "Join" # joining: "Joining class" # course_complete: "Course Complete" # play_arena: "Play Arena" # view_project: "View Project" # start: "Start" # last_level: "Last level played" # not_you: "Not you?" # continue_playing: "Continue Playing" # option1_header: "Invite Students by Email" # remove_student1: "Remove Student" # are_you_sure: "Are you sure you want to remove this student from this class?" # 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: "Keep Student" # removing_user: "Removing user" # subtitle: "Review course overviews and levels" # Flat style redesign # changelog: "View latest changes to course levels." # select_language: "Select language" # select_level: "Select level" # play_level: "Play Level" # concepts_covered: "Concepts covered" # view_guide_online: "Level Overviews and Solutions" # grants_lifetime_access: "Grants access to all Courses." # enrollment_credits_available: "Licenses Available:" # language_select: "Select a language" # ClassroomSettingsModal # language_cannot_change: "Language cannot be changed once students join a class." # avg_student_exp_label: "Average Student Programming Experience" # avg_student_exp_desc: "This will help us understand how to pace courses better." # avg_student_exp_select: "Select the best option" # avg_student_exp_none: "No Experience - little to no experience" # avg_student_exp_beginner: "Beginner - some exposure or block-based" # avg_student_exp_intermediate: "Intermediate - some experience with typed code" # avg_student_exp_advanced: "Advanced - extensive experience with typed code" # avg_student_exp_varied: "Varied Levels of Experience" # student_age_range_label: "Student Age Range" # student_age_range_younger: "Younger than 6" # student_age_range_older: "Older than 18" # student_age_range_to: "to" # 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: "Create Class" # class_name: "Class Name" # teacher_account_restricted: "Your account is a teacher account and cannot access student content." # account_restricted: "A student account is required to access this page." # update_account_login_title: "Log in to update your account" # update_account_title: "Your account needs attention!" # 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: "I am a teacher" # 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: "I am a student" # 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: "Select Your Hero" # select_your_hero_description: "You can always change your hero by going to your Courses page and clicking \"Change Hero\"" # select_this_hero: "Select this Hero" # current_hero: "Current Hero:" # current_hero_female: "Current Hero:" # 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: "You'll need to join a course to play this level." # 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: "Status:" # assessments: "Assessments" # challenges: "Challenges" # level_name: "Level Name:" # keep_trying: "Keep Trying" # start_challenge: "Start Challenge" # locked: "Locked" # concepts_used: "Concepts Used:" # 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: "Be the first to publish a project in this course!" # view_project: "View Project" # edit_project: "Edit Project" # teacher: # assigning_course: "Assigning course" # back_to_top: "Back to Top" # click_student_code: "Click on any level that the student has started or completed below to view the code they wrote." # code: "__name__'s Code" # complete_solution: "Complete Solution" # 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: "Partial Solution" # capstone_solution: "Capstone Solution" # removing_course: "Removing course" # 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: "__name__'s Student Code" # teacher_dashboard: "Teacher Dashboard" # Navbar # my_classes: "My Classes" # courses: "Course Guides" # enrollments: "Student Licenses" # resources: "Resources" # help: "Help" # language: "Language" # edit_class_settings: "edit class settings" # access_restricted: "Account Update Required" # teacher_account_required: "A teacher account is required to access this content." # create_teacher_account: "Create Teacher Account" # what_is_a_teacher_account: "What's a Teacher Account?" # 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: "Current Classes" # archived_classes: "Archived Classes" # archived_classes_blurb: "Classes can be archived for future reference. Unarchive a class to view it in the Current Classes list again." # view_class: "view class" # archive_class: "archive class" # unarchive_class: "unarchive class" # unarchive_this_class: "Unarchive this class" # no_students_yet: "This class has no students yet." # no_students_yet_view_class: "View class to add students." # try_refreshing: "(You may need to refresh the page)" # create_new_class: "Create a New Class" # class_overview: "Class Overview" # View Class page # avg_playtime: "Average level playtime" # total_playtime: "Total play time" # avg_completed: "Average levels completed" # total_completed: "Total levels completed" # created: "Created" # concepts_covered: "Concepts covered" # earliest_incomplete: "Earliest incomplete level" # latest_complete: "Latest completed level" # enroll_student: "Enroll student" # apply_license: "Apply License" # revoke_license: "Revoke License" # revoke_licenses: "Revoke All Licenses" # course_progress: "Course Progress" # not_applicable: "N/A" # edit: "edit" # edit_2: "Edit" # remove: "remove" # latest_completed: "Latest completed:" # sort_by: "Sort by" # progress: "Progress" # concepts_used: "Concepts used by Student:" # concept_checked: "Concept checked:" # completed: "Completed" # practice: "Practice" # started: "Started" # no_progress: "No progress" # not_required: "Not required" # view_student_code: "Click to view student code" # select_course: "Select course to view" # progress_color_key: "Progress color key:" # level_in_progress: "Level in Progress" # level_not_started: "Level Not Started" # project_or_arena: "Project or Arena" # students_not_assigned: "Students who have not been assigned {{courseName}}" # course_overview: "Course Overview" # copy_class_code: "Copy Class Code" # class_code_blurb: "Students can join your class using this Class Code. No email address is required when creating a Student account with this Class Code." # copy_class_url: "Copy Class URL" # class_join_url_blurb: "You can also post this unique class URL to a shared webpage." # add_students_manually: "Invite Students by Email" # bulk_assign: "Select course" # assigned_msg_1: "{{numberAssigned}} students were assigned {{courseName}}." # assigned_msg_2: "{{numberEnrolled}} licenses were applied." # assigned_msg_3: "You now have {{remainingSpots}} available licenses remaining." # assign_course: "Assign Course" # removed_course_msg: "{{numberRemoved}} students were removed from {{courseName}}." # remove_course: "Remove Course" # not_assigned_modal_title: "Courses were not assigned" # 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: "Enroll Selected Students" # no_students_selected: "No students were selected." # show_students_from: "Show students from" # Enroll students modal # apply_licenses_to_the_following_students: "Apply Licenses to the Following Students" # students_have_licenses: "The following students already have licenses applied:" # all_students: "All Students" # apply_licenses: "Apply Licenses" # not_enough_enrollments: "Not enough licenses available." # enrollments_blurb: "Students are required to have a license to access any content after the first course." # how_to_apply_licenses: "How to Apply Licenses" # export_student_progress: "Export Student Progress (CSV)" # send_email_to: "Send Recover Password Email to:" # email_sent: "Email sent" # send_recovery_email: "Send recovery email" # enter_new_password_below: "Enter new password below:" # change_password: "PI:PASSWORD:<PASSWORD>END_PI" # changed: "Changed" # available_credits: "Available Licenses" # pending_credits: "Pending Licenses" # empty_credits: "Exhausted Licenses" # license_remaining: "license remaining" # licenses_remaining: "licenses remaining" # one_license_used: "1 out of __totalLicenses__ licenses has been used" # num_licenses_used: "__numLicensesUsed__ out of __totalLicenses__ licenses have been used" # starter_licenses: "starter licenses" # start_date: "start date:" # end_date: "end date:" # get_enrollments_blurb: " We'll help you build a solution that meets the needs of your class, school or district." # 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: "Request Sent!" # assessments: "Assessments" # license_status: "License Status" # status_expired: "Expired on {{date}}" # status_not_enrolled: "Not Enrolled" # status_enrolled: "Expires on {{date}}" # select_all: "Select All" # project: "Project" # project_gallery: "Project Gallery" # view_project: "View Project" # unpublished: "(unpublished)" # view_arena_ladder: "View Arena Ladder" # resource_hub: "Resource Hub" # 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: "Additional guides coming soon!" # 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: "Overview" # student_details: "Student Details" # student_name: "PI:NAME:<NAME>END_PI" # no_name: "No name provided." # no_username: "No username provided." # no_email: "Student has no email address set." # student_profile: "Student Profile" # playtime_detail: "Playtime Detail" # student_completed: "Student Completed" # student_in_progress: "Student in Progress" # class_average: "Class Average" # not_assigned: "has not been assigned the following courses" # playtime_axis: "Playtime in Seconds" # levels_axis: "Levels in" # student_state: "How is" # student_state_2: "doing?" # 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: "Revoking..." # 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: "More Info" # 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: "Add Students" # 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: "Level:" # time_played_label: "Time Played:" # back_to_resource_hub: "Back to Resource Hub" # back_to_course_guides: "Back to Course Guides" # print_guide: "Print this guide" # 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: "Concept" # 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: "Share Licenses" # shared_by: "Shared By:" # add_teacher_label: "Enter exact teacher email:" # add_teacher_button: "Add Teacher" # 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." # have_not_shared: "You've not 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: "(you)" # one_license_used: "(1 license used)" # licenses_used: "(__licensesUsed__ licenses used)" # more_info: "More info" # sharing: # game: "Game" # webpage: "Webpage" # 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: "Share This Game" # share_web: "Share This Webpage" # victory_share_prefix: "Share this link to invite your friends & family to" # victory_share_prefix_short: "Invite people to" # victory_share_game: "play your game level" # victory_share_web: "view your webpage" # victory_share_suffix: "." # victory_course_share_prefix: "This link will let your friends & family" # victory_course_share_game: "play the game" # victory_course_share_web: "view the webpage" # victory_course_share_suffix: "you just created." # copy_url: "Copy URL" # share_with_teacher_email: "Send to your teacher" # game_dev: # creator: "PI:NAME:<NAME>END_PI" # web_dev: # image_gallery_title: "Image Gallery" # select_an_image: "Select an image you want to use" # scroll_down_for_more_images: "(Scroll down for more images)" # copy_the_url: "Copy the URL below" # copy_the_url_description: "Useful if you want to replace an existing image." # copy_the_img_tag: "Copy the <img> tag" # copy_the_img_tag_description: "Useful if you want to insert a new image." # copy_url: "Copy URL" # copy_img: "Copy <img>" # how_to_copy_paste: "How to Copy/Paste" # copy: "Copy" # paste: "Paste" # back_to_editing: "Back to Editing" classes: archmage_title: "Archmage" archmage_title_description: "(Programator)" archmage_summary: "Dacă ești un dezvoltator interesat să programezi jocuri educaționale, devino Archmage si ajută-ne să construim CodeCombat!" artisan_title: "Artizan" artisan_title_description: "(Creator de nivele)" artisan_summary: "Construiește si oferă nivele pentru tine si pentru prieteni tăi, ca să se joace. Devino Artisan si învață arta de a împărți cunoștințe despre programare." adventurer_title: "Aventurier" adventurer_title_description: "(Playtester de nivele)" adventurer_summary: "Primește nivelele noastre noi (chiar si cele pentru abonați) gratis cu o săptămână înainte si ajută-ne să reparăm bug-uri până la lansare." scribe_title: "PI:NAME:<NAME>END_PI" scribe_title_description: "(Editor de articole)" scribe_summary: "Un cod bun are nevoie de o documentație bună. Scrie, editează, si improvizează documentația citită de milioane de jucători în întreaga lume." diplomat_title: "Diplomat" diplomat_title_description: "(Translator)" diplomat_summary: "CodeCombat e localizat în 45+ de limbi de Diplomații noștri. Ajută-ne și contribuie la traducere." ambassador_title: "Ambasador" ambassador_title_description: "(Suport)" ambassador_summary: "Îmblânzește useri de pe forumul nostru si oferă direcți pentru cei cu întrebări. Ambasadori noștri reprezintă CodeCombat în fața lumii." # teacher_title: "Teacher" editor: main_title: "Editori CodeCombat" article_title: "Editor Articol" thang_title: "Editor Thang" level_title: "Editor Nivele" # course_title: "Course Editor" achievement_title: "Editor Achievement" poll_title: "Editor Sondaje" back: "Înapoi" revert: "Revino la versiunea anterioară" revert_models: "Resetează Modelele" pick_a_terrain: "Alege Terenul" dungeon: "Temniță" indoor: "Interior" desert: "Deșert" grassy: "Ierbos" # mountain: "Mountain" # glacier: "Glacier" small: "Mic" large: "Mare" fork_title: "Fork Versiune Nouă" fork_creating: "Creare Fork..." generate_terrain: "Generează Teren" more: "Mai Multe" wiki: "Wiki" live_chat: "Chat Live" thang_main: "Principal" thang_spritesheets: "Spritesheets" thang_colors: "Culori" level_some_options: "Opțiuni?" level_tab_thangs: "Thangs" level_tab_scripts: "Script-uri" level_tab_components: "Componente" level_tab_systems: "Sisteme" level_tab_docs: "Documentație" level_tab_thangs_title: "Thangs actuali" level_tab_thangs_all: "Toate" level_tab_thangs_conditions: "Condiți inițiale" level_tab_thangs_add: "Adaugă Thangs" # level_tab_thangs_search: "Search thangs" add_components: "Adaugă Componente" component_configs: "Configurarea Componentelor" config_thang: "Dublu click pentru a configura un thang" delete: "Șterge" duplicate: "Duplică" stop_duplicate: "Oprește Duplicarea" rotate: "Rotește" level_component_tab_title: "Componente actuale" level_component_btn_new: "Crează componentă nouă" level_systems_tab_title: "Sisteme actuale" level_systems_btn_new: "Crează sistem nou" level_systems_btn_add: "Adaugă Sistem" level_components_title: "Înapoi la toți Thangs" level_components_type: "Tip" level_component_edit_title: "Editează Componentă" level_component_config_schema: "Schema Config" level_system_edit_title: "Editează Sistem" create_system_title: "Crează sistem nou" new_component_title: "Crează componentă nouă" new_component_field_system: "Sistem" new_article_title: "Crează un articol nou" new_thang_title: "Crează un nou tip de Thang" new_level_title: "Crează un nivel nou" new_article_title_login: "Loghează-te pentru a crea un Articol Nou" new_thang_title_login: "Loghează-te pentru a crea un Thang de Tip Nou" new_level_title_login: "Loghează-te pentru a crea un Nivel Nou" new_achievement_title: "Crează un Achivement Nou" new_achievement_title_login: "Loghează-te pentru a crea un Achivement Nou" new_poll_title: "Crează un Sondaj Nou" new_poll_title_login: "Loghează-te pentru a crea un Sondaj Nou" article_search_title: "Caută articole aici" thang_search_title: "Caută tipuri de Thang aici" level_search_title: "Caută nivele aici" achievement_search_title: "Caută Achievements" poll_search_title: "Caută Sondaje" read_only_warning2: "Notă: nu poți salva editările aici, pentru că nu ești logat." no_achievements: "Nici-un achivement adăugat acestui nivel până acum." achievement_query_misc: "Key achievement din diverse" achievement_query_goals: "Key achievement din obiectivele nivelelor" level_completion: "Finalizare Nivel" pop_i18n: "Populează I18N" tasks: "Sarcini" clear_storage: "Șterge schimbările locale" # add_system_title: "Add Systems to Level" # done_adding: "Done Adding" article: edit_btn_preview: "Preview" edit_article_title: "Editează Articol" polls: priority: "Prioritate" contribute: page_title: "Contribuțtii" intro_blurb: "CodeCombat este 100% open source! Sute de jucători dedicați ne-au ajutat sa construim jocul în cea ce este astăzi. Alătură-te si scrie următorul capitol în aventura CodeCombat de a ajuta lumea să învețe cod!" # {change} alert_account_message_intro: "Salutare!" alert_account_message: "Pentru a te abona la mailurile clasei trebuie să fi logat." archmage_introduction: "Una dintre cele mai bune părți despre construirea unui joc este că sintetizează atât de multe lucruri diferite. Grafică, Sunet, Networking în timp real, Social Networking, și desigur multe dintre aspectele comune ale programării, de la gestiune low-level a bazelor de date, și administrare server până la construirea de interfețe. Este mult de muncă, și dacă ești un programator cu experiență, cu un dor de a se arunca cu capul înainte îm CodeCombat, această clasă ți se potrivește. Ne-ar plăcea să ne ajuți să construim cel mai bun joc de programare făcut vreodată." class_attributes: "Atribute pe clase" archmage_attribute_1_pref: "Cunoștințe în " archmage_attribute_1_suf: ", sau o dorință de a învăța. Majoritatea codului este în acest limbaj. Dacă ești fan Ruby sau Python, te vei simți ca acasă. Este JavaScript, dar cu o sintaxă mai frumoasă." archmage_attribute_2: "Ceva experiență în programare și inițiativă personală. Te vom ajuta să te orientezi, dar nu putem aloca prea mult timp pentru a te pregăti." how_to_join: "Cum să ni te alături" join_desc_1: "Oricine poate să ajute! Doar intrați pe " join_desc_2: "pentru a începe, bifați căsuța de dedesubt pentru a te marca ca un Archmage curajos și pentru a primi ultimele știri pe email. Vrei să discuți despre ce să faci sau cum să te implici mai mult? " join_desc_3: ", sau găsește-ne în " join_desc_4: "și pornim de acolo!" join_url_email: "Trimite-ne Email" # join_url_slack: "public Slack channel" archmage_subscribe_desc: "Primește email-uri despre noi oportunități de progrmare și anunțuri." artisan_introduction_pref: "Trebuie să construim nivele adiționale! Oamenii sunt nerăbdători pentru mai mult conținut, și noi putem face doar atât singuri. Momentan editorul de nivele abia este utilizabil până și de creatorii lui, așa că aveți grijă. Dacă ai viziuni cu campanii care cuprind loop-uri for pentru" artisan_introduction_suf: ", atunci aceasta ar fi clasa pentru tine." artisan_attribute_1: "Orice experiență în crearea de conținut ca acesta ar fi de preferat, precum folosirea editoarelor de nivele de la Blizzard. Dar nu este obligatoriu!" artisan_attribute_2: "Un chef de a face o mulțime de teste și iterări. Pentru a face nivele bune, trebuie să testați pe mai mulți oameni și să obțineți feedback, și să fiți pregăți să reparați o mulțime de lucruri." artisan_attribute_3: "Pentru moment trebui să ai nervi de oțel. Editorul nostru de nivele este abia la început și încă are multe probleme. Ai fost avertizat!" artisan_join_desc: "Folosiți editorul de nivele urmărind acești pași, mai mult sau mai puțin:" artisan_join_step1: "Citește documentația." artisan_join_step2: "Crează un nivel nou și explorează nivelele deja existente." artisan_join_step3: "Găsește-ne pe chatul nostru de Hipchat pentru ajutor." artisan_join_step4: "Postează nivelele tale pe forum pentru feedback." artisan_subscribe_desc: "Primește email-uri despre update-uri legate de Editorul de Nivele și anunțuri." adventurer_introduction: "Să fie clar ce implică rolul tău: tu ești tancul. Vei avea multe de îndurat. Avem nevoie de oameni care să testeze nivelele noi și să ne ajute să găsim moduri noi de a le îmbunătăți. Va fi greu; să creezi jocuri bune este un proces dificil și nimeni nu o face perfect din prima. Dacă crezi că poți îndura, atunci aceasta este clasa pentru tine." adventurer_attribute_1: "O sete de cunoaștere. Tu vrei să înveți cum să programezi și noi vrem să te învățăm. Cel mai probabil tu vei fi cel care va preda mai mult în acest caz." adventurer_attribute_2: "Carismatic. Formulează într-un mod clar ceea ce trebuie îmbunătățit și oferă sugestii." adventurer_join_pref: "Ori fă echipă (sau recrutează!) cu un Artizan și lucrează cu el, sau bifează căsuța de mai jos pentru a primi email când sunt noi nivele de testat. De asemenea vom posta despre nivele care trebuie revizuite pe rețelele noastre precum" adventurer_forum_url: "forumul nostru" adventurer_join_suf: "deci dacă preferi să fi înștiințat în acele moduri, înscrie-te acolo!" adventurer_subscribe_desc: "Primește email-uri când sunt noi nivele de testat." scribe_introduction_pref: "CodeCombat nu o să fie doar o colecție de nivele. Vor fi incluse resurse de cunoaștere, un wiki despre concepte de programare legate de fiecare nivel. În felul acesta fiecare Arisan nu trebuie să mai descrie în detaliu ce este un operator de comparație, ei pot să pună un link la un Articol mai bine documentat. Ceva asemănător cu ce " scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: " a construit. Dacă idea ta de distracție este să articulezi conceptele de programare în formă Markdown, această clasă ți s-ar potrivi." scribe_attribute_1: "Un talent în cuvinte este tot ce îți trebuie. Nu numai gramatică și ortografie, trebuie să poți să explici ideii complicate celorlați." contact_us_url: "Contactați-ne" # {change} scribe_join_description: "spune-ne câte ceva despre tine, experiențele tale despre programare și ce fel de lucruri ți-ar place să scri despre. Vom începe de acolo!." scribe_subscribe_desc: "Primește mailuri despre scrisul de articole." diplomat_introduction_pref: "Dacă ar fi un lucru care l-am învățat din " diplomat_launch_url: "lansarea din Octombire" diplomat_introduction_suf: "acesta ar fi că: există un interes mare pentru CodeCombat și în alte țări! Încercăm sa adunăm cât mai mulți translatori care sunt pregătiți să transforme un set de cuvinte intr-un alt set de cuvinte ca să facă CodeCombat cât mai accesibil în toată lumea. Dacă vrei să tragi cu ochiul la conțintul ce va apărea și să aduci nivele cât mai repede pentru conaționali tăi, această clasă ți se potriveste." diplomat_attribute_1: "Fluență în Engleză și limba în care vrei să traduci. Când explici ideii complicate este important să întelegi bine ambele limbi!" diplomat_i18n_page_prefix: "Poți începe să traduci nivele accesând" diplomat_i18n_page: "Pagina de traduceri" diplomat_i18n_page_suffix: ", sau interfața si website-ul pe GitHub." diplomat_join_pref_github: "Găsește fișierul pentru limba ta " diplomat_github_url: "pe GitHub" diplomat_join_suf_github: ", editeazăl online si trimite un pull request. Bifează căsuța de mai jos ca să fi up-to-date cu dezvoltările noastre internaționale!" diplomat_subscribe_desc: "Primește mail-uri despre dezvoltările i18n si niveluri de tradus." ambassador_introduction: "Aceasta este o comunitate pe care o construim, iar voi sunteți conexiunile. Avem forumui, email-uri, si rețele sociale cu mulți oameni cu care se poate vorbi despre joc și de la care se poate învața. Dacă vrei să ajuți oameni să se implice și să se distreze această clasă este potrivită pentru tine." ambassador_attribute_1: "Abilități de comunicare. Abilitatea de a indentifica problemele pe care jucătorii le au si șa îi poti ajuta. De asemenea, trebuie să ne informezi cu părerile jucătoriilor, ce le place și ce vor mai mult!" ambassador_join_desc: "spune-ne câte ceva despre tine, ce ai făcut si ce te interesează să faci. Vom porni de acolo!." ambassador_join_note_strong: "Notă" ambassador_join_note_desc: "Una din prioritățile noaste este să constrruim un joc multiplayer unde jucători noștri, dacă au probleme pot să cheme un wizard cu un nivel ridicat să îi ajute." ambassador_subscribe_desc: "Primește mailuri despre support updates și dezvoltări multiplayer." # teacher_subscribe_desc: "Get emails on updates and announcements for teachers." changes_auto_save: "Modificările sunt salvate automat când apeși checkbox-uri." diligent_scribes: "Scribii noștri:" powerful_archmages: "Bravii noștri Archmage:" creative_artisans: "Artizanii noștri creativi:" brave_adventurers: "Aventurierii noștri neînfricați:" translating_diplomats: "Diplomații noștri abili:" helpful_ambassadors: "Ambasadorii noștri de ajutor:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Jocurile mele" simulate: "Simulează" simulation_explanation: "Simulând jocuri poți afla poziția în clasament a jocului tău mai repede!" # simulation_explanation_leagues: "You will mainly help simulate games for allied players in your clans and courses." simulate_games: "Simulează Jocuri!" games_simulated_by: "Jocuri simulate de tine:" games_simulated_for: "Jocuri simulate pentru tine:" # games_in_queue: "Games currently in the queue:" games_simulated: "Jocuri simulate" games_played: "Jocuri jucate" ratio: "Rație" leaderboard: "Clasament" battle_as: "Luptă ca " summary_your: "Al tău " summary_matches: "Meciuri - " summary_wins: " Victorii, " summary_losses: " Înfrângeri" rank_no_code: "Nici un Cod nou pentru Clasament" rank_my_game: "Plasează-mi jocul in Clasament!" rank_submitting: "Se trimite..." rank_submitted: "Se trimite pentru Clasament" rank_failed: "A eșuat plasarea in clasament" rank_being_ranked: "Jocul se plasează in Clasament" rank_last_submitted: "trimis " help_simulate: "Ne ajuți simulând jocuri?" code_being_simulated: "Codul tău este simulat de alți jucători pentru clasament. Se va actualiza cum apar meciuri." no_ranked_matches_pre: "Nici un meci de clasament pentru " no_ranked_matches_post: " echipă! Joacă împotriva unor concurenți și revino apoi aici pentru a-ți plasa meciul in clasament." choose_opponent: "Alege un adversar" select_your_language: "Alege limbă!" tutorial_play: "Joacă Tutorial-ul" tutorial_recommended: "Recomandat dacă nu ai mai jucat niciodată înainte" tutorial_skip: "Sări peste Tutorial" tutorial_not_sure: "Nu ești sigur ce se întâmplă?" tutorial_play_first: "Joacă Tutorial-ul mai întâi." simple_ai: "AI simplu" # {change} warmup: "Încălzire" friends_playing: "Prieteni ce se Joacă" log_in_for_friends: "Loghează-te ca să joci cu prieteni tăi!" social_connect_blurb: "Conectează-te și joacă împotriva prietenilor tăi!" invite_friends_to_battle: "Invită-ți prieteni să se alăture bătăliei" fight: "Luptă!" watch_victory: "Vizualizează victoria" defeat_the: "Învinge" # watch_battle: "Watch the battle" tournament_started: ", a început" tournament_ends: "Turneul se termină" tournament_ended: "Turneul s-a terminat" tournament_rules: "Regulile Turneului" tournament_blurb: "Scrie cod, colectează aur, construiește armate, distruge inamici, câștigă premii, si îmbunătățeșteți cariera în turneul Lăcomiei de $40,000! Află detalii" tournament_blurb_criss_cross: "Caștigă pariuri, creează căi, păcălește-ți oponenți, strâange Pietre Prețioase, si îmbunătățeșteți cariera in turneul Criss-Cross! Află detalii" tournament_blurb_zero_sum: "Dezlănțuie creativitatea de programare în strângerea de aur sau în tactici de bătălie în alpine mirror match dintre vrăitori roșii și cei albaștrii.Turneul începe Vineri, 27 Martie și se va desfăsura până Luni, 6 Aprilie la 5PM PDT. Află detalii" # tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details" tournament_blurb_blog: "pe blogul nostru" rules: "Reguli" winners: "Învingători" # league: "League" # red_ai: "Red CPU" # "Red AI Wins", at end of multiplayer match playback # blue_ai: "Blue CPU" # wins: "Wins" # At end of multiplayer match playback # humans: "Red" # Ladder page display team name # ogres: "Blue" # 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: "Statistici" singleplayer_title: "Nivele Singleplayer" multiplayer_title: "Nivele Multiplayer" achievements_title: "Achievement-uri" last_played: "Ultima oară jucat" status: "Stare" status_completed: "Complet" status_unfinished: "Neterminat" no_singleplayer: "Nici-un joc Singleplayer jucat." no_multiplayer: "Nici-un joc Multiplayer jucat." no_achievements: "Nici-un Achivement câștigat." favorite_prefix: "Limbaj preferat" favorite_postfix: "." not_member_of_clans: "Nu ești membrul unui clan." # 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: "Ultimul câstigat" amount_achieved: "Sumă" achievement: "Achievement" current_xp_prefix: "" current_xp_postfix: " în total" new_xp_prefix: "" new_xp_postfix: " câștigat" left_xp_prefix: "" left_xp_infix: " până la level" 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: "Plăți" # prepaid_codes: "Prepaid Codes" purchased: "Cumpărate" # subscribe_for_gems: "Subscribe for gems" subscription: "Abonament" invoices: "Invoice-uri" service_apple: "Apple" service_web: "Web" paid_on: "Plătit pe" service: "Service" price: "Preț" gems: "Pietre Prețioase" active: "Activ" subscribed: "Abonat" unsubscribed: "Dezabonat" active_until: "Activ pPI:NAME:<NAME>END_PI" cost: "Cost" next_payment: "Următoarea Plată" card: "Card" status_unsubscribed_active: "Nu ești abonat si nu vei fi facturat, contul tău este activ deocamdată." status_unsubscribed: "Primește access la nivele noi, eroi, iteme, și Pietre Prețioase bonus cu un abonament CodeCombat!" # not_yet_verified: "Not yet verified." # resend_email: "Resend email" # email_sent: "Email sent! Check your inbox." # verifying_email: "Verifying your email address..." # successfully_verified: "You've successfully verified your email address!" # verify_error: "Something went wrong when verifying your email :(" # unsubscribe_from_marketing: "Unsubscribe __email__ from all CodeCombat marketing emails?" # unsubscribe_button: "Yes, unsubscribe" # unsubscribe_failed: "Failed" # unsubscribe_success: "Success" account_invoices: amount: "Sumă in dolari US" declined: "Cardul tău a fost refuzat" invalid_amount: "Introdu o sumă in dolari US." not_logged_in: "Logheazăte sau crează un cont pentru a accesa invoice-uri." pay: "Plată Invoice" purchasing: "Cumpăr..." retrying: "Eroare server, reîncerc." success: "Plătit cu success. Mulțumim!" # account_prepaid: # purchase_code: "Purchase a Subscription Code" # 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: "Users" # months: "Months" # purchase_total: "Total" # purchase_button: "Submit Purchase" # your_codes: "Your Codes" # redeem_codes: "Redeem a Subscription Code" # prepaid_code: "Prepaid Code" # lookup_code: "Lookup prepaid code" # apply_account: "Apply to your account" # copy_link: "You can copy the code's link and send it to someone." # quantity: "Quantity" # redeemed: "Redeemed" # no_codes: "No codes yet!" # you_can1: "You can" # you_can2: "purchase a prepaid code" # you_can3: "that can be applied to your own account or given to others." # 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 Bobby Duke 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: "Eroare la încărcarea pe server" # {change} connection_failure: "Conexiune eșuată." # connection_failure_desc: "It doesn’t look like you’re connected to the internet! Check your network connection and then reload this page." # login_required: "Login Required" # login_required_desc: "You need to be logged in to access this page." unauthorized: "Este nevoie să te loghezi. Ai cookies dezactivate?" forbidden: "Nu ai permisiune." # forbidden_desc: "Oh no, there’s nothing we can show you here! Make sure you’re logged into the correct account, or visit one of the links below to get back to programming!" # user_not_found: "User Not Found" not_found: "Nu a fost găsit." # not_found_desc: "Hm, there’s nothing here. Visit one of the following links to get back to programming!" not_allowed: "Metodă nepermisă." timeout: "Timeout Server." # {change} conflict: "Conflict resurse." bad_input: "Date greșite." server_error: "Eroare Server." unknown: "Eroare Necunoscută." # {change} # error: "ERROR" # general_desc: "Something went wrong, and it’s probably our fault. Try waiting a bit and then refreshing the page, or visit one of the following links to get back to programming!" resources: level: "Nivel" patch: "Patch" patches: "Patch-uri" system: "Sistem" systems: "Sisteme" component: "Componentă" components: "Componente" hero: "Erou" campaigns: "Campanii" # 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: "Arguments" # arithmetic: "Arithmetic" # 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: "Basic Syntax" # binary: "Binary" # 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: "Break Statements" # classes: "Classes" # continue_statements: "Continue Statements" # dom_events: "DOM Events" # dynamic_styling: "Dynamic Styling" # events: "Events" # 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: "Functions" # functions_parameters: "Parameters" # functions_multiple_parameters: "Multiple Parameters" # game_ai: "Game AI" # game_goals: "Game Goals" # game_spawn: "Game Spawn" # graphics: "Graphics" # graphs: "Graphs" # heaps: "Heaps" # if_condition: "Conditional If Statements" # if_else_if: "If/Else If Statements" # if_else_statements: "If/Else Statements" # if_statements: "If Statements" # 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: "Geometry" # math_operations: "Math Library Operations" # math_proportions: "Proportion Math" # math_trigonometry: "Trigonometry" # object_literals: "Object Literals" # parameters: "Parameters" # programs: "Programs" # properties: "Properties" # property_access: "Accessing Properties" # property_assignment: "Assigning Properties" # property_coordinate: "Coordinate Property" # queues: "Data Structures - Queues" # reading_docs: "Reading the Docs" # recursion: "Recursion" # return_statements: "Return Statements" # stacks: "Data Structures - Stacks" # strings: "Strings" # strings_concatenation: "String Concatenation" # strings_substrings: "Substring" # trees: "Data Structures - Trees" # variables: "Variables" # vectors: "Vectors" # while_condition_loops: "While Loops with Conditionals" # while_loops_simple: "While Loops" # while_loops_nested: "Nested While Loops" # xy_coordinates: "Coordinate Pairs" # advanced_strings: "Advanced Strings" # Rest of concepts are deprecated # algorithms: "Algorithms" # boolean_logic: "Boolean Logic" # basic_html: "Basic HTML" # basic_css: "Basic CSS" # basic_web_scripting: "Basic Web Scripting" # intermediate_html: "Intermediate HTML" # intermediate_css: "Intermediate CSS" # intermediate_web_scripting: "Intermediate Web Scripting" # advanced_html: "Advanced HTML" # advanced_css: "Advanced CSS" # advanced_web_scripting: "Advanced Web Scripting" # input_handling: "Input Handling" # while_loops: "While Loops" # place_game_objects: "Place game objects" # construct_mazes: "Construct mazes" # 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: "Basic JavaScript" # 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: "PI:NAME:<NAME>END_PI:" # enter_teacher_email: "Your teacher's email:" # teacher_email_placeholder: "PI:EMAIL:<EMAIL>END_PI" # student_name_placeholder: "type your name here" # teachers_section: "Teachers:" # students_section: "Students:" # teacher_notified: "We've notified your teacher that you want to play more CodeCombat in your classroom!" delta: added: "Adăugat" modified: "Modificat" # not_modified: "Not Modified" deleted: "Șters" moved_index: "Index Mutat" text_diff: "Diff Text" merge_conflict_with: "ÎBINĂ CONFLICTUL CU" no_changes: "PI:NAME:<NAME>END_PI" legal: page_title: "Aspecte Legale" # opensource_introduction: "CodeCombat is part of the open source community." opensource_description_prefix: "Vizitează " github_url: "pagina noastră de GitHub" opensource_description_center: "și ajută-ne dacă îți place! CodeCombat este construit peste o mulțime de proiecte open source, care noi le iubim. Vizitați" archmage_wiki_url: "Archmage wiki" opensource_description_suffix: "pentru o listă cu software-ul care fac acest joc posibil." practices_title: "Convenții" practices_description: "Acestea sunt promisiunile noastre către tine, jucătorul, fără așa mulți termeni legali." privacy_title: "Confidenţialitate şi termeni" privacy_description: "Nu o să iți vindem datele personale." security_title: "Securitate" security_description: "Ne străduim să vă protejăm informațiile personale. Fiind un proiect open-source, site-ul nostru oferă oricui posibilitatea de a ne revizui și îmbunătăți sistemul de securitate." email_title: "Email" email_description_prefix: "Noi nu vă vom inunda cu spam. Prin" email_settings_url: "setările tale de email" email_description_suffix: " sau prin link-urile din email-urile care vi le trimitem, puteți să schimbați preferințele și să vâ dezabonați oricând." cost_title: "Cost" # cost_description: "CodeCombat is free to play for all of its core levels, with a ${{price}} USD/mo subscription for access to extra level branches and {{gems}} bonus gems per month. You can cancel with a click, and we offer a 100% money-back guarantee." copyrights_title: "Drepturi de autor și licențe" contributor_title: "Acord de licență Contributor" contributor_description_prefix: "Toți contribuitorii, atât pe site cât și pe GitHub-ul nostru, sunt supuși la" cla_url: "ALC" contributor_description_suffix: "la care trebuie să fi de accord înainte să poți contribui." code_title: "Code - MIT" # {change} # 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: "MIT license" code_description_suffix: "Asta include tot codul din Systems și Components care este oferit de către CodeCombat cu scopul de a crea nivele." art_title: "Artă/Muzică - Conținut Comun " art_description_prefix: "Tot conținutul creativ/artistic este valabil sub" cc_license_url: "Creative Commons Attribution 4.0 International License" art_description_suffix: "Conținut comun este orice făcut general valabil de către CodeCombat cu scopul de a crea nivele. Asta include:" art_music: "Muzică" art_sound: "Sunet" art_artwork: "Artwork" art_sprites: "Sprites" art_other: "Orice si toate celelalte creații non-cod care sunt disponibile când se crează nivele." art_access: "Momentan nu există nici un sistem universal,ușor pentru preluarea acestor bunuri. În general, preluați-le precum site-ul din URL-urile folosite, contactați-ne pentru asistență, sau ajutați-ne sa extindem site-ul pentru a face aceste bunuri mai ușor accesibile." art_paragraph_1: "Pentru atribuire, vă rugăm numiți și lăsați referire link la codecombat.com unde este folosită sursa sau unde este adecvat pentru mediu. De exemplu:" use_list_1: "Dacă este folosit într-un film sau alt joc, includeți codecombat.com la credite." use_list_2: "Dacă este folosit pe un site, includeți un link in apropiere, de exemplu sub o imagine, sau in pagina generală de atribuiri unde menționați și alte Bunuri Creative și software open source folosit pe site. Ceva care face referință explicit la CodeCombat, precum o postare pe un blog care menționează CodeCombat, nu trebuie să se facă o atribuire separată." art_paragraph_2: "Dacă conținutul folosit nu este creat de către CodeCombat ci de către un utilizator al codecombat.com,atunci faceți referință către ei, și urmăriți indicațiile de atribuire prevăzute în descrierea resursei dacă există." rights_title: "Drepturi rezervate" rights_desc: "Toate drepturile sunt rezervate pentru Nivele în sine. Asta include" rights_scripts: "Script-uri" rights_unit: "Configurații de unități" rights_writings: "Scrieri" rights_media: "Media (sunete, muzică) și orice alt conținut creativ dezvoltat special pentru acel nivel care nu este valabil în mod normal pentru creat nivele." rights_clarification: "Pentru a clarifica, orice este valabil in Editorul de Nivele pentru scopul de a crea nivele se află sub CC, pe când conținutul creat cu Editorul de Nivele sau încărcat pentru a face nivelul nu se află." nutshell_title: "Pe scurt" nutshell_description: "Orice resurse vă punem la dispoziție în Editorul de Nivele puteți folosi liber cum vreți pentru a crea nivele. Dar ne rezervăm dreptul de a rezerva distribuția de nivele în sine (care sunt create pe codecombat.com) astfel încât să se poată percepe o taxă pentru ele pe vitor, dacă se va ajunge la așa ceva." # nutshell_see_also: "See also:" canonical: "Versiunea in engleză a acestui document este cea definitivă, versiunea canonică. Dacă există orice discrepanțe între traduceri, documentul in engleză are prioritate." # third_party_title: "Third Party Services" # third_party_description: "CodeCombat uses the following third party services (among others):" # cookies_message: "CodeCombat uses a few essential and non-essential cookies." # cookies_deny: "Decline non-essential cookies" ladder_prizes: title: "Premii Turnee" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Aceste premii se acordă în funcție de" blurb_2: "Regulile Turneului" blurb_3: "la jucători umani sau ogre de top." blurb_4: "Două echipe înseamnă dublul premiilor!" blurb_5: "(O să fie 2 câștigători pe primul loc, 2 pe locul 2, etc.)" rank: "Rank" prizes: "Premii" total_value: "Valoare Totala" in_cash: "în cash" custom_wizard: "Wizard CodeCombat personalizat" custom_avatar: "Avatar CodeCombat personalizat" heap: "pentru 6 luni de acces \"Startup\"" credits: "credite" one_month_coupon: "coupon: alege Rails sau HTML" one_month_discount: "discount, 30% off: choose either Rails or HTML" license: "licență" oreilly: "ebook la alegere" calendar: year: "An" day: "Zi" # month: "Month" january: "Ianuarie" # february: "February" # march: "March" # april: "April" # may: "May" # june: "June" # july: "July" # august: "August" # september: "September" # october: "October" # november: "November" # december: "December" # 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: "Email already taken" # username_taken: "Username already taken" # esper: # line_no: "Line $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: "Error: " # x_not_a_function: "$1 is not a function" # x_not_defined: "$1 is not defined" # 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: "Unexpected token" # unexpected_number: "Unexpected number" # 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: "Try `$1`" # there_is_no_function: "There is no function `$1`, but `$2` has a method `$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` has no method `$2`." # there_is_a_problem: "There is a problem with your code." # 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: "PI:NAME:<NAME>END_PI" # 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": "e = pp.scope {\n name: \"marvin gardens\"\n }\n ", "end": 6523, "score": 0.9998447299003601, "start": 6509, "tag": "NAME", "value": "marvin gardens" } ]
src/test/spec-parkplace.coffee
brekk/parkplace
0
assert = require 'assert' should = require 'should' _ = require 'lodash' pp = require '../lib/parkplace' (-> "use strict" try fixture = require './fixture.json' boardwalk = fixture.base mutableDef = fixture.definitions.mutable secretDef = fixture.definitions.secret readableDef = fixture.definitions.readable openDef = fixture.definitions.open writableDef = fixture.definitions.writable constantDef = fixture.definitions.constant guardedDef = fixture.definitions.guarded hiddenDef = fixture.definitions.hidden zoningCommittee = null # reusable tests itShouldBarfIf = (sentence, fx, negative=false)-> unless _.isString sentence throw new TypeError "Gimme a string for a sentence." unless _.isFunction fx throw new TypeError "Quit wasting time and gimme a function." negate = if negative then ' not' else '' it "should#{negate} throw an error if #{sentence}", ()-> if negative fx.should.not.throwError else fx.should.throwError itShouldNotBarfIf = (s, f, n=true)-> itShouldBarfIf s, f, n itShouldMaintainScope = ()-> itShouldBarfIf '.scope has not been called', ()-> pp.mutable 'test', 100 return itShouldRemainUnconfigurable = (prop)-> itShouldBarfIf 'configurable is false', ()-> pp.mutable prop, Math.random() * 2000 return itShouldRemainConfigurable = (prop)-> itShouldNotBarfIf 'configurable is false', ()-> pp.mutable prop, Math.random() * 2000 return itShouldNotBeWritable = (prop)-> itShouldBarfIf 'writable is false', ()-> boardwalk[prop] = Math.round Math.random() * 2000 itShouldBeWritable = (prop)-> itShouldNotBarfIf 'writable is true', ()-> boardwalk[prop] = Math.round Math.random() * 2000 itShouldNotBeEnumerable = (method, x)-> it 'should hide variables from enumerable scope', ()-> zoningCommittee[method] x.prop, x.value Object.keys(boardwalk).should.not.containEql x.prop boardwalk.propertyIsEnumerable(x.prop).should.eql false itShouldBeEnumerable = (method, x)-> it 'should show variables within enumerable scope', ()-> zoningCommittee[method] x.prop, x.value Object.keys(boardwalk).should.containEql x.prop boardwalk.propertyIsEnumerable(x.prop).should.eql true describe 'Parkplace', ()-> describe '.define', ()-> simple = {} it 'should be a method of Parkplace', ()-> pp.define.should.be.ok pp.define.should.be.a.Function it 'should define mutable properties with no other instructions', ()-> pp.define mutableDef.prop, mutableDef.value, null, simple simple.should.have.property mutableDef.prop simple.hasOwnProperty(mutableDef.prop).should.be.ok simple[mutableDef.prop].should.equal mutableDef.value (-> pp.define mutableDef.prop, Math.random()*10, null, simple ).should.not.throwError it 'should throw an error if no scope object is given and .scope is not called', ()-> (-> pp.define 'test', Math.random() * 10 ).should.throwError it 'should not throw an error if no scope object is given and .scope has been called', ()-> (-> zap = {} pzap = pp.scope zap pzap.define 'test', Math.random() * 10 ).should.not.throwError describe '.getSet', ()-> simple = {} it 'should be a method of Parkplace', ()-> pp.getSet.should.be.ok pp.getSet.should.be.a.Function it 'should define mutable getters and setters with no other instructions', ()-> rando = Math.round(Math.random() * 20000) + "KFBR392" pp.scope simple pp.getSet mutableDef.prop, { get: ()-> return rando } simple.should.have.property mutableDef.prop simple.hasOwnProperty(mutableDef.prop).should.be.ok simple[mutableDef.prop].should.equal rando (-> y = Math.round(Math.random() * 2000) pp.getSet mutableDef.prop, { set: (x)-> y = x return y + "KFBR392" get: ()-> return y + "KFBR392" } ).should.not.throwError describe '.scope', ()-> it 'should create a definer with a given scope', ()-> zoningCommittee = pp.scope boardwalk zoningCommittee.should.be.ok zoningCommittee.should.have.properties 'define', 'mutable', 'secret', 'writable', 'open', 'constant', 'guarded', 'writable' zoningCommittee.should.not.have.properties 'hidden', 'lookupHidden', 'scope' it 'should not leak definitions across scopes', ()-> zoningCommittee = pp.scope boardwalk zoningCommittee.mutable mutableDef.prop, mutableDef.value zoningCommittee.readable readableDef.prop, readableDef.value zoningCommittee.open openDef.prop, openDef.value zoningCommittee.writable writableDef.prop, writableDef.value zoningCommittee.constant constantDef.prop, constantDef.value zoningCommittee.guarded guardedDef.prop, guardedDef.value (-> someOtherZone = pp.scope { name: "marvin gardens" } someOtherZone.mutable mutableDef.prop, mutableDef.value someOtherZone.readable readableDef.prop, readableDef.value someOtherZone.open openDef.prop, openDef.value someOtherZone.writable writableDef.prop, writableDef.value someOtherZone.constant constantDef.prop, constantDef.value someOtherZone.guarded guardedDef.prop, guardedDef.value ).should.not.throwError (-> noFlexZone = pp.scope { name: "reading railroad" } noFlexZone.mutable mutableDef.prop, mutableDef.value noFlexZone.readable readableDef.prop, readableDef.value noFlexZone.open openDef.prop, openDef.value noFlexZone.writable writableDef.prop, writableDef.value noFlexZone.constant constantDef.prop, constantDef.value noFlexZone.guarded guardedDef.prop, guardedDef.value ).should.not.throwError it 'should add a .get and a .has method to the scoped definer', ()-> zoningCommittee.should.have.properties 'has', 'get' pp.should.not.have.properties 'has', 'get' describe '.mutable', ()-> # e: 1, w: 1, c: 1 itShouldMaintainScope() it 'should allow properties to be defined', ()-> zoningCommittee.mutable mutableDef.prop, mutableDef.value boardwalk[mutableDef.prop].should.be.ok itShouldNotBarfIf 'a property is redefined', ()-> zoningCommittee.mutable mutableDef.prop, 'zopzopzop' it 'should allow property definitions to be redefined', ()-> zoningCommittee.mutable mutableDef.prop, 'zopzopzop' boardwalk[mutableDef.prop].should.be.ok boardwalk[mutableDef.prop].should.eql 'zopzopzop' it 'should allow property values to be changed', ()-> hip3 = 'hiphiphip' boardwalk[mutableDef.prop] = hip3 boardwalk[mutableDef.prop].should.eql hip3 describe '.secret', ()-> # e: 0, w: 1, c: 0 itShouldMaintainScope() itShouldNotBeEnumerable 'secret', secretDef itShouldRemainUnconfigurable secretDef.value itShouldBeWritable secretDef.prop describe '.readable', ()-> # e: 1, w: 0, c: 0 itShouldMaintainScope() itShouldBeEnumerable 'readable', readableDef itShouldRemainUnconfigurable readableDef.value itShouldNotBeWritable readableDef.prop describe '.open ', ()-> # e: 1, w: 0, c: 1 itShouldMaintainScope() itShouldBeEnumerable 'open', openDef itShouldRemainConfigurable openDef.value itShouldNotBeWritable openDef.prop describe '.writable', ()-> # e: 1, w: 1, c: 0 itShouldMaintainScope() itShouldBeEnumerable 'writable', writableDef itShouldRemainConfigurable writableDef.prop itShouldBeWritable writableDef.prop describe '.constant', ()-> # e: 0, w: 0, c: 0 itShouldMaintainScope() itShouldNotBeEnumerable 'constant', constantDef itShouldRemainUnconfigurable writableDef.prop itShouldNotBeWritable writableDef.prop describe '.guarded', ()-> # e: 0, w: 0, c: 1 itShouldMaintainScope() itShouldNotBeEnumerable 'guarded', guardedDef itShouldNotBeWritable guardedDef.prop itShouldRemainConfigurable guardedDef.prop describe '.hidden', ()-> it 'should add hidden properties', ()-> pp.hidden hiddenDef.prop, hiddenDef.value describe '.scope().get', ()-> it 'should allow access to existing properties', ()-> x = zoningCommittee.get mutableDef.prop should(x).be.ok it 'should return null on non-extant properties', ()-> x = zoningCommittee.get 'jipjopple' should(x).not.be.ok should(x).eql null it 'should allow access to hidden scope', ()-> x = zoningCommittee.get hiddenDef.prop, true x.should.be.ok x.should.eql hiddenDef.value describe '.scope().has', ()-> it 'should return false on a non-present value', ()-> x = zoningCommittee.has 'whatevernonrealsies' (x).should.eql false it 'should return true on a present value', ()-> x = zoningCommittee.has hiddenDef.prop, true (x).should.be.ok describe '.lookupHidden', ()-> it 'should allow access to hidden values', ()-> x = pp.lookupHidden hiddenDef.prop x.should.be.ok x.should.eql hiddenDef.value catch e console.log "Error during testing!", e if e.stack? console.log e.stack ).call @
39262
assert = require 'assert' should = require 'should' _ = require 'lodash' pp = require '../lib/parkplace' (-> "use strict" try fixture = require './fixture.json' boardwalk = fixture.base mutableDef = fixture.definitions.mutable secretDef = fixture.definitions.secret readableDef = fixture.definitions.readable openDef = fixture.definitions.open writableDef = fixture.definitions.writable constantDef = fixture.definitions.constant guardedDef = fixture.definitions.guarded hiddenDef = fixture.definitions.hidden zoningCommittee = null # reusable tests itShouldBarfIf = (sentence, fx, negative=false)-> unless _.isString sentence throw new TypeError "Gimme a string for a sentence." unless _.isFunction fx throw new TypeError "Quit wasting time and gimme a function." negate = if negative then ' not' else '' it "should#{negate} throw an error if #{sentence}", ()-> if negative fx.should.not.throwError else fx.should.throwError itShouldNotBarfIf = (s, f, n=true)-> itShouldBarfIf s, f, n itShouldMaintainScope = ()-> itShouldBarfIf '.scope has not been called', ()-> pp.mutable 'test', 100 return itShouldRemainUnconfigurable = (prop)-> itShouldBarfIf 'configurable is false', ()-> pp.mutable prop, Math.random() * 2000 return itShouldRemainConfigurable = (prop)-> itShouldNotBarfIf 'configurable is false', ()-> pp.mutable prop, Math.random() * 2000 return itShouldNotBeWritable = (prop)-> itShouldBarfIf 'writable is false', ()-> boardwalk[prop] = Math.round Math.random() * 2000 itShouldBeWritable = (prop)-> itShouldNotBarfIf 'writable is true', ()-> boardwalk[prop] = Math.round Math.random() * 2000 itShouldNotBeEnumerable = (method, x)-> it 'should hide variables from enumerable scope', ()-> zoningCommittee[method] x.prop, x.value Object.keys(boardwalk).should.not.containEql x.prop boardwalk.propertyIsEnumerable(x.prop).should.eql false itShouldBeEnumerable = (method, x)-> it 'should show variables within enumerable scope', ()-> zoningCommittee[method] x.prop, x.value Object.keys(boardwalk).should.containEql x.prop boardwalk.propertyIsEnumerable(x.prop).should.eql true describe 'Parkplace', ()-> describe '.define', ()-> simple = {} it 'should be a method of Parkplace', ()-> pp.define.should.be.ok pp.define.should.be.a.Function it 'should define mutable properties with no other instructions', ()-> pp.define mutableDef.prop, mutableDef.value, null, simple simple.should.have.property mutableDef.prop simple.hasOwnProperty(mutableDef.prop).should.be.ok simple[mutableDef.prop].should.equal mutableDef.value (-> pp.define mutableDef.prop, Math.random()*10, null, simple ).should.not.throwError it 'should throw an error if no scope object is given and .scope is not called', ()-> (-> pp.define 'test', Math.random() * 10 ).should.throwError it 'should not throw an error if no scope object is given and .scope has been called', ()-> (-> zap = {} pzap = pp.scope zap pzap.define 'test', Math.random() * 10 ).should.not.throwError describe '.getSet', ()-> simple = {} it 'should be a method of Parkplace', ()-> pp.getSet.should.be.ok pp.getSet.should.be.a.Function it 'should define mutable getters and setters with no other instructions', ()-> rando = Math.round(Math.random() * 20000) + "KFBR392" pp.scope simple pp.getSet mutableDef.prop, { get: ()-> return rando } simple.should.have.property mutableDef.prop simple.hasOwnProperty(mutableDef.prop).should.be.ok simple[mutableDef.prop].should.equal rando (-> y = Math.round(Math.random() * 2000) pp.getSet mutableDef.prop, { set: (x)-> y = x return y + "KFBR392" get: ()-> return y + "KFBR392" } ).should.not.throwError describe '.scope', ()-> it 'should create a definer with a given scope', ()-> zoningCommittee = pp.scope boardwalk zoningCommittee.should.be.ok zoningCommittee.should.have.properties 'define', 'mutable', 'secret', 'writable', 'open', 'constant', 'guarded', 'writable' zoningCommittee.should.not.have.properties 'hidden', 'lookupHidden', 'scope' it 'should not leak definitions across scopes', ()-> zoningCommittee = pp.scope boardwalk zoningCommittee.mutable mutableDef.prop, mutableDef.value zoningCommittee.readable readableDef.prop, readableDef.value zoningCommittee.open openDef.prop, openDef.value zoningCommittee.writable writableDef.prop, writableDef.value zoningCommittee.constant constantDef.prop, constantDef.value zoningCommittee.guarded guardedDef.prop, guardedDef.value (-> someOtherZone = pp.scope { name: "<NAME>" } someOtherZone.mutable mutableDef.prop, mutableDef.value someOtherZone.readable readableDef.prop, readableDef.value someOtherZone.open openDef.prop, openDef.value someOtherZone.writable writableDef.prop, writableDef.value someOtherZone.constant constantDef.prop, constantDef.value someOtherZone.guarded guardedDef.prop, guardedDef.value ).should.not.throwError (-> noFlexZone = pp.scope { name: "reading railroad" } noFlexZone.mutable mutableDef.prop, mutableDef.value noFlexZone.readable readableDef.prop, readableDef.value noFlexZone.open openDef.prop, openDef.value noFlexZone.writable writableDef.prop, writableDef.value noFlexZone.constant constantDef.prop, constantDef.value noFlexZone.guarded guardedDef.prop, guardedDef.value ).should.not.throwError it 'should add a .get and a .has method to the scoped definer', ()-> zoningCommittee.should.have.properties 'has', 'get' pp.should.not.have.properties 'has', 'get' describe '.mutable', ()-> # e: 1, w: 1, c: 1 itShouldMaintainScope() it 'should allow properties to be defined', ()-> zoningCommittee.mutable mutableDef.prop, mutableDef.value boardwalk[mutableDef.prop].should.be.ok itShouldNotBarfIf 'a property is redefined', ()-> zoningCommittee.mutable mutableDef.prop, 'zopzopzop' it 'should allow property definitions to be redefined', ()-> zoningCommittee.mutable mutableDef.prop, 'zopzopzop' boardwalk[mutableDef.prop].should.be.ok boardwalk[mutableDef.prop].should.eql 'zopzopzop' it 'should allow property values to be changed', ()-> hip3 = 'hiphiphip' boardwalk[mutableDef.prop] = hip3 boardwalk[mutableDef.prop].should.eql hip3 describe '.secret', ()-> # e: 0, w: 1, c: 0 itShouldMaintainScope() itShouldNotBeEnumerable 'secret', secretDef itShouldRemainUnconfigurable secretDef.value itShouldBeWritable secretDef.prop describe '.readable', ()-> # e: 1, w: 0, c: 0 itShouldMaintainScope() itShouldBeEnumerable 'readable', readableDef itShouldRemainUnconfigurable readableDef.value itShouldNotBeWritable readableDef.prop describe '.open ', ()-> # e: 1, w: 0, c: 1 itShouldMaintainScope() itShouldBeEnumerable 'open', openDef itShouldRemainConfigurable openDef.value itShouldNotBeWritable openDef.prop describe '.writable', ()-> # e: 1, w: 1, c: 0 itShouldMaintainScope() itShouldBeEnumerable 'writable', writableDef itShouldRemainConfigurable writableDef.prop itShouldBeWritable writableDef.prop describe '.constant', ()-> # e: 0, w: 0, c: 0 itShouldMaintainScope() itShouldNotBeEnumerable 'constant', constantDef itShouldRemainUnconfigurable writableDef.prop itShouldNotBeWritable writableDef.prop describe '.guarded', ()-> # e: 0, w: 0, c: 1 itShouldMaintainScope() itShouldNotBeEnumerable 'guarded', guardedDef itShouldNotBeWritable guardedDef.prop itShouldRemainConfigurable guardedDef.prop describe '.hidden', ()-> it 'should add hidden properties', ()-> pp.hidden hiddenDef.prop, hiddenDef.value describe '.scope().get', ()-> it 'should allow access to existing properties', ()-> x = zoningCommittee.get mutableDef.prop should(x).be.ok it 'should return null on non-extant properties', ()-> x = zoningCommittee.get 'jipjopple' should(x).not.be.ok should(x).eql null it 'should allow access to hidden scope', ()-> x = zoningCommittee.get hiddenDef.prop, true x.should.be.ok x.should.eql hiddenDef.value describe '.scope().has', ()-> it 'should return false on a non-present value', ()-> x = zoningCommittee.has 'whatevernonrealsies' (x).should.eql false it 'should return true on a present value', ()-> x = zoningCommittee.has hiddenDef.prop, true (x).should.be.ok describe '.lookupHidden', ()-> it 'should allow access to hidden values', ()-> x = pp.lookupHidden hiddenDef.prop x.should.be.ok x.should.eql hiddenDef.value catch e console.log "Error during testing!", e if e.stack? console.log e.stack ).call @
true
assert = require 'assert' should = require 'should' _ = require 'lodash' pp = require '../lib/parkplace' (-> "use strict" try fixture = require './fixture.json' boardwalk = fixture.base mutableDef = fixture.definitions.mutable secretDef = fixture.definitions.secret readableDef = fixture.definitions.readable openDef = fixture.definitions.open writableDef = fixture.definitions.writable constantDef = fixture.definitions.constant guardedDef = fixture.definitions.guarded hiddenDef = fixture.definitions.hidden zoningCommittee = null # reusable tests itShouldBarfIf = (sentence, fx, negative=false)-> unless _.isString sentence throw new TypeError "Gimme a string for a sentence." unless _.isFunction fx throw new TypeError "Quit wasting time and gimme a function." negate = if negative then ' not' else '' it "should#{negate} throw an error if #{sentence}", ()-> if negative fx.should.not.throwError else fx.should.throwError itShouldNotBarfIf = (s, f, n=true)-> itShouldBarfIf s, f, n itShouldMaintainScope = ()-> itShouldBarfIf '.scope has not been called', ()-> pp.mutable 'test', 100 return itShouldRemainUnconfigurable = (prop)-> itShouldBarfIf 'configurable is false', ()-> pp.mutable prop, Math.random() * 2000 return itShouldRemainConfigurable = (prop)-> itShouldNotBarfIf 'configurable is false', ()-> pp.mutable prop, Math.random() * 2000 return itShouldNotBeWritable = (prop)-> itShouldBarfIf 'writable is false', ()-> boardwalk[prop] = Math.round Math.random() * 2000 itShouldBeWritable = (prop)-> itShouldNotBarfIf 'writable is true', ()-> boardwalk[prop] = Math.round Math.random() * 2000 itShouldNotBeEnumerable = (method, x)-> it 'should hide variables from enumerable scope', ()-> zoningCommittee[method] x.prop, x.value Object.keys(boardwalk).should.not.containEql x.prop boardwalk.propertyIsEnumerable(x.prop).should.eql false itShouldBeEnumerable = (method, x)-> it 'should show variables within enumerable scope', ()-> zoningCommittee[method] x.prop, x.value Object.keys(boardwalk).should.containEql x.prop boardwalk.propertyIsEnumerable(x.prop).should.eql true describe 'Parkplace', ()-> describe '.define', ()-> simple = {} it 'should be a method of Parkplace', ()-> pp.define.should.be.ok pp.define.should.be.a.Function it 'should define mutable properties with no other instructions', ()-> pp.define mutableDef.prop, mutableDef.value, null, simple simple.should.have.property mutableDef.prop simple.hasOwnProperty(mutableDef.prop).should.be.ok simple[mutableDef.prop].should.equal mutableDef.value (-> pp.define mutableDef.prop, Math.random()*10, null, simple ).should.not.throwError it 'should throw an error if no scope object is given and .scope is not called', ()-> (-> pp.define 'test', Math.random() * 10 ).should.throwError it 'should not throw an error if no scope object is given and .scope has been called', ()-> (-> zap = {} pzap = pp.scope zap pzap.define 'test', Math.random() * 10 ).should.not.throwError describe '.getSet', ()-> simple = {} it 'should be a method of Parkplace', ()-> pp.getSet.should.be.ok pp.getSet.should.be.a.Function it 'should define mutable getters and setters with no other instructions', ()-> rando = Math.round(Math.random() * 20000) + "KFBR392" pp.scope simple pp.getSet mutableDef.prop, { get: ()-> return rando } simple.should.have.property mutableDef.prop simple.hasOwnProperty(mutableDef.prop).should.be.ok simple[mutableDef.prop].should.equal rando (-> y = Math.round(Math.random() * 2000) pp.getSet mutableDef.prop, { set: (x)-> y = x return y + "KFBR392" get: ()-> return y + "KFBR392" } ).should.not.throwError describe '.scope', ()-> it 'should create a definer with a given scope', ()-> zoningCommittee = pp.scope boardwalk zoningCommittee.should.be.ok zoningCommittee.should.have.properties 'define', 'mutable', 'secret', 'writable', 'open', 'constant', 'guarded', 'writable' zoningCommittee.should.not.have.properties 'hidden', 'lookupHidden', 'scope' it 'should not leak definitions across scopes', ()-> zoningCommittee = pp.scope boardwalk zoningCommittee.mutable mutableDef.prop, mutableDef.value zoningCommittee.readable readableDef.prop, readableDef.value zoningCommittee.open openDef.prop, openDef.value zoningCommittee.writable writableDef.prop, writableDef.value zoningCommittee.constant constantDef.prop, constantDef.value zoningCommittee.guarded guardedDef.prop, guardedDef.value (-> someOtherZone = pp.scope { name: "PI:NAME:<NAME>END_PI" } someOtherZone.mutable mutableDef.prop, mutableDef.value someOtherZone.readable readableDef.prop, readableDef.value someOtherZone.open openDef.prop, openDef.value someOtherZone.writable writableDef.prop, writableDef.value someOtherZone.constant constantDef.prop, constantDef.value someOtherZone.guarded guardedDef.prop, guardedDef.value ).should.not.throwError (-> noFlexZone = pp.scope { name: "reading railroad" } noFlexZone.mutable mutableDef.prop, mutableDef.value noFlexZone.readable readableDef.prop, readableDef.value noFlexZone.open openDef.prop, openDef.value noFlexZone.writable writableDef.prop, writableDef.value noFlexZone.constant constantDef.prop, constantDef.value noFlexZone.guarded guardedDef.prop, guardedDef.value ).should.not.throwError it 'should add a .get and a .has method to the scoped definer', ()-> zoningCommittee.should.have.properties 'has', 'get' pp.should.not.have.properties 'has', 'get' describe '.mutable', ()-> # e: 1, w: 1, c: 1 itShouldMaintainScope() it 'should allow properties to be defined', ()-> zoningCommittee.mutable mutableDef.prop, mutableDef.value boardwalk[mutableDef.prop].should.be.ok itShouldNotBarfIf 'a property is redefined', ()-> zoningCommittee.mutable mutableDef.prop, 'zopzopzop' it 'should allow property definitions to be redefined', ()-> zoningCommittee.mutable mutableDef.prop, 'zopzopzop' boardwalk[mutableDef.prop].should.be.ok boardwalk[mutableDef.prop].should.eql 'zopzopzop' it 'should allow property values to be changed', ()-> hip3 = 'hiphiphip' boardwalk[mutableDef.prop] = hip3 boardwalk[mutableDef.prop].should.eql hip3 describe '.secret', ()-> # e: 0, w: 1, c: 0 itShouldMaintainScope() itShouldNotBeEnumerable 'secret', secretDef itShouldRemainUnconfigurable secretDef.value itShouldBeWritable secretDef.prop describe '.readable', ()-> # e: 1, w: 0, c: 0 itShouldMaintainScope() itShouldBeEnumerable 'readable', readableDef itShouldRemainUnconfigurable readableDef.value itShouldNotBeWritable readableDef.prop describe '.open ', ()-> # e: 1, w: 0, c: 1 itShouldMaintainScope() itShouldBeEnumerable 'open', openDef itShouldRemainConfigurable openDef.value itShouldNotBeWritable openDef.prop describe '.writable', ()-> # e: 1, w: 1, c: 0 itShouldMaintainScope() itShouldBeEnumerable 'writable', writableDef itShouldRemainConfigurable writableDef.prop itShouldBeWritable writableDef.prop describe '.constant', ()-> # e: 0, w: 0, c: 0 itShouldMaintainScope() itShouldNotBeEnumerable 'constant', constantDef itShouldRemainUnconfigurable writableDef.prop itShouldNotBeWritable writableDef.prop describe '.guarded', ()-> # e: 0, w: 0, c: 1 itShouldMaintainScope() itShouldNotBeEnumerable 'guarded', guardedDef itShouldNotBeWritable guardedDef.prop itShouldRemainConfigurable guardedDef.prop describe '.hidden', ()-> it 'should add hidden properties', ()-> pp.hidden hiddenDef.prop, hiddenDef.value describe '.scope().get', ()-> it 'should allow access to existing properties', ()-> x = zoningCommittee.get mutableDef.prop should(x).be.ok it 'should return null on non-extant properties', ()-> x = zoningCommittee.get 'jipjopple' should(x).not.be.ok should(x).eql null it 'should allow access to hidden scope', ()-> x = zoningCommittee.get hiddenDef.prop, true x.should.be.ok x.should.eql hiddenDef.value describe '.scope().has', ()-> it 'should return false on a non-present value', ()-> x = zoningCommittee.has 'whatevernonrealsies' (x).should.eql false it 'should return true on a present value', ()-> x = zoningCommittee.has hiddenDef.prop, true (x).should.be.ok describe '.lookupHidden', ()-> it 'should allow access to hidden values', ()-> x = pp.lookupHidden hiddenDef.prop x.should.be.ok x.should.eql hiddenDef.value catch e console.log "Error during testing!", e if e.stack? console.log e.stack ).call @
[ { "context": "scription various utility app directives\n# @author Michael Lin, Snaphappi Inc.\n#\n###\n\n\nangular.module('starter')", "end": 121, "score": 0.9969658851623535, "start": 110, "tag": "NAME", "value": "Michael Lin" } ]
app/js/services/app-directives.coffee
mixersoft/ionic-parse-facebook-scaffold
5
'use strict' ###* # @ngdoc directive # @name various # @description various utility app directives # @author Michael Lin, Snaphappi Inc. # ### angular.module('starter') .directive 'map', [ ()-> return { restrict: 'E', scope: { onCreate: '&' latlon: '=' # template: <map on-create="mapCreated(map)"" latlon="43.07493,-89.381388"></map> }, link: ($scope, $element, $attr)-> _map = null _initialize = ()-> # 43.07493, -89.381388 return if !$scope.latlon $scope.latlon = $scope.latlon.split(',') if _.isString $scope.latlon [lat,lon] = $scope.latlon # [lat,lon] = [43.07493, -89.381388] mapOptions = { center: new google.maps.LatLng(lat, lon), zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP } _map = new google.maps.Map($element[0], mapOptions) $scope.onCreate({map: _map}) # // Stop the side bar from dragging when mousedown/tapdown on the map google.maps.event.addDomListener $element[0], 'mousedown', (e)-> e.preventDefault(); return false; $scope.$watch 'latlon', (newVal, oldVal)-> return if !newVal return _initialize() if !_map newVal = newVal.split(',') if _.isString newVal [lat,lon] = newVal _map.setCenter(new google.maps.LatLng(lat, lon)) return if document.readyState == "complete" _initialize() else google.maps.event.addDomListener(window, 'load', _initialize); } ] .directive 'onImgLoad', ['$parse' , ($parse)-> # add ion-animation.scss spinnerMarkup = '<i class="icon ion-load-c ion-spin light"></i>' _clearGif = 'img/clear.gif' _handleLoad = (ev, photo, index)-> $elem = angular.element(ev.currentTarget) $elem.removeClass('loading') $elem.next().addClass('hide') onImgLoad = $elem.attr('on-img-load') fn = $parse(onImgLoad) scope = $elem.scope() scope.$apply ()-> fn scope, {$event: ev} return return _handleError = (ev)-> console.error "img.onerror, src="+ev.currentTarget.src return { restrict: 'A' link: (scope, $elem, attrs)-> # NOTE: using collection-repeat="item in items" attrs.$observe 'ng-src', ()-> $elem.addClass('loading') $elem.next().removeClass('hide') return $elem.on 'load', _handleLoad $elem.on 'error', _handleError scope.$on 'destroy', ()-> $elem.off _handleLoad $elem.off _handleError $elem.after(spinnerMarkup) return } ] .service 'PtrService', [ '$timeout' '$ionicScrollDelegate' ($timeout, $ionicScrollDelegate)-> ### * Trigger the pull-to-refresh on a specific scroll view delegate handle. * @param {string} delegateHandle - The `delegate-handle` assigned to the `ion-content` in the view. * see: https://calendee.com/2015/04/25/trigger-pull-to-refresh-in-ionic-framework-apps/ ### this.triggerPtr = (delegateHandle)-> $timeout ()-> scrollView = $ionicScrollDelegate.$getByHandle(delegateHandle).getScrollView(); return if (!scrollView) scrollView.__publish( scrollView.__scrollLeft, -scrollView.__refreshHeight, scrollView.__zoomLevel, true) scrollView.refreshStartTime = Date.now() scrollView.__refreshActive = true scrollView.__refreshHidden = false scrollView.__refreshShow() if scrollView.__refreshShow scrollView.__refreshActivate() if scrollView.__refreshActivate scrollView.__refreshStart() if scrollView.__refreshStart return ] .directive 'notify', ['notifyService' (notifyService)-> return { restrict: 'A' scope: true templateUrl: 'views/template/notify.html' link: (scope, element, attrs)-> scope.notify = notifyService if notifyService._cfg.debug window.debug.notify = notifyService return } ]
76826
'use strict' ###* # @ngdoc directive # @name various # @description various utility app directives # @author <NAME>, Snaphappi Inc. # ### angular.module('starter') .directive 'map', [ ()-> return { restrict: 'E', scope: { onCreate: '&' latlon: '=' # template: <map on-create="mapCreated(map)"" latlon="43.07493,-89.381388"></map> }, link: ($scope, $element, $attr)-> _map = null _initialize = ()-> # 43.07493, -89.381388 return if !$scope.latlon $scope.latlon = $scope.latlon.split(',') if _.isString $scope.latlon [lat,lon] = $scope.latlon # [lat,lon] = [43.07493, -89.381388] mapOptions = { center: new google.maps.LatLng(lat, lon), zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP } _map = new google.maps.Map($element[0], mapOptions) $scope.onCreate({map: _map}) # // Stop the side bar from dragging when mousedown/tapdown on the map google.maps.event.addDomListener $element[0], 'mousedown', (e)-> e.preventDefault(); return false; $scope.$watch 'latlon', (newVal, oldVal)-> return if !newVal return _initialize() if !_map newVal = newVal.split(',') if _.isString newVal [lat,lon] = newVal _map.setCenter(new google.maps.LatLng(lat, lon)) return if document.readyState == "complete" _initialize() else google.maps.event.addDomListener(window, 'load', _initialize); } ] .directive 'onImgLoad', ['$parse' , ($parse)-> # add ion-animation.scss spinnerMarkup = '<i class="icon ion-load-c ion-spin light"></i>' _clearGif = 'img/clear.gif' _handleLoad = (ev, photo, index)-> $elem = angular.element(ev.currentTarget) $elem.removeClass('loading') $elem.next().addClass('hide') onImgLoad = $elem.attr('on-img-load') fn = $parse(onImgLoad) scope = $elem.scope() scope.$apply ()-> fn scope, {$event: ev} return return _handleError = (ev)-> console.error "img.onerror, src="+ev.currentTarget.src return { restrict: 'A' link: (scope, $elem, attrs)-> # NOTE: using collection-repeat="item in items" attrs.$observe 'ng-src', ()-> $elem.addClass('loading') $elem.next().removeClass('hide') return $elem.on 'load', _handleLoad $elem.on 'error', _handleError scope.$on 'destroy', ()-> $elem.off _handleLoad $elem.off _handleError $elem.after(spinnerMarkup) return } ] .service 'PtrService', [ '$timeout' '$ionicScrollDelegate' ($timeout, $ionicScrollDelegate)-> ### * Trigger the pull-to-refresh on a specific scroll view delegate handle. * @param {string} delegateHandle - The `delegate-handle` assigned to the `ion-content` in the view. * see: https://calendee.com/2015/04/25/trigger-pull-to-refresh-in-ionic-framework-apps/ ### this.triggerPtr = (delegateHandle)-> $timeout ()-> scrollView = $ionicScrollDelegate.$getByHandle(delegateHandle).getScrollView(); return if (!scrollView) scrollView.__publish( scrollView.__scrollLeft, -scrollView.__refreshHeight, scrollView.__zoomLevel, true) scrollView.refreshStartTime = Date.now() scrollView.__refreshActive = true scrollView.__refreshHidden = false scrollView.__refreshShow() if scrollView.__refreshShow scrollView.__refreshActivate() if scrollView.__refreshActivate scrollView.__refreshStart() if scrollView.__refreshStart return ] .directive 'notify', ['notifyService' (notifyService)-> return { restrict: 'A' scope: true templateUrl: 'views/template/notify.html' link: (scope, element, attrs)-> scope.notify = notifyService if notifyService._cfg.debug window.debug.notify = notifyService return } ]
true
'use strict' ###* # @ngdoc directive # @name various # @description various utility app directives # @author PI:NAME:<NAME>END_PI, Snaphappi Inc. # ### angular.module('starter') .directive 'map', [ ()-> return { restrict: 'E', scope: { onCreate: '&' latlon: '=' # template: <map on-create="mapCreated(map)"" latlon="43.07493,-89.381388"></map> }, link: ($scope, $element, $attr)-> _map = null _initialize = ()-> # 43.07493, -89.381388 return if !$scope.latlon $scope.latlon = $scope.latlon.split(',') if _.isString $scope.latlon [lat,lon] = $scope.latlon # [lat,lon] = [43.07493, -89.381388] mapOptions = { center: new google.maps.LatLng(lat, lon), zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP } _map = new google.maps.Map($element[0], mapOptions) $scope.onCreate({map: _map}) # // Stop the side bar from dragging when mousedown/tapdown on the map google.maps.event.addDomListener $element[0], 'mousedown', (e)-> e.preventDefault(); return false; $scope.$watch 'latlon', (newVal, oldVal)-> return if !newVal return _initialize() if !_map newVal = newVal.split(',') if _.isString newVal [lat,lon] = newVal _map.setCenter(new google.maps.LatLng(lat, lon)) return if document.readyState == "complete" _initialize() else google.maps.event.addDomListener(window, 'load', _initialize); } ] .directive 'onImgLoad', ['$parse' , ($parse)-> # add ion-animation.scss spinnerMarkup = '<i class="icon ion-load-c ion-spin light"></i>' _clearGif = 'img/clear.gif' _handleLoad = (ev, photo, index)-> $elem = angular.element(ev.currentTarget) $elem.removeClass('loading') $elem.next().addClass('hide') onImgLoad = $elem.attr('on-img-load') fn = $parse(onImgLoad) scope = $elem.scope() scope.$apply ()-> fn scope, {$event: ev} return return _handleError = (ev)-> console.error "img.onerror, src="+ev.currentTarget.src return { restrict: 'A' link: (scope, $elem, attrs)-> # NOTE: using collection-repeat="item in items" attrs.$observe 'ng-src', ()-> $elem.addClass('loading') $elem.next().removeClass('hide') return $elem.on 'load', _handleLoad $elem.on 'error', _handleError scope.$on 'destroy', ()-> $elem.off _handleLoad $elem.off _handleError $elem.after(spinnerMarkup) return } ] .service 'PtrService', [ '$timeout' '$ionicScrollDelegate' ($timeout, $ionicScrollDelegate)-> ### * Trigger the pull-to-refresh on a specific scroll view delegate handle. * @param {string} delegateHandle - The `delegate-handle` assigned to the `ion-content` in the view. * see: https://calendee.com/2015/04/25/trigger-pull-to-refresh-in-ionic-framework-apps/ ### this.triggerPtr = (delegateHandle)-> $timeout ()-> scrollView = $ionicScrollDelegate.$getByHandle(delegateHandle).getScrollView(); return if (!scrollView) scrollView.__publish( scrollView.__scrollLeft, -scrollView.__refreshHeight, scrollView.__zoomLevel, true) scrollView.refreshStartTime = Date.now() scrollView.__refreshActive = true scrollView.__refreshHidden = false scrollView.__refreshShow() if scrollView.__refreshShow scrollView.__refreshActivate() if scrollView.__refreshActivate scrollView.__refreshStart() if scrollView.__refreshStart return ] .directive 'notify', ['notifyService' (notifyService)-> return { restrict: 'A' scope: true templateUrl: 'views/template/notify.html' link: (scope, element, attrs)-> scope.notify = notifyService if notifyService._cfg.debug window.debug.notify = notifyService return } ]
[ { "context": "type: CardType.Tile\n\t@type: CardType.Tile\n\tname: \"Tile\"\n\n\thp: 0\n\tmaxHP: 0\n\tmanaCost: 0\n\tisTargetable: fa", "end": 282, "score": 0.6139403581619263, "start": 278, "tag": "NAME", "value": "Tile" } ]
app/sdk/entities/tile.coffee
willroberts/duelyst
5
Logger = require 'app/common/logger' UtilsGameSession = require 'app/common/utils/utils_game_session' Entity = require './entity' CardType = require 'app/sdk/cards/cardType' _ = require 'underscore' class Tile extends Entity type: CardType.Tile @type: CardType.Tile name: "Tile" hp: 0 maxHP: 0 manaCost: 0 isTargetable: false isObstructing: false depleted: false dieOnDepleted: true # whether tile dies once used up obstructsOtherTiles: false canBeDispelled: true getPrivateDefaults: (gameSession) -> p = super(gameSession) p.occupant = null # current entity occupying tile p.occupantChangingAction = null # action that caused current unit to occupy tile return p getCanBeAppliedAnywhere: () -> return true silence: () -> if @canBeDispelled # silence/cleanse/dispel kills tiles @getGameSession().executeAction(@actionDie()) cleanse: @::silence dispel: @::silence # region OCCUPANT setOccupant: (occupant) -> if @_private.occupant != occupant @_private.occupant = occupant @_private.occupantChangingAction = @getGameSession().getExecutingAction() getOccupant: () -> return @_private.occupant getOccupantChangingAction: () -> return @_private.occupantChangingAction setDepleted: (depleted) -> @depleted = depleted if @depleted and @getDieOnDepleted() @getGameSession().executeAction(@actionDie()) getDepleted: () -> return @depleted getDieOnDepleted: ()-> return @dieOnDepleted # endregion OCCUPANT getObstructsOtherTiles: () -> return @obstructsOtherTiles module.exports = Tile
5145
Logger = require 'app/common/logger' UtilsGameSession = require 'app/common/utils/utils_game_session' Entity = require './entity' CardType = require 'app/sdk/cards/cardType' _ = require 'underscore' class Tile extends Entity type: CardType.Tile @type: CardType.Tile name: "<NAME>" hp: 0 maxHP: 0 manaCost: 0 isTargetable: false isObstructing: false depleted: false dieOnDepleted: true # whether tile dies once used up obstructsOtherTiles: false canBeDispelled: true getPrivateDefaults: (gameSession) -> p = super(gameSession) p.occupant = null # current entity occupying tile p.occupantChangingAction = null # action that caused current unit to occupy tile return p getCanBeAppliedAnywhere: () -> return true silence: () -> if @canBeDispelled # silence/cleanse/dispel kills tiles @getGameSession().executeAction(@actionDie()) cleanse: @::silence dispel: @::silence # region OCCUPANT setOccupant: (occupant) -> if @_private.occupant != occupant @_private.occupant = occupant @_private.occupantChangingAction = @getGameSession().getExecutingAction() getOccupant: () -> return @_private.occupant getOccupantChangingAction: () -> return @_private.occupantChangingAction setDepleted: (depleted) -> @depleted = depleted if @depleted and @getDieOnDepleted() @getGameSession().executeAction(@actionDie()) getDepleted: () -> return @depleted getDieOnDepleted: ()-> return @dieOnDepleted # endregion OCCUPANT getObstructsOtherTiles: () -> return @obstructsOtherTiles module.exports = Tile
true
Logger = require 'app/common/logger' UtilsGameSession = require 'app/common/utils/utils_game_session' Entity = require './entity' CardType = require 'app/sdk/cards/cardType' _ = require 'underscore' class Tile extends Entity type: CardType.Tile @type: CardType.Tile name: "PI:NAME:<NAME>END_PI" hp: 0 maxHP: 0 manaCost: 0 isTargetable: false isObstructing: false depleted: false dieOnDepleted: true # whether tile dies once used up obstructsOtherTiles: false canBeDispelled: true getPrivateDefaults: (gameSession) -> p = super(gameSession) p.occupant = null # current entity occupying tile p.occupantChangingAction = null # action that caused current unit to occupy tile return p getCanBeAppliedAnywhere: () -> return true silence: () -> if @canBeDispelled # silence/cleanse/dispel kills tiles @getGameSession().executeAction(@actionDie()) cleanse: @::silence dispel: @::silence # region OCCUPANT setOccupant: (occupant) -> if @_private.occupant != occupant @_private.occupant = occupant @_private.occupantChangingAction = @getGameSession().getExecutingAction() getOccupant: () -> return @_private.occupant getOccupantChangingAction: () -> return @_private.occupantChangingAction setDepleted: (depleted) -> @depleted = depleted if @depleted and @getDieOnDepleted() @getGameSession().executeAction(@actionDie()) getDepleted: () -> return @depleted getDieOnDepleted: ()-> return @dieOnDepleted # endregion OCCUPANT getObstructsOtherTiles: () -> return @obstructsOtherTiles module.exports = Tile
[ { "context": " expect(services.public).to.have.keys ['public1', 'publicServer']\n\n names = (obj.nam", "end": 8160, "score": 0.7468550801277161, "start": 8159, "tag": "KEY", "value": "1" } ]
spec/bijous-spec.coffee
mbrio/bijous
0
path = require 'path' fs = require 'fs' expect = require('chai').expect series = require 'array-series' sinon = require 'sinon' Bijous = require '../lib/bijous' findModule = (modules, name) -> return true for module in modules when module.name is name false describe 'Bijous', -> describe '#cwd', -> context 'when no cwd is specified', -> it 'should use the directory of the requiring module', -> bijous = new Bijous() expect(bijous.cwd).to.equal __dirname context 'when a cwd is specified', -> it 'should override the directory of the requiring module', -> src = path.join __dirname, 'src' expect(src).to.not.equal __dirname bijous = new Bijous { cwd: src } expect(bijous.cwd).to.equal src describe '#defaultBundleName', -> context 'when no defaultBundleName is specified', -> it 'should use the Bijous.defaultBundleName', -> bijous = new Bijous() expect(bijous.defaultBundleName).to.equal Bijous.defaultBundleName context 'when a defaultBundleName is specified', -> it 'should override the Bijous.defaultBundleName', -> cdbn = '$$' bijous = new Bijous defaultBundleName: cdbn expect(cdbn).to.not.equal Bijous.defaultBundleName expect(bijous.defaultBundleName).to.equal cdbn context 'when a falsy defaultBundleName is specified', -> it 'should use the Bijous.defaultBundleName', -> bijous = new Bijous defaultBundleName: null expect(bijous.defaultBundleName).to.equal Bijous.defaultBundleName describe '#bundles', -> context 'when no bundles are specified', -> it 'should use the default bundle pattern', -> bijous = new Bijous() expect(bijous.bundles).to.equal Bijous.defaultBundles context 'when bundles are specified', -> it 'should override the default bundle pattern', -> bundles = private: 'fixtures/modules/!(routes)' public: 'fixtures/public/!(routes)' expect(bundles).to.not.equal Bijous.defaultBundles bijous = new Bijous { bundles: bundles } expect(bijous.bundles).to.equal bundles describe '#list()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should find all modules for all bundles', -> bijous = new Bijous bundles: 'fixtures/modules/*' expect(bijous.list().files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' ] context 'and when specifying multiple bundles', -> it 'should find all modules for all bundles', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' expect(bijous.list().files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' 'fixtures/public/public1.coffee' 'fixtures/public/public2.coffee' 'fixtures/public/public-server.coffee' ] context 'when a bundle pattern is specified', -> it 'should find only modules pertaining to the specified bundle', -> bijous = new Bijous bundles: private: 'fixtures/modules/*', public: 'fixtures/public/*', empty: 'fixtures/empty/*' expect(bijous.list('private').files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' ] expect(bijous.list('public').files()).to.have.members [ 'fixtures/public/public1.coffee' 'fixtures/public/public2.coffee' 'fixtures/public/public-server.coffee' ] expect(bijous.list('empty').files()).to.be.empty describe '#require()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should require all modules for all bundles', -> bijous = new Bijous bundles: 'fixtures/modules/*' modules = (obj.name for obj in bijous.require()) expect(modules).to.have.members ['module1', 'module2', 'module3'] context 'and when specifying multiple bundles', -> it 'should require all modules for all bundles', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' modules = (obj.name for obj in bijous.require()) expect(modules).to.have.members [ 'module1', 'module2', 'module3', 'public1', 'public2', 'publicServer'] context 'when a bundle pattern is specified', -> it 'should require only modules pertaining to the specified bundle', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' modules = (obj.name for obj in bijous.require 'private') expect(modules).to.have.members [ 'module1', 'module2', 'module3'] modules = (obj.name for obj in bijous.require 'public') expect(modules).to.have.members [ 'public1', 'public2', 'publicServer'] modules = bijous.require 'empty' expect(modules).to.be.empty describe '#load()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should load all modules for all bundles', (done) -> bijous = new Bijous bundles: 'fixtures/modules/*' bijous.load (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services) expect(names).to.have.members ['module1', 'module2', 'module3'] done() context 'and when specifying multiple bundles', -> it 'should load all modules for all bundles', (done) -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' bijous.load (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['private', 'public'] expect(services.private).to.have.keys [ 'module1', 'module2', 'module3'] expect(services.public).to.have.keys ['public1', 'publicServer'] names = (obj.name for key, obj of services.private) expect(names).to.have.members ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services.public) expect(names).to.have.members ['public1', 'public-server'] done() context 'when a bundle pattern is specified', -> it 'should load all modules pertaining to a specific bundle', (done) -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' fns = [ (callback) -> bijous.load 'private', (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['private'] expect(services.private).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services.private) expect(names).to.have.members ['module1', 'module2', 'module3'] callback error (callback) -> bijous.load 'public', (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['public'] expect(services.public).to.have.keys ['public1', 'publicServer'] names = (obj.name for key, obj of services.public) expect(names).to.have.members ['public1', 'public-server'] callback error (callback) -> bijous.load 'empty', (error, services) -> expect(error).to.be.undefined expect(Object.keys(services)).to.be.empty callback error ] series fns, done context 'when an error occurs while loading a module', -> bijous = null beforeEach -> bijous = new Bijous { bundles: 'fixtures/errors/*' } context 'and when a callback is supplied', -> it 'should handle errors with callback', (done) -> bijous.load (error, services) -> expect(error).to.exist expect(Object.keys(services)).to.be.empty done() it 'should not emit the error event', (done) -> callback = sinon.spy() bijous.on 'error', callback bijous.load (error, services) -> cb = -> expect(callback.called).to.be.false done() setTimeout cb, 100 context 'and when no callback is supplied', -> it 'should emit the *error* event', (done) -> bijous.on 'error', (err) -> expect(err).to.exist expect(err.message).to.equal 'error1' done() bijous.load() context 'when an individual module has completed loading successfully', -> it 'should emit the *loaded* event and return any service', (done) -> bijous = new Bijous { bundles: 'fixtures/modules/*' } callback = sinon.spy() bijous.on 'loaded', callback bijous.load (error, services) -> expect(error).to.be.undefined expect(callback.calledThrice).to.be.true done() context 'when all modules have completed loading successfully', -> it 'should emit the *done* event and return any services', (done) -> bijous = new Bijous { bundles: 'fixtures/modules/*' } bijous.on 'done', (services) -> expect(services).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services) expect(names).to.have.members ['module1', 'module2', 'module3'] done() bijous.load()
66659
path = require 'path' fs = require 'fs' expect = require('chai').expect series = require 'array-series' sinon = require 'sinon' Bijous = require '../lib/bijous' findModule = (modules, name) -> return true for module in modules when module.name is name false describe 'Bijous', -> describe '#cwd', -> context 'when no cwd is specified', -> it 'should use the directory of the requiring module', -> bijous = new Bijous() expect(bijous.cwd).to.equal __dirname context 'when a cwd is specified', -> it 'should override the directory of the requiring module', -> src = path.join __dirname, 'src' expect(src).to.not.equal __dirname bijous = new Bijous { cwd: src } expect(bijous.cwd).to.equal src describe '#defaultBundleName', -> context 'when no defaultBundleName is specified', -> it 'should use the Bijous.defaultBundleName', -> bijous = new Bijous() expect(bijous.defaultBundleName).to.equal Bijous.defaultBundleName context 'when a defaultBundleName is specified', -> it 'should override the Bijous.defaultBundleName', -> cdbn = '$$' bijous = new Bijous defaultBundleName: cdbn expect(cdbn).to.not.equal Bijous.defaultBundleName expect(bijous.defaultBundleName).to.equal cdbn context 'when a falsy defaultBundleName is specified', -> it 'should use the Bijous.defaultBundleName', -> bijous = new Bijous defaultBundleName: null expect(bijous.defaultBundleName).to.equal Bijous.defaultBundleName describe '#bundles', -> context 'when no bundles are specified', -> it 'should use the default bundle pattern', -> bijous = new Bijous() expect(bijous.bundles).to.equal Bijous.defaultBundles context 'when bundles are specified', -> it 'should override the default bundle pattern', -> bundles = private: 'fixtures/modules/!(routes)' public: 'fixtures/public/!(routes)' expect(bundles).to.not.equal Bijous.defaultBundles bijous = new Bijous { bundles: bundles } expect(bijous.bundles).to.equal bundles describe '#list()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should find all modules for all bundles', -> bijous = new Bijous bundles: 'fixtures/modules/*' expect(bijous.list().files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' ] context 'and when specifying multiple bundles', -> it 'should find all modules for all bundles', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' expect(bijous.list().files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' 'fixtures/public/public1.coffee' 'fixtures/public/public2.coffee' 'fixtures/public/public-server.coffee' ] context 'when a bundle pattern is specified', -> it 'should find only modules pertaining to the specified bundle', -> bijous = new Bijous bundles: private: 'fixtures/modules/*', public: 'fixtures/public/*', empty: 'fixtures/empty/*' expect(bijous.list('private').files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' ] expect(bijous.list('public').files()).to.have.members [ 'fixtures/public/public1.coffee' 'fixtures/public/public2.coffee' 'fixtures/public/public-server.coffee' ] expect(bijous.list('empty').files()).to.be.empty describe '#require()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should require all modules for all bundles', -> bijous = new Bijous bundles: 'fixtures/modules/*' modules = (obj.name for obj in bijous.require()) expect(modules).to.have.members ['module1', 'module2', 'module3'] context 'and when specifying multiple bundles', -> it 'should require all modules for all bundles', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' modules = (obj.name for obj in bijous.require()) expect(modules).to.have.members [ 'module1', 'module2', 'module3', 'public1', 'public2', 'publicServer'] context 'when a bundle pattern is specified', -> it 'should require only modules pertaining to the specified bundle', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' modules = (obj.name for obj in bijous.require 'private') expect(modules).to.have.members [ 'module1', 'module2', 'module3'] modules = (obj.name for obj in bijous.require 'public') expect(modules).to.have.members [ 'public1', 'public2', 'publicServer'] modules = bijous.require 'empty' expect(modules).to.be.empty describe '#load()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should load all modules for all bundles', (done) -> bijous = new Bijous bundles: 'fixtures/modules/*' bijous.load (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services) expect(names).to.have.members ['module1', 'module2', 'module3'] done() context 'and when specifying multiple bundles', -> it 'should load all modules for all bundles', (done) -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' bijous.load (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['private', 'public'] expect(services.private).to.have.keys [ 'module1', 'module2', 'module3'] expect(services.public).to.have.keys ['public1', 'publicServer'] names = (obj.name for key, obj of services.private) expect(names).to.have.members ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services.public) expect(names).to.have.members ['public1', 'public-server'] done() context 'when a bundle pattern is specified', -> it 'should load all modules pertaining to a specific bundle', (done) -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' fns = [ (callback) -> bijous.load 'private', (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['private'] expect(services.private).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services.private) expect(names).to.have.members ['module1', 'module2', 'module3'] callback error (callback) -> bijous.load 'public', (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['public'] expect(services.public).to.have.keys ['public<KEY>', 'publicServer'] names = (obj.name for key, obj of services.public) expect(names).to.have.members ['public1', 'public-server'] callback error (callback) -> bijous.load 'empty', (error, services) -> expect(error).to.be.undefined expect(Object.keys(services)).to.be.empty callback error ] series fns, done context 'when an error occurs while loading a module', -> bijous = null beforeEach -> bijous = new Bijous { bundles: 'fixtures/errors/*' } context 'and when a callback is supplied', -> it 'should handle errors with callback', (done) -> bijous.load (error, services) -> expect(error).to.exist expect(Object.keys(services)).to.be.empty done() it 'should not emit the error event', (done) -> callback = sinon.spy() bijous.on 'error', callback bijous.load (error, services) -> cb = -> expect(callback.called).to.be.false done() setTimeout cb, 100 context 'and when no callback is supplied', -> it 'should emit the *error* event', (done) -> bijous.on 'error', (err) -> expect(err).to.exist expect(err.message).to.equal 'error1' done() bijous.load() context 'when an individual module has completed loading successfully', -> it 'should emit the *loaded* event and return any service', (done) -> bijous = new Bijous { bundles: 'fixtures/modules/*' } callback = sinon.spy() bijous.on 'loaded', callback bijous.load (error, services) -> expect(error).to.be.undefined expect(callback.calledThrice).to.be.true done() context 'when all modules have completed loading successfully', -> it 'should emit the *done* event and return any services', (done) -> bijous = new Bijous { bundles: 'fixtures/modules/*' } bijous.on 'done', (services) -> expect(services).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services) expect(names).to.have.members ['module1', 'module2', 'module3'] done() bijous.load()
true
path = require 'path' fs = require 'fs' expect = require('chai').expect series = require 'array-series' sinon = require 'sinon' Bijous = require '../lib/bijous' findModule = (modules, name) -> return true for module in modules when module.name is name false describe 'Bijous', -> describe '#cwd', -> context 'when no cwd is specified', -> it 'should use the directory of the requiring module', -> bijous = new Bijous() expect(bijous.cwd).to.equal __dirname context 'when a cwd is specified', -> it 'should override the directory of the requiring module', -> src = path.join __dirname, 'src' expect(src).to.not.equal __dirname bijous = new Bijous { cwd: src } expect(bijous.cwd).to.equal src describe '#defaultBundleName', -> context 'when no defaultBundleName is specified', -> it 'should use the Bijous.defaultBundleName', -> bijous = new Bijous() expect(bijous.defaultBundleName).to.equal Bijous.defaultBundleName context 'when a defaultBundleName is specified', -> it 'should override the Bijous.defaultBundleName', -> cdbn = '$$' bijous = new Bijous defaultBundleName: cdbn expect(cdbn).to.not.equal Bijous.defaultBundleName expect(bijous.defaultBundleName).to.equal cdbn context 'when a falsy defaultBundleName is specified', -> it 'should use the Bijous.defaultBundleName', -> bijous = new Bijous defaultBundleName: null expect(bijous.defaultBundleName).to.equal Bijous.defaultBundleName describe '#bundles', -> context 'when no bundles are specified', -> it 'should use the default bundle pattern', -> bijous = new Bijous() expect(bijous.bundles).to.equal Bijous.defaultBundles context 'when bundles are specified', -> it 'should override the default bundle pattern', -> bundles = private: 'fixtures/modules/!(routes)' public: 'fixtures/public/!(routes)' expect(bundles).to.not.equal Bijous.defaultBundles bijous = new Bijous { bundles: bundles } expect(bijous.bundles).to.equal bundles describe '#list()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should find all modules for all bundles', -> bijous = new Bijous bundles: 'fixtures/modules/*' expect(bijous.list().files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' ] context 'and when specifying multiple bundles', -> it 'should find all modules for all bundles', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' expect(bijous.list().files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' 'fixtures/public/public1.coffee' 'fixtures/public/public2.coffee' 'fixtures/public/public-server.coffee' ] context 'when a bundle pattern is specified', -> it 'should find only modules pertaining to the specified bundle', -> bijous = new Bijous bundles: private: 'fixtures/modules/*', public: 'fixtures/public/*', empty: 'fixtures/empty/*' expect(bijous.list('private').files()).to.have.members [ 'fixtures/modules/module1.coffee' 'fixtures/modules/module2.coffee' 'fixtures/modules/module3' ] expect(bijous.list('public').files()).to.have.members [ 'fixtures/public/public1.coffee' 'fixtures/public/public2.coffee' 'fixtures/public/public-server.coffee' ] expect(bijous.list('empty').files()).to.be.empty describe '#require()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should require all modules for all bundles', -> bijous = new Bijous bundles: 'fixtures/modules/*' modules = (obj.name for obj in bijous.require()) expect(modules).to.have.members ['module1', 'module2', 'module3'] context 'and when specifying multiple bundles', -> it 'should require all modules for all bundles', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' modules = (obj.name for obj in bijous.require()) expect(modules).to.have.members [ 'module1', 'module2', 'module3', 'public1', 'public2', 'publicServer'] context 'when a bundle pattern is specified', -> it 'should require only modules pertaining to the specified bundle', -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' modules = (obj.name for obj in bijous.require 'private') expect(modules).to.have.members [ 'module1', 'module2', 'module3'] modules = (obj.name for obj in bijous.require 'public') expect(modules).to.have.members [ 'public1', 'public2', 'publicServer'] modules = bijous.require 'empty' expect(modules).to.be.empty describe '#load()', -> context 'when no bundle pattern is specified', -> context 'and when specifying only one bundle', -> it 'should load all modules for all bundles', (done) -> bijous = new Bijous bundles: 'fixtures/modules/*' bijous.load (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services) expect(names).to.have.members ['module1', 'module2', 'module3'] done() context 'and when specifying multiple bundles', -> it 'should load all modules for all bundles', (done) -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' bijous.load (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['private', 'public'] expect(services.private).to.have.keys [ 'module1', 'module2', 'module3'] expect(services.public).to.have.keys ['public1', 'publicServer'] names = (obj.name for key, obj of services.private) expect(names).to.have.members ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services.public) expect(names).to.have.members ['public1', 'public-server'] done() context 'when a bundle pattern is specified', -> it 'should load all modules pertaining to a specific bundle', (done) -> bijous = new Bijous bundles: private: 'fixtures/modules/*' public: 'fixtures/public/*' empty: 'fixtures/empty/*' fns = [ (callback) -> bijous.load 'private', (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['private'] expect(services.private).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services.private) expect(names).to.have.members ['module1', 'module2', 'module3'] callback error (callback) -> bijous.load 'public', (error, services) -> expect(error).to.be.undefined expect(services).to.have.keys ['public'] expect(services.public).to.have.keys ['publicPI:KEY:<KEY>END_PI', 'publicServer'] names = (obj.name for key, obj of services.public) expect(names).to.have.members ['public1', 'public-server'] callback error (callback) -> bijous.load 'empty', (error, services) -> expect(error).to.be.undefined expect(Object.keys(services)).to.be.empty callback error ] series fns, done context 'when an error occurs while loading a module', -> bijous = null beforeEach -> bijous = new Bijous { bundles: 'fixtures/errors/*' } context 'and when a callback is supplied', -> it 'should handle errors with callback', (done) -> bijous.load (error, services) -> expect(error).to.exist expect(Object.keys(services)).to.be.empty done() it 'should not emit the error event', (done) -> callback = sinon.spy() bijous.on 'error', callback bijous.load (error, services) -> cb = -> expect(callback.called).to.be.false done() setTimeout cb, 100 context 'and when no callback is supplied', -> it 'should emit the *error* event', (done) -> bijous.on 'error', (err) -> expect(err).to.exist expect(err.message).to.equal 'error1' done() bijous.load() context 'when an individual module has completed loading successfully', -> it 'should emit the *loaded* event and return any service', (done) -> bijous = new Bijous { bundles: 'fixtures/modules/*' } callback = sinon.spy() bijous.on 'loaded', callback bijous.load (error, services) -> expect(error).to.be.undefined expect(callback.calledThrice).to.be.true done() context 'when all modules have completed loading successfully', -> it 'should emit the *done* event and return any services', (done) -> bijous = new Bijous { bundles: 'fixtures/modules/*' } bijous.on 'done', (services) -> expect(services).to.have.keys ['module1', 'module2', 'module3'] names = (obj.name for key, obj of services) expect(names).to.have.members ['module1', 'module2', 'module3'] done() bijous.load()
[ { "context": "mailAddress: @getAccount()\n password: @getPassword()\n success: (resp) =>\n cont", "end": 2762, "score": 0.8908627033233643, "start": 2750, "tag": "PASSWORD", "value": "@getPassword" }, { "context": " action: 'signup'\n ...
talk-account/client/app/signup.coffee
ikingye/talk-os
3,084
React = require 'react' Immutable = require 'immutable' ajax = require '../ajax' detect = require '../util/detect' locales = require '../locales' analytics = require '../util/analytics' controllers = require '../controllers' Space = React.createFactory require 'react-lite-space' MobileInput = React.createFactory require './mobile-input' VerifyMobile = React.createFactory require './verify-mobile' CaptchaIcons = React.createFactory require './captcha-icons' AccountSwitcher = React.createFactory require './account-switcher' ThirdpartyEntries = React.createFactory require './thirdparty-entries' {div, input, form, button, span, a} = React.DOM module.exports = React.createClass displayName: 'app-signup' propTypes: store: React.PropTypes.instanceOf(Immutable.Map).isRequired getInitialState: -> account = @getAccount() if detect.isQQEmail account error = locales.get 'warningAboutQQEmail', @getLanguage() tab: if (account[0] is '+') then 'mobile' else 'email' confirm: '' randomCode: null showVerifyMobile: false error: error or null captchaUid: null componentWillUnmount: -> @resetPassword() getAccount: -> @props.store.getIn ['client', 'account'] getPassword: -> @props.store.getIn ['client', 'password'] getLanguage: -> @props.store.getIn ['client', 'language'] isLoading: -> @props.store.getIn ['client', 'isLoading'] isAccountOk: -> detect.isEmail(@getAccount()) or detect.isMobile(@getAccount()) isPasswordOk: -> detect.isValidPassword(@getPassword()) isConfirmOk: -> @isPasswordOk() and (@getPassword() is @state.confirm) onAccountChange: (event) -> if detect.isQQEmail event.target.value error = locales.get 'warningAboutQQEmail', @getLanguage() @setState error: error or null controllers.updateAccount event.target.value onMobileAccountChange: (account) -> @setState error: null controllers.updateAccount account onPasswordChange: (event) -> @setState error: null controllers.updatePassword event.target.value onConfirmChange: (event) -> @setState error: null, confirm: event.target.value onRouteSignIn: (event) -> event.preventDefault() controllers.routeSignIn() onTabSwitch: (tab) -> @setState tab: tab error: null captchaUid: null @resetPassword() if tab is 'email' controllers.updateAccount '' else controllers.updateAccount '+86' onCaptchaSelect: (uid) -> @setState captchaUid: uid onSignUp: -> if @isConfirmOk() if @state.tab is 'email' if detect.isEmail @getAccount() ajax.emailSignUp data: emailAddress: @getAccount() password: @getPassword() success: (resp) => controllers.registerRedirectWithData('email') @setState error: null error: (err) => error = JSON.parse err.response @setState error: error.message analytics.registerError() else @setState error: locales.get('notEmail', @getLanguage()) else if @state.tab is 'mobile' if detect.isMobile @getAccount() if @state.captchaUid? ajax.mobileSendVerifyCode data: phoneNumber: @getAccount() action: 'signup' password: @getPassword() uid: @state.captchaUid success: (resp) => @setState error: null, randomCode: resp.randomCode, showVerifyMobile: true error: (err) => error = JSON.parse err.response @setState error: error.message else @setState error: locales.get('captchaIsRequired', @getLanguage()) else @setState error: locales.get('notPhoneNumber', @getLanguage()) else @setState error: locales.get('unknownAccountType', @getLanguage()) else @setState error: locales.get('passwordFormatWrong', @getLanguage()) onMobileVerify: (verifyCode) -> ajax.mobileSignInByVerifyCode data: randomCode: @state.randomCode verifyCode: verifyCode action: 'signin' success: (resp) => controllers.registerRedirectWithData('phone') @setState error: null error: (err) => error = JSON.parse err.response @setState error: error.message analytics.registerError() onBack: -> @setState showVerifyMobile: false onSubmit: (event) -> event.preventDefault() @onSignUp() renderOkIcon: -> span className: 'ok-icon icon icon-tick' renderVerifyMobile: -> VerifyMobile store: @props.store onResend: @onSignUp onVerify: @onMobileVerify onBack: @onBack error: @state.error isLoading: @isLoading() resetPassword: -> controllers.resetPassword() render: -> if @state.showVerifyMobile return @renderVerifyMobile() form className: 'app-signup control-panel', onSubmit: @onSubmit, AccountSwitcher tab: @state.tab, onSwitch: @onTabSwitch emailGuide: locales.get('signUpWithEmail', @getLanguage()) mobileGuide: locales.get('signUpWithMobile', @getLanguage()) Space height: 20 switch @state.tab when 'email' div className: 'as-line', input type: 'email', value: @getAccount(), onChange: @onAccountChange placeholder: locales.get('email', @getLanguage()) autoFocus: true if @isAccountOk() @renderOkIcon() when 'mobile' MobileInput language: @getLanguage() account: @getAccount(), onChange: @onMobileAccountChange autoFocus: true Space height: 10 div className: 'as-line', input type: 'password', value: @getPassword(), onChange: @onPasswordChange placeholder: locales.get('passwordNoShortThan6', @getLanguage()) if @isPasswordOk() @renderOkIcon() Space height: 10 div className: 'as-line', input type: 'password', value: @state.confirm, onChange: @onConfirmChange placeholder: locales.get('confirmPassword', @getLanguage()) if @isConfirmOk() @renderOkIcon() if @state.tab is 'mobile' div className: '', Space height: 10 CaptchaIcons lang: @getLanguage(), onSelect: @onCaptchaSelect, isDone: @state.captchaUid? Space height: 35 if @state.error? div className: 'as-line', span className: 'hint-error', @state.error Space height: 15 div className: 'as-line-filled', if @isLoading() button className: 'button is-primary is-disabled', locales.get('signUpJianliao', @getLanguage()) else button className: 'button is-primary', locales.get('signUpJianliao', @getLanguage()) Space height: 20 div className: 'as-line-centered', span className: 'text-guide', locales.get('alreadyHaveAccount', @getLanguage()) Space width: 5 a className: 'link-guide', onClick: @onRouteSignIn, locales.get('signIn', @getLanguage()) Space height: 120 ThirdpartyEntries language: @getLanguage()
33067
React = require 'react' Immutable = require 'immutable' ajax = require '../ajax' detect = require '../util/detect' locales = require '../locales' analytics = require '../util/analytics' controllers = require '../controllers' Space = React.createFactory require 'react-lite-space' MobileInput = React.createFactory require './mobile-input' VerifyMobile = React.createFactory require './verify-mobile' CaptchaIcons = React.createFactory require './captcha-icons' AccountSwitcher = React.createFactory require './account-switcher' ThirdpartyEntries = React.createFactory require './thirdparty-entries' {div, input, form, button, span, a} = React.DOM module.exports = React.createClass displayName: 'app-signup' propTypes: store: React.PropTypes.instanceOf(Immutable.Map).isRequired getInitialState: -> account = @getAccount() if detect.isQQEmail account error = locales.get 'warningAboutQQEmail', @getLanguage() tab: if (account[0] is '+') then 'mobile' else 'email' confirm: '' randomCode: null showVerifyMobile: false error: error or null captchaUid: null componentWillUnmount: -> @resetPassword() getAccount: -> @props.store.getIn ['client', 'account'] getPassword: -> @props.store.getIn ['client', 'password'] getLanguage: -> @props.store.getIn ['client', 'language'] isLoading: -> @props.store.getIn ['client', 'isLoading'] isAccountOk: -> detect.isEmail(@getAccount()) or detect.isMobile(@getAccount()) isPasswordOk: -> detect.isValidPassword(@getPassword()) isConfirmOk: -> @isPasswordOk() and (@getPassword() is @state.confirm) onAccountChange: (event) -> if detect.isQQEmail event.target.value error = locales.get 'warningAboutQQEmail', @getLanguage() @setState error: error or null controllers.updateAccount event.target.value onMobileAccountChange: (account) -> @setState error: null controllers.updateAccount account onPasswordChange: (event) -> @setState error: null controllers.updatePassword event.target.value onConfirmChange: (event) -> @setState error: null, confirm: event.target.value onRouteSignIn: (event) -> event.preventDefault() controllers.routeSignIn() onTabSwitch: (tab) -> @setState tab: tab error: null captchaUid: null @resetPassword() if tab is 'email' controllers.updateAccount '' else controllers.updateAccount '+86' onCaptchaSelect: (uid) -> @setState captchaUid: uid onSignUp: -> if @isConfirmOk() if @state.tab is 'email' if detect.isEmail @getAccount() ajax.emailSignUp data: emailAddress: @getAccount() password: <PASSWORD>() success: (resp) => controllers.registerRedirectWithData('email') @setState error: null error: (err) => error = JSON.parse err.response @setState error: error.message analytics.registerError() else @setState error: locales.get('notEmail', @getLanguage()) else if @state.tab is 'mobile' if detect.isMobile @getAccount() if @state.captchaUid? ajax.mobileSendVerifyCode data: phoneNumber: @getAccount() action: 'signup' password: <PASSWORD>() uid: @state.captchaUid success: (resp) => @setState error: null, randomCode: resp.randomCode, showVerifyMobile: true error: (err) => error = JSON.parse err.response @setState error: error.message else @setState error: locales.get('captchaIsRequired', @getLanguage()) else @setState error: locales.get('notPhoneNumber', @getLanguage()) else @setState error: locales.get('unknownAccountType', @getLanguage()) else @setState error: locales.get('passwordFormatWrong', @getLanguage()) onMobileVerify: (verifyCode) -> ajax.mobileSignInByVerifyCode data: randomCode: @state.randomCode verifyCode: verifyCode action: 'signin' success: (resp) => controllers.registerRedirectWithData('phone') @setState error: null error: (err) => error = JSON.parse err.response @setState error: error.message analytics.registerError() onBack: -> @setState showVerifyMobile: false onSubmit: (event) -> event.preventDefault() @onSignUp() renderOkIcon: -> span className: 'ok-icon icon icon-tick' renderVerifyMobile: -> VerifyMobile store: @props.store onResend: @onSignUp onVerify: @onMobileVerify onBack: @onBack error: @state.error isLoading: @isLoading() resetPassword: -> controllers.resetPassword() render: -> if @state.showVerifyMobile return @renderVerifyMobile() form className: 'app-signup control-panel', onSubmit: @onSubmit, AccountSwitcher tab: @state.tab, onSwitch: @onTabSwitch emailGuide: locales.get('signUpWithEmail', @getLanguage()) mobileGuide: locales.get('signUpWithMobile', @getLanguage()) Space height: 20 switch @state.tab when 'email' div className: 'as-line', input type: 'email', value: @getAccount(), onChange: @onAccountChange placeholder: locales.get('email', @getLanguage()) autoFocus: true if @isAccountOk() @renderOkIcon() when 'mobile' MobileInput language: @getLanguage() account: @getAccount(), onChange: @onMobileAccountChange autoFocus: true Space height: 10 div className: 'as-line', input type: 'password', value: @getPassword(), onChange: @onPasswordChange placeholder: locales.get('passwordNoShortThan6', @getLanguage()) if @isPasswordOk() @renderOkIcon() Space height: 10 div className: 'as-line', input type: 'password', value: @state.confirm, onChange: @onConfirmChange placeholder: locales.get('confirmPassword', @getLanguage()) if @isConfirmOk() @renderOkIcon() if @state.tab is 'mobile' div className: '', Space height: 10 CaptchaIcons lang: @getLanguage(), onSelect: @onCaptchaSelect, isDone: @state.captchaUid? Space height: 35 if @state.error? div className: 'as-line', span className: 'hint-error', @state.error Space height: 15 div className: 'as-line-filled', if @isLoading() button className: 'button is-primary is-disabled', locales.get('signUpJianliao', @getLanguage()) else button className: 'button is-primary', locales.get('signUpJianliao', @getLanguage()) Space height: 20 div className: 'as-line-centered', span className: 'text-guide', locales.get('alreadyHaveAccount', @getLanguage()) Space width: 5 a className: 'link-guide', onClick: @onRouteSignIn, locales.get('signIn', @getLanguage()) Space height: 120 ThirdpartyEntries language: @getLanguage()
true
React = require 'react' Immutable = require 'immutable' ajax = require '../ajax' detect = require '../util/detect' locales = require '../locales' analytics = require '../util/analytics' controllers = require '../controllers' Space = React.createFactory require 'react-lite-space' MobileInput = React.createFactory require './mobile-input' VerifyMobile = React.createFactory require './verify-mobile' CaptchaIcons = React.createFactory require './captcha-icons' AccountSwitcher = React.createFactory require './account-switcher' ThirdpartyEntries = React.createFactory require './thirdparty-entries' {div, input, form, button, span, a} = React.DOM module.exports = React.createClass displayName: 'app-signup' propTypes: store: React.PropTypes.instanceOf(Immutable.Map).isRequired getInitialState: -> account = @getAccount() if detect.isQQEmail account error = locales.get 'warningAboutQQEmail', @getLanguage() tab: if (account[0] is '+') then 'mobile' else 'email' confirm: '' randomCode: null showVerifyMobile: false error: error or null captchaUid: null componentWillUnmount: -> @resetPassword() getAccount: -> @props.store.getIn ['client', 'account'] getPassword: -> @props.store.getIn ['client', 'password'] getLanguage: -> @props.store.getIn ['client', 'language'] isLoading: -> @props.store.getIn ['client', 'isLoading'] isAccountOk: -> detect.isEmail(@getAccount()) or detect.isMobile(@getAccount()) isPasswordOk: -> detect.isValidPassword(@getPassword()) isConfirmOk: -> @isPasswordOk() and (@getPassword() is @state.confirm) onAccountChange: (event) -> if detect.isQQEmail event.target.value error = locales.get 'warningAboutQQEmail', @getLanguage() @setState error: error or null controllers.updateAccount event.target.value onMobileAccountChange: (account) -> @setState error: null controllers.updateAccount account onPasswordChange: (event) -> @setState error: null controllers.updatePassword event.target.value onConfirmChange: (event) -> @setState error: null, confirm: event.target.value onRouteSignIn: (event) -> event.preventDefault() controllers.routeSignIn() onTabSwitch: (tab) -> @setState tab: tab error: null captchaUid: null @resetPassword() if tab is 'email' controllers.updateAccount '' else controllers.updateAccount '+86' onCaptchaSelect: (uid) -> @setState captchaUid: uid onSignUp: -> if @isConfirmOk() if @state.tab is 'email' if detect.isEmail @getAccount() ajax.emailSignUp data: emailAddress: @getAccount() password: PI:PASSWORD:<PASSWORD>END_PI() success: (resp) => controllers.registerRedirectWithData('email') @setState error: null error: (err) => error = JSON.parse err.response @setState error: error.message analytics.registerError() else @setState error: locales.get('notEmail', @getLanguage()) else if @state.tab is 'mobile' if detect.isMobile @getAccount() if @state.captchaUid? ajax.mobileSendVerifyCode data: phoneNumber: @getAccount() action: 'signup' password: PI:PASSWORD:<PASSWORD>END_PI() uid: @state.captchaUid success: (resp) => @setState error: null, randomCode: resp.randomCode, showVerifyMobile: true error: (err) => error = JSON.parse err.response @setState error: error.message else @setState error: locales.get('captchaIsRequired', @getLanguage()) else @setState error: locales.get('notPhoneNumber', @getLanguage()) else @setState error: locales.get('unknownAccountType', @getLanguage()) else @setState error: locales.get('passwordFormatWrong', @getLanguage()) onMobileVerify: (verifyCode) -> ajax.mobileSignInByVerifyCode data: randomCode: @state.randomCode verifyCode: verifyCode action: 'signin' success: (resp) => controllers.registerRedirectWithData('phone') @setState error: null error: (err) => error = JSON.parse err.response @setState error: error.message analytics.registerError() onBack: -> @setState showVerifyMobile: false onSubmit: (event) -> event.preventDefault() @onSignUp() renderOkIcon: -> span className: 'ok-icon icon icon-tick' renderVerifyMobile: -> VerifyMobile store: @props.store onResend: @onSignUp onVerify: @onMobileVerify onBack: @onBack error: @state.error isLoading: @isLoading() resetPassword: -> controllers.resetPassword() render: -> if @state.showVerifyMobile return @renderVerifyMobile() form className: 'app-signup control-panel', onSubmit: @onSubmit, AccountSwitcher tab: @state.tab, onSwitch: @onTabSwitch emailGuide: locales.get('signUpWithEmail', @getLanguage()) mobileGuide: locales.get('signUpWithMobile', @getLanguage()) Space height: 20 switch @state.tab when 'email' div className: 'as-line', input type: 'email', value: @getAccount(), onChange: @onAccountChange placeholder: locales.get('email', @getLanguage()) autoFocus: true if @isAccountOk() @renderOkIcon() when 'mobile' MobileInput language: @getLanguage() account: @getAccount(), onChange: @onMobileAccountChange autoFocus: true Space height: 10 div className: 'as-line', input type: 'password', value: @getPassword(), onChange: @onPasswordChange placeholder: locales.get('passwordNoShortThan6', @getLanguage()) if @isPasswordOk() @renderOkIcon() Space height: 10 div className: 'as-line', input type: 'password', value: @state.confirm, onChange: @onConfirmChange placeholder: locales.get('confirmPassword', @getLanguage()) if @isConfirmOk() @renderOkIcon() if @state.tab is 'mobile' div className: '', Space height: 10 CaptchaIcons lang: @getLanguage(), onSelect: @onCaptchaSelect, isDone: @state.captchaUid? Space height: 35 if @state.error? div className: 'as-line', span className: 'hint-error', @state.error Space height: 15 div className: 'as-line-filled', if @isLoading() button className: 'button is-primary is-disabled', locales.get('signUpJianliao', @getLanguage()) else button className: 'button is-primary', locales.get('signUpJianliao', @getLanguage()) Space height: 20 div className: 'as-line-centered', span className: 'text-guide', locales.get('alreadyHaveAccount', @getLanguage()) Space width: 5 a className: 'link-guide', onClick: @onRouteSignIn, locales.get('signIn', @getLanguage()) Space height: 120 ThirdpartyEntries language: @getLanguage()
[ { "context": "for a standard project\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\n\nfs = require('fs')\n\n#\n# Preconverts coffe-sc", "end": 118, "score": 0.9998903870582581, "start": 101, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
cli/source.coffee
lovely-io/lovely.io-stl
2
# # This module handles source code compilation # for a standard project # # Copyright (C) 2011-2012 Nikolay Nemshilov # fs = require('fs') # # Preconverts coffe-script into javascript # # @param {String} CoffeeScript # @param {String} patch # @return {String} JavaScript # convert_from_coffee = (source, patch)-> if patch # hijacking the Coffee's class definitions and converting them in our classes source = source.replace /(\n\s*)class\s+([^\s]+)(\s+extends\s+([^\s]+))?/g, (match, start, Klass, smth, Super)-> if !Super then "#{start}#{Klass} = new Class" else "#{start}#{Klass} = new Class #{Super}," # replacing teh Coffee's 'super' calls with our own class calls source = source.replace /([^\w$\.])super(\(|\s)(.*?)([\)\n;])/g, (match, start, b1, params, b2)-> "#{start}this.$super(#{params});" # building the basic scripts source = require('coffee-script').compile(source, {bare: true}) # fixing coffee's void(0) hack back to `undefined` source.replace /([^a-z0-9\_]+)void\s+0([^a-z0-9]+)/ig, '$1undefined$2' # # Adds function names to the constructors so that # they appeared correctly in the debugging console # # @param {String} original # @return {String} patched # add_constructor_names = (source)-> source.replace /([a-zA-Z0-9_$]+)(\s*=\s*new\s+Class\()((.|\n)+?constructor:\s*function\s*\()/mg, (match, Klass, first, second)-> if second.indexOf('new Class') is -1 and second.match(/constructor:\s*function\s*\(/).length is 1 second = second.replace(/(constructor:\s*function)(\s*\()/, '$1 '+Klass.replace('.', '_')+'$2') "#{Klass}#{first}#{second}" else match.toString() # # Assembles the main source file and converts it into javascript # # @param {String} original coffeescript # @param {String} format name # @param {Boolean} patch for Lovely.IO module # @return {String} piece of javascript # assemble = (source, format, directory, patch)-> directory or= process.cwd() # inserting the related files source = source.replace /(\n([ \t]*))include[\(| ]+['"](.+?)['"](\);|\))?/mg, (m, start, spaces, filename) -> start + fs.readFileSync("#{directory}/#{filename}.#{format}") .toString().replace(/($|\n)/g, '$1'+spaces) + "\n\n" if format is 'coffee' then convert_from_coffee(source, patch) else source # # Builds the actual source code of the current project # # @param {String} package directory root # @param {Boolean} vanilla (non lovely.io) module build # @param {Boolean} send `true` if you don't want the styles to be emebedded in the build # @return {String} raw source code # compile = (directory, vanilla, no_style)-> directory or= process.cwd() options = require('./package').read(directory, vanilla) || {} format = if fs.existsSync("#{directory}/main.coffee") then 'coffee' else 'js' source = fs.readFileSync("#{directory}/main.#{format}").toString() # assembling the file with others source = assemble(source, format, directory, true) # adding the class names to the constructor functions source = add_constructor_names(source) # adding the package dependencies source = source.replace('%{version}', options.version) # vanilla, no lovely.io builds if vanilla || !options.name if options.name header = "/**\n * #{options.name}" header += " v#{options.version}" if options.version header += "\n *\n * #{options.description}" if options.description header += "\n *\n * Copyright (C) #{new Date().getFullYear()} #{options.author}" if options.author header += "\n */\n" else header = "" return header + """ (function (undefined) { #{source.replace(/(\n)/g, '$1 ')} }).apply(this); #{if no_style then '' else inline_css(directory, true)} """ # creating a standard AMD layout else if options.name is 'core' # core doesn't use AMD source = """ (function(undefined) { var global = this; #{source.replace(/(\n)/g, '$1 ')} }).apply(this) """ else # extracting the 'require' modules to make dependencies dependencies = [] source = source.replace /([^a-z0-9_\-\.])require\(('|")([^\.].+?)\2\)/ig, (match, start, quote, module)-> if options.dependencies and options.dependencies[module] module += "-#{options.dependencies[module]}" dependencies.push(module) unless module is 'core' # default core shouldn't be on the list return "#{start}Lovely.module('#{module}')" # adding the 'exports' object if /[^a-z0-9_\-\.]exports[^a-z0-9\_\-]/i.test(source) source = "var exports = {};\n\n"+ source; # adding the 'global' object if /[^a-z0-9_\-\.]global[^a-z0-9\_\-]/i.test(source) source = "var global = this;\n"+ source # creating the Lovely(....) definition module_name = options.name module_name+= "-#{options.version}" if options.version source = """ Lovely("#{module_name}", [#{"'#{name}'" for name in dependencies}], function() { var undefined = [][0]; #{source.replace(/(\n)/g, "$1 ")} #{if source.indexOf('var exports = {};') > -1 then "return exports;" else ""} }); #{if no_style then '' else inline_css(directory)} """ # creating a standard header block source = """ /** * lovely.io '#{options.name}' module v#{options.version} * * Copyright (C) #{new Date().getFullYear()} #{options.author} */ #{source} """ # # Minifies the source code # # @param {String} package directory root # @param {Boolean} vanilla (non lovely.io) module build # @param {Boolean} send `true` if you don't want the styles to be emebedded in the build # @return {String} minified source code # minify = (directory, vanilla, no_style)-> source = compile(directory, vanilla, no_style) ugly = require('uglify-js') build = ugly.parse(source) output = ugly.OutputStream() except = ['Class'] # extracting the exported class names so they didn't get mangled if match = source.match(/((ext\(\s*exports\s*,)|(\n\s+exports\s*=\s*))[^;]+?;/mg) for name in match[0].match(/[^a-zA-Z0-9_$][A-Z][a-zA-Z0-9_$]+/g) || [] except.push(name.substr(1)) if except.indexOf(name.substr(1)) is -1 build.figure_out_scope() build = build.transform(new ugly.Compressor(warnings: false)) build.figure_out_scope() build.compute_char_frequency() build.mangle_names(except: except) build.print(output) build = output.get() # fixing the ugly `'string'==` fuckups back to `'string' === ` build = build.replace(/("[a-z]+")(\!|=)=(typeof [a-z_$]+)/g, '$1$2==$3') # getting back the constructor names build = add_constructor_names(build) # copying the header over (source.match(/\/\*[\s\S]+?\*\/\s/m) || [''])[0] + build # # Converts various formats into vanilla CSS # # @param {String} original code # @param {String} format 'sass', 'scss', 'styl', 'css' # build_style = (style, format)-> if format in ['sass', 'styl'] require('stylus').render style, (err, css) -> if err then console.log(err) else style = css if format is 'scss' require('node-sass').render style, (err, css)-> if err then console.log(err) else style = css return style # # Embedds the styles as an inline javascript # # @param {String} package directory root # @return {String} inlined css # inline_css = (directory, not_lovely) -> for format in ['css', 'sass', 'styl', 'scss'] if fs.existsSync("#{directory}/main.#{format}") style = fs.readFileSync("#{directory}/main.#{format}").toString() break return "" if !style # minfigying the stylesheets style = build_style(style, format) # preserving IE hacks .replace(/\/\*\\\*\*\/:/g, '_ie8_s:') .replace(/\\9;/g, '_ie8_e;') # compacting the styles .replace(/\\/g, "\\\\") .replace(/\/\*[\S\s]*?\*\//img, '') .replace(/\n\s*\n/mg, "\n") .replace(/\s+/img, ' ') .replace(/\s*(\+|>|\||~|\{|\}|,|\)|\(|;|:|\*)\s*/img, '$1') .replace(/;\}/g, '}') .replace(/\)([^;}\s])/g, ') $1') .trim() # getting IE hacks back .replace(/([^\s])\*/g, '$1 *') .replace(/_ie8_s:/g, '/*\\\\**/:') .replace(/_ie8_e(;|})/g, '\\\\9$1') # escaping the quotes .replace(/"/g, '\\"') return "" if /^\s*$/.test(style) # no need to wrap an empty style """ // embedded css-styles (function() { var style = document.createElement('style'); var rules = document.createTextNode("#{style}"#{if not_lovely then '' else ".replace(/url\\(\"\\//g, 'url(\"'+ Lovely.hostUrl)"}); style.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(style); if (style.styleSheet) { style.styleSheet.cssText = rules.nodeValue; } else { style.appendChild(rules); } })(); """ exports.assemble = assemble exports.compile = compile exports.minify = minify exports.style = build_style
162920
# # This module handles source code compilation # for a standard project # # Copyright (C) 2011-2012 <NAME> # fs = require('fs') # # Preconverts coffe-script into javascript # # @param {String} CoffeeScript # @param {String} patch # @return {String} JavaScript # convert_from_coffee = (source, patch)-> if patch # hijacking the Coffee's class definitions and converting them in our classes source = source.replace /(\n\s*)class\s+([^\s]+)(\s+extends\s+([^\s]+))?/g, (match, start, Klass, smth, Super)-> if !Super then "#{start}#{Klass} = new Class" else "#{start}#{Klass} = new Class #{Super}," # replacing teh Coffee's 'super' calls with our own class calls source = source.replace /([^\w$\.])super(\(|\s)(.*?)([\)\n;])/g, (match, start, b1, params, b2)-> "#{start}this.$super(#{params});" # building the basic scripts source = require('coffee-script').compile(source, {bare: true}) # fixing coffee's void(0) hack back to `undefined` source.replace /([^a-z0-9\_]+)void\s+0([^a-z0-9]+)/ig, '$1undefined$2' # # Adds function names to the constructors so that # they appeared correctly in the debugging console # # @param {String} original # @return {String} patched # add_constructor_names = (source)-> source.replace /([a-zA-Z0-9_$]+)(\s*=\s*new\s+Class\()((.|\n)+?constructor:\s*function\s*\()/mg, (match, Klass, first, second)-> if second.indexOf('new Class') is -1 and second.match(/constructor:\s*function\s*\(/).length is 1 second = second.replace(/(constructor:\s*function)(\s*\()/, '$1 '+Klass.replace('.', '_')+'$2') "#{Klass}#{first}#{second}" else match.toString() # # Assembles the main source file and converts it into javascript # # @param {String} original coffeescript # @param {String} format name # @param {Boolean} patch for Lovely.IO module # @return {String} piece of javascript # assemble = (source, format, directory, patch)-> directory or= process.cwd() # inserting the related files source = source.replace /(\n([ \t]*))include[\(| ]+['"](.+?)['"](\);|\))?/mg, (m, start, spaces, filename) -> start + fs.readFileSync("#{directory}/#{filename}.#{format}") .toString().replace(/($|\n)/g, '$1'+spaces) + "\n\n" if format is 'coffee' then convert_from_coffee(source, patch) else source # # Builds the actual source code of the current project # # @param {String} package directory root # @param {Boolean} vanilla (non lovely.io) module build # @param {Boolean} send `true` if you don't want the styles to be emebedded in the build # @return {String} raw source code # compile = (directory, vanilla, no_style)-> directory or= process.cwd() options = require('./package').read(directory, vanilla) || {} format = if fs.existsSync("#{directory}/main.coffee") then 'coffee' else 'js' source = fs.readFileSync("#{directory}/main.#{format}").toString() # assembling the file with others source = assemble(source, format, directory, true) # adding the class names to the constructor functions source = add_constructor_names(source) # adding the package dependencies source = source.replace('%{version}', options.version) # vanilla, no lovely.io builds if vanilla || !options.name if options.name header = "/**\n * #{options.name}" header += " v#{options.version}" if options.version header += "\n *\n * #{options.description}" if options.description header += "\n *\n * Copyright (C) #{new Date().getFullYear()} #{options.author}" if options.author header += "\n */\n" else header = "" return header + """ (function (undefined) { #{source.replace(/(\n)/g, '$1 ')} }).apply(this); #{if no_style then '' else inline_css(directory, true)} """ # creating a standard AMD layout else if options.name is 'core' # core doesn't use AMD source = """ (function(undefined) { var global = this; #{source.replace(/(\n)/g, '$1 ')} }).apply(this) """ else # extracting the 'require' modules to make dependencies dependencies = [] source = source.replace /([^a-z0-9_\-\.])require\(('|")([^\.].+?)\2\)/ig, (match, start, quote, module)-> if options.dependencies and options.dependencies[module] module += "-#{options.dependencies[module]}" dependencies.push(module) unless module is 'core' # default core shouldn't be on the list return "#{start}Lovely.module('#{module}')" # adding the 'exports' object if /[^a-z0-9_\-\.]exports[^a-z0-9\_\-]/i.test(source) source = "var exports = {};\n\n"+ source; # adding the 'global' object if /[^a-z0-9_\-\.]global[^a-z0-9\_\-]/i.test(source) source = "var global = this;\n"+ source # creating the Lovely(....) definition module_name = options.name module_name+= "-#{options.version}" if options.version source = """ Lovely("#{module_name}", [#{"'#{name}'" for name in dependencies}], function() { var undefined = [][0]; #{source.replace(/(\n)/g, "$1 ")} #{if source.indexOf('var exports = {};') > -1 then "return exports;" else ""} }); #{if no_style then '' else inline_css(directory)} """ # creating a standard header block source = """ /** * lovely.io '#{options.name}' module v#{options.version} * * Copyright (C) #{new Date().getFullYear()} #{options.author} */ #{source} """ # # Minifies the source code # # @param {String} package directory root # @param {Boolean} vanilla (non lovely.io) module build # @param {Boolean} send `true` if you don't want the styles to be emebedded in the build # @return {String} minified source code # minify = (directory, vanilla, no_style)-> source = compile(directory, vanilla, no_style) ugly = require('uglify-js') build = ugly.parse(source) output = ugly.OutputStream() except = ['Class'] # extracting the exported class names so they didn't get mangled if match = source.match(/((ext\(\s*exports\s*,)|(\n\s+exports\s*=\s*))[^;]+?;/mg) for name in match[0].match(/[^a-zA-Z0-9_$][A-Z][a-zA-Z0-9_$]+/g) || [] except.push(name.substr(1)) if except.indexOf(name.substr(1)) is -1 build.figure_out_scope() build = build.transform(new ugly.Compressor(warnings: false)) build.figure_out_scope() build.compute_char_frequency() build.mangle_names(except: except) build.print(output) build = output.get() # fixing the ugly `'string'==` fuckups back to `'string' === ` build = build.replace(/("[a-z]+")(\!|=)=(typeof [a-z_$]+)/g, '$1$2==$3') # getting back the constructor names build = add_constructor_names(build) # copying the header over (source.match(/\/\*[\s\S]+?\*\/\s/m) || [''])[0] + build # # Converts various formats into vanilla CSS # # @param {String} original code # @param {String} format 'sass', 'scss', 'styl', 'css' # build_style = (style, format)-> if format in ['sass', 'styl'] require('stylus').render style, (err, css) -> if err then console.log(err) else style = css if format is 'scss' require('node-sass').render style, (err, css)-> if err then console.log(err) else style = css return style # # Embedds the styles as an inline javascript # # @param {String} package directory root # @return {String} inlined css # inline_css = (directory, not_lovely) -> for format in ['css', 'sass', 'styl', 'scss'] if fs.existsSync("#{directory}/main.#{format}") style = fs.readFileSync("#{directory}/main.#{format}").toString() break return "" if !style # minfigying the stylesheets style = build_style(style, format) # preserving IE hacks .replace(/\/\*\\\*\*\/:/g, '_ie8_s:') .replace(/\\9;/g, '_ie8_e;') # compacting the styles .replace(/\\/g, "\\\\") .replace(/\/\*[\S\s]*?\*\//img, '') .replace(/\n\s*\n/mg, "\n") .replace(/\s+/img, ' ') .replace(/\s*(\+|>|\||~|\{|\}|,|\)|\(|;|:|\*)\s*/img, '$1') .replace(/;\}/g, '}') .replace(/\)([^;}\s])/g, ') $1') .trim() # getting IE hacks back .replace(/([^\s])\*/g, '$1 *') .replace(/_ie8_s:/g, '/*\\\\**/:') .replace(/_ie8_e(;|})/g, '\\\\9$1') # escaping the quotes .replace(/"/g, '\\"') return "" if /^\s*$/.test(style) # no need to wrap an empty style """ // embedded css-styles (function() { var style = document.createElement('style'); var rules = document.createTextNode("#{style}"#{if not_lovely then '' else ".replace(/url\\(\"\\//g, 'url(\"'+ Lovely.hostUrl)"}); style.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(style); if (style.styleSheet) { style.styleSheet.cssText = rules.nodeValue; } else { style.appendChild(rules); } })(); """ exports.assemble = assemble exports.compile = compile exports.minify = minify exports.style = build_style
true
# # This module handles source code compilation # for a standard project # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # fs = require('fs') # # Preconverts coffe-script into javascript # # @param {String} CoffeeScript # @param {String} patch # @return {String} JavaScript # convert_from_coffee = (source, patch)-> if patch # hijacking the Coffee's class definitions and converting them in our classes source = source.replace /(\n\s*)class\s+([^\s]+)(\s+extends\s+([^\s]+))?/g, (match, start, Klass, smth, Super)-> if !Super then "#{start}#{Klass} = new Class" else "#{start}#{Klass} = new Class #{Super}," # replacing teh Coffee's 'super' calls with our own class calls source = source.replace /([^\w$\.])super(\(|\s)(.*?)([\)\n;])/g, (match, start, b1, params, b2)-> "#{start}this.$super(#{params});" # building the basic scripts source = require('coffee-script').compile(source, {bare: true}) # fixing coffee's void(0) hack back to `undefined` source.replace /([^a-z0-9\_]+)void\s+0([^a-z0-9]+)/ig, '$1undefined$2' # # Adds function names to the constructors so that # they appeared correctly in the debugging console # # @param {String} original # @return {String} patched # add_constructor_names = (source)-> source.replace /([a-zA-Z0-9_$]+)(\s*=\s*new\s+Class\()((.|\n)+?constructor:\s*function\s*\()/mg, (match, Klass, first, second)-> if second.indexOf('new Class') is -1 and second.match(/constructor:\s*function\s*\(/).length is 1 second = second.replace(/(constructor:\s*function)(\s*\()/, '$1 '+Klass.replace('.', '_')+'$2') "#{Klass}#{first}#{second}" else match.toString() # # Assembles the main source file and converts it into javascript # # @param {String} original coffeescript # @param {String} format name # @param {Boolean} patch for Lovely.IO module # @return {String} piece of javascript # assemble = (source, format, directory, patch)-> directory or= process.cwd() # inserting the related files source = source.replace /(\n([ \t]*))include[\(| ]+['"](.+?)['"](\);|\))?/mg, (m, start, spaces, filename) -> start + fs.readFileSync("#{directory}/#{filename}.#{format}") .toString().replace(/($|\n)/g, '$1'+spaces) + "\n\n" if format is 'coffee' then convert_from_coffee(source, patch) else source # # Builds the actual source code of the current project # # @param {String} package directory root # @param {Boolean} vanilla (non lovely.io) module build # @param {Boolean} send `true` if you don't want the styles to be emebedded in the build # @return {String} raw source code # compile = (directory, vanilla, no_style)-> directory or= process.cwd() options = require('./package').read(directory, vanilla) || {} format = if fs.existsSync("#{directory}/main.coffee") then 'coffee' else 'js' source = fs.readFileSync("#{directory}/main.#{format}").toString() # assembling the file with others source = assemble(source, format, directory, true) # adding the class names to the constructor functions source = add_constructor_names(source) # adding the package dependencies source = source.replace('%{version}', options.version) # vanilla, no lovely.io builds if vanilla || !options.name if options.name header = "/**\n * #{options.name}" header += " v#{options.version}" if options.version header += "\n *\n * #{options.description}" if options.description header += "\n *\n * Copyright (C) #{new Date().getFullYear()} #{options.author}" if options.author header += "\n */\n" else header = "" return header + """ (function (undefined) { #{source.replace(/(\n)/g, '$1 ')} }).apply(this); #{if no_style then '' else inline_css(directory, true)} """ # creating a standard AMD layout else if options.name is 'core' # core doesn't use AMD source = """ (function(undefined) { var global = this; #{source.replace(/(\n)/g, '$1 ')} }).apply(this) """ else # extracting the 'require' modules to make dependencies dependencies = [] source = source.replace /([^a-z0-9_\-\.])require\(('|")([^\.].+?)\2\)/ig, (match, start, quote, module)-> if options.dependencies and options.dependencies[module] module += "-#{options.dependencies[module]}" dependencies.push(module) unless module is 'core' # default core shouldn't be on the list return "#{start}Lovely.module('#{module}')" # adding the 'exports' object if /[^a-z0-9_\-\.]exports[^a-z0-9\_\-]/i.test(source) source = "var exports = {};\n\n"+ source; # adding the 'global' object if /[^a-z0-9_\-\.]global[^a-z0-9\_\-]/i.test(source) source = "var global = this;\n"+ source # creating the Lovely(....) definition module_name = options.name module_name+= "-#{options.version}" if options.version source = """ Lovely("#{module_name}", [#{"'#{name}'" for name in dependencies}], function() { var undefined = [][0]; #{source.replace(/(\n)/g, "$1 ")} #{if source.indexOf('var exports = {};') > -1 then "return exports;" else ""} }); #{if no_style then '' else inline_css(directory)} """ # creating a standard header block source = """ /** * lovely.io '#{options.name}' module v#{options.version} * * Copyright (C) #{new Date().getFullYear()} #{options.author} */ #{source} """ # # Minifies the source code # # @param {String} package directory root # @param {Boolean} vanilla (non lovely.io) module build # @param {Boolean} send `true` if you don't want the styles to be emebedded in the build # @return {String} minified source code # minify = (directory, vanilla, no_style)-> source = compile(directory, vanilla, no_style) ugly = require('uglify-js') build = ugly.parse(source) output = ugly.OutputStream() except = ['Class'] # extracting the exported class names so they didn't get mangled if match = source.match(/((ext\(\s*exports\s*,)|(\n\s+exports\s*=\s*))[^;]+?;/mg) for name in match[0].match(/[^a-zA-Z0-9_$][A-Z][a-zA-Z0-9_$]+/g) || [] except.push(name.substr(1)) if except.indexOf(name.substr(1)) is -1 build.figure_out_scope() build = build.transform(new ugly.Compressor(warnings: false)) build.figure_out_scope() build.compute_char_frequency() build.mangle_names(except: except) build.print(output) build = output.get() # fixing the ugly `'string'==` fuckups back to `'string' === ` build = build.replace(/("[a-z]+")(\!|=)=(typeof [a-z_$]+)/g, '$1$2==$3') # getting back the constructor names build = add_constructor_names(build) # copying the header over (source.match(/\/\*[\s\S]+?\*\/\s/m) || [''])[0] + build # # Converts various formats into vanilla CSS # # @param {String} original code # @param {String} format 'sass', 'scss', 'styl', 'css' # build_style = (style, format)-> if format in ['sass', 'styl'] require('stylus').render style, (err, css) -> if err then console.log(err) else style = css if format is 'scss' require('node-sass').render style, (err, css)-> if err then console.log(err) else style = css return style # # Embedds the styles as an inline javascript # # @param {String} package directory root # @return {String} inlined css # inline_css = (directory, not_lovely) -> for format in ['css', 'sass', 'styl', 'scss'] if fs.existsSync("#{directory}/main.#{format}") style = fs.readFileSync("#{directory}/main.#{format}").toString() break return "" if !style # minfigying the stylesheets style = build_style(style, format) # preserving IE hacks .replace(/\/\*\\\*\*\/:/g, '_ie8_s:') .replace(/\\9;/g, '_ie8_e;') # compacting the styles .replace(/\\/g, "\\\\") .replace(/\/\*[\S\s]*?\*\//img, '') .replace(/\n\s*\n/mg, "\n") .replace(/\s+/img, ' ') .replace(/\s*(\+|>|\||~|\{|\}|,|\)|\(|;|:|\*)\s*/img, '$1') .replace(/;\}/g, '}') .replace(/\)([^;}\s])/g, ') $1') .trim() # getting IE hacks back .replace(/([^\s])\*/g, '$1 *') .replace(/_ie8_s:/g, '/*\\\\**/:') .replace(/_ie8_e(;|})/g, '\\\\9$1') # escaping the quotes .replace(/"/g, '\\"') return "" if /^\s*$/.test(style) # no need to wrap an empty style """ // embedded css-styles (function() { var style = document.createElement('style'); var rules = document.createTextNode("#{style}"#{if not_lovely then '' else ".replace(/url\\(\"\\//g, 'url(\"'+ Lovely.hostUrl)"}); style.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(style); if (style.styleSheet) { style.styleSheet.cssText = rules.nodeValue; } else { style.appendChild(rules); } })(); """ exports.assemble = assemble exports.compile = compile exports.minify = minify exports.style = build_style
[ { "context": "rstName = newFirstName\n data.lastName = newLastName\n data.picture = newPicture\n ", "end": 1287, "score": 0.7033793926239014, "start": 1284, "tag": "NAME", "value": "new" } ]
client/views/profile.coffee
jameswhiteman/communicator-web
0
root = global ? window if root.Meteor.isClient Template.profile.helpers firstName: -> user = Meteor.user() if user return user.profile.firstName return '' lastName: -> user = Meteor.user() if user return user.profile.lastName return '' picture: -> user = Meteor.user() if user return user.profile.picture return '' hasFirstName: -> user = Meteor.user() if user and user.profile.firstName return true return false hasLastName: -> user = Meteor.user() if user and user.profile.lastName return true return false hasPicture: -> user = Meteor.user() if user and user.profile.picture return true return false Template.profile.events 'click #submit' : (e) -> newFirstName = $('#firstName').val() newLastName = $('#lastName').val() newPicture = $('#picture').val() data = Meteor.user().profile data.firstName = newFirstName data.lastName = newLastName data.picture = newPicture Meteor.users.update(Meteor.userId(), {$set: {profile: data}}) Materialize.toast 'Profile updated', 3000
66250
root = global ? window if root.Meteor.isClient Template.profile.helpers firstName: -> user = Meteor.user() if user return user.profile.firstName return '' lastName: -> user = Meteor.user() if user return user.profile.lastName return '' picture: -> user = Meteor.user() if user return user.profile.picture return '' hasFirstName: -> user = Meteor.user() if user and user.profile.firstName return true return false hasLastName: -> user = Meteor.user() if user and user.profile.lastName return true return false hasPicture: -> user = Meteor.user() if user and user.profile.picture return true return false Template.profile.events 'click #submit' : (e) -> newFirstName = $('#firstName').val() newLastName = $('#lastName').val() newPicture = $('#picture').val() data = Meteor.user().profile data.firstName = newFirstName data.lastName = <NAME>LastName data.picture = newPicture Meteor.users.update(Meteor.userId(), {$set: {profile: data}}) Materialize.toast 'Profile updated', 3000
true
root = global ? window if root.Meteor.isClient Template.profile.helpers firstName: -> user = Meteor.user() if user return user.profile.firstName return '' lastName: -> user = Meteor.user() if user return user.profile.lastName return '' picture: -> user = Meteor.user() if user return user.profile.picture return '' hasFirstName: -> user = Meteor.user() if user and user.profile.firstName return true return false hasLastName: -> user = Meteor.user() if user and user.profile.lastName return true return false hasPicture: -> user = Meteor.user() if user and user.profile.picture return true return false Template.profile.events 'click #submit' : (e) -> newFirstName = $('#firstName').val() newLastName = $('#lastName').val() newPicture = $('#picture').val() data = Meteor.user().profile data.firstName = newFirstName data.lastName = PI:NAME:<NAME>END_PILastName data.picture = newPicture Meteor.users.update(Meteor.userId(), {$set: {profile: data}}) Materialize.toast 'Profile updated', 3000
[ { "context": "urrent_class = =>\n cls = new Class(\n name: current_class\n super_classes: _.clone(current_super_", "end": 654, "score": 0.9349086880683899, "start": 647, "tag": "NAME", "value": "current" } ]
temp/graph-examples/model-master/model_app/controllers.coffee
cnstntn-kndrtv/terrapin
0
EXAMPLES = {} EXAMPLES["simple"] = """ Class1 : BaseClass1 +method1 +method2 -method3 Class2 : BaseClass1 +method1 +method2 -method3 Class3 : Class2 +method1 +method2 -method3 """ show_example = (which) -> $("#source_input").val(EXAMPLES[which]) create_parser = -> previous_source = "" current_class = "" current_super_classes = [] members_map = "+": [] "-": [] add_class = (cls) => existing_class = current_diagram.find((c) -> c.get("name") is cls.name ) if existing_class existing_class.set cls else current_diagram.add cls add_current_class = => cls = new Class( name: current_class super_classes: _.clone(current_super_classes) public_methods: _.clone(members_map["+"]) private_methods: _.clone(members_map["-"]) ) add_class(name: sc) for sc in current_super_classes add_class(cls) current_class = "" current_super_classes = [] members_map["+"] = [] members_map["-"] = [] -> source = $("#source_input").val() unless source is previous_source current_diagram.reset() previous_source = source lines = source.split("\n") _.each lines, (line) -> return if line.trim().length is 0 first_char = line.charAt(0) if members_map[first_char] members_map[first_char].push line.substr(1) else add_current_class() unless current_class is "" if line.indexOf(":") >= 0 parts = line.split(":") current_class = parts[0].trim() current_super_classes = parts[1].trim().split(",") else current_class = line add_current_class() $ -> parse = create_parser() $("a[data-toggle=\"tab\"]").on "shown", (e) -> parse() $("#load_simple_example").on "click", (e) -> show_example("simple")
211701
EXAMPLES = {} EXAMPLES["simple"] = """ Class1 : BaseClass1 +method1 +method2 -method3 Class2 : BaseClass1 +method1 +method2 -method3 Class3 : Class2 +method1 +method2 -method3 """ show_example = (which) -> $("#source_input").val(EXAMPLES[which]) create_parser = -> previous_source = "" current_class = "" current_super_classes = [] members_map = "+": [] "-": [] add_class = (cls) => existing_class = current_diagram.find((c) -> c.get("name") is cls.name ) if existing_class existing_class.set cls else current_diagram.add cls add_current_class = => cls = new Class( name: <NAME>_class super_classes: _.clone(current_super_classes) public_methods: _.clone(members_map["+"]) private_methods: _.clone(members_map["-"]) ) add_class(name: sc) for sc in current_super_classes add_class(cls) current_class = "" current_super_classes = [] members_map["+"] = [] members_map["-"] = [] -> source = $("#source_input").val() unless source is previous_source current_diagram.reset() previous_source = source lines = source.split("\n") _.each lines, (line) -> return if line.trim().length is 0 first_char = line.charAt(0) if members_map[first_char] members_map[first_char].push line.substr(1) else add_current_class() unless current_class is "" if line.indexOf(":") >= 0 parts = line.split(":") current_class = parts[0].trim() current_super_classes = parts[1].trim().split(",") else current_class = line add_current_class() $ -> parse = create_parser() $("a[data-toggle=\"tab\"]").on "shown", (e) -> parse() $("#load_simple_example").on "click", (e) -> show_example("simple")
true
EXAMPLES = {} EXAMPLES["simple"] = """ Class1 : BaseClass1 +method1 +method2 -method3 Class2 : BaseClass1 +method1 +method2 -method3 Class3 : Class2 +method1 +method2 -method3 """ show_example = (which) -> $("#source_input").val(EXAMPLES[which]) create_parser = -> previous_source = "" current_class = "" current_super_classes = [] members_map = "+": [] "-": [] add_class = (cls) => existing_class = current_diagram.find((c) -> c.get("name") is cls.name ) if existing_class existing_class.set cls else current_diagram.add cls add_current_class = => cls = new Class( name: PI:NAME:<NAME>END_PI_class super_classes: _.clone(current_super_classes) public_methods: _.clone(members_map["+"]) private_methods: _.clone(members_map["-"]) ) add_class(name: sc) for sc in current_super_classes add_class(cls) current_class = "" current_super_classes = [] members_map["+"] = [] members_map["-"] = [] -> source = $("#source_input").val() unless source is previous_source current_diagram.reset() previous_source = source lines = source.split("\n") _.each lines, (line) -> return if line.trim().length is 0 first_char = line.charAt(0) if members_map[first_char] members_map[first_char].push line.substr(1) else add_current_class() unless current_class is "" if line.indexOf(":") >= 0 parts = line.split(":") current_class = parts[0].trim() current_super_classes = parts[1].trim().split(",") else current_class = line add_current_class() $ -> parse = create_parser() $("a[data-toggle=\"tab\"]").on "shown", (e) -> parse() $("#load_simple_example").on "click", (e) -> show_example("simple")
[ { "context": "3-2014 TheGrid (Rituwall Inc.)\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed und", "end": 129, "score": 0.9998415112495422, "start": 116, "tag": "NAME", "value": "Henri Bergius" }, { "context": "(Rituwall Inc.)\n# (c) 2011-2012 He...
src/lib/InternalSocket.coffee
jonnor/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 {EventEmitter} = require 'events' # ## Internal Sockets # # The default communications mechanism between NoFlo processes is # an _internal socket_, which is responsible for accepting information # packets sent from processes' outports, and emitting corresponding # events so that the packets can be caught to the inport of the # connected process. class InternalSocket extends EventEmitter regularEmitEvent: (event, data) -> @emit event, data debugEmitEvent: (event, data) -> try @emit event, data catch error @emit 'error', id: @to.process.id error: error metadata: @metadata constructor: (@metadata = {}) -> @connected = false @groups = [] @dataDelegate = null @debug = false @emitEvent = @regularEmitEvent # ## Socket connections # # Sockets that are attached to the ports of processes may be # either connected or disconnected. The semantical meaning of # a connection is that the outport is in the process of sending # data. Disconnecting means an end of transmission. # # This can be used for example to signal the beginning and end # of information packets resulting from the reading of a single # file or a database query. # # Example, disconnecting when a file has been completely read: # # readBuffer: (fd, position, size, buffer) -> # fs.read fd, buffer, 0, buffer.length, position, (err, bytes, buffer) => # # Send data. The first send will also connect if not # # already connected. # @outPorts.out.send buffer.slice 0, bytes # position += buffer.length # # # Disconnect when the file has been completely read # return @outPorts.out.disconnect() if position >= size # # # Otherwise, call same method recursively # @readBuffer fd, position, size, buffer connect: -> return if @connected @connected = true @emitEvent 'connect', @ disconnect: -> return unless @connected @connected = false @emitEvent 'disconnect', @ isConnected: -> @connected # ## Sending information packets # # The _send_ method is used by a processe's outport to # send information packets. The actual packet contents are # not defined by NoFlo, and may be any valid JavaScript data # structure. # # The packet contents however should be such that may be safely # serialized or deserialized via JSON. This way the NoFlo networks # can be constructed with more flexibility, as file buffers or # message queues can be used as additional packet relay mechanisms. send: (data) -> @connect() unless @connected data = @dataDelegate() if data is undefined and typeof @dataDelegate is 'function' @emitEvent 'data', data # ## Information Packet grouping # # Processes sending data to sockets may also group the packets # when necessary. This allows transmitting tree structures as # a stream of packets. # # For example, an object could be split into multiple packets # where each property is identified by a separate grouping: # # # Group by object ID # @outPorts.out.beginGroup object.id # # for property, value of object # @outPorts.out.beginGroup property # @outPorts.out.send value # @outPorts.out.endGroup() # # @outPorts.out.endGroup() # # This would cause a tree structure to be sent to the receiving # process as a stream of packets. So, an article object may be # as packets like: # # * `/<article id>/title/Lorem ipsum` # * `/<article id>/author/Henri Bergius` # # Components are free to ignore groupings, but are recommended # to pass received groupings onward if the data structures remain # intact through the component's processing. beginGroup: (group) -> @groups.push group @emitEvent 'begingroup', group endGroup: -> return unless @groups.length @emitEvent 'endgroup', @groups.pop() # ## Socket data delegation # # Sockets have the option to receive data from a delegate function # should the `send` method receive undefined for `data`. This # helps in the case of defaulting values. setDataDelegate: (delegate) -> unless typeof delegate is 'function' throw Error 'A data delegate must be a function.' @dataDelegate = delegate # ## Socket debug mode # # Sockets can catch exceptions happening in processes when data is # sent to them. These errors can then be reported to the network for # notification to the developer. setDebug: (active) -> @debug = active @emitEvent = if @debug then @debugEmitEvent else @regularEmitEvent # ## Socket identifiers # # Socket identifiers are mainly used for debugging purposes. # Typical identifiers look like _ReadFile:OUT -> Display:IN_, # but for sockets sending initial information packets to # components may also loom like _DATA -> ReadFile:SOURCE_. getId: -> fromStr = (from) -> "#{from.process.id}() #{from.port.toUpperCase()}" toStr = (to) -> "#{to.port.toUpperCase()} #{to.process.id}()" return "UNDEFINED" unless @from or @to return "#{fromStr(@from)} -> ANON" if @from and not @to return "DATA -> #{toStr(@to)}" unless @from "#{fromStr(@from)} -> #{toStr(@to)}" exports.InternalSocket = InternalSocket exports.createSocket = -> new InternalSocket
79699
# 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 {EventEmitter} = require 'events' # ## Internal Sockets # # The default communications mechanism between NoFlo processes is # an _internal socket_, which is responsible for accepting information # packets sent from processes' outports, and emitting corresponding # events so that the packets can be caught to the inport of the # connected process. class InternalSocket extends EventEmitter regularEmitEvent: (event, data) -> @emit event, data debugEmitEvent: (event, data) -> try @emit event, data catch error @emit 'error', id: @to.process.id error: error metadata: @metadata constructor: (@metadata = {}) -> @connected = false @groups = [] @dataDelegate = null @debug = false @emitEvent = @regularEmitEvent # ## Socket connections # # Sockets that are attached to the ports of processes may be # either connected or disconnected. The semantical meaning of # a connection is that the outport is in the process of sending # data. Disconnecting means an end of transmission. # # This can be used for example to signal the beginning and end # of information packets resulting from the reading of a single # file or a database query. # # Example, disconnecting when a file has been completely read: # # readBuffer: (fd, position, size, buffer) -> # fs.read fd, buffer, 0, buffer.length, position, (err, bytes, buffer) => # # Send data. The first send will also connect if not # # already connected. # @outPorts.out.send buffer.slice 0, bytes # position += buffer.length # # # Disconnect when the file has been completely read # return @outPorts.out.disconnect() if position >= size # # # Otherwise, call same method recursively # @readBuffer fd, position, size, buffer connect: -> return if @connected @connected = true @emitEvent 'connect', @ disconnect: -> return unless @connected @connected = false @emitEvent 'disconnect', @ isConnected: -> @connected # ## Sending information packets # # The _send_ method is used by a processe's outport to # send information packets. The actual packet contents are # not defined by NoFlo, and may be any valid JavaScript data # structure. # # The packet contents however should be such that may be safely # serialized or deserialized via JSON. This way the NoFlo networks # can be constructed with more flexibility, as file buffers or # message queues can be used as additional packet relay mechanisms. send: (data) -> @connect() unless @connected data = @dataDelegate() if data is undefined and typeof @dataDelegate is 'function' @emitEvent 'data', data # ## Information Packet grouping # # Processes sending data to sockets may also group the packets # when necessary. This allows transmitting tree structures as # a stream of packets. # # For example, an object could be split into multiple packets # where each property is identified by a separate grouping: # # # Group by object ID # @outPorts.out.beginGroup object.id # # for property, value of object # @outPorts.out.beginGroup property # @outPorts.out.send value # @outPorts.out.endGroup() # # @outPorts.out.endGroup() # # This would cause a tree structure to be sent to the receiving # process as a stream of packets. So, an article object may be # as packets like: # # * `/<article id>/title/Lorem ipsum` # * `/<article id>/author/<NAME>` # # Components are free to ignore groupings, but are recommended # to pass received groupings onward if the data structures remain # intact through the component's processing. beginGroup: (group) -> @groups.push group @emitEvent 'begingroup', group endGroup: -> return unless @groups.length @emitEvent 'endgroup', @groups.pop() # ## Socket data delegation # # Sockets have the option to receive data from a delegate function # should the `send` method receive undefined for `data`. This # helps in the case of defaulting values. setDataDelegate: (delegate) -> unless typeof delegate is 'function' throw Error 'A data delegate must be a function.' @dataDelegate = delegate # ## Socket debug mode # # Sockets can catch exceptions happening in processes when data is # sent to them. These errors can then be reported to the network for # notification to the developer. setDebug: (active) -> @debug = active @emitEvent = if @debug then @debugEmitEvent else @regularEmitEvent # ## Socket identifiers # # Socket identifiers are mainly used for debugging purposes. # Typical identifiers look like _ReadFile:OUT -> Display:IN_, # but for sockets sending initial information packets to # components may also loom like _DATA -> ReadFile:SOURCE_. getId: -> fromStr = (from) -> "#{from.process.id}() #{from.port.toUpperCase()}" toStr = (to) -> "#{to.port.toUpperCase()} #{to.process.id}()" return "UNDEFINED" unless @from or @to return "#{fromStr(@from)} -> ANON" if @from and not @to return "DATA -> #{toStr(@to)}" unless @from "#{fromStr(@from)} -> #{toStr(@to)}" exports.InternalSocket = InternalSocket exports.createSocket = -> new InternalSocket
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 {EventEmitter} = require 'events' # ## Internal Sockets # # The default communications mechanism between NoFlo processes is # an _internal socket_, which is responsible for accepting information # packets sent from processes' outports, and emitting corresponding # events so that the packets can be caught to the inport of the # connected process. class InternalSocket extends EventEmitter regularEmitEvent: (event, data) -> @emit event, data debugEmitEvent: (event, data) -> try @emit event, data catch error @emit 'error', id: @to.process.id error: error metadata: @metadata constructor: (@metadata = {}) -> @connected = false @groups = [] @dataDelegate = null @debug = false @emitEvent = @regularEmitEvent # ## Socket connections # # Sockets that are attached to the ports of processes may be # either connected or disconnected. The semantical meaning of # a connection is that the outport is in the process of sending # data. Disconnecting means an end of transmission. # # This can be used for example to signal the beginning and end # of information packets resulting from the reading of a single # file or a database query. # # Example, disconnecting when a file has been completely read: # # readBuffer: (fd, position, size, buffer) -> # fs.read fd, buffer, 0, buffer.length, position, (err, bytes, buffer) => # # Send data. The first send will also connect if not # # already connected. # @outPorts.out.send buffer.slice 0, bytes # position += buffer.length # # # Disconnect when the file has been completely read # return @outPorts.out.disconnect() if position >= size # # # Otherwise, call same method recursively # @readBuffer fd, position, size, buffer connect: -> return if @connected @connected = true @emitEvent 'connect', @ disconnect: -> return unless @connected @connected = false @emitEvent 'disconnect', @ isConnected: -> @connected # ## Sending information packets # # The _send_ method is used by a processe's outport to # send information packets. The actual packet contents are # not defined by NoFlo, and may be any valid JavaScript data # structure. # # The packet contents however should be such that may be safely # serialized or deserialized via JSON. This way the NoFlo networks # can be constructed with more flexibility, as file buffers or # message queues can be used as additional packet relay mechanisms. send: (data) -> @connect() unless @connected data = @dataDelegate() if data is undefined and typeof @dataDelegate is 'function' @emitEvent 'data', data # ## Information Packet grouping # # Processes sending data to sockets may also group the packets # when necessary. This allows transmitting tree structures as # a stream of packets. # # For example, an object could be split into multiple packets # where each property is identified by a separate grouping: # # # Group by object ID # @outPorts.out.beginGroup object.id # # for property, value of object # @outPorts.out.beginGroup property # @outPorts.out.send value # @outPorts.out.endGroup() # # @outPorts.out.endGroup() # # This would cause a tree structure to be sent to the receiving # process as a stream of packets. So, an article object may be # as packets like: # # * `/<article id>/title/Lorem ipsum` # * `/<article id>/author/PI:NAME:<NAME>END_PI` # # Components are free to ignore groupings, but are recommended # to pass received groupings onward if the data structures remain # intact through the component's processing. beginGroup: (group) -> @groups.push group @emitEvent 'begingroup', group endGroup: -> return unless @groups.length @emitEvent 'endgroup', @groups.pop() # ## Socket data delegation # # Sockets have the option to receive data from a delegate function # should the `send` method receive undefined for `data`. This # helps in the case of defaulting values. setDataDelegate: (delegate) -> unless typeof delegate is 'function' throw Error 'A data delegate must be a function.' @dataDelegate = delegate # ## Socket debug mode # # Sockets can catch exceptions happening in processes when data is # sent to them. These errors can then be reported to the network for # notification to the developer. setDebug: (active) -> @debug = active @emitEvent = if @debug then @debugEmitEvent else @regularEmitEvent # ## Socket identifiers # # Socket identifiers are mainly used for debugging purposes. # Typical identifiers look like _ReadFile:OUT -> Display:IN_, # but for sockets sending initial information packets to # components may also loom like _DATA -> ReadFile:SOURCE_. getId: -> fromStr = (from) -> "#{from.process.id}() #{from.port.toUpperCase()}" toStr = (to) -> "#{to.port.toUpperCase()} #{to.process.id}()" return "UNDEFINED" unless @from or @to return "#{fromStr(@from)} -> ANON" if @from and not @to return "DATA -> #{toStr(@to)}" unless @from "#{fromStr(@from)} -> #{toStr(@to)}" exports.InternalSocket = InternalSocket exports.createSocket = -> new InternalSocket
[ { "context": "# © 2015 Logan Martel\n# Extensible class for terminal emulator in web a", "end": 21, "score": 0.9998800158500671, "start": 9, "tag": "NAME", "value": "Logan Martel" }, { "context": ", \"projects\", \"skills\", \"resume\"]\n\t,\t@secrets = [\"gandalf\"]\n\t) ->\n\t\tins...
javascripts/terminal.coffee
TuringPlanck/loganmartel
0
# © 2015 Logan Martel # Extensible class for terminal emulator in web application class Terminal constructor:\ ( @target=".shell .text" , @PS1="$ " , @welcome="./hello_friend" , @guide="Run 'help' for basic commands" , @commands= ["about", "projects", "skills", "resume", "interests", "glass_sort", "clear","ls", "help"] , @broadcasts= ["about", "projects", "skills", "resume"] , @secrets = ["gandalf"] ) -> instance = @ history = [] index = history.length # build basic broadcasting commands (instance[command] = -> instance["broadcast"](command)) for command in @broadcasts # enable ctrl + l to clear terminal $(document).keydown (e) -> if e.which == 76 && e.ctrlKey e.preventDefault() instance.clear() instance.newline() # up and down to traverse history $(document).keydown (e) -> code = e.which if code == 38 || code == 40 e.preventDefault() input = $('input#command').last() index-- if code == 38 and index - 1 >= 0 index++ if code == 40 and index + 1 <= history.length if 0 <= index < history.length input.val(history[index]) else input.val('') # tab completion $(document).keydown (e) -> if e.which == 9 e.preventDefault() input = $('input#command').last() str = input.val() options = instance.commands.concat(instance.secrets) results = [] for command in options if command.substr(0, str.length) is str results.push(command) return if results.length is 0 else if results.length is 1 return input.val(results[0]) instance.print("<br>") for option in results instance.print ("#{option}<br>") instance.newline # process command on enter $(document.body).on 'keyup', 'input#command', (e) -> if e.which == 13 $(@).blur() $(@).prop 'readonly', true command = $(@).val() command = command.toLowerCase() instance.print("<br>") # try calling command try if command in ["init","newline"] throw "no h4x0rs allowed!" if command.substr(0,2) == "cd" console.log instance["cd"]() else instance["#{command}"]() history.push(command) index = history.length catch e console.log(e) instance.print("command unavailable") finally setTimeout (-> instance.newline()), 200 command_line = '<input type="text" id="command" value="" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">' init: -> @greet(@welcome, 0, 100) print: (element) -> $target = $(@target) $target.append(element) newline: -> @print("<br> #{@PS1}") @print(command_line) $("input#command").last().focus() greet: (message, index, interval) -> if index < message.length @print(message[index++]) setTimeout (=> @greet(message, index, interval)), interval else @broadcast("go") $(document).on "done", => @print("<br> #{@guide}") @newline() help: -> @print ("#{command}<br>") for command in @commands when command isnt "help" broadcast: (event) -> $(document).trigger(event) clear: -> $(@target).empty() interests: -> @print("Hey, I'm looking for projects in:<br>") @print("machine learning (esp. NLP)<br>") @print("back-end (mobile or web)<br>") @print("biotech (esp. bioinformatics)<br>") @print("Shoot me an email if you want to work together!") glass_sort: -> window.open("http://loganmartel.me/GlassSort/") ls: -> @print("Hey, secret commands will be updated here as they are added:<br>") @print ("1. #{command}<br>") for command in @secrets cd: -> @print("I'm sorry, Dave. I'm afraid I can't let you do that.") gandalf: -> window.open("https://youtu.be/Sagg08DrO5U") terminal = new Terminal() terminal.init()
23854
# © 2015 <NAME> # Extensible class for terminal emulator in web application class Terminal constructor:\ ( @target=".shell .text" , @PS1="$ " , @welcome="./hello_friend" , @guide="Run 'help' for basic commands" , @commands= ["about", "projects", "skills", "resume", "interests", "glass_sort", "clear","ls", "help"] , @broadcasts= ["about", "projects", "skills", "resume"] , @secrets = ["<KEY>"] ) -> instance = @ history = [] index = history.length # build basic broadcasting commands (instance[command] = -> instance["broadcast"](command)) for command in @broadcasts # enable ctrl + l to clear terminal $(document).keydown (e) -> if e.which == 76 && e.ctrlKey e.preventDefault() instance.clear() instance.newline() # up and down to traverse history $(document).keydown (e) -> code = e.which if code == 38 || code == 40 e.preventDefault() input = $('input#command').last() index-- if code == 38 and index - 1 >= 0 index++ if code == 40 and index + 1 <= history.length if 0 <= index < history.length input.val(history[index]) else input.val('') # tab completion $(document).keydown (e) -> if e.which == 9 e.preventDefault() input = $('input#command').last() str = input.val() options = instance.commands.concat(instance.secrets) results = [] for command in options if command.substr(0, str.length) is str results.push(command) return if results.length is 0 else if results.length is 1 return input.val(results[0]) instance.print("<br>") for option in results instance.print ("#{option}<br>") instance.newline # process command on enter $(document.body).on 'keyup', 'input#command', (e) -> if e.which == 13 $(@).blur() $(@).prop 'readonly', true command = $(@).val() command = command.toLowerCase() instance.print("<br>") # try calling command try if command in ["init","newline"] throw "no h4x0rs allowed!" if command.substr(0,2) == "cd" console.log instance["cd"]() else instance["#{command}"]() history.push(command) index = history.length catch e console.log(e) instance.print("command unavailable") finally setTimeout (-> instance.newline()), 200 command_line = '<input type="text" id="command" value="" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">' init: -> @greet(@welcome, 0, 100) print: (element) -> $target = $(@target) $target.append(element) newline: -> @print("<br> #{@PS1}") @print(command_line) $("input#command").last().focus() greet: (message, index, interval) -> if index < message.length @print(message[index++]) setTimeout (=> @greet(message, index, interval)), interval else @broadcast("go") $(document).on "done", => @print("<br> #{@guide}") @newline() help: -> @print ("#{command}<br>") for command in @commands when command isnt "help" broadcast: (event) -> $(document).trigger(event) clear: -> $(@target).empty() interests: -> @print("Hey, I'm looking for projects in:<br>") @print("machine learning (esp. NLP)<br>") @print("back-end (mobile or web)<br>") @print("biotech (esp. bioinformatics)<br>") @print("Shoot me an email if you want to work together!") glass_sort: -> window.open("http://loganmartel.me/GlassSort/") ls: -> @print("Hey, secret commands will be updated here as they are added:<br>") @print ("1. #{command}<br>") for command in @secrets cd: -> @print("I'm sorry, <NAME>. I'm afraid I can't let you do that.") gandalf: -> window.open("https://youtu.be/Sagg08DrO5U") terminal = new Terminal() terminal.init()
true
# © 2015 PI:NAME:<NAME>END_PI # Extensible class for terminal emulator in web application class Terminal constructor:\ ( @target=".shell .text" , @PS1="$ " , @welcome="./hello_friend" , @guide="Run 'help' for basic commands" , @commands= ["about", "projects", "skills", "resume", "interests", "glass_sort", "clear","ls", "help"] , @broadcasts= ["about", "projects", "skills", "resume"] , @secrets = ["PI:KEY:<KEY>END_PI"] ) -> instance = @ history = [] index = history.length # build basic broadcasting commands (instance[command] = -> instance["broadcast"](command)) for command in @broadcasts # enable ctrl + l to clear terminal $(document).keydown (e) -> if e.which == 76 && e.ctrlKey e.preventDefault() instance.clear() instance.newline() # up and down to traverse history $(document).keydown (e) -> code = e.which if code == 38 || code == 40 e.preventDefault() input = $('input#command').last() index-- if code == 38 and index - 1 >= 0 index++ if code == 40 and index + 1 <= history.length if 0 <= index < history.length input.val(history[index]) else input.val('') # tab completion $(document).keydown (e) -> if e.which == 9 e.preventDefault() input = $('input#command').last() str = input.val() options = instance.commands.concat(instance.secrets) results = [] for command in options if command.substr(0, str.length) is str results.push(command) return if results.length is 0 else if results.length is 1 return input.val(results[0]) instance.print("<br>") for option in results instance.print ("#{option}<br>") instance.newline # process command on enter $(document.body).on 'keyup', 'input#command', (e) -> if e.which == 13 $(@).blur() $(@).prop 'readonly', true command = $(@).val() command = command.toLowerCase() instance.print("<br>") # try calling command try if command in ["init","newline"] throw "no h4x0rs allowed!" if command.substr(0,2) == "cd" console.log instance["cd"]() else instance["#{command}"]() history.push(command) index = history.length catch e console.log(e) instance.print("command unavailable") finally setTimeout (-> instance.newline()), 200 command_line = '<input type="text" id="command" value="" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">' init: -> @greet(@welcome, 0, 100) print: (element) -> $target = $(@target) $target.append(element) newline: -> @print("<br> #{@PS1}") @print(command_line) $("input#command").last().focus() greet: (message, index, interval) -> if index < message.length @print(message[index++]) setTimeout (=> @greet(message, index, interval)), interval else @broadcast("go") $(document).on "done", => @print("<br> #{@guide}") @newline() help: -> @print ("#{command}<br>") for command in @commands when command isnt "help" broadcast: (event) -> $(document).trigger(event) clear: -> $(@target).empty() interests: -> @print("Hey, I'm looking for projects in:<br>") @print("machine learning (esp. NLP)<br>") @print("back-end (mobile or web)<br>") @print("biotech (esp. bioinformatics)<br>") @print("Shoot me an email if you want to work together!") glass_sort: -> window.open("http://loganmartel.me/GlassSort/") ls: -> @print("Hey, secret commands will be updated here as they are added:<br>") @print ("1. #{command}<br>") for command in @secrets cd: -> @print("I'm sorry, PI:NAME:<NAME>END_PI. I'm afraid I can't let you do that.") gandalf: -> window.open("https://youtu.be/Sagg08DrO5U") terminal = new Terminal() terminal.init()
[ { "context": "# The MIT License (MIT)\n# \n# Copyright (c) 2013 Alytis\n# \n# Permission is hereby granted, free of charge", "end": 54, "score": 0.9986651539802551, "start": 48, "tag": "NAME", "value": "Alytis" } ]
src/bone.coffee
monokrome/HyperBone
0
# The MIT License (MIT) # # Copyright (c) 2013 Alytis # # 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. class Bone models: {} collections: {} service: null registry: communicationType: 'cors' constructor: (@originalOptions) -> _.extend @, Backbone.Events _.extend @registry, @originalOptions @parseOptions() if @originalOptions.autoDiscover? and @originalOptions.autoDiscover is true @originalOptions.discover() parseOptions: => @registry.communicationType = @registry.communicationType.toLowerCase() @service = new @registry.serviceType @ discover: -> @request @registry.root, success: @service.discoverResources url: (url) -> @service.url url request: (url, options) => # Wraps jQuery's ajax call in order to automatically convert requests between # different communication types (IE, CORS or JSON-P) and generate URLs # when necessary. options = options or {} options.dataType = @registry.communicationType # TODO: Get this to use the HTTP standard Accept header, not ?format=jsonp if @registry.communicationType == 'jsonp' options.crossDomain ?= true @service.request url, options module.exports = {Bone}
99515
# The MIT License (MIT) # # Copyright (c) 2013 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class Bone models: {} collections: {} service: null registry: communicationType: 'cors' constructor: (@originalOptions) -> _.extend @, Backbone.Events _.extend @registry, @originalOptions @parseOptions() if @originalOptions.autoDiscover? and @originalOptions.autoDiscover is true @originalOptions.discover() parseOptions: => @registry.communicationType = @registry.communicationType.toLowerCase() @service = new @registry.serviceType @ discover: -> @request @registry.root, success: @service.discoverResources url: (url) -> @service.url url request: (url, options) => # Wraps jQuery's ajax call in order to automatically convert requests between # different communication types (IE, CORS or JSON-P) and generate URLs # when necessary. options = options or {} options.dataType = @registry.communicationType # TODO: Get this to use the HTTP standard Accept header, not ?format=jsonp if @registry.communicationType == 'jsonp' options.crossDomain ?= true @service.request url, options module.exports = {Bone}
true
# The MIT License (MIT) # # Copyright (c) 2013 PI:NAME:<NAME>END_PI # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class Bone models: {} collections: {} service: null registry: communicationType: 'cors' constructor: (@originalOptions) -> _.extend @, Backbone.Events _.extend @registry, @originalOptions @parseOptions() if @originalOptions.autoDiscover? and @originalOptions.autoDiscover is true @originalOptions.discover() parseOptions: => @registry.communicationType = @registry.communicationType.toLowerCase() @service = new @registry.serviceType @ discover: -> @request @registry.root, success: @service.discoverResources url: (url) -> @service.url url request: (url, options) => # Wraps jQuery's ajax call in order to automatically convert requests between # different communication types (IE, CORS or JSON-P) and generate URLs # when necessary. options = options or {} options.dataType = @registry.communicationType # TODO: Get this to use the HTTP standard Accept header, not ?format=jsonp if @registry.communicationType == 'jsonp' options.crossDomain ?= true @service.request url, options module.exports = {Bone}
[ { "context": "s= []\n\n i= 0\n\n keys.push\n name: 'まばたき'\n time: 0\n weight: 0.00\n\n keys", "end": 1196, "score": 0.9986559152603149, "start": 1192, "tag": "KEY", "value": "まばたき" }, { "context": " weight: 0.00\n\n keys.push\n name...
src/app/loaders.coffee
59naga/vpd.berabou.me
2
# Dependencies vpvpVpd= require 'vpvp-vpd' pako= require 'pako' # Publish app= angular.module process.env.APP app.factory 'Loaders',($window,Promise,renderer)-> class Loader constructor: (pmxName,vmdName)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vmd= @loadVmd vmdName @model= @createModel() isFulfilled: -> @pmx.isFulfilled() and @vmd.isFulfilled() nextDelta: -> @delta= @clock.getDelta() loadPmx: (pmxName,params={})-> new Promise (resolve)-> pmx= new THREE.MMD.PMX pmx.load pmxName,(pmx)-> pmx.createMesh params,(mesh)-> resolve {pmx,mesh} loadVmd: (vmdName)-> new Promise (resolve)-> vmd= new THREE.MMD.VMD vmd.load vmdName,resolve loadVpd: (vpdName)-> new Promise (resolve)-> xhr= new XMLHttpRequest xhr.open 'GET',vpdName,yes xhr.responseType= 'arraybuffer' xhr.send() xhr.onload= -> resolve vpvpVpd.parse new Buffer xhr.response generateBlinkAnimation: (pmx,vpd)-> # duration= 0.03333333333333333 targets= [] keys= [] i= 0 keys.push name: 'まばたき' time: 0 weight: 0.00 keys.push name: 'まばたき' time: 3.0 weight: 0.00 keys.push name: 'まばたき' time: 3.05 weight: 1.00 keys.push name: 'まばたき' time: 3.20 weight: 0.00 targets.push {keys} finalTarget= targets[targets.length-1] maxTime= finalTarget.keys[finalTarget.keys.length-1].time {duration:maxTime,targets} generateSkinAnimation: (pmx,vpd)-> duration= 0.03333333333333333 targets= [] for pBone in pmx.bones keys= [] for vBone in vpd.bones continue unless pBone.name is vBone.name pos= vBone.position.slice() rot= vBone.quaternion.slice() rot[0]*= -1 rot[1]*= -1 interp= new Uint8Array [20,20,0,0,20,20,20,20,107,107,107,107,107,107,107,107] keys.push name: vBone.name time: 0 pos: pos rot: rot interp: interp keys.push name: vBone.name time: duration pos: pos rot: rot interp: interp targets.push {keys} {duration,targets} createModel: -> Promise.all [@pmx,@vmd] .spread ({pmx,mesh},vmd)=> mAnimation= vmd.generateMorphAnimation pmx morph= new THREE.MMD.MMDMorph mesh, mAnimation if mAnimation sAnimation= vmd.generateSkinAnimation pmx skin= new THREE.MMD.MMDSkin mesh, sAnimation if sAnimation if mesh.geometry.MMDIKs.length ik= new THREE.MMD.MMDIK mesh if mesh.geometry.MMDIKs.length and window.Ammo physi= new THREE.MMD.MMDPhysi mesh physiPlugin= render: => physi.preSimulate @delta THREE.MMD.btWorld.stepSimulation @delta physi.postSimulate @delta hasAd= pmx.bones.some (bone)-> bone.additionalTransform addTrans= new THREE.MMD.MMDAddTrans pmx, mesh if hasAd {mesh,morph,skin,ik,physi,physiPlugin,addTrans} class VpdLoader extends Loader constructor: (pmxName,vpdName)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vpd= @loadVpd vpdName @model= @createModel() isFulfilled: -> @pmx.isFulfilled() and @vpd.isFulfilled() createModel: -> Promise.all [@pmx,@vpd] .spread ({pmx,mesh},vpd)=> mAnimation= @generateBlinkAnimation pmx,vpd morph= new THREE.MMD.MMDMorph mesh, mAnimation if mAnimation base64= @deflate vpd if @base64 sAnimation= @generateSkinAnimation pmx,vpd skin= new THREE.MMD.MMDSkin mesh, sAnimation if sAnimation if mesh.geometry.MMDIKs.length ik= new THREE.MMD.MMDIK mesh if mesh.geometry.MMDIKs.length and window.Ammo physi= new THREE.MMD.MMDPhysi mesh physiPlugin= render: => physi.preSimulate @delta THREE.MMD.btWorld.stepSimulation @delta physi.postSimulate @delta hasAd= pmx.bones.some (bone)-> bone.additionalTransform addTrans= new THREE.MMD.MMDAddTrans pmx, mesh if hasAd {mesh,morph,skin,ik,physi,physiPlugin,addTrans,base64} deflate: (vpd)-> data= (vpvpVpd.mangle vpd).join ',' 'b64:'+(new Buffer (pako.deflate data,{to:'string'})).toString('base64') class Base64Loader extends VpdLoader constructor: (pmxName,base64)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vpd= @loadVpd base64 @model= @createModel() loadVpd: (base64)-> deflated= (new Buffer base64.slice(4),'base64').toString() data= (pako.inflate deflated,{to:'string'}).split ',' bones= vpvpVpd.restore data for bone in bones bone.position[key]= parseFloat value for value,key in bone.position bone.quaternion[key]= parseFloat value for value,key in bone.quaternion Promise.resolve {bones} {Loader,VpdLoader,Base64Loader}
139101
# Dependencies vpvpVpd= require 'vpvp-vpd' pako= require 'pako' # Publish app= angular.module process.env.APP app.factory 'Loaders',($window,Promise,renderer)-> class Loader constructor: (pmxName,vmdName)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vmd= @loadVmd vmdName @model= @createModel() isFulfilled: -> @pmx.isFulfilled() and @vmd.isFulfilled() nextDelta: -> @delta= @clock.getDelta() loadPmx: (pmxName,params={})-> new Promise (resolve)-> pmx= new THREE.MMD.PMX pmx.load pmxName,(pmx)-> pmx.createMesh params,(mesh)-> resolve {pmx,mesh} loadVmd: (vmdName)-> new Promise (resolve)-> vmd= new THREE.MMD.VMD vmd.load vmdName,resolve loadVpd: (vpdName)-> new Promise (resolve)-> xhr= new XMLHttpRequest xhr.open 'GET',vpdName,yes xhr.responseType= 'arraybuffer' xhr.send() xhr.onload= -> resolve vpvpVpd.parse new Buffer xhr.response generateBlinkAnimation: (pmx,vpd)-> # duration= 0.03333333333333333 targets= [] keys= [] i= 0 keys.push name: '<KEY>' time: 0 weight: 0.00 keys.push name: '<KEY>' time: 3.0 weight: 0.00 keys.push name: '<KEY>' time: 3.05 weight: 1.00 keys.push name: '<KEY>' time: 3.20 weight: 0.00 targets.push {keys} finalTarget= targets[targets.length-1] maxTime= finalTarget.keys[finalTarget.keys.length-1].time {duration:maxTime,targets} generateSkinAnimation: (pmx,vpd)-> duration= 0.03333333333333333 targets= [] for pBone in pmx.bones keys= [] for vBone in vpd.bones continue unless pBone.name is vBone.name pos= vBone.position.slice() rot= vBone.quaternion.slice() rot[0]*= -1 rot[1]*= -1 interp= new Uint8Array [20,20,0,0,20,20,20,20,107,107,107,107,107,107,107,107] keys.push name: vBone.name time: 0 pos: pos rot: rot interp: interp keys.push name: vBone.name time: duration pos: pos rot: rot interp: interp targets.push {keys} {duration,targets} createModel: -> Promise.all [@pmx,@vmd] .spread ({pmx,mesh},vmd)=> mAnimation= vmd.generateMorphAnimation pmx morph= new THREE.MMD.MMDMorph mesh, mAnimation if mAnimation sAnimation= vmd.generateSkinAnimation pmx skin= new THREE.MMD.MMDSkin mesh, sAnimation if sAnimation if mesh.geometry.MMDIKs.length ik= new THREE.MMD.MMDIK mesh if mesh.geometry.MMDIKs.length and window.Ammo physi= new THREE.MMD.MMDPhysi mesh physiPlugin= render: => physi.preSimulate @delta THREE.MMD.btWorld.stepSimulation @delta physi.postSimulate @delta hasAd= pmx.bones.some (bone)-> bone.additionalTransform addTrans= new THREE.MMD.MMDAddTrans pmx, mesh if hasAd {mesh,morph,skin,ik,physi,physiPlugin,addTrans} class VpdLoader extends Loader constructor: (pmxName,vpdName)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vpd= @loadVpd vpdName @model= @createModel() isFulfilled: -> @pmx.isFulfilled() and @vpd.isFulfilled() createModel: -> Promise.all [@pmx,@vpd] .spread ({pmx,mesh},vpd)=> mAnimation= @generateBlinkAnimation pmx,vpd morph= new THREE.MMD.MMDMorph mesh, mAnimation if mAnimation base64= @deflate vpd if @base64 sAnimation= @generateSkinAnimation pmx,vpd skin= new THREE.MMD.MMDSkin mesh, sAnimation if sAnimation if mesh.geometry.MMDIKs.length ik= new THREE.MMD.MMDIK mesh if mesh.geometry.MMDIKs.length and window.Ammo physi= new THREE.MMD.MMDPhysi mesh physiPlugin= render: => physi.preSimulate @delta THREE.MMD.btWorld.stepSimulation @delta physi.postSimulate @delta hasAd= pmx.bones.some (bone)-> bone.additionalTransform addTrans= new THREE.MMD.MMDAddTrans pmx, mesh if hasAd {mesh,morph,skin,ik,physi,physiPlugin,addTrans,base64} deflate: (vpd)-> data= (vpvpVpd.mangle vpd).join ',' 'b64:'+(new Buffer (pako.deflate data,{to:'string'})).toString('base64') class Base64Loader extends VpdLoader constructor: (pmxName,base64)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vpd= @loadVpd base64 @model= @createModel() loadVpd: (base64)-> deflated= (new Buffer base64.slice(4),'base64').toString() data= (pako.inflate deflated,{to:'string'}).split ',' bones= vpvpVpd.restore data for bone in bones bone.position[key]= parseFloat value for value,key in bone.position bone.quaternion[key]= parseFloat value for value,key in bone.quaternion Promise.resolve {bones} {Loader,VpdLoader,Base64Loader}
true
# Dependencies vpvpVpd= require 'vpvp-vpd' pako= require 'pako' # Publish app= angular.module process.env.APP app.factory 'Loaders',($window,Promise,renderer)-> class Loader constructor: (pmxName,vmdName)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vmd= @loadVmd vmdName @model= @createModel() isFulfilled: -> @pmx.isFulfilled() and @vmd.isFulfilled() nextDelta: -> @delta= @clock.getDelta() loadPmx: (pmxName,params={})-> new Promise (resolve)-> pmx= new THREE.MMD.PMX pmx.load pmxName,(pmx)-> pmx.createMesh params,(mesh)-> resolve {pmx,mesh} loadVmd: (vmdName)-> new Promise (resolve)-> vmd= new THREE.MMD.VMD vmd.load vmdName,resolve loadVpd: (vpdName)-> new Promise (resolve)-> xhr= new XMLHttpRequest xhr.open 'GET',vpdName,yes xhr.responseType= 'arraybuffer' xhr.send() xhr.onload= -> resolve vpvpVpd.parse new Buffer xhr.response generateBlinkAnimation: (pmx,vpd)-> # duration= 0.03333333333333333 targets= [] keys= [] i= 0 keys.push name: 'PI:KEY:<KEY>END_PI' time: 0 weight: 0.00 keys.push name: 'PI:KEY:<KEY>END_PI' time: 3.0 weight: 0.00 keys.push name: 'PI:KEY:<KEY>END_PI' time: 3.05 weight: 1.00 keys.push name: 'PI:KEY:<KEY>END_PI' time: 3.20 weight: 0.00 targets.push {keys} finalTarget= targets[targets.length-1] maxTime= finalTarget.keys[finalTarget.keys.length-1].time {duration:maxTime,targets} generateSkinAnimation: (pmx,vpd)-> duration= 0.03333333333333333 targets= [] for pBone in pmx.bones keys= [] for vBone in vpd.bones continue unless pBone.name is vBone.name pos= vBone.position.slice() rot= vBone.quaternion.slice() rot[0]*= -1 rot[1]*= -1 interp= new Uint8Array [20,20,0,0,20,20,20,20,107,107,107,107,107,107,107,107] keys.push name: vBone.name time: 0 pos: pos rot: rot interp: interp keys.push name: vBone.name time: duration pos: pos rot: rot interp: interp targets.push {keys} {duration,targets} createModel: -> Promise.all [@pmx,@vmd] .spread ({pmx,mesh},vmd)=> mAnimation= vmd.generateMorphAnimation pmx morph= new THREE.MMD.MMDMorph mesh, mAnimation if mAnimation sAnimation= vmd.generateSkinAnimation pmx skin= new THREE.MMD.MMDSkin mesh, sAnimation if sAnimation if mesh.geometry.MMDIKs.length ik= new THREE.MMD.MMDIK mesh if mesh.geometry.MMDIKs.length and window.Ammo physi= new THREE.MMD.MMDPhysi mesh physiPlugin= render: => physi.preSimulate @delta THREE.MMD.btWorld.stepSimulation @delta physi.postSimulate @delta hasAd= pmx.bones.some (bone)-> bone.additionalTransform addTrans= new THREE.MMD.MMDAddTrans pmx, mesh if hasAd {mesh,morph,skin,ik,physi,physiPlugin,addTrans} class VpdLoader extends Loader constructor: (pmxName,vpdName)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vpd= @loadVpd vpdName @model= @createModel() isFulfilled: -> @pmx.isFulfilled() and @vpd.isFulfilled() createModel: -> Promise.all [@pmx,@vpd] .spread ({pmx,mesh},vpd)=> mAnimation= @generateBlinkAnimation pmx,vpd morph= new THREE.MMD.MMDMorph mesh, mAnimation if mAnimation base64= @deflate vpd if @base64 sAnimation= @generateSkinAnimation pmx,vpd skin= new THREE.MMD.MMDSkin mesh, sAnimation if sAnimation if mesh.geometry.MMDIKs.length ik= new THREE.MMD.MMDIK mesh if mesh.geometry.MMDIKs.length and window.Ammo physi= new THREE.MMD.MMDPhysi mesh physiPlugin= render: => physi.preSimulate @delta THREE.MMD.btWorld.stepSimulation @delta physi.postSimulate @delta hasAd= pmx.bones.some (bone)-> bone.additionalTransform addTrans= new THREE.MMD.MMDAddTrans pmx, mesh if hasAd {mesh,morph,skin,ik,physi,physiPlugin,addTrans,base64} deflate: (vpd)-> data= (vpvpVpd.mangle vpd).join ',' 'b64:'+(new Buffer (pako.deflate data,{to:'string'})).toString('base64') class Base64Loader extends VpdLoader constructor: (pmxName,base64)-> @clock= new THREE.Clock @pmx= @loadPmx pmxName @vpd= @loadVpd base64 @model= @createModel() loadVpd: (base64)-> deflated= (new Buffer base64.slice(4),'base64').toString() data= (pako.inflate deflated,{to:'string'}).split ',' bones= vpvpVpd.restore data for bone in bones bone.position[key]= parseFloat value for value,key in bone.position bone.quaternion[key]= parseFloat value for value,key in bone.quaternion Promise.resolve {bones} {Loader,VpdLoader,Base64Loader}
[ { "context": "lert(\"Galloping...\")\n super(45)\n\nsam: new Snake(\"Sammy the Python\")\ntom: new Horse(\"Tommy the Palomino\")\n\nsam.move(", "end": 325, "score": 0.9951704740524292, "start": 309, "tag": "NAME", "value": "Sammy the Python" }, { "context": "am: new Snake(\"Sammy th...
documentation/coffee/super.coffee
tlrobinson/coffee-script
1
Animal: => Animal::move: meters => alert(this.name + " moved " + meters + "m.") Snake: name => this.name: name Snake extends Animal Snake::move: => alert("Slithering...") super(5) Horse: name => this.name: name Horse extends Animal Horse::move: => alert("Galloping...") super(45) sam: new Snake("Sammy the Python") tom: new Horse("Tommy the Palomino") sam.move() tom.move()
124951
Animal: => Animal::move: meters => alert(this.name + " moved " + meters + "m.") Snake: name => this.name: name Snake extends Animal Snake::move: => alert("Slithering...") super(5) Horse: name => this.name: name Horse extends Animal Horse::move: => alert("Galloping...") super(45) sam: new Snake("<NAME>") tom: new Horse("<NAME>") sam.move() tom.move()
true
Animal: => Animal::move: meters => alert(this.name + " moved " + meters + "m.") Snake: name => this.name: name Snake extends Animal Snake::move: => alert("Slithering...") super(5) Horse: name => this.name: name Horse extends Animal Horse::move: => alert("Galloping...") super(45) sam: new Snake("PI:NAME:<NAME>END_PI") tom: new Horse("PI:NAME:<NAME>END_PI") sam.move() tom.move()
[ { "context": "# # service layer\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L", "end": 55, "score": 0.9998607635498047, "start": 41, "tag": "NAME", "value": "JeongHoon Byun" }, { "context": " layer\n#\n# Copyright (c) 2013 JeongHoon Byun...
src/service.coffee
outsideris/popularconvention
421
# # service layer # # Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> logger = (require './helpers').logger helpers = (require './helpers') http = require 'http' fs = require 'fs' zlib = require 'zlib' path = require 'path' spawn = require('child_process').spawn persistence = require './persistence' timeline = require './timeline' parser = require './parser/parser' schedule = require 'node-schedule' _ = require 'underscore' hljs = require 'highlight.js' # connect MongoDB persistence.open (err) -> return logger.error 'mongodb is not connected', {err: err} if err? logger.info 'mongodb is connected' # directory for temporary download json files from github archive archiveDir = "#{__dirname}/archive" fs.exists archiveDir, (exist) -> if not exist then fs.mkdirSync archiveDir service = module.exports = # description object to display infomation footer in site totalDesc: lastUpdate: null startDate: null endDate: null regdate: null # download timeline json file from github archive fetchGithubArchive: (datetime, callback) -> (http.get "http://data.githubarchive.org/#{datetime}.json.gz", (res) -> gzip = zlib.createGunzip() fstream = fs.createWriteStream "#{archiveDir}/#{datetime}.json" unzip = res.pipe gzip unzip.pipe fstream unzip.on 'end', -> logger.info "downloaded #{datetime}.json" importIntoMongodb(datetime, callback) ).on 'error', (e) -> logger.error 'fetch githubarchive: ', {err: e} processTimeline: (callback) -> persistence.findOneWorklogToProcess (err, worklog) -> logger.error 'findOneWorklogToProcess: ', {err: err} if err? return callback() if err? or not worklog? logger.debug "found worklog to process : #{worklog.file}" timeline.checkApiLimit (remainingCount) -> if remainingCount > 2500 persistence.processWorklog worklog._id, (err) -> if err? logger.error 'findOneWorklogs: ', {err: err} return callback err logger.debug "start processing : #{worklog.file}" persistence.findTimeline worklog.file, (err, cursor) -> if err? logger.error 'findOneWorklogs: ', {err: err} return callback err logger.debug "found timeline : #{worklog.file}" cursor.count (err, count) -> logger.debug "timer #{worklog.file} has #{count}" isCompleted = false processCount = 0 innerLoop = (cur, concurrency) -> innerLoop(cur, concurrency - 1) if concurrency? and concurrency > 1 logger.debug "start batch ##{concurrency}" if concurrency? and concurrency > 1 processCount += 1 cur.nextObject (err, item) -> if err? logger.error "in nextObject: ", {err: err} return if item? logger.debug "found item", {item: item._id} urls = timeline.getCommitUrls item logger.debug "urls: #{urls.length} - ", {urls: urls} if urls.length is 0 innerLoop cur return invokedInnerLoop = false urls.forEach (url) -> timeline.getCommitInfo url, (err, commit) -> if err? logger.error 'getCommitInfo: ', {err: err, limit: /^API Rate Limit Exceeded/i.test(err.message), isCompleted: isCompleted, processCount: processCount} if /^API Rate Limit Exceeded/i.test(err.message) and not isCompleted and processCount > 2000 isCompleted = true persistence.completeWorklog worklog._id, (err) -> if err? isCompleted = false logger.error 'completeWorklog: ', {err: err} logger.debug 'completed worklog', {file: worklog.file} else if not /^API Rate Limit Exceeded/i.test(err.message) innerLoop cur else logger.debug "parsing commit #{url} : ", {commit: commit} conventions = parser.parse commit logger.debug "get conventions ", {convention: conventions} conventions.forEach (conv) -> data = file: worklog.file lang: conv.lang convention: conv regdate: new Date() persistence.insertConvention data, (err) -> logger.error 'insertConvention', {err: err} if err? logger.info "insered convention - #{processCount}" logger.debug "before callback #{invokedInnerLoop} - #{item._id}" if not invokedInnerLoop logger.debug "call recurrsive - #{item._id}" innerLoop cur invokedInnerLoop = true else logger.debug "no item - #{processCount}" if not isCompleted and processCount > 2000 isCompleted = true persistence.completeWorklog worklog._id, (err) -> if err? isCompleted = false logger.error 'completeWorklog: ', {err: err} logger.debug 'completed worklog', {file: worklog.file} innerLoop(cursor, 5) callback() summarizeScore: (callback) -> persistence.findOneWorklogToSummarize (err, worklog) -> logger.error 'findOneWorklogToSummarize: ', {err: err} if err? return callback() if err? or not worklog? # summarize score in case of completed 2 hours ago if new Date - worklog.completeDate > 7200000 persistence.findConvention worklog.file, (err, cursor) -> if err? logger.error 'findConvention: ', {err: err} return cursor.toArray (err, docs) -> conventionList = [] docs.forEach (doc) -> if hasLang(conventionList , doc) baseConv = getConventionByLang doc.lang, conventionList mergeConvention baseConv.convention, doc.convention else delete doc._id doc.regdate = new Date doc.shortfile = doc.file.substr 0, doc.file.lastIndexOf '-' conventionList.push doc # convert commits to commit count ( ( value.commits = value.commits.length if value.commits? ) for key, value of item.convention ) for item in conventionList fileOfDay = worklog.file.substr 0, worklog.file.lastIndexOf '-' # merge convention if convention of same is exist mergeInExistConvention = (convList) -> if convList.length conv = convList.pop() persistence.findScoreByFileAndLang fileOfDay, conv.lang, (err, item) -> if err? logger.error 'findScoreByFile', {err: err} return logger.debug 'findScoreByFileAndLang', {item: item} if item? mergeConvention conv.convention, item.convention, conv._id = item._id persistence.upsertScore conv, (err) -> if err? logger.error 'upsertScore', {err: err} logger.info 'upserted score', {conv: conv} mergeInExistConvention convList else persistence.summarizeWorklog worklog._id, (err) -> if err? logger.error 'summarizeWorklog', {err: err} return logger.info 'summarized worklog', {file: worklog.file} persistence.dropTimeline worklog.file, (err) -> if err? logger.error 'drop timeline collection', {err: err} return logger.info 'dropped timeline collection', {collection: worklog.file} mergeInExistConvention conventionList callback() else callback() findScore: (lang, callback) -> persistence.findScoreByLang lang, (err, cursor) -> if err? logger.error 'findScoreByLang', {err: err} return callback(err) langParser = parser.getParser(".#{lang}") if (langParser) languageDescription = parser.getParser(".#{lang}").parse("", {}, "") else callback new Error "#{lang} is not found" dailyData = [] cursor.toArray (err, docs) -> logger.error "findScoreByLang toArray", {err: err} if err? logger.debug "findByLang", {docs: docs} if docs?.length docs.forEach (doc) -> # set convention description from parser (if key isnt 'lang' doc.convention[key].title = languageDescription[key].title doc.convention[key].column = languageDescription[key].column ) for key of doc.convention score = lang: lang file: doc.shortfile convention: doc.convention dailyData.push score makeResult(lang, dailyData, callback) else callback new Error "#{lang} is not found" findDescription: (force, callback) -> # get commit count from cacahing when cache value is exist and in 1 hour if not force and service.totalDesc.regdate? and (new Date - service.totalDesc.regdate) < 3600000 callback null, service.totalDesc else desc = {} persistence.findLastestScore (err, item) -> if err? logger.error 'findLastestScore', {err: err} return callback err if item? # caching service.totalDesc.lastUpdate = item.file persistence.findPeriodOfScore (err, docs) -> if err? logger.error 'findPeriodOfScore', {err: err} return callback err if docs?.length > 0 docs.sort (a, b) -> if a.shortfile > b.shortfile then 1 else -1 # caching service.totalDesc.startDate = docs[0].shortfile service.totalDesc.endDate = docs[docs.length - 1].shortfile service.totalDesc.regdate = new Date callback null, service.totalDesc else callback null, service.totalDesc # private hasLang = (sum, elem) -> sum.some (el) -> el.lang is elem.lang getConventionByLang = (lang, convList) -> result = null convList.forEach (elem) -> result = elem if elem.lang is lang result getHighlightName = (lang) -> map = js: 'javascript' java: 'java' py: 'python' scala: 'scala' rb: 'ruby' cs: 'cs' php: 'php' map[lang] mongoImportCmd = "" findMongoImportCmd = (datetime, callback) -> if (mongoImportCmd) callback null, mongoImportCmd else which = spawn 'which', ["mongoimport"] which.stdout.on 'data', (data) -> mongoImportCmd = data.toString() which.on 'exit', (code) -> if (code is 0) # remove trailing new line mongoImportCmd = mongoImportCmd.match(/([\w\/]+)/)[0] if mongoImportCmd.match(/([\w\/]+)/) callback null, mongoImportCmd else logger.error "mongoimport doesn't exist." callback(code) importIntoMongodb = (datetime, callback) -> findMongoImportCmd datetime, (err, mongoCmd) -> if err? logger.error "error occured during mongoimport" else args = [ '--host', process.env['MONGODB_HOST'] '--port', process.env['MONGODB_PORT'] '--db', 'popular_convention2' '--collection', datetime '--file', "#{archiveDir}/#{datetime}.json" '--type', 'json' ] if process.env['NODE_ENV'] is 'production' args = args.concat [ '--username', process.env["MONGODB_USER"] '--password', process.env["MONGODB_PASS"] ] mongoimport = spawn mongoCmd, args mongoimport.stderr.on 'data', (data) -> logger.error "mongoimport error occured" mongoimport.on 'close', (code) -> logger.info "mongoimport exited with code #{code}" doc = file: datetime inProcess: false completed: false summarize: false persistence.insertWorklogs doc, (-> callback()) if code is 0 callback(code) if code isnt 0 deleteArchiveFile(datetime) deleteArchiveFile = (datetime) -> fs.unlink "#{archiveDir}/#{datetime}.json", (err) -> logger.error "delete #{archiveDir}/#{datetime}.json" if err mergeConvention = (baseConvention, newConvention) -> ( if key isnt 'lang' if newConvention[key]? conv[k] += newConvention[key][k] for k of conv when k isnt 'commits' if conv.commits.concat? conv.commits = _.uniq(conv.commits.concat newConvention[key].commits) else conv.commits = conv.commits + newConvention[key].commits )for key, conv of baseConvention makeResult = (lang, dailyData, callback) -> sumData = lang: lang period: [] raw: dailyData dailyData.forEach (data) -> if not sumData.scores? sumData.scores = data.convention sumData.period.push data.file else (if key isnt 'lang' if (data.convention[key]?) sumData.scores[key].column.forEach (elem) -> sumData.scores[key][elem.key] += data.convention[key][elem.key] sumData.scores[key].commits += data.convention[key].commits ) for key of sumData.scores # add new field not exist ( sumData.scores[key] = data.convention[key] ) for key in Object.keys(data.convention).filter (x) -> !~Object.keys(sumData.scores).indexOf x sumData.period.push data.file # get total for percentage (if key isnt 'lang' total = 0 sumData.scores[key].column.forEach (elem) -> total += sumData.scores[key][elem.key] elem.code = hljs.highlight(getHighlightName(lang), elem.code).value sumData.scores[key].total = total ) for key of sumData.scores callback null, sumData
111465
# # service layer # # Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> logger = (require './helpers').logger helpers = (require './helpers') http = require 'http' fs = require 'fs' zlib = require 'zlib' path = require 'path' spawn = require('child_process').spawn persistence = require './persistence' timeline = require './timeline' parser = require './parser/parser' schedule = require 'node-schedule' _ = require 'underscore' hljs = require 'highlight.js' # connect MongoDB persistence.open (err) -> return logger.error 'mongodb is not connected', {err: err} if err? logger.info 'mongodb is connected' # directory for temporary download json files from github archive archiveDir = "#{__dirname}/archive" fs.exists archiveDir, (exist) -> if not exist then fs.mkdirSync archiveDir service = module.exports = # description object to display infomation footer in site totalDesc: lastUpdate: null startDate: null endDate: null regdate: null # download timeline json file from github archive fetchGithubArchive: (datetime, callback) -> (http.get "http://data.githubarchive.org/#{datetime}.json.gz", (res) -> gzip = zlib.createGunzip() fstream = fs.createWriteStream "#{archiveDir}/#{datetime}.json" unzip = res.pipe gzip unzip.pipe fstream unzip.on 'end', -> logger.info "downloaded #{datetime}.json" importIntoMongodb(datetime, callback) ).on 'error', (e) -> logger.error 'fetch githubarchive: ', {err: e} processTimeline: (callback) -> persistence.findOneWorklogToProcess (err, worklog) -> logger.error 'findOneWorklogToProcess: ', {err: err} if err? return callback() if err? or not worklog? logger.debug "found worklog to process : #{worklog.file}" timeline.checkApiLimit (remainingCount) -> if remainingCount > 2500 persistence.processWorklog worklog._id, (err) -> if err? logger.error 'findOneWorklogs: ', {err: err} return callback err logger.debug "start processing : #{worklog.file}" persistence.findTimeline worklog.file, (err, cursor) -> if err? logger.error 'findOneWorklogs: ', {err: err} return callback err logger.debug "found timeline : #{worklog.file}" cursor.count (err, count) -> logger.debug "timer #{worklog.file} has #{count}" isCompleted = false processCount = 0 innerLoop = (cur, concurrency) -> innerLoop(cur, concurrency - 1) if concurrency? and concurrency > 1 logger.debug "start batch ##{concurrency}" if concurrency? and concurrency > 1 processCount += 1 cur.nextObject (err, item) -> if err? logger.error "in nextObject: ", {err: err} return if item? logger.debug "found item", {item: item._id} urls = timeline.getCommitUrls item logger.debug "urls: #{urls.length} - ", {urls: urls} if urls.length is 0 innerLoop cur return invokedInnerLoop = false urls.forEach (url) -> timeline.getCommitInfo url, (err, commit) -> if err? logger.error 'getCommitInfo: ', {err: err, limit: /^API Rate Limit Exceeded/i.test(err.message), isCompleted: isCompleted, processCount: processCount} if /^API Rate Limit Exceeded/i.test(err.message) and not isCompleted and processCount > 2000 isCompleted = true persistence.completeWorklog worklog._id, (err) -> if err? isCompleted = false logger.error 'completeWorklog: ', {err: err} logger.debug 'completed worklog', {file: worklog.file} else if not /^API Rate Limit Exceeded/i.test(err.message) innerLoop cur else logger.debug "parsing commit #{url} : ", {commit: commit} conventions = parser.parse commit logger.debug "get conventions ", {convention: conventions} conventions.forEach (conv) -> data = file: worklog.file lang: conv.lang convention: conv regdate: new Date() persistence.insertConvention data, (err) -> logger.error 'insertConvention', {err: err} if err? logger.info "insered convention - #{processCount}" logger.debug "before callback #{invokedInnerLoop} - #{item._id}" if not invokedInnerLoop logger.debug "call recurrsive - #{item._id}" innerLoop cur invokedInnerLoop = true else logger.debug "no item - #{processCount}" if not isCompleted and processCount > 2000 isCompleted = true persistence.completeWorklog worklog._id, (err) -> if err? isCompleted = false logger.error 'completeWorklog: ', {err: err} logger.debug 'completed worklog', {file: worklog.file} innerLoop(cursor, 5) callback() summarizeScore: (callback) -> persistence.findOneWorklogToSummarize (err, worklog) -> logger.error 'findOneWorklogToSummarize: ', {err: err} if err? return callback() if err? or not worklog? # summarize score in case of completed 2 hours ago if new Date - worklog.completeDate > 7200000 persistence.findConvention worklog.file, (err, cursor) -> if err? logger.error 'findConvention: ', {err: err} return cursor.toArray (err, docs) -> conventionList = [] docs.forEach (doc) -> if hasLang(conventionList , doc) baseConv = getConventionByLang doc.lang, conventionList mergeConvention baseConv.convention, doc.convention else delete doc._id doc.regdate = new Date doc.shortfile = doc.file.substr 0, doc.file.lastIndexOf '-' conventionList.push doc # convert commits to commit count ( ( value.commits = value.commits.length if value.commits? ) for key, value of item.convention ) for item in conventionList fileOfDay = worklog.file.substr 0, worklog.file.lastIndexOf '-' # merge convention if convention of same is exist mergeInExistConvention = (convList) -> if convList.length conv = convList.pop() persistence.findScoreByFileAndLang fileOfDay, conv.lang, (err, item) -> if err? logger.error 'findScoreByFile', {err: err} return logger.debug 'findScoreByFileAndLang', {item: item} if item? mergeConvention conv.convention, item.convention, conv._id = item._id persistence.upsertScore conv, (err) -> if err? logger.error 'upsertScore', {err: err} logger.info 'upserted score', {conv: conv} mergeInExistConvention convList else persistence.summarizeWorklog worklog._id, (err) -> if err? logger.error 'summarizeWorklog', {err: err} return logger.info 'summarized worklog', {file: worklog.file} persistence.dropTimeline worklog.file, (err) -> if err? logger.error 'drop timeline collection', {err: err} return logger.info 'dropped timeline collection', {collection: worklog.file} mergeInExistConvention conventionList callback() else callback() findScore: (lang, callback) -> persistence.findScoreByLang lang, (err, cursor) -> if err? logger.error 'findScoreByLang', {err: err} return callback(err) langParser = parser.getParser(".#{lang}") if (langParser) languageDescription = parser.getParser(".#{lang}").parse("", {}, "") else callback new Error "#{lang} is not found" dailyData = [] cursor.toArray (err, docs) -> logger.error "findScoreByLang toArray", {err: err} if err? logger.debug "findByLang", {docs: docs} if docs?.length docs.forEach (doc) -> # set convention description from parser (if key isnt 'lang' doc.convention[key].title = languageDescription[key].title doc.convention[key].column = languageDescription[key].column ) for key of doc.convention score = lang: lang file: doc.shortfile convention: doc.convention dailyData.push score makeResult(lang, dailyData, callback) else callback new Error "#{lang} is not found" findDescription: (force, callback) -> # get commit count from cacahing when cache value is exist and in 1 hour if not force and service.totalDesc.regdate? and (new Date - service.totalDesc.regdate) < 3600000 callback null, service.totalDesc else desc = {} persistence.findLastestScore (err, item) -> if err? logger.error 'findLastestScore', {err: err} return callback err if item? # caching service.totalDesc.lastUpdate = item.file persistence.findPeriodOfScore (err, docs) -> if err? logger.error 'findPeriodOfScore', {err: err} return callback err if docs?.length > 0 docs.sort (a, b) -> if a.shortfile > b.shortfile then 1 else -1 # caching service.totalDesc.startDate = docs[0].shortfile service.totalDesc.endDate = docs[docs.length - 1].shortfile service.totalDesc.regdate = new Date callback null, service.totalDesc else callback null, service.totalDesc # private hasLang = (sum, elem) -> sum.some (el) -> el.lang is elem.lang getConventionByLang = (lang, convList) -> result = null convList.forEach (elem) -> result = elem if elem.lang is lang result getHighlightName = (lang) -> map = js: 'javascript' java: 'java' py: 'python' scala: 'scala' rb: 'ruby' cs: 'cs' php: 'php' map[lang] mongoImportCmd = "" findMongoImportCmd = (datetime, callback) -> if (mongoImportCmd) callback null, mongoImportCmd else which = spawn 'which', ["mongoimport"] which.stdout.on 'data', (data) -> mongoImportCmd = data.toString() which.on 'exit', (code) -> if (code is 0) # remove trailing new line mongoImportCmd = mongoImportCmd.match(/([\w\/]+)/)[0] if mongoImportCmd.match(/([\w\/]+)/) callback null, mongoImportCmd else logger.error "mongoimport doesn't exist." callback(code) importIntoMongodb = (datetime, callback) -> findMongoImportCmd datetime, (err, mongoCmd) -> if err? logger.error "error occured during mongoimport" else args = [ '--host', process.env['MONGODB_HOST'] '--port', process.env['MONGODB_PORT'] '--db', 'popular_convention2' '--collection', datetime '--file', "#{archiveDir}/#{datetime}.json" '--type', 'json' ] if process.env['NODE_ENV'] is 'production' args = args.concat [ '--username', process.env["MONGODB_USER"] '--password', process.env["MONGODB_PASS"] ] mongoimport = spawn mongoCmd, args mongoimport.stderr.on 'data', (data) -> logger.error "mongoimport error occured" mongoimport.on 'close', (code) -> logger.info "mongoimport exited with code #{code}" doc = file: datetime inProcess: false completed: false summarize: false persistence.insertWorklogs doc, (-> callback()) if code is 0 callback(code) if code isnt 0 deleteArchiveFile(datetime) deleteArchiveFile = (datetime) -> fs.unlink "#{archiveDir}/#{datetime}.json", (err) -> logger.error "delete #{archiveDir}/#{datetime}.json" if err mergeConvention = (baseConvention, newConvention) -> ( if key isnt '<KEY>' if newConvention[key]? conv[k] += newConvention[key][k] for k of conv when k isnt 'commits' if conv.commits.concat? conv.commits = _.uniq(conv.commits.concat newConvention[key].commits) else conv.commits = conv.commits + newConvention[key].commits )for key, conv of baseConvention makeResult = (lang, dailyData, callback) -> sumData = lang: lang period: [] raw: dailyData dailyData.forEach (data) -> if not sumData.scores? sumData.scores = data.convention sumData.period.push data.file else (if key isnt 'lang' if (data.convention[key]?) sumData.scores[key].column.forEach (elem) -> sumData.scores[key][elem.key] += data.convention[key][elem.key] sumData.scores[key].commits += data.convention[key].commits ) for key of sumData.scores # add new field not exist ( sumData.scores[key] = data.convention[key] ) for key in Object.keys(data.convention).filter (x) -> !~Object.keys(sumData.scores).indexOf x sumData.period.push data.file # get total for percentage (if key isnt 'lang' total = 0 sumData.scores[key].column.forEach (elem) -> total += sumData.scores[key][elem.key] elem.code = hljs.highlight(getHighlightName(lang), elem.code).value sumData.scores[key].total = total ) for key of sumData.scores callback null, sumData
true
# # service layer # # Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/> # Licensed under the MIT license. # <http://outsider.mit-license.org/> logger = (require './helpers').logger helpers = (require './helpers') http = require 'http' fs = require 'fs' zlib = require 'zlib' path = require 'path' spawn = require('child_process').spawn persistence = require './persistence' timeline = require './timeline' parser = require './parser/parser' schedule = require 'node-schedule' _ = require 'underscore' hljs = require 'highlight.js' # connect MongoDB persistence.open (err) -> return logger.error 'mongodb is not connected', {err: err} if err? logger.info 'mongodb is connected' # directory for temporary download json files from github archive archiveDir = "#{__dirname}/archive" fs.exists archiveDir, (exist) -> if not exist then fs.mkdirSync archiveDir service = module.exports = # description object to display infomation footer in site totalDesc: lastUpdate: null startDate: null endDate: null regdate: null # download timeline json file from github archive fetchGithubArchive: (datetime, callback) -> (http.get "http://data.githubarchive.org/#{datetime}.json.gz", (res) -> gzip = zlib.createGunzip() fstream = fs.createWriteStream "#{archiveDir}/#{datetime}.json" unzip = res.pipe gzip unzip.pipe fstream unzip.on 'end', -> logger.info "downloaded #{datetime}.json" importIntoMongodb(datetime, callback) ).on 'error', (e) -> logger.error 'fetch githubarchive: ', {err: e} processTimeline: (callback) -> persistence.findOneWorklogToProcess (err, worklog) -> logger.error 'findOneWorklogToProcess: ', {err: err} if err? return callback() if err? or not worklog? logger.debug "found worklog to process : #{worklog.file}" timeline.checkApiLimit (remainingCount) -> if remainingCount > 2500 persistence.processWorklog worklog._id, (err) -> if err? logger.error 'findOneWorklogs: ', {err: err} return callback err logger.debug "start processing : #{worklog.file}" persistence.findTimeline worklog.file, (err, cursor) -> if err? logger.error 'findOneWorklogs: ', {err: err} return callback err logger.debug "found timeline : #{worklog.file}" cursor.count (err, count) -> logger.debug "timer #{worklog.file} has #{count}" isCompleted = false processCount = 0 innerLoop = (cur, concurrency) -> innerLoop(cur, concurrency - 1) if concurrency? and concurrency > 1 logger.debug "start batch ##{concurrency}" if concurrency? and concurrency > 1 processCount += 1 cur.nextObject (err, item) -> if err? logger.error "in nextObject: ", {err: err} return if item? logger.debug "found item", {item: item._id} urls = timeline.getCommitUrls item logger.debug "urls: #{urls.length} - ", {urls: urls} if urls.length is 0 innerLoop cur return invokedInnerLoop = false urls.forEach (url) -> timeline.getCommitInfo url, (err, commit) -> if err? logger.error 'getCommitInfo: ', {err: err, limit: /^API Rate Limit Exceeded/i.test(err.message), isCompleted: isCompleted, processCount: processCount} if /^API Rate Limit Exceeded/i.test(err.message) and not isCompleted and processCount > 2000 isCompleted = true persistence.completeWorklog worklog._id, (err) -> if err? isCompleted = false logger.error 'completeWorklog: ', {err: err} logger.debug 'completed worklog', {file: worklog.file} else if not /^API Rate Limit Exceeded/i.test(err.message) innerLoop cur else logger.debug "parsing commit #{url} : ", {commit: commit} conventions = parser.parse commit logger.debug "get conventions ", {convention: conventions} conventions.forEach (conv) -> data = file: worklog.file lang: conv.lang convention: conv regdate: new Date() persistence.insertConvention data, (err) -> logger.error 'insertConvention', {err: err} if err? logger.info "insered convention - #{processCount}" logger.debug "before callback #{invokedInnerLoop} - #{item._id}" if not invokedInnerLoop logger.debug "call recurrsive - #{item._id}" innerLoop cur invokedInnerLoop = true else logger.debug "no item - #{processCount}" if not isCompleted and processCount > 2000 isCompleted = true persistence.completeWorklog worklog._id, (err) -> if err? isCompleted = false logger.error 'completeWorklog: ', {err: err} logger.debug 'completed worklog', {file: worklog.file} innerLoop(cursor, 5) callback() summarizeScore: (callback) -> persistence.findOneWorklogToSummarize (err, worklog) -> logger.error 'findOneWorklogToSummarize: ', {err: err} if err? return callback() if err? or not worklog? # summarize score in case of completed 2 hours ago if new Date - worklog.completeDate > 7200000 persistence.findConvention worklog.file, (err, cursor) -> if err? logger.error 'findConvention: ', {err: err} return cursor.toArray (err, docs) -> conventionList = [] docs.forEach (doc) -> if hasLang(conventionList , doc) baseConv = getConventionByLang doc.lang, conventionList mergeConvention baseConv.convention, doc.convention else delete doc._id doc.regdate = new Date doc.shortfile = doc.file.substr 0, doc.file.lastIndexOf '-' conventionList.push doc # convert commits to commit count ( ( value.commits = value.commits.length if value.commits? ) for key, value of item.convention ) for item in conventionList fileOfDay = worklog.file.substr 0, worklog.file.lastIndexOf '-' # merge convention if convention of same is exist mergeInExistConvention = (convList) -> if convList.length conv = convList.pop() persistence.findScoreByFileAndLang fileOfDay, conv.lang, (err, item) -> if err? logger.error 'findScoreByFile', {err: err} return logger.debug 'findScoreByFileAndLang', {item: item} if item? mergeConvention conv.convention, item.convention, conv._id = item._id persistence.upsertScore conv, (err) -> if err? logger.error 'upsertScore', {err: err} logger.info 'upserted score', {conv: conv} mergeInExistConvention convList else persistence.summarizeWorklog worklog._id, (err) -> if err? logger.error 'summarizeWorklog', {err: err} return logger.info 'summarized worklog', {file: worklog.file} persistence.dropTimeline worklog.file, (err) -> if err? logger.error 'drop timeline collection', {err: err} return logger.info 'dropped timeline collection', {collection: worklog.file} mergeInExistConvention conventionList callback() else callback() findScore: (lang, callback) -> persistence.findScoreByLang lang, (err, cursor) -> if err? logger.error 'findScoreByLang', {err: err} return callback(err) langParser = parser.getParser(".#{lang}") if (langParser) languageDescription = parser.getParser(".#{lang}").parse("", {}, "") else callback new Error "#{lang} is not found" dailyData = [] cursor.toArray (err, docs) -> logger.error "findScoreByLang toArray", {err: err} if err? logger.debug "findByLang", {docs: docs} if docs?.length docs.forEach (doc) -> # set convention description from parser (if key isnt 'lang' doc.convention[key].title = languageDescription[key].title doc.convention[key].column = languageDescription[key].column ) for key of doc.convention score = lang: lang file: doc.shortfile convention: doc.convention dailyData.push score makeResult(lang, dailyData, callback) else callback new Error "#{lang} is not found" findDescription: (force, callback) -> # get commit count from cacahing when cache value is exist and in 1 hour if not force and service.totalDesc.regdate? and (new Date - service.totalDesc.regdate) < 3600000 callback null, service.totalDesc else desc = {} persistence.findLastestScore (err, item) -> if err? logger.error 'findLastestScore', {err: err} return callback err if item? # caching service.totalDesc.lastUpdate = item.file persistence.findPeriodOfScore (err, docs) -> if err? logger.error 'findPeriodOfScore', {err: err} return callback err if docs?.length > 0 docs.sort (a, b) -> if a.shortfile > b.shortfile then 1 else -1 # caching service.totalDesc.startDate = docs[0].shortfile service.totalDesc.endDate = docs[docs.length - 1].shortfile service.totalDesc.regdate = new Date callback null, service.totalDesc else callback null, service.totalDesc # private hasLang = (sum, elem) -> sum.some (el) -> el.lang is elem.lang getConventionByLang = (lang, convList) -> result = null convList.forEach (elem) -> result = elem if elem.lang is lang result getHighlightName = (lang) -> map = js: 'javascript' java: 'java' py: 'python' scala: 'scala' rb: 'ruby' cs: 'cs' php: 'php' map[lang] mongoImportCmd = "" findMongoImportCmd = (datetime, callback) -> if (mongoImportCmd) callback null, mongoImportCmd else which = spawn 'which', ["mongoimport"] which.stdout.on 'data', (data) -> mongoImportCmd = data.toString() which.on 'exit', (code) -> if (code is 0) # remove trailing new line mongoImportCmd = mongoImportCmd.match(/([\w\/]+)/)[0] if mongoImportCmd.match(/([\w\/]+)/) callback null, mongoImportCmd else logger.error "mongoimport doesn't exist." callback(code) importIntoMongodb = (datetime, callback) -> findMongoImportCmd datetime, (err, mongoCmd) -> if err? logger.error "error occured during mongoimport" else args = [ '--host', process.env['MONGODB_HOST'] '--port', process.env['MONGODB_PORT'] '--db', 'popular_convention2' '--collection', datetime '--file', "#{archiveDir}/#{datetime}.json" '--type', 'json' ] if process.env['NODE_ENV'] is 'production' args = args.concat [ '--username', process.env["MONGODB_USER"] '--password', process.env["MONGODB_PASS"] ] mongoimport = spawn mongoCmd, args mongoimport.stderr.on 'data', (data) -> logger.error "mongoimport error occured" mongoimport.on 'close', (code) -> logger.info "mongoimport exited with code #{code}" doc = file: datetime inProcess: false completed: false summarize: false persistence.insertWorklogs doc, (-> callback()) if code is 0 callback(code) if code isnt 0 deleteArchiveFile(datetime) deleteArchiveFile = (datetime) -> fs.unlink "#{archiveDir}/#{datetime}.json", (err) -> logger.error "delete #{archiveDir}/#{datetime}.json" if err mergeConvention = (baseConvention, newConvention) -> ( if key isnt 'PI:KEY:<KEY>END_PI' if newConvention[key]? conv[k] += newConvention[key][k] for k of conv when k isnt 'commits' if conv.commits.concat? conv.commits = _.uniq(conv.commits.concat newConvention[key].commits) else conv.commits = conv.commits + newConvention[key].commits )for key, conv of baseConvention makeResult = (lang, dailyData, callback) -> sumData = lang: lang period: [] raw: dailyData dailyData.forEach (data) -> if not sumData.scores? sumData.scores = data.convention sumData.period.push data.file else (if key isnt 'lang' if (data.convention[key]?) sumData.scores[key].column.forEach (elem) -> sumData.scores[key][elem.key] += data.convention[key][elem.key] sumData.scores[key].commits += data.convention[key].commits ) for key of sumData.scores # add new field not exist ( sumData.scores[key] = data.convention[key] ) for key in Object.keys(data.convention).filter (x) -> !~Object.keys(sumData.scores).indexOf x sumData.period.push data.file # get total for percentage (if key isnt 'lang' total = 0 sumData.scores[key].column.forEach (elem) -> total += sumData.scores[key][elem.key] elem.code = hljs.highlight(getHighlightName(lang), elem.code).value sumData.scores[key].total = total ) for key of sumData.scores callback null, sumData
[ { "context": "r\n @renderer.pause()\n\n getName: -> 'Extruded'\n\n getForm: ->\n @runButton = $('<button", "end": 13378, "score": 0.9986192584037781, "start": 13370, "tag": "NAME", "value": "Extruded" } ]
csat/visualization/assets/coffeescripts/strategies.coffee
GaretJax/csat
0
class Strategy getName: -> '<Abstract strategy>' activate: (@viewer) -> deactivate: -> setScene: (@scene) -> getForm: -> $('<div/>') .addClass('strategy-config') .append($('<p class="muted">No settings for this strategy</p>')) class SingleStrategy extends Strategy constructor: (@layoutFactories) -> @config = new LayoutConfigurator(@layoutFactories) @config.callbacks.layoutChanged.add(@_layoutChangedCb) getName: -> 'Single graph' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) $('<div/>').addClass('strategy-config') .append(@config.getForm()) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown)) _layoutStartedCb: => @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: => @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.run()) _layoutDoneCb: => if @_switchingLayout @mainStatus.removeClass('running').find('div').text('') @_switchingLayout = false else @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) _layoutChangedCb: (factory) => if @renderer @_switchingLayout = true if not @renderer.layout or not @renderer.isRunning() @_layoutDoneCb() @renderer.setLayout(@_getLayout()) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) return _getLayout: -> layout = @config.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout activate: (@viewer) -> if not @renderer @renderer = new GraphRenderer(@viewer.model, @viewer) @_layoutChangedCb() else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer deactivate: -> if @renderer @renderer.pause() class ClusteredStrategy extends SingleStrategy getName: -> 'Clustered' activate: (@viewer) -> if not @renderer @renderer = new ClusteredGraphRenderer(@viewer.model, @viewer) @_layoutChangedCb() else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer class DomainStrategy extends Strategy constructor: (@domainLayoutFactories, @globalLayoutFactories) -> @globalLayoutConfig = new LayoutConfigurator(@globalLayoutFactories) @globalLayoutConfig.callbacks.layoutChanged.add(@_globalLayoutChangedCb) getName: -> 'Multi-level (per domain)' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) config = @globalLayoutConfig.getForm() $('.algorithm-select label', config).text('Outer algorithm') $('<div/>').addClass('strategy-config') .append(config) .append( $('<p/>') .addClass('muted') .text('Domain-specific layout algorithms can be configured in the domain settings.') ) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown)) setupDomain: (domainModel, i) => el = $(".sidebar .domains li:nth-child(#{i + 1})", @viewer.container) config = new LayoutConfigurator(@domainLayoutFactories) actions = $('<div/>') .addClass('actions') .append($('<a href="#"/>') .append($('<i class="icon-pause"/>')) .append($('<i class="icon-play"/>')) .one('click', (e) => e.preventDefault() @renderer.runPartition(i) )) .append($.spinner(20, 'mini')) domain = { id: i element: el config: config actions: actions form: config.getForm() } config.callbacks.layoutChanged.add((factory) => @_domainLayoutChangedCb(factory, domain) ) domain _getGlobalLayout: -> layout = @globalLayoutConfig.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout _getDomainLayout: (domain) -> layout = domain.config.getLayout() layout.callbacks.started.add(=> @_layoutStartedCb(domain)) layout.callbacks.resumed.add(=> @_layoutStartedCb(domain)) layout.callbacks.paused.add(=> @_layoutPausedCb(domain)) layout.callbacks.done.add(=> @_layoutDoneCb(domain)) layout _layoutStartedCb: (domain) => if domain domain.element.addClass('running').removeClass('paused') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.pausePartition(domain.id) ) if @renderer.someLayoutsRunning() @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: (domain) => if domain domain.element.addClass('paused').removeClass('running') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.runPartition(domain.id) ) if not @renderer.someLayoutsRunning() if @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) else @mainStatus.removeClass('running').find('div').text('Done') @runButton.text('Resume').off('click').one('click', => @renderer.run()) _layoutDoneCb: (domain) => if domain domain.element.removeClass('paused').removeClass('running') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.runPartition(domain.id) ) if not @renderer.someLayoutsRunning() if not @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) else @mainStatus.removeClass('running').find('div').text('Paused.') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) _globalLayoutChangedCb: (factory) => if @renderer running = @renderer.globalLayout and @renderer.globalLayout.isRunning() @renderer.setGlobalLayout(@_getGlobalLayout()) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) if running @renderer.runGlobal() return _domainLayoutChangedCb: (factory, domain) => if @renderer @renderer.stopPartition(domain.id) layout = @_getDomainLayout(domain) running = @renderer.allLayoutsRunning() @renderer.setPartitionLayout(domain.id, layout) if running later(10, => @renderer.runPartition(domain.id)) return activate: (@viewer) -> if not @renderer @renderer = new PartitionedGraphRenderer(@viewer.model, @viewer) @renderer.setGlobalLayout(@_getGlobalLayout()) @domains = [] @viewer.model.domains.iter((domainModel, i) => domain = @setupDomain(domainModel, i) @renderer.setPartitionLayout(i, @_getDomainLayout(domain)) @domains.push(domain) ) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @domains.iter((domain, i) => domain.element.find('a.settings').before(domain.actions) settings = domain.element.find('.pop-out') tab = makeSettingsTab(settings, "layout-settings-#{i}", 'Layout') tab.append(domain.form) settings.tabs('refresh') ) @renderer.step() @renderer deactivate: -> @renderer.stop() @domains.iter((domain, i) => domain.actions.detach() domain.form.detach() removeSettingsTab(domain.element.find('.pop-out'), "layout-settings-#{i}") ) class ExtrudedStrategy extends Strategy constructor: (@domainsLayoutFactories, @nodesLayoutFactories) -> @domainsLayoutConfig = new LayoutConfigurator(@domainsLayoutFactories) @nodesLayoutConfig = new LayoutConfigurator(@nodesLayoutFactories) @domainsLayoutConfig.callbacks.layoutChanged.add(@_domainsLayoutChangedCb) @nodesLayoutConfig.callbacks.layoutChanged.add(@_nodesLayoutChangedCb) _domainsLayoutChangedCb: (factory) => if @renderer @renderer.domainsLayout.stop() @_layoutDoneCb() @renderer.setDomainsLayout(@_getLayout(@domainsLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) _nodesLayoutChangedCb: (factory) => if @renderer @renderer.nodesLayout.stop() @_layoutDoneCb() @renderer.setNodesLayout(@_getLayout(@nodesLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) _layoutStartedCb: => @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: => if not @renderer.someLayoutsRunning() @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) _layoutDoneCb: => if @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Paused.') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) else if @renderer.someLayoutsRunning() @runButton.text('Pause').off('click').one('click', => @renderer.pause()) else # All done @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) _getLayout: (config) -> layout = config.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout activate: (@viewer) -> if not @renderer @renderer = new ExtrudedGraphRenderer(@viewer.model, @viewer) @renderer.setDomainsLayout(@_getLayout(@domainsLayoutConfig)) @renderer.setNodesLayout(@_getLayout(@nodesLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer deactivate: -> if @renderer @renderer.pause() getName: -> 'Extruded' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) domainsConfig = @domainsLayoutConfig.getForm() $('.algorithm-select label', domainsConfig).text('Domains algorithm') nodesConfig = @nodesLayoutConfig.getForm() $('.algorithm-select label', nodesConfig).text('Nodes algorithm') $('<div/>').addClass('strategy-config extruded') .append(domainsConfig) .append(nodesConfig) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown))
31389
class Strategy getName: -> '<Abstract strategy>' activate: (@viewer) -> deactivate: -> setScene: (@scene) -> getForm: -> $('<div/>') .addClass('strategy-config') .append($('<p class="muted">No settings for this strategy</p>')) class SingleStrategy extends Strategy constructor: (@layoutFactories) -> @config = new LayoutConfigurator(@layoutFactories) @config.callbacks.layoutChanged.add(@_layoutChangedCb) getName: -> 'Single graph' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) $('<div/>').addClass('strategy-config') .append(@config.getForm()) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown)) _layoutStartedCb: => @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: => @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.run()) _layoutDoneCb: => if @_switchingLayout @mainStatus.removeClass('running').find('div').text('') @_switchingLayout = false else @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) _layoutChangedCb: (factory) => if @renderer @_switchingLayout = true if not @renderer.layout or not @renderer.isRunning() @_layoutDoneCb() @renderer.setLayout(@_getLayout()) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) return _getLayout: -> layout = @config.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout activate: (@viewer) -> if not @renderer @renderer = new GraphRenderer(@viewer.model, @viewer) @_layoutChangedCb() else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer deactivate: -> if @renderer @renderer.pause() class ClusteredStrategy extends SingleStrategy getName: -> 'Clustered' activate: (@viewer) -> if not @renderer @renderer = new ClusteredGraphRenderer(@viewer.model, @viewer) @_layoutChangedCb() else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer class DomainStrategy extends Strategy constructor: (@domainLayoutFactories, @globalLayoutFactories) -> @globalLayoutConfig = new LayoutConfigurator(@globalLayoutFactories) @globalLayoutConfig.callbacks.layoutChanged.add(@_globalLayoutChangedCb) getName: -> 'Multi-level (per domain)' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) config = @globalLayoutConfig.getForm() $('.algorithm-select label', config).text('Outer algorithm') $('<div/>').addClass('strategy-config') .append(config) .append( $('<p/>') .addClass('muted') .text('Domain-specific layout algorithms can be configured in the domain settings.') ) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown)) setupDomain: (domainModel, i) => el = $(".sidebar .domains li:nth-child(#{i + 1})", @viewer.container) config = new LayoutConfigurator(@domainLayoutFactories) actions = $('<div/>') .addClass('actions') .append($('<a href="#"/>') .append($('<i class="icon-pause"/>')) .append($('<i class="icon-play"/>')) .one('click', (e) => e.preventDefault() @renderer.runPartition(i) )) .append($.spinner(20, 'mini')) domain = { id: i element: el config: config actions: actions form: config.getForm() } config.callbacks.layoutChanged.add((factory) => @_domainLayoutChangedCb(factory, domain) ) domain _getGlobalLayout: -> layout = @globalLayoutConfig.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout _getDomainLayout: (domain) -> layout = domain.config.getLayout() layout.callbacks.started.add(=> @_layoutStartedCb(domain)) layout.callbacks.resumed.add(=> @_layoutStartedCb(domain)) layout.callbacks.paused.add(=> @_layoutPausedCb(domain)) layout.callbacks.done.add(=> @_layoutDoneCb(domain)) layout _layoutStartedCb: (domain) => if domain domain.element.addClass('running').removeClass('paused') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.pausePartition(domain.id) ) if @renderer.someLayoutsRunning() @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: (domain) => if domain domain.element.addClass('paused').removeClass('running') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.runPartition(domain.id) ) if not @renderer.someLayoutsRunning() if @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) else @mainStatus.removeClass('running').find('div').text('Done') @runButton.text('Resume').off('click').one('click', => @renderer.run()) _layoutDoneCb: (domain) => if domain domain.element.removeClass('paused').removeClass('running') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.runPartition(domain.id) ) if not @renderer.someLayoutsRunning() if not @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) else @mainStatus.removeClass('running').find('div').text('Paused.') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) _globalLayoutChangedCb: (factory) => if @renderer running = @renderer.globalLayout and @renderer.globalLayout.isRunning() @renderer.setGlobalLayout(@_getGlobalLayout()) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) if running @renderer.runGlobal() return _domainLayoutChangedCb: (factory, domain) => if @renderer @renderer.stopPartition(domain.id) layout = @_getDomainLayout(domain) running = @renderer.allLayoutsRunning() @renderer.setPartitionLayout(domain.id, layout) if running later(10, => @renderer.runPartition(domain.id)) return activate: (@viewer) -> if not @renderer @renderer = new PartitionedGraphRenderer(@viewer.model, @viewer) @renderer.setGlobalLayout(@_getGlobalLayout()) @domains = [] @viewer.model.domains.iter((domainModel, i) => domain = @setupDomain(domainModel, i) @renderer.setPartitionLayout(i, @_getDomainLayout(domain)) @domains.push(domain) ) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @domains.iter((domain, i) => domain.element.find('a.settings').before(domain.actions) settings = domain.element.find('.pop-out') tab = makeSettingsTab(settings, "layout-settings-#{i}", 'Layout') tab.append(domain.form) settings.tabs('refresh') ) @renderer.step() @renderer deactivate: -> @renderer.stop() @domains.iter((domain, i) => domain.actions.detach() domain.form.detach() removeSettingsTab(domain.element.find('.pop-out'), "layout-settings-#{i}") ) class ExtrudedStrategy extends Strategy constructor: (@domainsLayoutFactories, @nodesLayoutFactories) -> @domainsLayoutConfig = new LayoutConfigurator(@domainsLayoutFactories) @nodesLayoutConfig = new LayoutConfigurator(@nodesLayoutFactories) @domainsLayoutConfig.callbacks.layoutChanged.add(@_domainsLayoutChangedCb) @nodesLayoutConfig.callbacks.layoutChanged.add(@_nodesLayoutChangedCb) _domainsLayoutChangedCb: (factory) => if @renderer @renderer.domainsLayout.stop() @_layoutDoneCb() @renderer.setDomainsLayout(@_getLayout(@domainsLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) _nodesLayoutChangedCb: (factory) => if @renderer @renderer.nodesLayout.stop() @_layoutDoneCb() @renderer.setNodesLayout(@_getLayout(@nodesLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) _layoutStartedCb: => @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: => if not @renderer.someLayoutsRunning() @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) _layoutDoneCb: => if @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Paused.') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) else if @renderer.someLayoutsRunning() @runButton.text('Pause').off('click').one('click', => @renderer.pause()) else # All done @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) _getLayout: (config) -> layout = config.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout activate: (@viewer) -> if not @renderer @renderer = new ExtrudedGraphRenderer(@viewer.model, @viewer) @renderer.setDomainsLayout(@_getLayout(@domainsLayoutConfig)) @renderer.setNodesLayout(@_getLayout(@nodesLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer deactivate: -> if @renderer @renderer.pause() getName: -> '<NAME>' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) domainsConfig = @domainsLayoutConfig.getForm() $('.algorithm-select label', domainsConfig).text('Domains algorithm') nodesConfig = @nodesLayoutConfig.getForm() $('.algorithm-select label', nodesConfig).text('Nodes algorithm') $('<div/>').addClass('strategy-config extruded') .append(domainsConfig) .append(nodesConfig) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown))
true
class Strategy getName: -> '<Abstract strategy>' activate: (@viewer) -> deactivate: -> setScene: (@scene) -> getForm: -> $('<div/>') .addClass('strategy-config') .append($('<p class="muted">No settings for this strategy</p>')) class SingleStrategy extends Strategy constructor: (@layoutFactories) -> @config = new LayoutConfigurator(@layoutFactories) @config.callbacks.layoutChanged.add(@_layoutChangedCb) getName: -> 'Single graph' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) $('<div/>').addClass('strategy-config') .append(@config.getForm()) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown)) _layoutStartedCb: => @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: => @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.run()) _layoutDoneCb: => if @_switchingLayout @mainStatus.removeClass('running').find('div').text('') @_switchingLayout = false else @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) _layoutChangedCb: (factory) => if @renderer @_switchingLayout = true if not @renderer.layout or not @renderer.isRunning() @_layoutDoneCb() @renderer.setLayout(@_getLayout()) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) return _getLayout: -> layout = @config.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout activate: (@viewer) -> if not @renderer @renderer = new GraphRenderer(@viewer.model, @viewer) @_layoutChangedCb() else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer deactivate: -> if @renderer @renderer.pause() class ClusteredStrategy extends SingleStrategy getName: -> 'Clustered' activate: (@viewer) -> if not @renderer @renderer = new ClusteredGraphRenderer(@viewer.model, @viewer) @_layoutChangedCb() else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer class DomainStrategy extends Strategy constructor: (@domainLayoutFactories, @globalLayoutFactories) -> @globalLayoutConfig = new LayoutConfigurator(@globalLayoutFactories) @globalLayoutConfig.callbacks.layoutChanged.add(@_globalLayoutChangedCb) getName: -> 'Multi-level (per domain)' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) config = @globalLayoutConfig.getForm() $('.algorithm-select label', config).text('Outer algorithm') $('<div/>').addClass('strategy-config') .append(config) .append( $('<p/>') .addClass('muted') .text('Domain-specific layout algorithms can be configured in the domain settings.') ) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown)) setupDomain: (domainModel, i) => el = $(".sidebar .domains li:nth-child(#{i + 1})", @viewer.container) config = new LayoutConfigurator(@domainLayoutFactories) actions = $('<div/>') .addClass('actions') .append($('<a href="#"/>') .append($('<i class="icon-pause"/>')) .append($('<i class="icon-play"/>')) .one('click', (e) => e.preventDefault() @renderer.runPartition(i) )) .append($.spinner(20, 'mini')) domain = { id: i element: el config: config actions: actions form: config.getForm() } config.callbacks.layoutChanged.add((factory) => @_domainLayoutChangedCb(factory, domain) ) domain _getGlobalLayout: -> layout = @globalLayoutConfig.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout _getDomainLayout: (domain) -> layout = domain.config.getLayout() layout.callbacks.started.add(=> @_layoutStartedCb(domain)) layout.callbacks.resumed.add(=> @_layoutStartedCb(domain)) layout.callbacks.paused.add(=> @_layoutPausedCb(domain)) layout.callbacks.done.add(=> @_layoutDoneCb(domain)) layout _layoutStartedCb: (domain) => if domain domain.element.addClass('running').removeClass('paused') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.pausePartition(domain.id) ) if @renderer.someLayoutsRunning() @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: (domain) => if domain domain.element.addClass('paused').removeClass('running') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.runPartition(domain.id) ) if not @renderer.someLayoutsRunning() if @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) else @mainStatus.removeClass('running').find('div').text('Done') @runButton.text('Resume').off('click').one('click', => @renderer.run()) _layoutDoneCb: (domain) => if domain domain.element.removeClass('paused').removeClass('running') domain.actions.find('a').off('click').one('click', (e) => e.preventDefault() @renderer.runPartition(domain.id) ) if not @renderer.someLayoutsRunning() if not @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) else @mainStatus.removeClass('running').find('div').text('Paused.') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) _globalLayoutChangedCb: (factory) => if @renderer running = @renderer.globalLayout and @renderer.globalLayout.isRunning() @renderer.setGlobalLayout(@_getGlobalLayout()) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) if running @renderer.runGlobal() return _domainLayoutChangedCb: (factory, domain) => if @renderer @renderer.stopPartition(domain.id) layout = @_getDomainLayout(domain) running = @renderer.allLayoutsRunning() @renderer.setPartitionLayout(domain.id, layout) if running later(10, => @renderer.runPartition(domain.id)) return activate: (@viewer) -> if not @renderer @renderer = new PartitionedGraphRenderer(@viewer.model, @viewer) @renderer.setGlobalLayout(@_getGlobalLayout()) @domains = [] @viewer.model.domains.iter((domainModel, i) => domain = @setupDomain(domainModel, i) @renderer.setPartitionLayout(i, @_getDomainLayout(domain)) @domains.push(domain) ) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @domains.iter((domain, i) => domain.element.find('a.settings').before(domain.actions) settings = domain.element.find('.pop-out') tab = makeSettingsTab(settings, "layout-settings-#{i}", 'Layout') tab.append(domain.form) settings.tabs('refresh') ) @renderer.step() @renderer deactivate: -> @renderer.stop() @domains.iter((domain, i) => domain.actions.detach() domain.form.detach() removeSettingsTab(domain.element.find('.pop-out'), "layout-settings-#{i}") ) class ExtrudedStrategy extends Strategy constructor: (@domainsLayoutFactories, @nodesLayoutFactories) -> @domainsLayoutConfig = new LayoutConfigurator(@domainsLayoutFactories) @nodesLayoutConfig = new LayoutConfigurator(@nodesLayoutFactories) @domainsLayoutConfig.callbacks.layoutChanged.add(@_domainsLayoutChangedCb) @nodesLayoutConfig.callbacks.layoutChanged.add(@_nodesLayoutChangedCb) _domainsLayoutChangedCb: (factory) => if @renderer @renderer.domainsLayout.stop() @_layoutDoneCb() @renderer.setDomainsLayout(@_getLayout(@domainsLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) _nodesLayoutChangedCb: (factory) => if @renderer @renderer.nodesLayout.stop() @_layoutDoneCb() @renderer.setNodesLayout(@_getLayout(@nodesLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) _layoutStartedCb: => @mainStatus.addClass('running').find('div').text('Running...') @runButton.text('Pause').off('click').one('click', => @renderer.pause()) _layoutPausedCb: => if not @renderer.someLayoutsRunning() @mainStatus.removeClass('running').find('div').text('Paused') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) _layoutDoneCb: => if @renderer.someLayoutsPaused() @mainStatus.removeClass('running').find('div').text('Paused.') @runButton.text('Resume').off('click').one('click', => @renderer.resume()) else if @renderer.someLayoutsRunning() @runButton.text('Pause').off('click').one('click', => @renderer.pause()) else # All done @mainStatus.removeClass('running').find('div').text('Done.') @runButton.text('Run').off('click').one('click', => @renderer.run()) _getLayout: (config) -> layout = config.getLayout() layout.callbacks.started.add(@_layoutStartedCb) layout.callbacks.resumed.add(@_layoutStartedCb) layout.callbacks.paused.add(@_layoutPausedCb) layout.callbacks.done.add(@_layoutDoneCb) layout activate: (@viewer) -> if not @renderer @renderer = new ExtrudedGraphRenderer(@viewer.model, @viewer) @renderer.setDomainsLayout(@_getLayout(@domainsLayoutConfig)) @renderer.setNodesLayout(@_getLayout(@nodesLayoutConfig)) @renderer.draw(@viewer.getCleanScene(), @viewer.camera) else @renderer.draw(@viewer.getCleanScene(), @viewer.camera) @renderer.step() @renderer deactivate: -> if @renderer @renderer.pause() getName: -> 'PI:NAME:<NAME>END_PI' getForm: -> @runButton = $('<button/>') .addClass('btn btn-primary') .text('Run') .one('click', => @renderer.run()) menu = $('<ul/>').addClass('dropdown-menu') menu.append($('<li/>').append($('<a href="#"/>').text('Restart all').click(=> @renderer.stop() @renderer.run() ))) dropdown = $('<div/>') .addClass('btn-group') .append(@runButton) .append($('<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>')) .append(menu) @mainStatus = $('<div/>') .addClass('status') .append($.spinner(20, 'small')) .append($('<div/>')) domainsConfig = @domainsLayoutConfig.getForm() $('.algorithm-select label', domainsConfig).text('Domains algorithm') nodesConfig = @nodesLayoutConfig.getForm() $('.algorithm-select label', nodesConfig).text('Nodes algorithm') $('<div/>').addClass('strategy-config extruded') .append(domainsConfig) .append(nodesConfig) .append($('<div/>') .addClass('form-actions') .append(@mainStatus) .append(dropdown))
[ { "context": "meta:\n name: \"shiptag\"\n version: \"2019/05/25/02\"\n\ndata:\n mapname: [\n ", "end": 22, "score": 0.4568105936050415, "start": 20, "tag": "NAME", "value": "ag" } ]
fcd/shiptag.cson
xykdaGhost/poi
1
meta: name: "shiptag" version: "2019/05/25/02" data: mapname: [ "E1" "E2" "E3" "E4" "E4" "E5" ] color: [ "#9E9E9E" "#FF9800" "#03A9F4" "#8BC34A" "#FFEB3B" "#009688" ] fleetname: "zh-CN": [ "第百四战队" "第二舰队" "北方部队" "机动部队" "攻略部队" "夏威夷派遣部队" ] "zh-TW": [ "第百四戰隊" "第二艦隊" "北方部隊" "機動部隊" "攻略部隊" "夏威夷派遣部隊" ] "ja-JP": [ "第百四戦隊" "第二艦隊" "北方部隊" "機動部隊" "攻略部隊" "ハワイ派遣艦隊" ] "en-US": [ "Squad 104" "2nd Fleet" "North Force" "Task Force" "Capture Force" "Hawaii Dispatch Fleet" ]
98534
meta: name: "shipt<NAME>" version: "2019/05/25/02" data: mapname: [ "E1" "E2" "E3" "E4" "E4" "E5" ] color: [ "#9E9E9E" "#FF9800" "#03A9F4" "#8BC34A" "#FFEB3B" "#009688" ] fleetname: "zh-CN": [ "第百四战队" "第二舰队" "北方部队" "机动部队" "攻略部队" "夏威夷派遣部队" ] "zh-TW": [ "第百四戰隊" "第二艦隊" "北方部隊" "機動部隊" "攻略部隊" "夏威夷派遣部隊" ] "ja-JP": [ "第百四戦隊" "第二艦隊" "北方部隊" "機動部隊" "攻略部隊" "ハワイ派遣艦隊" ] "en-US": [ "Squad 104" "2nd Fleet" "North Force" "Task Force" "Capture Force" "Hawaii Dispatch Fleet" ]
true
meta: name: "shiptPI:NAME:<NAME>END_PI" version: "2019/05/25/02" data: mapname: [ "E1" "E2" "E3" "E4" "E4" "E5" ] color: [ "#9E9E9E" "#FF9800" "#03A9F4" "#8BC34A" "#FFEB3B" "#009688" ] fleetname: "zh-CN": [ "第百四战队" "第二舰队" "北方部队" "机动部队" "攻略部队" "夏威夷派遣部队" ] "zh-TW": [ "第百四戰隊" "第二艦隊" "北方部隊" "機動部隊" "攻略部隊" "夏威夷派遣部隊" ] "ja-JP": [ "第百四戦隊" "第二艦隊" "北方部隊" "機動部隊" "攻略部隊" "ハワイ派遣艦隊" ] "en-US": [ "Squad 104" "2nd Fleet" "North Force" "Task Force" "Capture Force" "Hawaii Dispatch Fleet" ]
[ { "context": "y, refsList of refsIndex\n\n if refKey == 'CREDO'\n continue\n\n for ref in refsL", "end": 1063, "score": 0.6590322256088257, "start": 1058, "tag": "KEY", "value": "CREDO" }, { "context": "ef.link = ref.xref_url\n\n if refKey == '...
src/glados/static/coffee/views/References/ReferencesView.coffee
BNext-IQT/glados-frontend-chembl-main-interface
33
glados.useNameSpace 'glados.views.References', ReferencesView: Backbone.View.extend initialize: -> @config = arguments[0].config @model.on 'change', @render, @ render: -> refsGroups = [] refsFilter = @config.filter if @config.is_unichem references = @model.get('_metadata').unichem if not references? @renderWhenNoRefs() return refsIndex = _.groupBy(references, 'src_name') for refKey, refsList of refsIndex refsGroups.push src_name: refKey src_url: refsList[0].src_url ref_items: refsList else references = @model.get('cross_references') if not references? @renderWhenNoRefs() return if refsFilter? references = _.filter(references, refsFilter) if references.length == 0 @renderWhenNoRefs() return refsIndex = _.groupBy(references, 'xref_src') for refKey, refsList of refsIndex if refKey == 'CREDO' continue for ref in refsList ref.src_url = ref.xref_src_url ref.link = ref.xref_url if refKey == 'PDBe' ref.id = ref.xref_id else ref.id = ref.xref_name ref.id ?= ref.xref_id ref.is_atc = refKey == 'ATC' ref.vertical_list = refKey in ['GoComponent', 'GoFunction', 'GoProcess', 'InterPro', 'Pfam'] refsGroups.push src_name: refKey src_url: refsList[0].xref_src_url ref_items: refsList refsGroups.sort (a, b) -> a.src_name.localeCompare(b.src_name) referencesContainer = $(@el) glados.Utils.fillContentForElement referencesContainer, references_groups: refsGroups renderWhenNoRefs: -> referencesContainer = $(@el) glados.Utils.fillContentForElement referencesContainer, { is_unichem: @config.is_unichem chembl_id: @model.get('id') }, 'Handlebars-Common-No-References'
104740
glados.useNameSpace 'glados.views.References', ReferencesView: Backbone.View.extend initialize: -> @config = arguments[0].config @model.on 'change', @render, @ render: -> refsGroups = [] refsFilter = @config.filter if @config.is_unichem references = @model.get('_metadata').unichem if not references? @renderWhenNoRefs() return refsIndex = _.groupBy(references, 'src_name') for refKey, refsList of refsIndex refsGroups.push src_name: refKey src_url: refsList[0].src_url ref_items: refsList else references = @model.get('cross_references') if not references? @renderWhenNoRefs() return if refsFilter? references = _.filter(references, refsFilter) if references.length == 0 @renderWhenNoRefs() return refsIndex = _.groupBy(references, 'xref_src') for refKey, refsList of refsIndex if refKey == '<KEY>' continue for ref in refsList ref.src_url = ref.xref_src_url ref.link = ref.xref_url if refKey == '<KEY>' ref.id = ref.xref_id else ref.id = ref.xref_name ref.id ?= ref.xref_id ref.is_atc = refKey == 'ATC' ref.vertical_list = refKey in ['GoComponent', 'GoFunction', 'GoProcess', 'InterPro', 'Pfam'] refsGroups.push src_name: refKey src_url: refsList[0].xref_src_url ref_items: refsList refsGroups.sort (a, b) -> a.src_name.localeCompare(b.src_name) referencesContainer = $(@el) glados.Utils.fillContentForElement referencesContainer, references_groups: refsGroups renderWhenNoRefs: -> referencesContainer = $(@el) glados.Utils.fillContentForElement referencesContainer, { is_unichem: @config.is_unichem chembl_id: @model.get('id') }, 'Handlebars-Common-No-References'
true
glados.useNameSpace 'glados.views.References', ReferencesView: Backbone.View.extend initialize: -> @config = arguments[0].config @model.on 'change', @render, @ render: -> refsGroups = [] refsFilter = @config.filter if @config.is_unichem references = @model.get('_metadata').unichem if not references? @renderWhenNoRefs() return refsIndex = _.groupBy(references, 'src_name') for refKey, refsList of refsIndex refsGroups.push src_name: refKey src_url: refsList[0].src_url ref_items: refsList else references = @model.get('cross_references') if not references? @renderWhenNoRefs() return if refsFilter? references = _.filter(references, refsFilter) if references.length == 0 @renderWhenNoRefs() return refsIndex = _.groupBy(references, 'xref_src') for refKey, refsList of refsIndex if refKey == 'PI:KEY:<KEY>END_PI' continue for ref in refsList ref.src_url = ref.xref_src_url ref.link = ref.xref_url if refKey == 'PI:KEY:<KEY>END_PI' ref.id = ref.xref_id else ref.id = ref.xref_name ref.id ?= ref.xref_id ref.is_atc = refKey == 'ATC' ref.vertical_list = refKey in ['GoComponent', 'GoFunction', 'GoProcess', 'InterPro', 'Pfam'] refsGroups.push src_name: refKey src_url: refsList[0].xref_src_url ref_items: refsList refsGroups.sort (a, b) -> a.src_name.localeCompare(b.src_name) referencesContainer = $(@el) glados.Utils.fillContentForElement referencesContainer, references_groups: refsGroups renderWhenNoRefs: -> referencesContainer = $(@el) glados.Utils.fillContentForElement referencesContainer, { is_unichem: @config.is_unichem chembl_id: @model.get('id') }, 'Handlebars-Common-No-References'
[ { "context": "menus, etc:\n\n msg.currentUser ?= new User name: @whose(msg)\n msg.currentUser.fetch()\n .then (@user", "end": 2181, "score": 0.9927724003791809, "start": 2175, "tag": "USERNAME", "value": "@whose" }, { "context": "itialState\n\n if newRecord\n slackUs...
src/app.coffee
citizencode/swarmbot
21
{airbrake} = require './util/setup' # do this first { d, json, log, p, pjson, type } = require 'lightsaber' { defaults, isEmpty, merge } = require 'lodash' swarmbot = require './models/swarmbot' KeenioInfo = require './services/keenio-info.coffee' User = require './models/user' controllers = projects: require './controllers/projects-state-controller' rewards: require './controllers/rewards-state-controller' rewardTypes: require './controllers/reward-types-state-controller' users: require './controllers/users-state-controller' class App @COIN = '❂' @MAX_SLACK_IMAGE_SIZE = Math.pow 2,19 @SLACK_NON_TEXT_FIELDS = [ 'author_icon' 'color' 'short' ] @airbrake = airbrake @init: (@robot)-> @slack = @robot.adapter.client @authFirebase() @robot.respond /(.*)/, (msg)=> @respondAndReply msg # custom catch-all routing @robot.enter (res)=> @greet res # greet new users @respondAndReply: (msg)-> @respondTo(msg).then (reply)=> debugReply pjson reply @pmReply msg, reply if @isPublic msg msg.reply "Let's take this offline. I PM'd you :smile:" @authFirebase: -> if process.env.FIREBASE_SECRET? swarmbot.firebase().authWithCustomToken process.env.FIREBASE_SECRET, (error)-> throw error if error @whose: (msg)-> "slack:#{msg.message.user.id}" @isPublic: (msg)-> msg.message.room isnt msg.message.user?.name @addResponder: (pattern, cb)-> @responses ?= [] @responses.push [pattern, cb] @respondTo: (msg)-> @route(msg) .then (textOrAttachments)=> @addFallbackTextIfNeeded textOrAttachments @route: (msg)-> debug "in @route: msg.match?[1] => #{msg.match?[1]}" # commands that were added with @addResponder: if @responses? and input = msg.match[1] for [pattern, cb] in @responses if match = input.match pattern msg.match = msg.message.match(pattern) return new Promise (resolve, reject)=> debug "Command: `#{input}`, Matched: #{pattern}" cb(msg) resolve('') # custom routing, using controllers, menus, etc: msg.currentUser ?= new User name: @whose(msg) msg.currentUser.fetch() .then (@user)=> @registerUser @user, msg.message.user, @user.newRecord() .then (@user)=> debug "state: #{@user.get 'state'}" [controllerName, action] = @user.get('state').split('#') controllerClass = controllers[controllerName] controller = new controllerClass(msg) if controllerClass? unless controller and controller[action] errorMessage = "Unexpected @user state #{@user.get('state')} -- resetting to default state" msg.send("*#{errorMessage}*") if process.env.NODE_ENV is 'development' errorLog errorMessage return @user.set('state', User::initialState) .then => @route(msg) controller.input = msg.match[1] lastMenuItems = @user.get('menu') menuAction = lastMenuItems?[controller.input?.toLowerCase()] if menuAction? # specific menu action of entered command debug "Command: #{controller.input}, controllerName: #{controllerName}, menuAction: #{json menuAction}" controller.execute(menuAction) else if controller[action]? # default action for this state debug "Command: #{controller.input}, controllerName: #{controllerName}, action: #{action}" controller[action]( @user.get('stateData') ) else throw new Error("Action for state '#{@user.get('state')}' not defined.") @pmReply: (msg, textOrAttachments)=> channel = msg.message.user.name @sendMessage channel, textOrAttachments @sendMessage: (channel, textOrAttachments)=> if type(textOrAttachments) is 'string' @robot.messageRoom(channel, textOrAttachments) else if type(textOrAttachments) in ['array', 'object'] @sendAttachmentMessage(channel, textOrAttachments) else throw new Error "Unexpected type(textOrAttachments) -> #{type(textOrAttachments)}" @sendAttachmentMessage: (channel, attachment)=> @robot.adapter.customMessage channel: channel attachments: attachment @addFallbackTextIfNeeded: (textOrAttachments)-> if type(textOrAttachments) is 'string' textOrAttachments else if type(textOrAttachments) is 'object' @fallbackForAttachment(textOrAttachments) else if type(textOrAttachments) is 'array' for attachment in textOrAttachments @fallbackForAttachment(attachment) @fallbackForAttachment: (attachment)-> if isEmpty attachment.fallback?.trim() inspectFallback "Attachment:\n#{pjson attachment}" fallbackText = @extractTextLines(attachment).join("\n") inspectFallback "Fallback text:\n#{fallbackText}" attachment.fallback = fallbackText else inspectFallback "Attachment arrived with fallback already set:\n#{pjson attachment}" attachment @extractTextLines: (element)-> lines = [] if type(element) is 'array' for item in element lines.push @extractTextLines(item)... else if type(element) is 'object' for key, value of element if (key not in @SLACK_NON_TEXT_FIELDS) and value lines.push @extractTextLines(value)... else if type(element) is 'string' or type(element) is 'number' lines.push element.toString() else throw new Error "Unexpected attachment chunk type: '#{type(element)}' for #{pjson element}" lines @registerUser: (user, slackUser, newRecord)-> attributes = lastActiveOnSlack: Date.now() state: user.get('state') or User::initialState if newRecord slackUsername = slackUser.name slackId = slackUser.id realName = slackUser.real_name emailAddress = slackUser.email_address attributes.slackUsername = slackUsername if slackUsername attributes.firstSeen = Date.now() attributes.realName = realName if realName attributes.emailAddress = emailAddress if emailAddress attributes.slackId = slackId if slackId user.update attributes .then (user)=> if newRecord (new KeenioInfo()).createUser(user) user @greet: (res)-> currentUser = new User name: @whose(res) currentUser.fetch() .then (@user)=> @user.set('state', 'users#welcome') # goes away if this is new home page .then => @route res .then (welcome)=> @pmReply res, welcome @user.set 'state', User::initialState .then => @route res .then (projects)=> @pmReply res, projects @notify: (message)-> if not App.airbrake debug """No airbrake configured; message NOT delivered: "#{message}" """ return envelope = if message instanceof Error message else new Error message App.airbrake.notify envelope, (errorNotifying, url)-> if errorNotifying debug errorNotifying else debug """Delivered to #{url} -- #{envelope.message}""" module.exports = App
131626
{airbrake} = require './util/setup' # do this first { d, json, log, p, pjson, type } = require 'lightsaber' { defaults, isEmpty, merge } = require 'lodash' swarmbot = require './models/swarmbot' KeenioInfo = require './services/keenio-info.coffee' User = require './models/user' controllers = projects: require './controllers/projects-state-controller' rewards: require './controllers/rewards-state-controller' rewardTypes: require './controllers/reward-types-state-controller' users: require './controllers/users-state-controller' class App @COIN = '❂' @MAX_SLACK_IMAGE_SIZE = Math.pow 2,19 @SLACK_NON_TEXT_FIELDS = [ 'author_icon' 'color' 'short' ] @airbrake = airbrake @init: (@robot)-> @slack = @robot.adapter.client @authFirebase() @robot.respond /(.*)/, (msg)=> @respondAndReply msg # custom catch-all routing @robot.enter (res)=> @greet res # greet new users @respondAndReply: (msg)-> @respondTo(msg).then (reply)=> debugReply pjson reply @pmReply msg, reply if @isPublic msg msg.reply "Let's take this offline. I PM'd you :smile:" @authFirebase: -> if process.env.FIREBASE_SECRET? swarmbot.firebase().authWithCustomToken process.env.FIREBASE_SECRET, (error)-> throw error if error @whose: (msg)-> "slack:#{msg.message.user.id}" @isPublic: (msg)-> msg.message.room isnt msg.message.user?.name @addResponder: (pattern, cb)-> @responses ?= [] @responses.push [pattern, cb] @respondTo: (msg)-> @route(msg) .then (textOrAttachments)=> @addFallbackTextIfNeeded textOrAttachments @route: (msg)-> debug "in @route: msg.match?[1] => #{msg.match?[1]}" # commands that were added with @addResponder: if @responses? and input = msg.match[1] for [pattern, cb] in @responses if match = input.match pattern msg.match = msg.message.match(pattern) return new Promise (resolve, reject)=> debug "Command: `#{input}`, Matched: #{pattern}" cb(msg) resolve('') # custom routing, using controllers, menus, etc: msg.currentUser ?= new User name: @whose(msg) msg.currentUser.fetch() .then (@user)=> @registerUser @user, msg.message.user, @user.newRecord() .then (@user)=> debug "state: #{@user.get 'state'}" [controllerName, action] = @user.get('state').split('#') controllerClass = controllers[controllerName] controller = new controllerClass(msg) if controllerClass? unless controller and controller[action] errorMessage = "Unexpected @user state #{@user.get('state')} -- resetting to default state" msg.send("*#{errorMessage}*") if process.env.NODE_ENV is 'development' errorLog errorMessage return @user.set('state', User::initialState) .then => @route(msg) controller.input = msg.match[1] lastMenuItems = @user.get('menu') menuAction = lastMenuItems?[controller.input?.toLowerCase()] if menuAction? # specific menu action of entered command debug "Command: #{controller.input}, controllerName: #{controllerName}, menuAction: #{json menuAction}" controller.execute(menuAction) else if controller[action]? # default action for this state debug "Command: #{controller.input}, controllerName: #{controllerName}, action: #{action}" controller[action]( @user.get('stateData') ) else throw new Error("Action for state '#{@user.get('state')}' not defined.") @pmReply: (msg, textOrAttachments)=> channel = msg.message.user.name @sendMessage channel, textOrAttachments @sendMessage: (channel, textOrAttachments)=> if type(textOrAttachments) is 'string' @robot.messageRoom(channel, textOrAttachments) else if type(textOrAttachments) in ['array', 'object'] @sendAttachmentMessage(channel, textOrAttachments) else throw new Error "Unexpected type(textOrAttachments) -> #{type(textOrAttachments)}" @sendAttachmentMessage: (channel, attachment)=> @robot.adapter.customMessage channel: channel attachments: attachment @addFallbackTextIfNeeded: (textOrAttachments)-> if type(textOrAttachments) is 'string' textOrAttachments else if type(textOrAttachments) is 'object' @fallbackForAttachment(textOrAttachments) else if type(textOrAttachments) is 'array' for attachment in textOrAttachments @fallbackForAttachment(attachment) @fallbackForAttachment: (attachment)-> if isEmpty attachment.fallback?.trim() inspectFallback "Attachment:\n#{pjson attachment}" fallbackText = @extractTextLines(attachment).join("\n") inspectFallback "Fallback text:\n#{fallbackText}" attachment.fallback = fallbackText else inspectFallback "Attachment arrived with fallback already set:\n#{pjson attachment}" attachment @extractTextLines: (element)-> lines = [] if type(element) is 'array' for item in element lines.push @extractTextLines(item)... else if type(element) is 'object' for key, value of element if (key not in @SLACK_NON_TEXT_FIELDS) and value lines.push @extractTextLines(value)... else if type(element) is 'string' or type(element) is 'number' lines.push element.toString() else throw new Error "Unexpected attachment chunk type: '#{type(element)}' for #{pjson element}" lines @registerUser: (user, slackUser, newRecord)-> attributes = lastActiveOnSlack: Date.now() state: user.get('state') or User::initialState if newRecord slackUsername = slackUser.name slackId = slackUser.id realName = slackUser.real_name emailAddress = slackUser.email_address attributes.slackUsername = slackUsername if slackUsername attributes.firstSeen = Date.now() attributes.realName = <NAME> if realName attributes.emailAddress = emailAddress if emailAddress attributes.slackId = slackId if slackId user.update attributes .then (user)=> if newRecord (new KeenioInfo()).createUser(user) user @greet: (res)-> currentUser = new User name: @whose(res) currentUser.fetch() .then (@user)=> @user.set('state', 'users#welcome') # goes away if this is new home page .then => @route res .then (welcome)=> @pmReply res, welcome @user.set 'state', User::initialState .then => @route res .then (projects)=> @pmReply res, projects @notify: (message)-> if not App.airbrake debug """No airbrake configured; message NOT delivered: "#{message}" """ return envelope = if message instanceof Error message else new Error message App.airbrake.notify envelope, (errorNotifying, url)-> if errorNotifying debug errorNotifying else debug """Delivered to #{url} -- #{envelope.message}""" module.exports = App
true
{airbrake} = require './util/setup' # do this first { d, json, log, p, pjson, type } = require 'lightsaber' { defaults, isEmpty, merge } = require 'lodash' swarmbot = require './models/swarmbot' KeenioInfo = require './services/keenio-info.coffee' User = require './models/user' controllers = projects: require './controllers/projects-state-controller' rewards: require './controllers/rewards-state-controller' rewardTypes: require './controllers/reward-types-state-controller' users: require './controllers/users-state-controller' class App @COIN = '❂' @MAX_SLACK_IMAGE_SIZE = Math.pow 2,19 @SLACK_NON_TEXT_FIELDS = [ 'author_icon' 'color' 'short' ] @airbrake = airbrake @init: (@robot)-> @slack = @robot.adapter.client @authFirebase() @robot.respond /(.*)/, (msg)=> @respondAndReply msg # custom catch-all routing @robot.enter (res)=> @greet res # greet new users @respondAndReply: (msg)-> @respondTo(msg).then (reply)=> debugReply pjson reply @pmReply msg, reply if @isPublic msg msg.reply "Let's take this offline. I PM'd you :smile:" @authFirebase: -> if process.env.FIREBASE_SECRET? swarmbot.firebase().authWithCustomToken process.env.FIREBASE_SECRET, (error)-> throw error if error @whose: (msg)-> "slack:#{msg.message.user.id}" @isPublic: (msg)-> msg.message.room isnt msg.message.user?.name @addResponder: (pattern, cb)-> @responses ?= [] @responses.push [pattern, cb] @respondTo: (msg)-> @route(msg) .then (textOrAttachments)=> @addFallbackTextIfNeeded textOrAttachments @route: (msg)-> debug "in @route: msg.match?[1] => #{msg.match?[1]}" # commands that were added with @addResponder: if @responses? and input = msg.match[1] for [pattern, cb] in @responses if match = input.match pattern msg.match = msg.message.match(pattern) return new Promise (resolve, reject)=> debug "Command: `#{input}`, Matched: #{pattern}" cb(msg) resolve('') # custom routing, using controllers, menus, etc: msg.currentUser ?= new User name: @whose(msg) msg.currentUser.fetch() .then (@user)=> @registerUser @user, msg.message.user, @user.newRecord() .then (@user)=> debug "state: #{@user.get 'state'}" [controllerName, action] = @user.get('state').split('#') controllerClass = controllers[controllerName] controller = new controllerClass(msg) if controllerClass? unless controller and controller[action] errorMessage = "Unexpected @user state #{@user.get('state')} -- resetting to default state" msg.send("*#{errorMessage}*") if process.env.NODE_ENV is 'development' errorLog errorMessage return @user.set('state', User::initialState) .then => @route(msg) controller.input = msg.match[1] lastMenuItems = @user.get('menu') menuAction = lastMenuItems?[controller.input?.toLowerCase()] if menuAction? # specific menu action of entered command debug "Command: #{controller.input}, controllerName: #{controllerName}, menuAction: #{json menuAction}" controller.execute(menuAction) else if controller[action]? # default action for this state debug "Command: #{controller.input}, controllerName: #{controllerName}, action: #{action}" controller[action]( @user.get('stateData') ) else throw new Error("Action for state '#{@user.get('state')}' not defined.") @pmReply: (msg, textOrAttachments)=> channel = msg.message.user.name @sendMessage channel, textOrAttachments @sendMessage: (channel, textOrAttachments)=> if type(textOrAttachments) is 'string' @robot.messageRoom(channel, textOrAttachments) else if type(textOrAttachments) in ['array', 'object'] @sendAttachmentMessage(channel, textOrAttachments) else throw new Error "Unexpected type(textOrAttachments) -> #{type(textOrAttachments)}" @sendAttachmentMessage: (channel, attachment)=> @robot.adapter.customMessage channel: channel attachments: attachment @addFallbackTextIfNeeded: (textOrAttachments)-> if type(textOrAttachments) is 'string' textOrAttachments else if type(textOrAttachments) is 'object' @fallbackForAttachment(textOrAttachments) else if type(textOrAttachments) is 'array' for attachment in textOrAttachments @fallbackForAttachment(attachment) @fallbackForAttachment: (attachment)-> if isEmpty attachment.fallback?.trim() inspectFallback "Attachment:\n#{pjson attachment}" fallbackText = @extractTextLines(attachment).join("\n") inspectFallback "Fallback text:\n#{fallbackText}" attachment.fallback = fallbackText else inspectFallback "Attachment arrived with fallback already set:\n#{pjson attachment}" attachment @extractTextLines: (element)-> lines = [] if type(element) is 'array' for item in element lines.push @extractTextLines(item)... else if type(element) is 'object' for key, value of element if (key not in @SLACK_NON_TEXT_FIELDS) and value lines.push @extractTextLines(value)... else if type(element) is 'string' or type(element) is 'number' lines.push element.toString() else throw new Error "Unexpected attachment chunk type: '#{type(element)}' for #{pjson element}" lines @registerUser: (user, slackUser, newRecord)-> attributes = lastActiveOnSlack: Date.now() state: user.get('state') or User::initialState if newRecord slackUsername = slackUser.name slackId = slackUser.id realName = slackUser.real_name emailAddress = slackUser.email_address attributes.slackUsername = slackUsername if slackUsername attributes.firstSeen = Date.now() attributes.realName = PI:NAME:<NAME>END_PI if realName attributes.emailAddress = emailAddress if emailAddress attributes.slackId = slackId if slackId user.update attributes .then (user)=> if newRecord (new KeenioInfo()).createUser(user) user @greet: (res)-> currentUser = new User name: @whose(res) currentUser.fetch() .then (@user)=> @user.set('state', 'users#welcome') # goes away if this is new home page .then => @route res .then (welcome)=> @pmReply res, welcome @user.set 'state', User::initialState .then => @route res .then (projects)=> @pmReply res, projects @notify: (message)-> if not App.airbrake debug """No airbrake configured; message NOT delivered: "#{message}" """ return envelope = if message instanceof Error message else new Error message App.airbrake.notify envelope, (errorNotifying, url)-> if errorNotifying debug errorNotifying else debug """Delivered to #{url} -- #{envelope.message}""" module.exports = App
[ { "context": "age, State, Resource, Analytics) ->\n\n ID_PASS = 'id_pass'\n\n $scope.accounts = []\n $scope.option = { apiK", "end": 151, "score": 0.9991331696510315, "start": 144, "tag": "PASSWORD", "value": "id_pass" } ]
coffee/controllers/accountCtrl.coffee
oparkadiusz/RedmineTimeTracker
0
timeTracker.controller 'AccountCtrl', ($scope, $modal, Redmine, Account, Project, Ticket, Message, State, Resource, Analytics) -> ID_PASS = 'id_pass' $scope.accounts = [] $scope.option = { apiKey:'', id:'', pass:'', url:'' } $scope.authWay = ID_PASS $scope.searchField = text: '' $scope.state = State $scope.isSaving = false $scope.R = Resource ### Initialize. ### init = -> Account.getAccounts (accounts) -> if not accounts? or not accounts[0]? then return for account in accounts loadProject account ### load project. ### loadProject = (account) -> Redmine.get(account).loadProjects loadProjectSuccess(account), loadProjectError ### show loaded project. if project is already loaded, overwrites by new project. ### loadProjectSuccess = (account) -> (msg) -> if msg.projects? for a, i in $scope.accounts when a.url is msg.url $scope.accounts.splice i, 1 break account.projectCount = msg.projects.length $scope.accounts.push account Message.toast Resource.string("msgLoadProjectSuccess").format(account.url) else loadProjectError msg ### show fail message. ### loadProjectError = (msg) -> Message.toast Resource.string("msgLoadProjectFail") ### Load the user ID associated to Authentication info. ### $scope.addAccount = () -> $scope.isSaving = true if not $scope.option.url? or $scope.option.url.length is 0 Message.toast Resource.string("msgRequestInputURL") $scope.isSaving = false return $scope.option.url = util.getUrl $scope.option.url Redmine.remove({url: $scope.option.url}) if $scope.authWay is ID_PASS option = url: $scope.option.url id: $scope.option.id pass: $scope.option.pass else option = url: $scope.option.url apiKey: $scope.option.apiKey Redmine.get(option).findUser(addAccount, failAuthentication) ### add account. ### addAccount = (msg) -> if msg?.user?.id? $scope.option.url = msg.account.url Account.addAccount msg.account, (result) -> if result $scope.isSaving = $scope.state.isAdding = false Message.toast Resource.string("msgAuthSuccess"), 3000 Analytics.sendEvent 'internal', 'auth', 'success' loadProject msg.account else failAuthentication null else failAuthentication msg ### fail to save ### failAuthentication = (msg) -> $scope.isSaving = false Message.toast Resource.string("msgAuthFail"), 3000 Analytics.sendEvent 'internal', 'auth', 'fail' ### filter account. ### $scope.accountFilter = (account) -> if $scope.searchField.text.isBlank() then return true return (account.url + "").contains($scope.searchField.text) ### open dialog for remove account. ### $scope.openRemoveAccount = (url) -> modal = $modal.open templateUrl: '/views/removeAccount.html' controller: removeAccountCtrl modal.result.then () -> removeAccount(url) , () -> # canceled ### controller for remove account dialog. ### removeAccountCtrl = ($scope, $modalInstance, Resource) -> $scope.R = Resource $scope.ok = () -> $modalInstance.close true $scope.cancel = () -> $modalInstance.dismiss 'canceled.' removeAccountCtrl.$inject = ['$scope', '$modalInstance', 'Resource'] ### remove account from chrome sync. ### removeAccount = (url) -> Account.removeAccount url, () -> Redmine.remove({url: url}) for a, i in $scope.accounts when a.url is url $scope.accounts.splice i, 1 break Project.removeUrl url Ticket.removeUrl url Message.toast Resource.string("msgAccountRemoved").format(url) ### Start Initialize. ### init()
53230
timeTracker.controller 'AccountCtrl', ($scope, $modal, Redmine, Account, Project, Ticket, Message, State, Resource, Analytics) -> ID_PASS = '<PASSWORD>' $scope.accounts = [] $scope.option = { apiKey:'', id:'', pass:'', url:'' } $scope.authWay = ID_PASS $scope.searchField = text: '' $scope.state = State $scope.isSaving = false $scope.R = Resource ### Initialize. ### init = -> Account.getAccounts (accounts) -> if not accounts? or not accounts[0]? then return for account in accounts loadProject account ### load project. ### loadProject = (account) -> Redmine.get(account).loadProjects loadProjectSuccess(account), loadProjectError ### show loaded project. if project is already loaded, overwrites by new project. ### loadProjectSuccess = (account) -> (msg) -> if msg.projects? for a, i in $scope.accounts when a.url is msg.url $scope.accounts.splice i, 1 break account.projectCount = msg.projects.length $scope.accounts.push account Message.toast Resource.string("msgLoadProjectSuccess").format(account.url) else loadProjectError msg ### show fail message. ### loadProjectError = (msg) -> Message.toast Resource.string("msgLoadProjectFail") ### Load the user ID associated to Authentication info. ### $scope.addAccount = () -> $scope.isSaving = true if not $scope.option.url? or $scope.option.url.length is 0 Message.toast Resource.string("msgRequestInputURL") $scope.isSaving = false return $scope.option.url = util.getUrl $scope.option.url Redmine.remove({url: $scope.option.url}) if $scope.authWay is ID_PASS option = url: $scope.option.url id: $scope.option.id pass: $scope.option.pass else option = url: $scope.option.url apiKey: $scope.option.apiKey Redmine.get(option).findUser(addAccount, failAuthentication) ### add account. ### addAccount = (msg) -> if msg?.user?.id? $scope.option.url = msg.account.url Account.addAccount msg.account, (result) -> if result $scope.isSaving = $scope.state.isAdding = false Message.toast Resource.string("msgAuthSuccess"), 3000 Analytics.sendEvent 'internal', 'auth', 'success' loadProject msg.account else failAuthentication null else failAuthentication msg ### fail to save ### failAuthentication = (msg) -> $scope.isSaving = false Message.toast Resource.string("msgAuthFail"), 3000 Analytics.sendEvent 'internal', 'auth', 'fail' ### filter account. ### $scope.accountFilter = (account) -> if $scope.searchField.text.isBlank() then return true return (account.url + "").contains($scope.searchField.text) ### open dialog for remove account. ### $scope.openRemoveAccount = (url) -> modal = $modal.open templateUrl: '/views/removeAccount.html' controller: removeAccountCtrl modal.result.then () -> removeAccount(url) , () -> # canceled ### controller for remove account dialog. ### removeAccountCtrl = ($scope, $modalInstance, Resource) -> $scope.R = Resource $scope.ok = () -> $modalInstance.close true $scope.cancel = () -> $modalInstance.dismiss 'canceled.' removeAccountCtrl.$inject = ['$scope', '$modalInstance', 'Resource'] ### remove account from chrome sync. ### removeAccount = (url) -> Account.removeAccount url, () -> Redmine.remove({url: url}) for a, i in $scope.accounts when a.url is url $scope.accounts.splice i, 1 break Project.removeUrl url Ticket.removeUrl url Message.toast Resource.string("msgAccountRemoved").format(url) ### Start Initialize. ### init()
true
timeTracker.controller 'AccountCtrl', ($scope, $modal, Redmine, Account, Project, Ticket, Message, State, Resource, Analytics) -> ID_PASS = 'PI:PASSWORD:<PASSWORD>END_PI' $scope.accounts = [] $scope.option = { apiKey:'', id:'', pass:'', url:'' } $scope.authWay = ID_PASS $scope.searchField = text: '' $scope.state = State $scope.isSaving = false $scope.R = Resource ### Initialize. ### init = -> Account.getAccounts (accounts) -> if not accounts? or not accounts[0]? then return for account in accounts loadProject account ### load project. ### loadProject = (account) -> Redmine.get(account).loadProjects loadProjectSuccess(account), loadProjectError ### show loaded project. if project is already loaded, overwrites by new project. ### loadProjectSuccess = (account) -> (msg) -> if msg.projects? for a, i in $scope.accounts when a.url is msg.url $scope.accounts.splice i, 1 break account.projectCount = msg.projects.length $scope.accounts.push account Message.toast Resource.string("msgLoadProjectSuccess").format(account.url) else loadProjectError msg ### show fail message. ### loadProjectError = (msg) -> Message.toast Resource.string("msgLoadProjectFail") ### Load the user ID associated to Authentication info. ### $scope.addAccount = () -> $scope.isSaving = true if not $scope.option.url? or $scope.option.url.length is 0 Message.toast Resource.string("msgRequestInputURL") $scope.isSaving = false return $scope.option.url = util.getUrl $scope.option.url Redmine.remove({url: $scope.option.url}) if $scope.authWay is ID_PASS option = url: $scope.option.url id: $scope.option.id pass: $scope.option.pass else option = url: $scope.option.url apiKey: $scope.option.apiKey Redmine.get(option).findUser(addAccount, failAuthentication) ### add account. ### addAccount = (msg) -> if msg?.user?.id? $scope.option.url = msg.account.url Account.addAccount msg.account, (result) -> if result $scope.isSaving = $scope.state.isAdding = false Message.toast Resource.string("msgAuthSuccess"), 3000 Analytics.sendEvent 'internal', 'auth', 'success' loadProject msg.account else failAuthentication null else failAuthentication msg ### fail to save ### failAuthentication = (msg) -> $scope.isSaving = false Message.toast Resource.string("msgAuthFail"), 3000 Analytics.sendEvent 'internal', 'auth', 'fail' ### filter account. ### $scope.accountFilter = (account) -> if $scope.searchField.text.isBlank() then return true return (account.url + "").contains($scope.searchField.text) ### open dialog for remove account. ### $scope.openRemoveAccount = (url) -> modal = $modal.open templateUrl: '/views/removeAccount.html' controller: removeAccountCtrl modal.result.then () -> removeAccount(url) , () -> # canceled ### controller for remove account dialog. ### removeAccountCtrl = ($scope, $modalInstance, Resource) -> $scope.R = Resource $scope.ok = () -> $modalInstance.close true $scope.cancel = () -> $modalInstance.dismiss 'canceled.' removeAccountCtrl.$inject = ['$scope', '$modalInstance', 'Resource'] ### remove account from chrome sync. ### removeAccount = (url) -> Account.removeAccount url, () -> Redmine.remove({url: url}) for a, i in $scope.accounts when a.url is url $scope.accounts.splice i, 1 break Project.removeUrl url Ticket.removeUrl url Message.toast Resource.string("msgAccountRemoved").format(url) ### Start Initialize. ### init()
[ { "context": " .init').text 'Welcome to the photography game. As Mark, you must do your job for at least 4 month. Do no", "end": 6907, "score": 0.9959393739700317, "start": 6903, "tag": "NAME", "value": "Mark" } ]
public/javascripts/game.photography.coffee
STAB-Inc/DECO1800-Project
3
### @file Handles the functionality of the photography game. ### jQuery(document).ready -> class event ### Constructs the event object. @constructor @param {string} title Title of the event. @param {string} time The game time of when the event occurred. @param {string} content The description of the event. @param {boolean} special Whether if the event is a special event. @param {boolean} warn Whether if the event is a warning. ### constructor: (@title, @time, @content, @special=false, @warn=false) -> class randomEvent extends event ### Constructs the random event object. Extends events. @constructor @param {string} title Title of the event. @param {string} time The game time of when the event occurred. @param {string} content The description of the event. @param {boolean} special Whether if the event is a special event. @param {boolean} warn Whether if the event is a warning. @param {boolean} popup Whether if the event has its own overlay, or added to the event log. @param {integer} chance The chance of the event occurance should it be selected. @param {object} effects The list of effects to affect the player by. ### constructor: (@title, @time, @content, @special=false, @popup=false, @chance, @effects) -> super(@title, @time, @content, @special, @warn) class gamePhoto ### Constructs the game photo object. @constructor @param {integer} value The value of the photo. @param {boolean} washed Whether if the photo has been washed @param {string} img The image associated with the photo. @param {string} title The title of the photo. @param {integer} quailty The quailty of the photo. ### constructor: (@value, @washed, @img, @title, @quailty) -> ### Global variables and constants. ### locations = [] validData = [] gameGlobal = { eventOccurrence: 0 init: { isStory: false isPlus: false stats: { CAB: 1000 workingCapital: 0 assets: 0 liabilities: 600 insanity: 0 } }, trackers: { monthPassed: 0 photosSold: 0 moneyEarned: 0 }, turnConsts: { interest: 1.5 pictureWashingTime: 14 stdLiabilities: 600 alert: false randomEvents: [ new randomEvent('Machine Gun Fire!', 'currentTime', 'You wake up in a cold sweat. The sound of a german machine gun barks out from the window. How coud this be? Germans in Australia? You grab your rifle from under your pillow and rush to the window. You ready your rifle and aim, looking for the enemy. BANG! BANG! BARK! YAP! You look at the neighbours small terrier. Barking...', false, true, 30, effects = {insanity: 20}), new randomEvent('German Bombs!', 'currentTime', 'A loud explosion shakes the ground and you see a building crumble into dust in the distance. Sirens. We have been attacked! You rush to see the chaos, pushing the bystanders aside. They are not running, strangely calm. Do they not recognize death when the see it? Then you see it. A construction crew. Dynamite.', false, true, 20, effects = {insanity: 30}), new randomEvent('Air raid!', 'currentTime', 'The sound of engines fills the air. The twins propellers of a German byplane. You look up to the sky, a small dot. It may be far now, but the machine guns will be upon us soon. Cover. Need to get safe. You yell to the people around you. GET INSIDE! GET INSIDE NOW! They look at you confused. They dont understand. You look up again. A toy. You look to your side, a car.', false, true, 24, effects = {insanity: 20}), new randomEvent('Landmines!', 'currentTime', 'You scan the ground carefully as you walk along the beaten dirt path. A habit you learned after one of your squadmate had his legs blown off by a German M24 mine. You stop. Under a pile of leaves you spot it. The glimmer of metal. Shrapnel to viciously tear you apart. You are no sapper but this could kill someone. You throw a rock a it. The empty can of beans rolls away.', false, true, 20, effects = {insanity: 10}), new randomEvent('Dazed', 'currentTime', 'You aim the camera at the young couple who had asked you for a picture. Slowly. 3. 2. 1. Click. FLASH. You open your eyes. The fields. The soldiers are readying for a charge. OVER THE TOP. You shake yourself awake. The couple is looking at you worryingly. How long was I out?', false, true, 20, effects = {insanity: 10}), new randomEvent('The enemy charges!', 'currentTime', 'You are pacing along the street. Footsteps... You turn round and see a man running after you. Yelling. Immediately you run at him. Disarm and subdue you think. Disarm. You tackle him to the ground. He falls with a thud. Subdue. You raise your fist. As you prepare to bring it down on your assailant. Its your wallet. "Please stop! You dropped your wallet! Take it!', false, true, 20, effects = {insanity: 20}) ] } } ### Submits session data to the server. @param {object} data the data to be submitted. @return AJAX deferred promise. ### submitUserData = (data) -> $.ajax url: '/routes/user.php' type: 'POST' data: data ### Display the response status to the DOM @param {DOMElement} target The DOM element to display the response to. @param {object} res The response to display. ### showResStatus = (target, res) -> if res.status == 'success' $(target).css 'color', '' $(target).text res.message else $(target).css 'color', 'red' $(target).text res.message ### Saves the a item to the user's collection. ### saveItem = (img, des) -> submitUserData({ method: 'saveItem' image: img description: des }).then (res) -> showResStatus '#savePicOverlay .status', JSON.parse res ### Gets the value of the paramater in the query string of a GET request. @param {string} name the key of the corrosponding value to retrieve. @return The sorted array. ### getParam = (name) -> results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href) return results[1] || 0 ### Retrieves the GET paramater from the query string. Sets up the interface and game constants accordingly. ### try storyMode = getParam('story') == 'true' plusMode = getParam('plus') == 'true' if storyMode gameGlobal.init.isStory = true $('.tutorial .init').text 'Welcome to the photography game. As Mark, you must do your job for at least 4 month. Do not let your Working Capital drop below -$2000.' $('#playAgain').text 'Continue' $('#playAgain').parent().attr 'href', 'chapter3.html' $('.skip').show() $('.save, #endGame .score').hide() $('#playAgain').addClass('continue') if plusMode $('.continueScreen h3').text 'Chapter 4 Completed' $('.continueScreen p').remove() $('.continueScreen h3').after '<p>Photography Game Mode Plus Now Avaliable</p>' $('.continueScreen .buttonContainer a:first-child').attr('href', 'end.html').find('button').text 'Continue to Finale' if getParam('diff') == 'extended' gameGlobal.init.stats = { CAB: 2500, workingCapital: 0, assets: 0, liabilities: 1000 } if plusMode $('#tutorial .pPlus').text 'In Plus Mode, you will have to deal with additional events and control your insanity meter. The game will end should it gets too high.' gameGlobal.init.isPlus = true else $('.pPlus').remove() ### Skips the game when in story mode. Completes the chapter for the user. ### $('.skip, .continue').click (e) -> $('.continueScreen').show() $('#selectionArea, #gameArea').hide() id = '2' if gameGlobal.init.isPlus then id = '4' submitUserData({ method: 'chapterComplete' chapterId: id }).then (res) -> res = JSON.parse res if res.status == 'success' return 0 ### Retrieves resources from the dataset. @param {integer} amount The amount of resources to retrieve. @return AJAX deferred promise. ### retrieveResources = (amount) -> reqParam = { resource_id: '9913b881-d76d-43f5-acd6-3541a130853d', limit: amount } $.ajax { url: 'https://data.gov.au/api/action/datastore_search', data: reqParam, dataType: 'jsonp', cache: true } ### Converts degrees to radians. @param {float} deg The degree to convert to radians. @return The corrosponding radian value of the input. ### deg2rad = (deg) -> return deg * (Math.PI/180) ### Calculates the distance travelled from two lat, lng coordinates. @param {object} from The initial lat, lng coordinates. @param {object} to The final lat, lng coordinates. @return The distance between the two points in km. ### distanceTravelled = (from, to) -> lat1 = from.lat lng1 = from.lng lat2 = to.lat lng2 = to.lng R = 6371 dLat = deg2rad(lat2-lat1) dLng = deg2rad(lng2-lng1); a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLng/2) * Math.sin(dLng/2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); dist = R * c return dist; class tutorialHandler ### Constructs the game tutorial object. @constructor @param {DOMElement} domPanels The set of tutorial elements active in the DOM. ### constructor: (@domPanels) -> @step = 0; ### Displays the panel in view. ### init: -> $(@domPanels[@step]).show() @setButton() ### Switch to the next panel. ### next: -> @step++ $(@domPanels[@step]).show() $(@domPanels[@step - 1]).hide() @setButton() ### Switch to the previous panel ### prev: -> @step-- $(@domPanels[@step]).show() $(@domPanels[@step + 1]).hide() @setButton() ### Generates the avaliable buttons depending on the step. @see this.step ### setButton: -> @domPanels.find('.buttonContainer').remove() if @step == 0 @domPanels.append $('<div class="buttonContainer"> <button class="prev hidden">Previous</button> <button class="next">Next</button> </div>') else if @step == @domPanels.length - 1 @domPanels.append $('<div class="buttonContainer"> <button class="prev">Previous</button> <button class="next hidden">Next</button> </div>') else @domPanels.append $('<div class="buttonContainer"> <button class="prev">Previous</button> <button class="next">Next</button> </div>') class gameLocation ### Constructs the game location object @constructor @param {object} position The position of the location. @param {string} The name of the location. @param {data} Metadata associated with this position. @param {boolean} rare Whether if the location is a rare location or not @param {string} icon The icon to use for this location. ### constructor: (@position, @name, @data, @rare, @icon) -> @marker @value @travelExpense @travelTime ### Adds the location to the map. @param {object} map The google map element to add to. ### addTo: (map) -> if @icon marker = new google.maps.Marker({ position: @position, map: map, icon: @icon, title: @name }) else marker = new google.maps.Marker({ position: @position, map: map, title: @name }) @marker = marker @setListener(@marker) ### Sets event listeners on a marker @param {object} marker The google maps marker object to bind the event listener to. ### setListener: (marker) -> self = this marker.addListener 'click', -> player.moveTo(self) marker.addListener 'mouseover', -> travelDistance = parseInt(distanceTravelled(player.position, self.position)) travelTime = travelDistance/232 $('#locationInfoOverlay #title').text self.data.description $('#locationInfoOverlay #position').text 'Distance away ' + travelDistance + 'km' $('#locationInfoOverlay #value').text 'Potential Revenue $' + self.value $('#locationInfoOverlay #travelExpense').text 'Travel Expense $' + parseInt((travelDistance*0.6)/10) $('#locationInfoOverlay #travelTime').text 'Travel Time: at least ' + travelTime.toFixed(2) + ' Hours' @value = self.value class playerMarker extends gameLocation ### Constructs the player marker object. Extends the game location object @constructor @param {object} position The position of the player. @param {string} The name of the player. @param {data} Metadata associated with this player. @depreciated @param {string} icon The icon to use for this player. @param {object} stats JSON data of the player's stats. ### constructor: (@position, @name, @data, @icon, @stats) -> super(@position, @name, @data, @icon) @playerMarker @preStat @inventory = [] ### Adds the player marker to the map. @param {object} map The google map element to add to. ### initTo: (map) -> @playerMarker = new SlidingMarker({ position: @position, map: map, icon: 'https://developers.google.com/maps/documentation/javascript/images/custom-marker.png', title: @name, optimized: false, zIndex: 100 }) ### Moves the player marker to another location and calculates the result of moving to the location. @param {object} location gameLocation object, for the player marker to move to. ### moveTo: (location) -> location.marker.setVisible false location.travelExpense = parseInt((distanceTravelled(this.position, location.position)*0.6)/10) location.travelTime = parseFloat((distanceTravelled(this.position, location.position)/232).toFixed(2)) @position = location.position @playerAt = location @playerMarker.setPosition(new google.maps.LatLng(location.position.lat, location.position.lng)) newStats = @stats newStats.CAB -= player.playerAt.travelExpense timeTaken = location.travelTime + Math.random()*5 gameTime.incrementTime(timeTaken) gameEvents.addEvent(new event 'Moved to', gameTime.getFormatted(), location.name + ' in ' + timeTaken.toFixed(2) + ' hours') $('#takePic').show() $('#takeDrink').show() updateMarkers() @updateStats(newStats) if gameGlobal.init.isPlus gameGlobal.eventOccurrence += 0.5 if gameGlobal.eventOccurrence > 1 randEvent = gameGlobal.turnConsts.randomEvents[Math.floor(Math.random() * gameGlobal.turnConsts.randomEvents.length)] if randEvent.chance > Math.random() * 100 gameEvents.addEvent randEvent gameGlobal.eventOccurrence = 0 ### Depreciates the player's inventory. ### depreciateInv: -> depreciation = 0 for item in @inventory if item.value < 1 return else depreciation += item.value - item.value*0.9 item.value = item.value*0.9 newStats = player.stats newStats.assets -= depreciation.toFixed 2 if depreciation > 0 then gameEvents.addEvent new event 'Depreciation - ', gameTime.getFormatted(),'Photos depreciated by $' + depreciation.toFixed(2), false, true @updateStats(newStats) ### Updates the player stats and animates it in the DOM. @param {object} stats The new stats to update to. ### updateStats: (stats) -> animateText = (elem, from, to) -> $(current: from).animate { current: to }, duration: 500 step: -> $('#playerInfoOverlay #stats ' + elem + ' .val').text @current.toFixed() assets = parseInt (@stats.assets + @stats.CAB) workingCapital = parseInt (assets - @stats.liabilities) animateText '#CAB', parseInt($('#playerInfoOverlay #stats #CAB .val').text()), stats.CAB animateText '#liabilities', parseInt($('#playerInfoOverlay #stats #liabilities .val').text()), stats.liabilities animateText '#assets', parseInt($('#playerInfoOverlay #stats #assets .val').text()), assets animateText '#workingCapital', parseInt($('#playerInfoOverlay #stats #workingCapital .val').text()), workingCapital @preStat = { CAB: stats.CAB, workingCapital: workingCapital, assets: assets, liabilities: stats.liabilities insanity: stats.insanity } if workingCapital <= -1000 && @stats.CAB <= 0 $('#playerInfoOverlay #stats #workingCapital, #playerInfoOverlay #stats #CAB').css 'color', 'red' else $('#playerInfoOverlay #stats #workingCapital, #playerInfoOverlay #stats #CAB').css 'color', '' gameGlobal.turnConsts.alert = false class timeManager ### Constructs the time manager object. @constructor @param {array} baseTime The initial date/time to start the game with. ### constructor: (@baseTime) -> @timeCounter = 0 @dateCounter = 0 @monthCounter = 0 @yearCounter = 0 ### Increases the game time by hours. @param {integer} hours The hours to increase the game time by. ### incrementTime: (hours) -> @timeCounter += hours while @timeCounter >= 24 @incrementDays(1) @timeCounter -= 24 if @timeCounter < 24 @timeCounter = @timeCounter % 24 break ### Increases the game time by days. @param {integer} days The days to increase the game time by. ### incrementDays: (days) -> i = 0 while i <= days @dateCounter++ player.depreciateInv() gameInsanity.setBar(gameInsanity.value * 0.95) i++ if i >= days i = 0 break while @dateCounter >= 30 @incrementMonths(1) @dateCounter -= 30 endTurn(@getFormatted()) if @dateCounter < 30 @dateCounter = @dateCounter % 30 break ### Increases the game time by months. @param {integer} months The monthes to increase the game time by. ### incrementMonths: (months) -> @monthCounter += months while @monthCounter >= 12 @incrementYears(1) @monthCounter -= 12 if @monthCounter < 12 @monthCounter = @monthCounter % 12 break ### Increases the game time by years. @param {integer} years The years to increase the game time by. ### incrementYears: (years) -> @yearCounter += years ### Gets the current game time. @return Array containing the game time. ### getAll: -> return [@baseTime[0] + @yearCounter, @baseTime[1] + @monthCounter, @baseTime[2] + @dateCounter, parseInt(@baseTime[3]) + @timeCounter] ### Gets the formatted current game time. @return Stringified and formatted game time. ### getFormatted: -> year = @baseTime[0] + @yearCounter month = @baseTime[1] + @monthCounter date = @baseTime[2] + @dateCounter hours = parseInt(@baseTime[3]) + @timeCounter minutes = parseInt((hours - Math.floor(hours))*60) if date > 30 date -= date - 30 if String(parseInt(minutes)).length == 2 then return year + '/' + month + '/' + date + ' ' + String(Math.floor(hours)) + ':' + String(parseInt(minutes)) else return year + '/' + month + '/' + date + ' ' + String(Math.floor(hours)) + ':' + String(parseInt(minutes)) + '0' class eventManager ### Constructs the event manager to handles all events. @constructor @param {DOMElement} domSelector The DOM element to display the event on. ### constructor: (@domSelector, @domOverlay) -> @events = [] ### Adds a event to the event manager @param {object} event The event object to add to the event manager. ### addEvent: (event) -> if event.time == 'currentTime' then event.time = gameTime.getFormatted() if event.constructor.name == 'randomEvent' if event.effects gameInsanity.updateBar event.effects.insanity newStats = player.stats for effectName in Object.keys event.effects newStats[effectName] += event.effects[effectName] player.updateStats(newStats) @domOverlay.find('.title').text event.title @domOverlay.find('.content').text event.content @domOverlay.show() else @events.push(event) if event.warn $('<div class="row"> <p class="time">' + event.time + '</p> <p class="title warn">' + event.title + '</p> <p class="content">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() else if event.special $('<div class="row"> <p class="time special">' + event.time + '</p> <p class="title special">' + event.title + '</p> <p class="content special">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() else $('<div class="row"> <p class="time">' + event.time + '</p> <p class="title">' + event.title + '</p> <p class="content">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() class playerInsanity ### Constructs playerInsanity object to handle player insanity events. @constructor @param {DOMElement} domSelector The DOM element to display the event on. @param {integer} initValue The initial insanity value ### constructor: (@domSelector, @initVal) -> @value = @initVal ### Sets the insanity bar to a value @param {integer} value the level of insanity to set to. ### setBar: (value) -> @value = value @domSelector.find('.bar').css 'height', @value + '%' ### Update the insanity level by a value @param {integer} value the level to increase the current insanity level by. ### updateBar: (value) -> if @value + value > 100 endGame() @domSelector.find('.bar').css 'height', '100%' else @value += value if @value < 0 then return else @domSelector.find('.bar').css 'height', @value + '%' ### Processes and validates an array of data. @param {array} data The set of data to process. @return The array of processed data/ ### processData = (data) -> processedData = [] for item in data.result.records if item['dcterms:spatial'] if item['dcterms:spatial'].split(';')[1] processedData.push(item) return processedData ### Generates google map markers from a set of data @param {array} data The set of data to generate markers from. ### generateMarkers = (data) -> marker = [] i = 0 for place in data lat = parseFloat(place['dcterms:spatial'].split(';')[1].split(',')[0]) lng = parseFloat(place['dcterms:spatial'].split(';')[1].split(',')[1]) marker[i] = new gameLocation {lat, lng}, place['dcterms:spatial'].split(';')[0], {'title': place['dc:title'], 'description': place['dc:description'], 'img': place['150_pixel_jpg']}, false marker[i].addTo(googleMap) locations.push(marker[i]) setValue(marker[i]) i++ updateMarkers() ### Sets the value of a given location based on the distance from the player. @param {object} location gameLocation object to set the value by. ### setValue = (location) -> rare = Math.random() <= 0.05; if rare location.value = parseInt((Math.random()*distanceTravelled(player.position, location.position) + 100)) location.rare = true else location.value = parseInt((Math.random()*distanceTravelled(player.position, location.position) + 100)/10) ### Updates the markers as the user player moves. @see playerMarker.prototype.moveTo() ### updateMarkers = -> for location in locations hide = Math.random() >= 0.8; show = Math.random() <= 0.2; if hide location.marker.setVisible(false) ### Instantiate the game components. ### gameEvents = new eventManager $('#eventLog .eventContainer'), $('#randomEventOverlay') gameTime = new timeManager [1939, 1, 1, 0] gameTutorial = new tutorialHandler $('.tutorial') gameInsanity = new playerInsanity $('#insanityBar'), 0 player = new playerMarker {lat: -25.363, lng: 151.044}, 'player', {'type':'self'} ,'https://developers.google.com/maps/documentation/javascript/images/custom-marker.png' player.initTo googleMap player.stats = gameGlobal.init.stats player.updateStats player.stats class photographyGame ### Constructs the photography game. @constructor @param {boolean} debug The debug state of the game. ### constructor: (@debug) -> @score = 0 ### Initialize the photography game. @param {integer} amount The amount of markers to initialize the game with. ### init: (amount) -> localInit = -> validData.sort -> return 0.5 - Math.random() generateMarkers(validData.slice(0, amount)) gameTutorial.init() gameEvents.addEvent(new event 'Game started', gameTime.getFormatted(), '') if localStorage.getItem 'photographyGameData' validData = processData(JSON.parse(localStorage.getItem 'photographyGameData')) if amount > validData.length retrieveResources(3000).then (res) -> localStorage.setItem 'photographyGameData', JSON.stringify(res) validData = processData res localInit() else localInit() else retrieveResources(3000).then (res) -> localStorage.setItem 'photographyGameData', JSON.stringify(res) validData = processData res localInit() ### Saves the current user score to the database. ### saveScore: -> gameId = '2' if gameGlobal.init.isPlus then gameId = '4' submitUserData({ method: 'saveScore' gameId: gameId value: @score }).then (res) -> res = JSON.parse res if res.status == 'success' $('#gameEnd .status').css 'color', '' $('#gameEnd .status').text res.message else $('#gameEnd .status').css 'color', 'red' $('#gameEnd .status').text res.message ### Instantiate the photography game. ### currentGame = new photographyGame false if getParam('diff') == 'normal' currentGame.init(100) else if getParam('diff') == 'extended' currentGame.init(500) ### Displays the end game screen. ### endGame = -> $('#gameEnd .stat').text 'You survived for ' + gameGlobal.trackers.monthPassed + ' Months, selling ' + gameGlobal.trackers.photosSold + ' photos and making over $' + gameGlobal.trackers.moneyEarned currentGame.score = gameGlobal.trackers.monthPassed*gameGlobal.trackers.photosSold*gameGlobal.trackers.moneyEarned $('#gameEnd .score').text 'Your score: ' + currentGame.score + ' pt' $('#gameEnd').show(); ### Ends the month. @param {string} date The date which the month ended on. ### endTurn = (date) -> if gameGlobal.init.isStory && gameGlobal.trackers.monthPassed >= 3 if gameGlobal.init.isPlus $('#gameEnd h4').text 'You wake up one day, you feel pain all across your body...' else $('#gameEnd h4').text 'You recieve a letter from the army. Now you can finally join the front lines.' $('#gameEnd .score').hide() endGame() gameGlobal.turnConsts.interest = (Math.random()*5).toFixed(2) gameEvents.addEvent(new event 'The month comes to an end.', date, 'Paid $' + player.stats.liabilities + ' in expenses', true) newStats = player.stats newStats.CAB -= player.stats.liabilities newStats.liabilities = gameGlobal.turnConsts.stdLiabilities player.updateStats(newStats) if player.preStat.workingCapital <= -1000 && player.preStat.CAB <= 0 if gameGlobal.turnConsts.alert then endGame() else gameGlobal.trackers.monthPassed += 1 gameGlobal.turnConsts.alert = true else gameGlobal.trackers.monthPassed += 1 if gameGlobal.turnConsts.alert && player.preStat.workingCapital > -1000 && player.preStat.CAB > 0 gameGlobal.turnConsts.alert = false for location in locations show = Math.random() > 0.2 if show location.marker.setVisible(true) ### Displays the taking picture screen. ### $('#takePic').hide() $('#takePic').click -> $('#takingPic .section3').css 'width', (Math.floor(Math.random() * (10 + 2))) + 1 + '%' $('#takingPic .section2').css 'width', (Math.floor(Math.random() * (19 + 2))) + '%' $('#takingPic .section4').css 'width', (Math.floor(Math.random() * (19 + 2))) + '%' $('#takingPic .slider').css 'left', 0 $('#takingPic .start, #takingPic .stop').prop 'disabled', false $('#takingPic .shotStats').hide() $('#takingPic').show() $('#takingPic .viewInv').hide() $('#takingPic .close').hide() $(this).hide() $('#takeDrink').hide() ### Starts the animation of the slider when taking the picture. ### $('#takingPic .start').click -> $(this).prop 'disabled', true $('#takingPic .slider').animate({ 'left': $('#takingPic .section1').width() + $('#takingPic .section2').width() + $('#takingPic .section3').width() + $('#takingPic .section4').width() + $('#takingPic .section5').width() + 'px'; }, 1000, -> calculatePicValue() ) ### Ends the animation of the slider when taking the picture. ### $('#takingPic .stop').click -> $(this).prop 'disabled', true $('#takingPic .slider').stop() $('#takingPic .close').show() calculatePicValue() ### Calculates the value of the picture based on the slider position. ### calculatePicValue = -> $('#takingPic .viewInv').show() $('#takingPic .shotStats').show(); multiplier = 1 quailty = 1 sliderPosition = parseInt($('#takingPic .slider').css('left'), 10) inBlue = ($('#takingPic .section1').position().left + $('#takingPic .section1').width()) <= sliderPosition && sliderPosition <= $('#takingPic .section5').position().left inGreen = ($('#takingPic .section2').position().left + $('#takingPic .section2').width()) <= sliderPosition && sliderPosition <= $('#takingPic .section4').position().left if inBlue && inGreen multiplier = 1.4 quailty = 0 $('.shotStats').text 'You take a high quailty photo, this will surely sell for more!' else if inBlue $('.shotStats').text 'You take a average photo.' else multiplier = 0.8 quailty = 2 $('.shotStats').text 'The shot comes out all smudged...' addShotToInv(multiplier, quailty) timeTaken = Math.floor(Math.random()*10) + 24 gameTime.incrementTime(timeTaken) gameEvents.addEvent(new event 'Taking Pictures', gameTime.getFormatted(), 'You spend some time around ' + player.playerAt.name + '. '+ timeTaken + ' hours later, you finally take a picture of value.') if player.playerAt.rare gameEvents.addEvent(new event 'Rare Picture -', gameTime.getFormatted(), 'You take a rare picture.', true) if !gameGlobal.init.isStory if $('#savePicOverlay .img img').length == 0 $('#savePicOverlay .img').append $('<img src="' + player.playerAt.data.img + '">') else $('#savePicOverlay .img img').attr 'src', player.playerAt.data.img $('#savePicOverlay .title').text player.playerAt.data.title $('#savePicOverlay #confirmSavePic').prop 'disabled', false $('#savePicOverlay').show() ### Instantiate the game photo object and adds a photographic shot to the inventory @param {integer} multiplier The scalar to multiple the value of the shot by. @param {integer} quailty The quailty of the picture. ### addShotToInv = (multiplier, quailty) -> photoValue = player.playerAt.value*multiplier shotTaken = new gamePhoto photoValue, false, player.playerAt.data.img, player.playerAt.data.title, quailty player.inventory.push(shotTaken) player.playerAt.marker.setVisible(false) newStats = player.stats newStats.assets += photoValue newStats.workingCapital -= player.playerAt.travelExpense/2 player.updateStats(newStats) ### Displays the player inventory and closes previous element's parent. ### $('.viewInv').click -> closeParent(this) displayInv() ### Displays the player inventory. ### $('#checkInv').click -> displayInv() ### Generates the player inventory. ### displayInv = -> $('#blockOverlay').show() $('#inventory .photoContainer').remove() $('#inventory').show() potentialValue = 0; sellableValue = 0; for item in player.inventory pictureContainer = $('<div class="photoContainer"></div>') picture = $(' <div class="crop"> <img class="photo" src="' + item.img + '"/> </div>').css('filter', 'blur('+ item.quailty + 'px') picture.appendTo(pictureContainer) if !item.washed pictureContainer.appendTo($('#inventory .cameraRoll')) potentialValue += item.value else pictureContainer.appendTo($('#inventory .washedPics')) sellableValue += item.value $('<aside> <p>Value $' + parseInt(item.value) + '</p> <p>' + item.title + '</p> </aside>').appendTo(pictureContainer) $('#rollValue').text('Total value $' + parseInt(potentialValue + sellableValue)) $('#sellableValue').text('Sellable Pictures value $' + parseInt(sellableValue)) ### Displays the waiting screen. ### $('#wait').click -> if $('#waitTimeInput').val() == '' then $('#waitTimeInput').parent().find('button.confirm').prop 'disabled', true $('#waitInfo').show() ### Waits and passes the game time. ### $('#confirmWait').click -> gameTime.incrementDays(parseInt($('#waitTimeInput').val())) if parseInt($('#waitTimeInput').val()) != 1 then gameEvents.addEvent(new event '', gameTime.getFormatted(), 'You wait ' + $('#waitTimeInput').val() + ' days') else gameEvents.addEvent(new event '', gameTime.getFormatted(), 'You wait ' + $('#waitTimeInput').val() + ' day') validData.sort -> return 0.5 - Math.random() generateMarkers(validData.slice(0, parseInt($('#waitTimeInput').val())/2)) for location in locations show = Math.floor(Math.random() * (30)) <= parseInt($('#waitTimeInput').val())/2 if show location.marker.setVisible true ### Displays the pictures avaliable for washing. ### $('#washPic').click -> notWashed = [] for item in player.inventory if !item.washed then notWashed.push(item) if notWashed.length == 0 $('#washPicOverlay p').text 'There are no pictures to wash.' $('#washPicOverlay').show() $('#washPicOverlay #confirmWashPic').hide() else for item in player.inventory item.washed = true $('#washPicOverlay p').text 'Washing photos takes ' + gameGlobal.turnConsts.pictureWashingTime + ' days. Proceed?' $('#washPicOverlay').show() $('#washPicOverlay #confirmWashPic').show() ### Washes all unwashed pictures in the player's inventory. ### $('#confirmWashPic').click -> gameTime.incrementTime(10*Math.random()) gameTime.incrementDays(gameGlobal.turnConsts.pictureWashingTime) gameEvents.addEvent(new event 'Washed pictures.', gameTime.getFormatted(), 'You wash all pictures in your camera.' ) ### Displays the take loan screen. ### $('#takeLoan').click -> $('#IR').text('Current interest rate ' + gameGlobal.turnConsts.interest + '%') if $('#loanInput').val() == '' then $('#loanInput').parent().find('button.confirm').prop 'disabled', true $('#loanOverlay').show() ### Confirms the loan to the player. ### $('#confirmLoan').click -> newStats = player.stats newStats.liabilities += parseInt($('#loanInput').val())+parseInt($('#loanInput').val())*(gameGlobal.turnConsts.interest/10) newStats.CAB += parseInt($('#loanInput').val()) player.updateStats(newStats) gameEvents.addEvent(new event 'Bank loan.', gameTime.getFormatted(), 'You take a bank loan of $' + parseInt($('#loanInput').val())) ### Validates the input to ensure the input is a number and non empty. ### $('#loanInput, #waitTimeInput').keyup -> if !$.isNumeric($(this).val()) || $(this).val() == '' $(this).parent().find('.err').text '*Input must be a number' $(this).parent().find('button.confirm').prop 'disabled', true else $(this).parent().find('.err').text '' $(this).parent().find('button.confirm').prop 'disabled', false ### Displays the sell pictures screen. ### $('#sellPic').click -> sellablePhotos = 0 photosValue = 0 for photo in player.inventory if photo.washed sellablePhotos += 1 photosValue += photo.value $('#soldInfoOverlay p').text 'Potential Earnings $' + parseInt(photosValue) + ' from ' + sellablePhotos + ' Photo/s' if sellablePhotos == 0 then $('#soldInfoOverlay button').hide() else $('#soldInfoOverlay button').show() $('#soldInfoOverlay').show() ### Sells the washed photos in the player's inventory. ### $('#sellPhotos').click -> photosSold = 0 earningsEst = 0 earningsAct = 0 newInventory = [] newStats = player.stats for photo in player.inventory if photo.washed earningsAct += parseInt(photo.value + (photo.value*Math.random())) earningsEst += photo.value photosSold += 1 gameGlobal.trackers.photosSold += 1 gameGlobal.trackers.moneyEarned += earningsAct else newInventory.push(photo) timeTaken = ((Math.random()*2)+1)*photosSold player.inventory = newInventory newStats.CAB += earningsAct newStats.assets -= earningsEst player.updateStats(newStats) gameTime.incrementDays(parseInt(timeTaken)) if parseInt(timeTaken) == 1 then gameEvents.addEvent(new event 'Selling Pictures.', gameTime.getFormatted(), 'It took ' + parseInt(timeTaken) + ' day to finally sell everything. Earned $' + earningsAct + ' from selling ' + photosSold + ' Photo/s.') else gameEvents.addEvent(new event 'Selling Pictures.', gameTime.getFormatted(), 'It took ' + parseInt(timeTaken) + ' days to finally sell everything. Earned $' + earningsAct + ' from selling ' + photosSold + ' Photo/s.') ### Blocks the game when a overlay/interface is active. ### $('#actions button').click -> if $(this).attr('id') != 'takeDrink' then $('#blockOverlay').show() ### Closes the overlay. ### $('.confirm, .close').click -> closeParent(this) ### Saves the DOM element to the player's collection. ### $('#confirmSavePic').click -> saveItem $('#savePicOverlay .img img').attr('src'), $('#savePicOverlay .title').text() $(this).prop 'disabled', true ### Closes the parent of the original DOM element @param {DOMElement} self The element whose parent should be hidden. ### closeParent = (self) -> $(self).parent().hide() $('#blockOverlay').hide() $('.status').text '' ### jQuery UI draggable handler. ### $('#actions').draggable() $('#actions').mousedown -> $('#actions p').text 'Actions' ### Saves the current user score. ### $('#saveScore').click -> currentGame.saveScore() ### Binds the generated buttons to the click event. ### $('body').on 'click', '.tutorial .next', -> gameTutorial.next() $('body').on 'click', '.tutorial .prev', -> gameTutorial.prev() ### Handles new Plus mode mechanics ### $('#randomEventOverlay .break').click -> gameTime.incrementDays(5) gameEvents.addEvent new event 'You take sometime off...', gameTime.getFormatted(), '' gameInsanity.setBar gameInsanity.value*0.75 $('#randomEventOverlay .seeDoc').click -> gameTime.incrementDays(2) newStats = player.stats newStats.CAB -= 500 player.updateStats newStats gameEvents.addEvent new event 'You visit a nearby doctor...', gameTime.getFormatted(), '' gameInsanity.setBar gameInsanity.value*0.25 gameGlobal.eventOccurrence = -1 $('#takeDrink').hide() $('#takeDrink').click -> $('#takePic').hide() $(this).hide() gameEvents.addEvent new event 'You go to a nearby pub', gameTime.getFormatted(), 'You spend $50 on some shots. It relieves some of your stress...' newStats = player.stats newStats.CAB -= 50 player.updateStats newStats gameInsanity.updateBar -5
2179
### @file Handles the functionality of the photography game. ### jQuery(document).ready -> class event ### Constructs the event object. @constructor @param {string} title Title of the event. @param {string} time The game time of when the event occurred. @param {string} content The description of the event. @param {boolean} special Whether if the event is a special event. @param {boolean} warn Whether if the event is a warning. ### constructor: (@title, @time, @content, @special=false, @warn=false) -> class randomEvent extends event ### Constructs the random event object. Extends events. @constructor @param {string} title Title of the event. @param {string} time The game time of when the event occurred. @param {string} content The description of the event. @param {boolean} special Whether if the event is a special event. @param {boolean} warn Whether if the event is a warning. @param {boolean} popup Whether if the event has its own overlay, or added to the event log. @param {integer} chance The chance of the event occurance should it be selected. @param {object} effects The list of effects to affect the player by. ### constructor: (@title, @time, @content, @special=false, @popup=false, @chance, @effects) -> super(@title, @time, @content, @special, @warn) class gamePhoto ### Constructs the game photo object. @constructor @param {integer} value The value of the photo. @param {boolean} washed Whether if the photo has been washed @param {string} img The image associated with the photo. @param {string} title The title of the photo. @param {integer} quailty The quailty of the photo. ### constructor: (@value, @washed, @img, @title, @quailty) -> ### Global variables and constants. ### locations = [] validData = [] gameGlobal = { eventOccurrence: 0 init: { isStory: false isPlus: false stats: { CAB: 1000 workingCapital: 0 assets: 0 liabilities: 600 insanity: 0 } }, trackers: { monthPassed: 0 photosSold: 0 moneyEarned: 0 }, turnConsts: { interest: 1.5 pictureWashingTime: 14 stdLiabilities: 600 alert: false randomEvents: [ new randomEvent('Machine Gun Fire!', 'currentTime', 'You wake up in a cold sweat. The sound of a german machine gun barks out from the window. How coud this be? Germans in Australia? You grab your rifle from under your pillow and rush to the window. You ready your rifle and aim, looking for the enemy. BANG! BANG! BARK! YAP! You look at the neighbours small terrier. Barking...', false, true, 30, effects = {insanity: 20}), new randomEvent('German Bombs!', 'currentTime', 'A loud explosion shakes the ground and you see a building crumble into dust in the distance. Sirens. We have been attacked! You rush to see the chaos, pushing the bystanders aside. They are not running, strangely calm. Do they not recognize death when the see it? Then you see it. A construction crew. Dynamite.', false, true, 20, effects = {insanity: 30}), new randomEvent('Air raid!', 'currentTime', 'The sound of engines fills the air. The twins propellers of a German byplane. You look up to the sky, a small dot. It may be far now, but the machine guns will be upon us soon. Cover. Need to get safe. You yell to the people around you. GET INSIDE! GET INSIDE NOW! They look at you confused. They dont understand. You look up again. A toy. You look to your side, a car.', false, true, 24, effects = {insanity: 20}), new randomEvent('Landmines!', 'currentTime', 'You scan the ground carefully as you walk along the beaten dirt path. A habit you learned after one of your squadmate had his legs blown off by a German M24 mine. You stop. Under a pile of leaves you spot it. The glimmer of metal. Shrapnel to viciously tear you apart. You are no sapper but this could kill someone. You throw a rock a it. The empty can of beans rolls away.', false, true, 20, effects = {insanity: 10}), new randomEvent('Dazed', 'currentTime', 'You aim the camera at the young couple who had asked you for a picture. Slowly. 3. 2. 1. Click. FLASH. You open your eyes. The fields. The soldiers are readying for a charge. OVER THE TOP. You shake yourself awake. The couple is looking at you worryingly. How long was I out?', false, true, 20, effects = {insanity: 10}), new randomEvent('The enemy charges!', 'currentTime', 'You are pacing along the street. Footsteps... You turn round and see a man running after you. Yelling. Immediately you run at him. Disarm and subdue you think. Disarm. You tackle him to the ground. He falls with a thud. Subdue. You raise your fist. As you prepare to bring it down on your assailant. Its your wallet. "Please stop! You dropped your wallet! Take it!', false, true, 20, effects = {insanity: 20}) ] } } ### Submits session data to the server. @param {object} data the data to be submitted. @return AJAX deferred promise. ### submitUserData = (data) -> $.ajax url: '/routes/user.php' type: 'POST' data: data ### Display the response status to the DOM @param {DOMElement} target The DOM element to display the response to. @param {object} res The response to display. ### showResStatus = (target, res) -> if res.status == 'success' $(target).css 'color', '' $(target).text res.message else $(target).css 'color', 'red' $(target).text res.message ### Saves the a item to the user's collection. ### saveItem = (img, des) -> submitUserData({ method: 'saveItem' image: img description: des }).then (res) -> showResStatus '#savePicOverlay .status', JSON.parse res ### Gets the value of the paramater in the query string of a GET request. @param {string} name the key of the corrosponding value to retrieve. @return The sorted array. ### getParam = (name) -> results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href) return results[1] || 0 ### Retrieves the GET paramater from the query string. Sets up the interface and game constants accordingly. ### try storyMode = getParam('story') == 'true' plusMode = getParam('plus') == 'true' if storyMode gameGlobal.init.isStory = true $('.tutorial .init').text 'Welcome to the photography game. As <NAME>, you must do your job for at least 4 month. Do not let your Working Capital drop below -$2000.' $('#playAgain').text 'Continue' $('#playAgain').parent().attr 'href', 'chapter3.html' $('.skip').show() $('.save, #endGame .score').hide() $('#playAgain').addClass('continue') if plusMode $('.continueScreen h3').text 'Chapter 4 Completed' $('.continueScreen p').remove() $('.continueScreen h3').after '<p>Photography Game Mode Plus Now Avaliable</p>' $('.continueScreen .buttonContainer a:first-child').attr('href', 'end.html').find('button').text 'Continue to Finale' if getParam('diff') == 'extended' gameGlobal.init.stats = { CAB: 2500, workingCapital: 0, assets: 0, liabilities: 1000 } if plusMode $('#tutorial .pPlus').text 'In Plus Mode, you will have to deal with additional events and control your insanity meter. The game will end should it gets too high.' gameGlobal.init.isPlus = true else $('.pPlus').remove() ### Skips the game when in story mode. Completes the chapter for the user. ### $('.skip, .continue').click (e) -> $('.continueScreen').show() $('#selectionArea, #gameArea').hide() id = '2' if gameGlobal.init.isPlus then id = '4' submitUserData({ method: 'chapterComplete' chapterId: id }).then (res) -> res = JSON.parse res if res.status == 'success' return 0 ### Retrieves resources from the dataset. @param {integer} amount The amount of resources to retrieve. @return AJAX deferred promise. ### retrieveResources = (amount) -> reqParam = { resource_id: '9913b881-d76d-43f5-acd6-3541a130853d', limit: amount } $.ajax { url: 'https://data.gov.au/api/action/datastore_search', data: reqParam, dataType: 'jsonp', cache: true } ### Converts degrees to radians. @param {float} deg The degree to convert to radians. @return The corrosponding radian value of the input. ### deg2rad = (deg) -> return deg * (Math.PI/180) ### Calculates the distance travelled from two lat, lng coordinates. @param {object} from The initial lat, lng coordinates. @param {object} to The final lat, lng coordinates. @return The distance between the two points in km. ### distanceTravelled = (from, to) -> lat1 = from.lat lng1 = from.lng lat2 = to.lat lng2 = to.lng R = 6371 dLat = deg2rad(lat2-lat1) dLng = deg2rad(lng2-lng1); a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLng/2) * Math.sin(dLng/2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); dist = R * c return dist; class tutorialHandler ### Constructs the game tutorial object. @constructor @param {DOMElement} domPanels The set of tutorial elements active in the DOM. ### constructor: (@domPanels) -> @step = 0; ### Displays the panel in view. ### init: -> $(@domPanels[@step]).show() @setButton() ### Switch to the next panel. ### next: -> @step++ $(@domPanels[@step]).show() $(@domPanels[@step - 1]).hide() @setButton() ### Switch to the previous panel ### prev: -> @step-- $(@domPanels[@step]).show() $(@domPanels[@step + 1]).hide() @setButton() ### Generates the avaliable buttons depending on the step. @see this.step ### setButton: -> @domPanels.find('.buttonContainer').remove() if @step == 0 @domPanels.append $('<div class="buttonContainer"> <button class="prev hidden">Previous</button> <button class="next">Next</button> </div>') else if @step == @domPanels.length - 1 @domPanels.append $('<div class="buttonContainer"> <button class="prev">Previous</button> <button class="next hidden">Next</button> </div>') else @domPanels.append $('<div class="buttonContainer"> <button class="prev">Previous</button> <button class="next">Next</button> </div>') class gameLocation ### Constructs the game location object @constructor @param {object} position The position of the location. @param {string} The name of the location. @param {data} Metadata associated with this position. @param {boolean} rare Whether if the location is a rare location or not @param {string} icon The icon to use for this location. ### constructor: (@position, @name, @data, @rare, @icon) -> @marker @value @travelExpense @travelTime ### Adds the location to the map. @param {object} map The google map element to add to. ### addTo: (map) -> if @icon marker = new google.maps.Marker({ position: @position, map: map, icon: @icon, title: @name }) else marker = new google.maps.Marker({ position: @position, map: map, title: @name }) @marker = marker @setListener(@marker) ### Sets event listeners on a marker @param {object} marker The google maps marker object to bind the event listener to. ### setListener: (marker) -> self = this marker.addListener 'click', -> player.moveTo(self) marker.addListener 'mouseover', -> travelDistance = parseInt(distanceTravelled(player.position, self.position)) travelTime = travelDistance/232 $('#locationInfoOverlay #title').text self.data.description $('#locationInfoOverlay #position').text 'Distance away ' + travelDistance + 'km' $('#locationInfoOverlay #value').text 'Potential Revenue $' + self.value $('#locationInfoOverlay #travelExpense').text 'Travel Expense $' + parseInt((travelDistance*0.6)/10) $('#locationInfoOverlay #travelTime').text 'Travel Time: at least ' + travelTime.toFixed(2) + ' Hours' @value = self.value class playerMarker extends gameLocation ### Constructs the player marker object. Extends the game location object @constructor @param {object} position The position of the player. @param {string} The name of the player. @param {data} Metadata associated with this player. @depreciated @param {string} icon The icon to use for this player. @param {object} stats JSON data of the player's stats. ### constructor: (@position, @name, @data, @icon, @stats) -> super(@position, @name, @data, @icon) @playerMarker @preStat @inventory = [] ### Adds the player marker to the map. @param {object} map The google map element to add to. ### initTo: (map) -> @playerMarker = new SlidingMarker({ position: @position, map: map, icon: 'https://developers.google.com/maps/documentation/javascript/images/custom-marker.png', title: @name, optimized: false, zIndex: 100 }) ### Moves the player marker to another location and calculates the result of moving to the location. @param {object} location gameLocation object, for the player marker to move to. ### moveTo: (location) -> location.marker.setVisible false location.travelExpense = parseInt((distanceTravelled(this.position, location.position)*0.6)/10) location.travelTime = parseFloat((distanceTravelled(this.position, location.position)/232).toFixed(2)) @position = location.position @playerAt = location @playerMarker.setPosition(new google.maps.LatLng(location.position.lat, location.position.lng)) newStats = @stats newStats.CAB -= player.playerAt.travelExpense timeTaken = location.travelTime + Math.random()*5 gameTime.incrementTime(timeTaken) gameEvents.addEvent(new event 'Moved to', gameTime.getFormatted(), location.name + ' in ' + timeTaken.toFixed(2) + ' hours') $('#takePic').show() $('#takeDrink').show() updateMarkers() @updateStats(newStats) if gameGlobal.init.isPlus gameGlobal.eventOccurrence += 0.5 if gameGlobal.eventOccurrence > 1 randEvent = gameGlobal.turnConsts.randomEvents[Math.floor(Math.random() * gameGlobal.turnConsts.randomEvents.length)] if randEvent.chance > Math.random() * 100 gameEvents.addEvent randEvent gameGlobal.eventOccurrence = 0 ### Depreciates the player's inventory. ### depreciateInv: -> depreciation = 0 for item in @inventory if item.value < 1 return else depreciation += item.value - item.value*0.9 item.value = item.value*0.9 newStats = player.stats newStats.assets -= depreciation.toFixed 2 if depreciation > 0 then gameEvents.addEvent new event 'Depreciation - ', gameTime.getFormatted(),'Photos depreciated by $' + depreciation.toFixed(2), false, true @updateStats(newStats) ### Updates the player stats and animates it in the DOM. @param {object} stats The new stats to update to. ### updateStats: (stats) -> animateText = (elem, from, to) -> $(current: from).animate { current: to }, duration: 500 step: -> $('#playerInfoOverlay #stats ' + elem + ' .val').text @current.toFixed() assets = parseInt (@stats.assets + @stats.CAB) workingCapital = parseInt (assets - @stats.liabilities) animateText '#CAB', parseInt($('#playerInfoOverlay #stats #CAB .val').text()), stats.CAB animateText '#liabilities', parseInt($('#playerInfoOverlay #stats #liabilities .val').text()), stats.liabilities animateText '#assets', parseInt($('#playerInfoOverlay #stats #assets .val').text()), assets animateText '#workingCapital', parseInt($('#playerInfoOverlay #stats #workingCapital .val').text()), workingCapital @preStat = { CAB: stats.CAB, workingCapital: workingCapital, assets: assets, liabilities: stats.liabilities insanity: stats.insanity } if workingCapital <= -1000 && @stats.CAB <= 0 $('#playerInfoOverlay #stats #workingCapital, #playerInfoOverlay #stats #CAB').css 'color', 'red' else $('#playerInfoOverlay #stats #workingCapital, #playerInfoOverlay #stats #CAB').css 'color', '' gameGlobal.turnConsts.alert = false class timeManager ### Constructs the time manager object. @constructor @param {array} baseTime The initial date/time to start the game with. ### constructor: (@baseTime) -> @timeCounter = 0 @dateCounter = 0 @monthCounter = 0 @yearCounter = 0 ### Increases the game time by hours. @param {integer} hours The hours to increase the game time by. ### incrementTime: (hours) -> @timeCounter += hours while @timeCounter >= 24 @incrementDays(1) @timeCounter -= 24 if @timeCounter < 24 @timeCounter = @timeCounter % 24 break ### Increases the game time by days. @param {integer} days The days to increase the game time by. ### incrementDays: (days) -> i = 0 while i <= days @dateCounter++ player.depreciateInv() gameInsanity.setBar(gameInsanity.value * 0.95) i++ if i >= days i = 0 break while @dateCounter >= 30 @incrementMonths(1) @dateCounter -= 30 endTurn(@getFormatted()) if @dateCounter < 30 @dateCounter = @dateCounter % 30 break ### Increases the game time by months. @param {integer} months The monthes to increase the game time by. ### incrementMonths: (months) -> @monthCounter += months while @monthCounter >= 12 @incrementYears(1) @monthCounter -= 12 if @monthCounter < 12 @monthCounter = @monthCounter % 12 break ### Increases the game time by years. @param {integer} years The years to increase the game time by. ### incrementYears: (years) -> @yearCounter += years ### Gets the current game time. @return Array containing the game time. ### getAll: -> return [@baseTime[0] + @yearCounter, @baseTime[1] + @monthCounter, @baseTime[2] + @dateCounter, parseInt(@baseTime[3]) + @timeCounter] ### Gets the formatted current game time. @return Stringified and formatted game time. ### getFormatted: -> year = @baseTime[0] + @yearCounter month = @baseTime[1] + @monthCounter date = @baseTime[2] + @dateCounter hours = parseInt(@baseTime[3]) + @timeCounter minutes = parseInt((hours - Math.floor(hours))*60) if date > 30 date -= date - 30 if String(parseInt(minutes)).length == 2 then return year + '/' + month + '/' + date + ' ' + String(Math.floor(hours)) + ':' + String(parseInt(minutes)) else return year + '/' + month + '/' + date + ' ' + String(Math.floor(hours)) + ':' + String(parseInt(minutes)) + '0' class eventManager ### Constructs the event manager to handles all events. @constructor @param {DOMElement} domSelector The DOM element to display the event on. ### constructor: (@domSelector, @domOverlay) -> @events = [] ### Adds a event to the event manager @param {object} event The event object to add to the event manager. ### addEvent: (event) -> if event.time == 'currentTime' then event.time = gameTime.getFormatted() if event.constructor.name == 'randomEvent' if event.effects gameInsanity.updateBar event.effects.insanity newStats = player.stats for effectName in Object.keys event.effects newStats[effectName] += event.effects[effectName] player.updateStats(newStats) @domOverlay.find('.title').text event.title @domOverlay.find('.content').text event.content @domOverlay.show() else @events.push(event) if event.warn $('<div class="row"> <p class="time">' + event.time + '</p> <p class="title warn">' + event.title + '</p> <p class="content">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() else if event.special $('<div class="row"> <p class="time special">' + event.time + '</p> <p class="title special">' + event.title + '</p> <p class="content special">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() else $('<div class="row"> <p class="time">' + event.time + '</p> <p class="title">' + event.title + '</p> <p class="content">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() class playerInsanity ### Constructs playerInsanity object to handle player insanity events. @constructor @param {DOMElement} domSelector The DOM element to display the event on. @param {integer} initValue The initial insanity value ### constructor: (@domSelector, @initVal) -> @value = @initVal ### Sets the insanity bar to a value @param {integer} value the level of insanity to set to. ### setBar: (value) -> @value = value @domSelector.find('.bar').css 'height', @value + '%' ### Update the insanity level by a value @param {integer} value the level to increase the current insanity level by. ### updateBar: (value) -> if @value + value > 100 endGame() @domSelector.find('.bar').css 'height', '100%' else @value += value if @value < 0 then return else @domSelector.find('.bar').css 'height', @value + '%' ### Processes and validates an array of data. @param {array} data The set of data to process. @return The array of processed data/ ### processData = (data) -> processedData = [] for item in data.result.records if item['dcterms:spatial'] if item['dcterms:spatial'].split(';')[1] processedData.push(item) return processedData ### Generates google map markers from a set of data @param {array} data The set of data to generate markers from. ### generateMarkers = (data) -> marker = [] i = 0 for place in data lat = parseFloat(place['dcterms:spatial'].split(';')[1].split(',')[0]) lng = parseFloat(place['dcterms:spatial'].split(';')[1].split(',')[1]) marker[i] = new gameLocation {lat, lng}, place['dcterms:spatial'].split(';')[0], {'title': place['dc:title'], 'description': place['dc:description'], 'img': place['150_pixel_jpg']}, false marker[i].addTo(googleMap) locations.push(marker[i]) setValue(marker[i]) i++ updateMarkers() ### Sets the value of a given location based on the distance from the player. @param {object} location gameLocation object to set the value by. ### setValue = (location) -> rare = Math.random() <= 0.05; if rare location.value = parseInt((Math.random()*distanceTravelled(player.position, location.position) + 100)) location.rare = true else location.value = parseInt((Math.random()*distanceTravelled(player.position, location.position) + 100)/10) ### Updates the markers as the user player moves. @see playerMarker.prototype.moveTo() ### updateMarkers = -> for location in locations hide = Math.random() >= 0.8; show = Math.random() <= 0.2; if hide location.marker.setVisible(false) ### Instantiate the game components. ### gameEvents = new eventManager $('#eventLog .eventContainer'), $('#randomEventOverlay') gameTime = new timeManager [1939, 1, 1, 0] gameTutorial = new tutorialHandler $('.tutorial') gameInsanity = new playerInsanity $('#insanityBar'), 0 player = new playerMarker {lat: -25.363, lng: 151.044}, 'player', {'type':'self'} ,'https://developers.google.com/maps/documentation/javascript/images/custom-marker.png' player.initTo googleMap player.stats = gameGlobal.init.stats player.updateStats player.stats class photographyGame ### Constructs the photography game. @constructor @param {boolean} debug The debug state of the game. ### constructor: (@debug) -> @score = 0 ### Initialize the photography game. @param {integer} amount The amount of markers to initialize the game with. ### init: (amount) -> localInit = -> validData.sort -> return 0.5 - Math.random() generateMarkers(validData.slice(0, amount)) gameTutorial.init() gameEvents.addEvent(new event 'Game started', gameTime.getFormatted(), '') if localStorage.getItem 'photographyGameData' validData = processData(JSON.parse(localStorage.getItem 'photographyGameData')) if amount > validData.length retrieveResources(3000).then (res) -> localStorage.setItem 'photographyGameData', JSON.stringify(res) validData = processData res localInit() else localInit() else retrieveResources(3000).then (res) -> localStorage.setItem 'photographyGameData', JSON.stringify(res) validData = processData res localInit() ### Saves the current user score to the database. ### saveScore: -> gameId = '2' if gameGlobal.init.isPlus then gameId = '4' submitUserData({ method: 'saveScore' gameId: gameId value: @score }).then (res) -> res = JSON.parse res if res.status == 'success' $('#gameEnd .status').css 'color', '' $('#gameEnd .status').text res.message else $('#gameEnd .status').css 'color', 'red' $('#gameEnd .status').text res.message ### Instantiate the photography game. ### currentGame = new photographyGame false if getParam('diff') == 'normal' currentGame.init(100) else if getParam('diff') == 'extended' currentGame.init(500) ### Displays the end game screen. ### endGame = -> $('#gameEnd .stat').text 'You survived for ' + gameGlobal.trackers.monthPassed + ' Months, selling ' + gameGlobal.trackers.photosSold + ' photos and making over $' + gameGlobal.trackers.moneyEarned currentGame.score = gameGlobal.trackers.monthPassed*gameGlobal.trackers.photosSold*gameGlobal.trackers.moneyEarned $('#gameEnd .score').text 'Your score: ' + currentGame.score + ' pt' $('#gameEnd').show(); ### Ends the month. @param {string} date The date which the month ended on. ### endTurn = (date) -> if gameGlobal.init.isStory && gameGlobal.trackers.monthPassed >= 3 if gameGlobal.init.isPlus $('#gameEnd h4').text 'You wake up one day, you feel pain all across your body...' else $('#gameEnd h4').text 'You recieve a letter from the army. Now you can finally join the front lines.' $('#gameEnd .score').hide() endGame() gameGlobal.turnConsts.interest = (Math.random()*5).toFixed(2) gameEvents.addEvent(new event 'The month comes to an end.', date, 'Paid $' + player.stats.liabilities + ' in expenses', true) newStats = player.stats newStats.CAB -= player.stats.liabilities newStats.liabilities = gameGlobal.turnConsts.stdLiabilities player.updateStats(newStats) if player.preStat.workingCapital <= -1000 && player.preStat.CAB <= 0 if gameGlobal.turnConsts.alert then endGame() else gameGlobal.trackers.monthPassed += 1 gameGlobal.turnConsts.alert = true else gameGlobal.trackers.monthPassed += 1 if gameGlobal.turnConsts.alert && player.preStat.workingCapital > -1000 && player.preStat.CAB > 0 gameGlobal.turnConsts.alert = false for location in locations show = Math.random() > 0.2 if show location.marker.setVisible(true) ### Displays the taking picture screen. ### $('#takePic').hide() $('#takePic').click -> $('#takingPic .section3').css 'width', (Math.floor(Math.random() * (10 + 2))) + 1 + '%' $('#takingPic .section2').css 'width', (Math.floor(Math.random() * (19 + 2))) + '%' $('#takingPic .section4').css 'width', (Math.floor(Math.random() * (19 + 2))) + '%' $('#takingPic .slider').css 'left', 0 $('#takingPic .start, #takingPic .stop').prop 'disabled', false $('#takingPic .shotStats').hide() $('#takingPic').show() $('#takingPic .viewInv').hide() $('#takingPic .close').hide() $(this).hide() $('#takeDrink').hide() ### Starts the animation of the slider when taking the picture. ### $('#takingPic .start').click -> $(this).prop 'disabled', true $('#takingPic .slider').animate({ 'left': $('#takingPic .section1').width() + $('#takingPic .section2').width() + $('#takingPic .section3').width() + $('#takingPic .section4').width() + $('#takingPic .section5').width() + 'px'; }, 1000, -> calculatePicValue() ) ### Ends the animation of the slider when taking the picture. ### $('#takingPic .stop').click -> $(this).prop 'disabled', true $('#takingPic .slider').stop() $('#takingPic .close').show() calculatePicValue() ### Calculates the value of the picture based on the slider position. ### calculatePicValue = -> $('#takingPic .viewInv').show() $('#takingPic .shotStats').show(); multiplier = 1 quailty = 1 sliderPosition = parseInt($('#takingPic .slider').css('left'), 10) inBlue = ($('#takingPic .section1').position().left + $('#takingPic .section1').width()) <= sliderPosition && sliderPosition <= $('#takingPic .section5').position().left inGreen = ($('#takingPic .section2').position().left + $('#takingPic .section2').width()) <= sliderPosition && sliderPosition <= $('#takingPic .section4').position().left if inBlue && inGreen multiplier = 1.4 quailty = 0 $('.shotStats').text 'You take a high quailty photo, this will surely sell for more!' else if inBlue $('.shotStats').text 'You take a average photo.' else multiplier = 0.8 quailty = 2 $('.shotStats').text 'The shot comes out all smudged...' addShotToInv(multiplier, quailty) timeTaken = Math.floor(Math.random()*10) + 24 gameTime.incrementTime(timeTaken) gameEvents.addEvent(new event 'Taking Pictures', gameTime.getFormatted(), 'You spend some time around ' + player.playerAt.name + '. '+ timeTaken + ' hours later, you finally take a picture of value.') if player.playerAt.rare gameEvents.addEvent(new event 'Rare Picture -', gameTime.getFormatted(), 'You take a rare picture.', true) if !gameGlobal.init.isStory if $('#savePicOverlay .img img').length == 0 $('#savePicOverlay .img').append $('<img src="' + player.playerAt.data.img + '">') else $('#savePicOverlay .img img').attr 'src', player.playerAt.data.img $('#savePicOverlay .title').text player.playerAt.data.title $('#savePicOverlay #confirmSavePic').prop 'disabled', false $('#savePicOverlay').show() ### Instantiate the game photo object and adds a photographic shot to the inventory @param {integer} multiplier The scalar to multiple the value of the shot by. @param {integer} quailty The quailty of the picture. ### addShotToInv = (multiplier, quailty) -> photoValue = player.playerAt.value*multiplier shotTaken = new gamePhoto photoValue, false, player.playerAt.data.img, player.playerAt.data.title, quailty player.inventory.push(shotTaken) player.playerAt.marker.setVisible(false) newStats = player.stats newStats.assets += photoValue newStats.workingCapital -= player.playerAt.travelExpense/2 player.updateStats(newStats) ### Displays the player inventory and closes previous element's parent. ### $('.viewInv').click -> closeParent(this) displayInv() ### Displays the player inventory. ### $('#checkInv').click -> displayInv() ### Generates the player inventory. ### displayInv = -> $('#blockOverlay').show() $('#inventory .photoContainer').remove() $('#inventory').show() potentialValue = 0; sellableValue = 0; for item in player.inventory pictureContainer = $('<div class="photoContainer"></div>') picture = $(' <div class="crop"> <img class="photo" src="' + item.img + '"/> </div>').css('filter', 'blur('+ item.quailty + 'px') picture.appendTo(pictureContainer) if !item.washed pictureContainer.appendTo($('#inventory .cameraRoll')) potentialValue += item.value else pictureContainer.appendTo($('#inventory .washedPics')) sellableValue += item.value $('<aside> <p>Value $' + parseInt(item.value) + '</p> <p>' + item.title + '</p> </aside>').appendTo(pictureContainer) $('#rollValue').text('Total value $' + parseInt(potentialValue + sellableValue)) $('#sellableValue').text('Sellable Pictures value $' + parseInt(sellableValue)) ### Displays the waiting screen. ### $('#wait').click -> if $('#waitTimeInput').val() == '' then $('#waitTimeInput').parent().find('button.confirm').prop 'disabled', true $('#waitInfo').show() ### Waits and passes the game time. ### $('#confirmWait').click -> gameTime.incrementDays(parseInt($('#waitTimeInput').val())) if parseInt($('#waitTimeInput').val()) != 1 then gameEvents.addEvent(new event '', gameTime.getFormatted(), 'You wait ' + $('#waitTimeInput').val() + ' days') else gameEvents.addEvent(new event '', gameTime.getFormatted(), 'You wait ' + $('#waitTimeInput').val() + ' day') validData.sort -> return 0.5 - Math.random() generateMarkers(validData.slice(0, parseInt($('#waitTimeInput').val())/2)) for location in locations show = Math.floor(Math.random() * (30)) <= parseInt($('#waitTimeInput').val())/2 if show location.marker.setVisible true ### Displays the pictures avaliable for washing. ### $('#washPic').click -> notWashed = [] for item in player.inventory if !item.washed then notWashed.push(item) if notWashed.length == 0 $('#washPicOverlay p').text 'There are no pictures to wash.' $('#washPicOverlay').show() $('#washPicOverlay #confirmWashPic').hide() else for item in player.inventory item.washed = true $('#washPicOverlay p').text 'Washing photos takes ' + gameGlobal.turnConsts.pictureWashingTime + ' days. Proceed?' $('#washPicOverlay').show() $('#washPicOverlay #confirmWashPic').show() ### Washes all unwashed pictures in the player's inventory. ### $('#confirmWashPic').click -> gameTime.incrementTime(10*Math.random()) gameTime.incrementDays(gameGlobal.turnConsts.pictureWashingTime) gameEvents.addEvent(new event 'Washed pictures.', gameTime.getFormatted(), 'You wash all pictures in your camera.' ) ### Displays the take loan screen. ### $('#takeLoan').click -> $('#IR').text('Current interest rate ' + gameGlobal.turnConsts.interest + '%') if $('#loanInput').val() == '' then $('#loanInput').parent().find('button.confirm').prop 'disabled', true $('#loanOverlay').show() ### Confirms the loan to the player. ### $('#confirmLoan').click -> newStats = player.stats newStats.liabilities += parseInt($('#loanInput').val())+parseInt($('#loanInput').val())*(gameGlobal.turnConsts.interest/10) newStats.CAB += parseInt($('#loanInput').val()) player.updateStats(newStats) gameEvents.addEvent(new event 'Bank loan.', gameTime.getFormatted(), 'You take a bank loan of $' + parseInt($('#loanInput').val())) ### Validates the input to ensure the input is a number and non empty. ### $('#loanInput, #waitTimeInput').keyup -> if !$.isNumeric($(this).val()) || $(this).val() == '' $(this).parent().find('.err').text '*Input must be a number' $(this).parent().find('button.confirm').prop 'disabled', true else $(this).parent().find('.err').text '' $(this).parent().find('button.confirm').prop 'disabled', false ### Displays the sell pictures screen. ### $('#sellPic').click -> sellablePhotos = 0 photosValue = 0 for photo in player.inventory if photo.washed sellablePhotos += 1 photosValue += photo.value $('#soldInfoOverlay p').text 'Potential Earnings $' + parseInt(photosValue) + ' from ' + sellablePhotos + ' Photo/s' if sellablePhotos == 0 then $('#soldInfoOverlay button').hide() else $('#soldInfoOverlay button').show() $('#soldInfoOverlay').show() ### Sells the washed photos in the player's inventory. ### $('#sellPhotos').click -> photosSold = 0 earningsEst = 0 earningsAct = 0 newInventory = [] newStats = player.stats for photo in player.inventory if photo.washed earningsAct += parseInt(photo.value + (photo.value*Math.random())) earningsEst += photo.value photosSold += 1 gameGlobal.trackers.photosSold += 1 gameGlobal.trackers.moneyEarned += earningsAct else newInventory.push(photo) timeTaken = ((Math.random()*2)+1)*photosSold player.inventory = newInventory newStats.CAB += earningsAct newStats.assets -= earningsEst player.updateStats(newStats) gameTime.incrementDays(parseInt(timeTaken)) if parseInt(timeTaken) == 1 then gameEvents.addEvent(new event 'Selling Pictures.', gameTime.getFormatted(), 'It took ' + parseInt(timeTaken) + ' day to finally sell everything. Earned $' + earningsAct + ' from selling ' + photosSold + ' Photo/s.') else gameEvents.addEvent(new event 'Selling Pictures.', gameTime.getFormatted(), 'It took ' + parseInt(timeTaken) + ' days to finally sell everything. Earned $' + earningsAct + ' from selling ' + photosSold + ' Photo/s.') ### Blocks the game when a overlay/interface is active. ### $('#actions button').click -> if $(this).attr('id') != 'takeDrink' then $('#blockOverlay').show() ### Closes the overlay. ### $('.confirm, .close').click -> closeParent(this) ### Saves the DOM element to the player's collection. ### $('#confirmSavePic').click -> saveItem $('#savePicOverlay .img img').attr('src'), $('#savePicOverlay .title').text() $(this).prop 'disabled', true ### Closes the parent of the original DOM element @param {DOMElement} self The element whose parent should be hidden. ### closeParent = (self) -> $(self).parent().hide() $('#blockOverlay').hide() $('.status').text '' ### jQuery UI draggable handler. ### $('#actions').draggable() $('#actions').mousedown -> $('#actions p').text 'Actions' ### Saves the current user score. ### $('#saveScore').click -> currentGame.saveScore() ### Binds the generated buttons to the click event. ### $('body').on 'click', '.tutorial .next', -> gameTutorial.next() $('body').on 'click', '.tutorial .prev', -> gameTutorial.prev() ### Handles new Plus mode mechanics ### $('#randomEventOverlay .break').click -> gameTime.incrementDays(5) gameEvents.addEvent new event 'You take sometime off...', gameTime.getFormatted(), '' gameInsanity.setBar gameInsanity.value*0.75 $('#randomEventOverlay .seeDoc').click -> gameTime.incrementDays(2) newStats = player.stats newStats.CAB -= 500 player.updateStats newStats gameEvents.addEvent new event 'You visit a nearby doctor...', gameTime.getFormatted(), '' gameInsanity.setBar gameInsanity.value*0.25 gameGlobal.eventOccurrence = -1 $('#takeDrink').hide() $('#takeDrink').click -> $('#takePic').hide() $(this).hide() gameEvents.addEvent new event 'You go to a nearby pub', gameTime.getFormatted(), 'You spend $50 on some shots. It relieves some of your stress...' newStats = player.stats newStats.CAB -= 50 player.updateStats newStats gameInsanity.updateBar -5
true
### @file Handles the functionality of the photography game. ### jQuery(document).ready -> class event ### Constructs the event object. @constructor @param {string} title Title of the event. @param {string} time The game time of when the event occurred. @param {string} content The description of the event. @param {boolean} special Whether if the event is a special event. @param {boolean} warn Whether if the event is a warning. ### constructor: (@title, @time, @content, @special=false, @warn=false) -> class randomEvent extends event ### Constructs the random event object. Extends events. @constructor @param {string} title Title of the event. @param {string} time The game time of when the event occurred. @param {string} content The description of the event. @param {boolean} special Whether if the event is a special event. @param {boolean} warn Whether if the event is a warning. @param {boolean} popup Whether if the event has its own overlay, or added to the event log. @param {integer} chance The chance of the event occurance should it be selected. @param {object} effects The list of effects to affect the player by. ### constructor: (@title, @time, @content, @special=false, @popup=false, @chance, @effects) -> super(@title, @time, @content, @special, @warn) class gamePhoto ### Constructs the game photo object. @constructor @param {integer} value The value of the photo. @param {boolean} washed Whether if the photo has been washed @param {string} img The image associated with the photo. @param {string} title The title of the photo. @param {integer} quailty The quailty of the photo. ### constructor: (@value, @washed, @img, @title, @quailty) -> ### Global variables and constants. ### locations = [] validData = [] gameGlobal = { eventOccurrence: 0 init: { isStory: false isPlus: false stats: { CAB: 1000 workingCapital: 0 assets: 0 liabilities: 600 insanity: 0 } }, trackers: { monthPassed: 0 photosSold: 0 moneyEarned: 0 }, turnConsts: { interest: 1.5 pictureWashingTime: 14 stdLiabilities: 600 alert: false randomEvents: [ new randomEvent('Machine Gun Fire!', 'currentTime', 'You wake up in a cold sweat. The sound of a german machine gun barks out from the window. How coud this be? Germans in Australia? You grab your rifle from under your pillow and rush to the window. You ready your rifle and aim, looking for the enemy. BANG! BANG! BARK! YAP! You look at the neighbours small terrier. Barking...', false, true, 30, effects = {insanity: 20}), new randomEvent('German Bombs!', 'currentTime', 'A loud explosion shakes the ground and you see a building crumble into dust in the distance. Sirens. We have been attacked! You rush to see the chaos, pushing the bystanders aside. They are not running, strangely calm. Do they not recognize death when the see it? Then you see it. A construction crew. Dynamite.', false, true, 20, effects = {insanity: 30}), new randomEvent('Air raid!', 'currentTime', 'The sound of engines fills the air. The twins propellers of a German byplane. You look up to the sky, a small dot. It may be far now, but the machine guns will be upon us soon. Cover. Need to get safe. You yell to the people around you. GET INSIDE! GET INSIDE NOW! They look at you confused. They dont understand. You look up again. A toy. You look to your side, a car.', false, true, 24, effects = {insanity: 20}), new randomEvent('Landmines!', 'currentTime', 'You scan the ground carefully as you walk along the beaten dirt path. A habit you learned after one of your squadmate had his legs blown off by a German M24 mine. You stop. Under a pile of leaves you spot it. The glimmer of metal. Shrapnel to viciously tear you apart. You are no sapper but this could kill someone. You throw a rock a it. The empty can of beans rolls away.', false, true, 20, effects = {insanity: 10}), new randomEvent('Dazed', 'currentTime', 'You aim the camera at the young couple who had asked you for a picture. Slowly. 3. 2. 1. Click. FLASH. You open your eyes. The fields. The soldiers are readying for a charge. OVER THE TOP. You shake yourself awake. The couple is looking at you worryingly. How long was I out?', false, true, 20, effects = {insanity: 10}), new randomEvent('The enemy charges!', 'currentTime', 'You are pacing along the street. Footsteps... You turn round and see a man running after you. Yelling. Immediately you run at him. Disarm and subdue you think. Disarm. You tackle him to the ground. He falls with a thud. Subdue. You raise your fist. As you prepare to bring it down on your assailant. Its your wallet. "Please stop! You dropped your wallet! Take it!', false, true, 20, effects = {insanity: 20}) ] } } ### Submits session data to the server. @param {object} data the data to be submitted. @return AJAX deferred promise. ### submitUserData = (data) -> $.ajax url: '/routes/user.php' type: 'POST' data: data ### Display the response status to the DOM @param {DOMElement} target The DOM element to display the response to. @param {object} res The response to display. ### showResStatus = (target, res) -> if res.status == 'success' $(target).css 'color', '' $(target).text res.message else $(target).css 'color', 'red' $(target).text res.message ### Saves the a item to the user's collection. ### saveItem = (img, des) -> submitUserData({ method: 'saveItem' image: img description: des }).then (res) -> showResStatus '#savePicOverlay .status', JSON.parse res ### Gets the value of the paramater in the query string of a GET request. @param {string} name the key of the corrosponding value to retrieve. @return The sorted array. ### getParam = (name) -> results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href) return results[1] || 0 ### Retrieves the GET paramater from the query string. Sets up the interface and game constants accordingly. ### try storyMode = getParam('story') == 'true' plusMode = getParam('plus') == 'true' if storyMode gameGlobal.init.isStory = true $('.tutorial .init').text 'Welcome to the photography game. As PI:NAME:<NAME>END_PI, you must do your job for at least 4 month. Do not let your Working Capital drop below -$2000.' $('#playAgain').text 'Continue' $('#playAgain').parent().attr 'href', 'chapter3.html' $('.skip').show() $('.save, #endGame .score').hide() $('#playAgain').addClass('continue') if plusMode $('.continueScreen h3').text 'Chapter 4 Completed' $('.continueScreen p').remove() $('.continueScreen h3').after '<p>Photography Game Mode Plus Now Avaliable</p>' $('.continueScreen .buttonContainer a:first-child').attr('href', 'end.html').find('button').text 'Continue to Finale' if getParam('diff') == 'extended' gameGlobal.init.stats = { CAB: 2500, workingCapital: 0, assets: 0, liabilities: 1000 } if plusMode $('#tutorial .pPlus').text 'In Plus Mode, you will have to deal with additional events and control your insanity meter. The game will end should it gets too high.' gameGlobal.init.isPlus = true else $('.pPlus').remove() ### Skips the game when in story mode. Completes the chapter for the user. ### $('.skip, .continue').click (e) -> $('.continueScreen').show() $('#selectionArea, #gameArea').hide() id = '2' if gameGlobal.init.isPlus then id = '4' submitUserData({ method: 'chapterComplete' chapterId: id }).then (res) -> res = JSON.parse res if res.status == 'success' return 0 ### Retrieves resources from the dataset. @param {integer} amount The amount of resources to retrieve. @return AJAX deferred promise. ### retrieveResources = (amount) -> reqParam = { resource_id: '9913b881-d76d-43f5-acd6-3541a130853d', limit: amount } $.ajax { url: 'https://data.gov.au/api/action/datastore_search', data: reqParam, dataType: 'jsonp', cache: true } ### Converts degrees to radians. @param {float} deg The degree to convert to radians. @return The corrosponding radian value of the input. ### deg2rad = (deg) -> return deg * (Math.PI/180) ### Calculates the distance travelled from two lat, lng coordinates. @param {object} from The initial lat, lng coordinates. @param {object} to The final lat, lng coordinates. @return The distance between the two points in km. ### distanceTravelled = (from, to) -> lat1 = from.lat lng1 = from.lng lat2 = to.lat lng2 = to.lng R = 6371 dLat = deg2rad(lat2-lat1) dLng = deg2rad(lng2-lng1); a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLng/2) * Math.sin(dLng/2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); dist = R * c return dist; class tutorialHandler ### Constructs the game tutorial object. @constructor @param {DOMElement} domPanels The set of tutorial elements active in the DOM. ### constructor: (@domPanels) -> @step = 0; ### Displays the panel in view. ### init: -> $(@domPanels[@step]).show() @setButton() ### Switch to the next panel. ### next: -> @step++ $(@domPanels[@step]).show() $(@domPanels[@step - 1]).hide() @setButton() ### Switch to the previous panel ### prev: -> @step-- $(@domPanels[@step]).show() $(@domPanels[@step + 1]).hide() @setButton() ### Generates the avaliable buttons depending on the step. @see this.step ### setButton: -> @domPanels.find('.buttonContainer').remove() if @step == 0 @domPanels.append $('<div class="buttonContainer"> <button class="prev hidden">Previous</button> <button class="next">Next</button> </div>') else if @step == @domPanels.length - 1 @domPanels.append $('<div class="buttonContainer"> <button class="prev">Previous</button> <button class="next hidden">Next</button> </div>') else @domPanels.append $('<div class="buttonContainer"> <button class="prev">Previous</button> <button class="next">Next</button> </div>') class gameLocation ### Constructs the game location object @constructor @param {object} position The position of the location. @param {string} The name of the location. @param {data} Metadata associated with this position. @param {boolean} rare Whether if the location is a rare location or not @param {string} icon The icon to use for this location. ### constructor: (@position, @name, @data, @rare, @icon) -> @marker @value @travelExpense @travelTime ### Adds the location to the map. @param {object} map The google map element to add to. ### addTo: (map) -> if @icon marker = new google.maps.Marker({ position: @position, map: map, icon: @icon, title: @name }) else marker = new google.maps.Marker({ position: @position, map: map, title: @name }) @marker = marker @setListener(@marker) ### Sets event listeners on a marker @param {object} marker The google maps marker object to bind the event listener to. ### setListener: (marker) -> self = this marker.addListener 'click', -> player.moveTo(self) marker.addListener 'mouseover', -> travelDistance = parseInt(distanceTravelled(player.position, self.position)) travelTime = travelDistance/232 $('#locationInfoOverlay #title').text self.data.description $('#locationInfoOverlay #position').text 'Distance away ' + travelDistance + 'km' $('#locationInfoOverlay #value').text 'Potential Revenue $' + self.value $('#locationInfoOverlay #travelExpense').text 'Travel Expense $' + parseInt((travelDistance*0.6)/10) $('#locationInfoOverlay #travelTime').text 'Travel Time: at least ' + travelTime.toFixed(2) + ' Hours' @value = self.value class playerMarker extends gameLocation ### Constructs the player marker object. Extends the game location object @constructor @param {object} position The position of the player. @param {string} The name of the player. @param {data} Metadata associated with this player. @depreciated @param {string} icon The icon to use for this player. @param {object} stats JSON data of the player's stats. ### constructor: (@position, @name, @data, @icon, @stats) -> super(@position, @name, @data, @icon) @playerMarker @preStat @inventory = [] ### Adds the player marker to the map. @param {object} map The google map element to add to. ### initTo: (map) -> @playerMarker = new SlidingMarker({ position: @position, map: map, icon: 'https://developers.google.com/maps/documentation/javascript/images/custom-marker.png', title: @name, optimized: false, zIndex: 100 }) ### Moves the player marker to another location and calculates the result of moving to the location. @param {object} location gameLocation object, for the player marker to move to. ### moveTo: (location) -> location.marker.setVisible false location.travelExpense = parseInt((distanceTravelled(this.position, location.position)*0.6)/10) location.travelTime = parseFloat((distanceTravelled(this.position, location.position)/232).toFixed(2)) @position = location.position @playerAt = location @playerMarker.setPosition(new google.maps.LatLng(location.position.lat, location.position.lng)) newStats = @stats newStats.CAB -= player.playerAt.travelExpense timeTaken = location.travelTime + Math.random()*5 gameTime.incrementTime(timeTaken) gameEvents.addEvent(new event 'Moved to', gameTime.getFormatted(), location.name + ' in ' + timeTaken.toFixed(2) + ' hours') $('#takePic').show() $('#takeDrink').show() updateMarkers() @updateStats(newStats) if gameGlobal.init.isPlus gameGlobal.eventOccurrence += 0.5 if gameGlobal.eventOccurrence > 1 randEvent = gameGlobal.turnConsts.randomEvents[Math.floor(Math.random() * gameGlobal.turnConsts.randomEvents.length)] if randEvent.chance > Math.random() * 100 gameEvents.addEvent randEvent gameGlobal.eventOccurrence = 0 ### Depreciates the player's inventory. ### depreciateInv: -> depreciation = 0 for item in @inventory if item.value < 1 return else depreciation += item.value - item.value*0.9 item.value = item.value*0.9 newStats = player.stats newStats.assets -= depreciation.toFixed 2 if depreciation > 0 then gameEvents.addEvent new event 'Depreciation - ', gameTime.getFormatted(),'Photos depreciated by $' + depreciation.toFixed(2), false, true @updateStats(newStats) ### Updates the player stats and animates it in the DOM. @param {object} stats The new stats to update to. ### updateStats: (stats) -> animateText = (elem, from, to) -> $(current: from).animate { current: to }, duration: 500 step: -> $('#playerInfoOverlay #stats ' + elem + ' .val').text @current.toFixed() assets = parseInt (@stats.assets + @stats.CAB) workingCapital = parseInt (assets - @stats.liabilities) animateText '#CAB', parseInt($('#playerInfoOverlay #stats #CAB .val').text()), stats.CAB animateText '#liabilities', parseInt($('#playerInfoOverlay #stats #liabilities .val').text()), stats.liabilities animateText '#assets', parseInt($('#playerInfoOverlay #stats #assets .val').text()), assets animateText '#workingCapital', parseInt($('#playerInfoOverlay #stats #workingCapital .val').text()), workingCapital @preStat = { CAB: stats.CAB, workingCapital: workingCapital, assets: assets, liabilities: stats.liabilities insanity: stats.insanity } if workingCapital <= -1000 && @stats.CAB <= 0 $('#playerInfoOverlay #stats #workingCapital, #playerInfoOverlay #stats #CAB').css 'color', 'red' else $('#playerInfoOverlay #stats #workingCapital, #playerInfoOverlay #stats #CAB').css 'color', '' gameGlobal.turnConsts.alert = false class timeManager ### Constructs the time manager object. @constructor @param {array} baseTime The initial date/time to start the game with. ### constructor: (@baseTime) -> @timeCounter = 0 @dateCounter = 0 @monthCounter = 0 @yearCounter = 0 ### Increases the game time by hours. @param {integer} hours The hours to increase the game time by. ### incrementTime: (hours) -> @timeCounter += hours while @timeCounter >= 24 @incrementDays(1) @timeCounter -= 24 if @timeCounter < 24 @timeCounter = @timeCounter % 24 break ### Increases the game time by days. @param {integer} days The days to increase the game time by. ### incrementDays: (days) -> i = 0 while i <= days @dateCounter++ player.depreciateInv() gameInsanity.setBar(gameInsanity.value * 0.95) i++ if i >= days i = 0 break while @dateCounter >= 30 @incrementMonths(1) @dateCounter -= 30 endTurn(@getFormatted()) if @dateCounter < 30 @dateCounter = @dateCounter % 30 break ### Increases the game time by months. @param {integer} months The monthes to increase the game time by. ### incrementMonths: (months) -> @monthCounter += months while @monthCounter >= 12 @incrementYears(1) @monthCounter -= 12 if @monthCounter < 12 @monthCounter = @monthCounter % 12 break ### Increases the game time by years. @param {integer} years The years to increase the game time by. ### incrementYears: (years) -> @yearCounter += years ### Gets the current game time. @return Array containing the game time. ### getAll: -> return [@baseTime[0] + @yearCounter, @baseTime[1] + @monthCounter, @baseTime[2] + @dateCounter, parseInt(@baseTime[3]) + @timeCounter] ### Gets the formatted current game time. @return Stringified and formatted game time. ### getFormatted: -> year = @baseTime[0] + @yearCounter month = @baseTime[1] + @monthCounter date = @baseTime[2] + @dateCounter hours = parseInt(@baseTime[3]) + @timeCounter minutes = parseInt((hours - Math.floor(hours))*60) if date > 30 date -= date - 30 if String(parseInt(minutes)).length == 2 then return year + '/' + month + '/' + date + ' ' + String(Math.floor(hours)) + ':' + String(parseInt(minutes)) else return year + '/' + month + '/' + date + ' ' + String(Math.floor(hours)) + ':' + String(parseInt(minutes)) + '0' class eventManager ### Constructs the event manager to handles all events. @constructor @param {DOMElement} domSelector The DOM element to display the event on. ### constructor: (@domSelector, @domOverlay) -> @events = [] ### Adds a event to the event manager @param {object} event The event object to add to the event manager. ### addEvent: (event) -> if event.time == 'currentTime' then event.time = gameTime.getFormatted() if event.constructor.name == 'randomEvent' if event.effects gameInsanity.updateBar event.effects.insanity newStats = player.stats for effectName in Object.keys event.effects newStats[effectName] += event.effects[effectName] player.updateStats(newStats) @domOverlay.find('.title').text event.title @domOverlay.find('.content').text event.content @domOverlay.show() else @events.push(event) if event.warn $('<div class="row"> <p class="time">' + event.time + '</p> <p class="title warn">' + event.title + '</p> <p class="content">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() else if event.special $('<div class="row"> <p class="time special">' + event.time + '</p> <p class="title special">' + event.title + '</p> <p class="content special">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() else $('<div class="row"> <p class="time">' + event.time + '</p> <p class="title">' + event.title + '</p> <p class="content">' + event.content + '</p> </div>').hide().prependTo(@domSelector).fadeIn() class playerInsanity ### Constructs playerInsanity object to handle player insanity events. @constructor @param {DOMElement} domSelector The DOM element to display the event on. @param {integer} initValue The initial insanity value ### constructor: (@domSelector, @initVal) -> @value = @initVal ### Sets the insanity bar to a value @param {integer} value the level of insanity to set to. ### setBar: (value) -> @value = value @domSelector.find('.bar').css 'height', @value + '%' ### Update the insanity level by a value @param {integer} value the level to increase the current insanity level by. ### updateBar: (value) -> if @value + value > 100 endGame() @domSelector.find('.bar').css 'height', '100%' else @value += value if @value < 0 then return else @domSelector.find('.bar').css 'height', @value + '%' ### Processes and validates an array of data. @param {array} data The set of data to process. @return The array of processed data/ ### processData = (data) -> processedData = [] for item in data.result.records if item['dcterms:spatial'] if item['dcterms:spatial'].split(';')[1] processedData.push(item) return processedData ### Generates google map markers from a set of data @param {array} data The set of data to generate markers from. ### generateMarkers = (data) -> marker = [] i = 0 for place in data lat = parseFloat(place['dcterms:spatial'].split(';')[1].split(',')[0]) lng = parseFloat(place['dcterms:spatial'].split(';')[1].split(',')[1]) marker[i] = new gameLocation {lat, lng}, place['dcterms:spatial'].split(';')[0], {'title': place['dc:title'], 'description': place['dc:description'], 'img': place['150_pixel_jpg']}, false marker[i].addTo(googleMap) locations.push(marker[i]) setValue(marker[i]) i++ updateMarkers() ### Sets the value of a given location based on the distance from the player. @param {object} location gameLocation object to set the value by. ### setValue = (location) -> rare = Math.random() <= 0.05; if rare location.value = parseInt((Math.random()*distanceTravelled(player.position, location.position) + 100)) location.rare = true else location.value = parseInt((Math.random()*distanceTravelled(player.position, location.position) + 100)/10) ### Updates the markers as the user player moves. @see playerMarker.prototype.moveTo() ### updateMarkers = -> for location in locations hide = Math.random() >= 0.8; show = Math.random() <= 0.2; if hide location.marker.setVisible(false) ### Instantiate the game components. ### gameEvents = new eventManager $('#eventLog .eventContainer'), $('#randomEventOverlay') gameTime = new timeManager [1939, 1, 1, 0] gameTutorial = new tutorialHandler $('.tutorial') gameInsanity = new playerInsanity $('#insanityBar'), 0 player = new playerMarker {lat: -25.363, lng: 151.044}, 'player', {'type':'self'} ,'https://developers.google.com/maps/documentation/javascript/images/custom-marker.png' player.initTo googleMap player.stats = gameGlobal.init.stats player.updateStats player.stats class photographyGame ### Constructs the photography game. @constructor @param {boolean} debug The debug state of the game. ### constructor: (@debug) -> @score = 0 ### Initialize the photography game. @param {integer} amount The amount of markers to initialize the game with. ### init: (amount) -> localInit = -> validData.sort -> return 0.5 - Math.random() generateMarkers(validData.slice(0, amount)) gameTutorial.init() gameEvents.addEvent(new event 'Game started', gameTime.getFormatted(), '') if localStorage.getItem 'photographyGameData' validData = processData(JSON.parse(localStorage.getItem 'photographyGameData')) if amount > validData.length retrieveResources(3000).then (res) -> localStorage.setItem 'photographyGameData', JSON.stringify(res) validData = processData res localInit() else localInit() else retrieveResources(3000).then (res) -> localStorage.setItem 'photographyGameData', JSON.stringify(res) validData = processData res localInit() ### Saves the current user score to the database. ### saveScore: -> gameId = '2' if gameGlobal.init.isPlus then gameId = '4' submitUserData({ method: 'saveScore' gameId: gameId value: @score }).then (res) -> res = JSON.parse res if res.status == 'success' $('#gameEnd .status').css 'color', '' $('#gameEnd .status').text res.message else $('#gameEnd .status').css 'color', 'red' $('#gameEnd .status').text res.message ### Instantiate the photography game. ### currentGame = new photographyGame false if getParam('diff') == 'normal' currentGame.init(100) else if getParam('diff') == 'extended' currentGame.init(500) ### Displays the end game screen. ### endGame = -> $('#gameEnd .stat').text 'You survived for ' + gameGlobal.trackers.monthPassed + ' Months, selling ' + gameGlobal.trackers.photosSold + ' photos and making over $' + gameGlobal.trackers.moneyEarned currentGame.score = gameGlobal.trackers.monthPassed*gameGlobal.trackers.photosSold*gameGlobal.trackers.moneyEarned $('#gameEnd .score').text 'Your score: ' + currentGame.score + ' pt' $('#gameEnd').show(); ### Ends the month. @param {string} date The date which the month ended on. ### endTurn = (date) -> if gameGlobal.init.isStory && gameGlobal.trackers.monthPassed >= 3 if gameGlobal.init.isPlus $('#gameEnd h4').text 'You wake up one day, you feel pain all across your body...' else $('#gameEnd h4').text 'You recieve a letter from the army. Now you can finally join the front lines.' $('#gameEnd .score').hide() endGame() gameGlobal.turnConsts.interest = (Math.random()*5).toFixed(2) gameEvents.addEvent(new event 'The month comes to an end.', date, 'Paid $' + player.stats.liabilities + ' in expenses', true) newStats = player.stats newStats.CAB -= player.stats.liabilities newStats.liabilities = gameGlobal.turnConsts.stdLiabilities player.updateStats(newStats) if player.preStat.workingCapital <= -1000 && player.preStat.CAB <= 0 if gameGlobal.turnConsts.alert then endGame() else gameGlobal.trackers.monthPassed += 1 gameGlobal.turnConsts.alert = true else gameGlobal.trackers.monthPassed += 1 if gameGlobal.turnConsts.alert && player.preStat.workingCapital > -1000 && player.preStat.CAB > 0 gameGlobal.turnConsts.alert = false for location in locations show = Math.random() > 0.2 if show location.marker.setVisible(true) ### Displays the taking picture screen. ### $('#takePic').hide() $('#takePic').click -> $('#takingPic .section3').css 'width', (Math.floor(Math.random() * (10 + 2))) + 1 + '%' $('#takingPic .section2').css 'width', (Math.floor(Math.random() * (19 + 2))) + '%' $('#takingPic .section4').css 'width', (Math.floor(Math.random() * (19 + 2))) + '%' $('#takingPic .slider').css 'left', 0 $('#takingPic .start, #takingPic .stop').prop 'disabled', false $('#takingPic .shotStats').hide() $('#takingPic').show() $('#takingPic .viewInv').hide() $('#takingPic .close').hide() $(this).hide() $('#takeDrink').hide() ### Starts the animation of the slider when taking the picture. ### $('#takingPic .start').click -> $(this).prop 'disabled', true $('#takingPic .slider').animate({ 'left': $('#takingPic .section1').width() + $('#takingPic .section2').width() + $('#takingPic .section3').width() + $('#takingPic .section4').width() + $('#takingPic .section5').width() + 'px'; }, 1000, -> calculatePicValue() ) ### Ends the animation of the slider when taking the picture. ### $('#takingPic .stop').click -> $(this).prop 'disabled', true $('#takingPic .slider').stop() $('#takingPic .close').show() calculatePicValue() ### Calculates the value of the picture based on the slider position. ### calculatePicValue = -> $('#takingPic .viewInv').show() $('#takingPic .shotStats').show(); multiplier = 1 quailty = 1 sliderPosition = parseInt($('#takingPic .slider').css('left'), 10) inBlue = ($('#takingPic .section1').position().left + $('#takingPic .section1').width()) <= sliderPosition && sliderPosition <= $('#takingPic .section5').position().left inGreen = ($('#takingPic .section2').position().left + $('#takingPic .section2').width()) <= sliderPosition && sliderPosition <= $('#takingPic .section4').position().left if inBlue && inGreen multiplier = 1.4 quailty = 0 $('.shotStats').text 'You take a high quailty photo, this will surely sell for more!' else if inBlue $('.shotStats').text 'You take a average photo.' else multiplier = 0.8 quailty = 2 $('.shotStats').text 'The shot comes out all smudged...' addShotToInv(multiplier, quailty) timeTaken = Math.floor(Math.random()*10) + 24 gameTime.incrementTime(timeTaken) gameEvents.addEvent(new event 'Taking Pictures', gameTime.getFormatted(), 'You spend some time around ' + player.playerAt.name + '. '+ timeTaken + ' hours later, you finally take a picture of value.') if player.playerAt.rare gameEvents.addEvent(new event 'Rare Picture -', gameTime.getFormatted(), 'You take a rare picture.', true) if !gameGlobal.init.isStory if $('#savePicOverlay .img img').length == 0 $('#savePicOverlay .img').append $('<img src="' + player.playerAt.data.img + '">') else $('#savePicOverlay .img img').attr 'src', player.playerAt.data.img $('#savePicOverlay .title').text player.playerAt.data.title $('#savePicOverlay #confirmSavePic').prop 'disabled', false $('#savePicOverlay').show() ### Instantiate the game photo object and adds a photographic shot to the inventory @param {integer} multiplier The scalar to multiple the value of the shot by. @param {integer} quailty The quailty of the picture. ### addShotToInv = (multiplier, quailty) -> photoValue = player.playerAt.value*multiplier shotTaken = new gamePhoto photoValue, false, player.playerAt.data.img, player.playerAt.data.title, quailty player.inventory.push(shotTaken) player.playerAt.marker.setVisible(false) newStats = player.stats newStats.assets += photoValue newStats.workingCapital -= player.playerAt.travelExpense/2 player.updateStats(newStats) ### Displays the player inventory and closes previous element's parent. ### $('.viewInv').click -> closeParent(this) displayInv() ### Displays the player inventory. ### $('#checkInv').click -> displayInv() ### Generates the player inventory. ### displayInv = -> $('#blockOverlay').show() $('#inventory .photoContainer').remove() $('#inventory').show() potentialValue = 0; sellableValue = 0; for item in player.inventory pictureContainer = $('<div class="photoContainer"></div>') picture = $(' <div class="crop"> <img class="photo" src="' + item.img + '"/> </div>').css('filter', 'blur('+ item.quailty + 'px') picture.appendTo(pictureContainer) if !item.washed pictureContainer.appendTo($('#inventory .cameraRoll')) potentialValue += item.value else pictureContainer.appendTo($('#inventory .washedPics')) sellableValue += item.value $('<aside> <p>Value $' + parseInt(item.value) + '</p> <p>' + item.title + '</p> </aside>').appendTo(pictureContainer) $('#rollValue').text('Total value $' + parseInt(potentialValue + sellableValue)) $('#sellableValue').text('Sellable Pictures value $' + parseInt(sellableValue)) ### Displays the waiting screen. ### $('#wait').click -> if $('#waitTimeInput').val() == '' then $('#waitTimeInput').parent().find('button.confirm').prop 'disabled', true $('#waitInfo').show() ### Waits and passes the game time. ### $('#confirmWait').click -> gameTime.incrementDays(parseInt($('#waitTimeInput').val())) if parseInt($('#waitTimeInput').val()) != 1 then gameEvents.addEvent(new event '', gameTime.getFormatted(), 'You wait ' + $('#waitTimeInput').val() + ' days') else gameEvents.addEvent(new event '', gameTime.getFormatted(), 'You wait ' + $('#waitTimeInput').val() + ' day') validData.sort -> return 0.5 - Math.random() generateMarkers(validData.slice(0, parseInt($('#waitTimeInput').val())/2)) for location in locations show = Math.floor(Math.random() * (30)) <= parseInt($('#waitTimeInput').val())/2 if show location.marker.setVisible true ### Displays the pictures avaliable for washing. ### $('#washPic').click -> notWashed = [] for item in player.inventory if !item.washed then notWashed.push(item) if notWashed.length == 0 $('#washPicOverlay p').text 'There are no pictures to wash.' $('#washPicOverlay').show() $('#washPicOverlay #confirmWashPic').hide() else for item in player.inventory item.washed = true $('#washPicOverlay p').text 'Washing photos takes ' + gameGlobal.turnConsts.pictureWashingTime + ' days. Proceed?' $('#washPicOverlay').show() $('#washPicOverlay #confirmWashPic').show() ### Washes all unwashed pictures in the player's inventory. ### $('#confirmWashPic').click -> gameTime.incrementTime(10*Math.random()) gameTime.incrementDays(gameGlobal.turnConsts.pictureWashingTime) gameEvents.addEvent(new event 'Washed pictures.', gameTime.getFormatted(), 'You wash all pictures in your camera.' ) ### Displays the take loan screen. ### $('#takeLoan').click -> $('#IR').text('Current interest rate ' + gameGlobal.turnConsts.interest + '%') if $('#loanInput').val() == '' then $('#loanInput').parent().find('button.confirm').prop 'disabled', true $('#loanOverlay').show() ### Confirms the loan to the player. ### $('#confirmLoan').click -> newStats = player.stats newStats.liabilities += parseInt($('#loanInput').val())+parseInt($('#loanInput').val())*(gameGlobal.turnConsts.interest/10) newStats.CAB += parseInt($('#loanInput').val()) player.updateStats(newStats) gameEvents.addEvent(new event 'Bank loan.', gameTime.getFormatted(), 'You take a bank loan of $' + parseInt($('#loanInput').val())) ### Validates the input to ensure the input is a number and non empty. ### $('#loanInput, #waitTimeInput').keyup -> if !$.isNumeric($(this).val()) || $(this).val() == '' $(this).parent().find('.err').text '*Input must be a number' $(this).parent().find('button.confirm').prop 'disabled', true else $(this).parent().find('.err').text '' $(this).parent().find('button.confirm').prop 'disabled', false ### Displays the sell pictures screen. ### $('#sellPic').click -> sellablePhotos = 0 photosValue = 0 for photo in player.inventory if photo.washed sellablePhotos += 1 photosValue += photo.value $('#soldInfoOverlay p').text 'Potential Earnings $' + parseInt(photosValue) + ' from ' + sellablePhotos + ' Photo/s' if sellablePhotos == 0 then $('#soldInfoOverlay button').hide() else $('#soldInfoOverlay button').show() $('#soldInfoOverlay').show() ### Sells the washed photos in the player's inventory. ### $('#sellPhotos').click -> photosSold = 0 earningsEst = 0 earningsAct = 0 newInventory = [] newStats = player.stats for photo in player.inventory if photo.washed earningsAct += parseInt(photo.value + (photo.value*Math.random())) earningsEst += photo.value photosSold += 1 gameGlobal.trackers.photosSold += 1 gameGlobal.trackers.moneyEarned += earningsAct else newInventory.push(photo) timeTaken = ((Math.random()*2)+1)*photosSold player.inventory = newInventory newStats.CAB += earningsAct newStats.assets -= earningsEst player.updateStats(newStats) gameTime.incrementDays(parseInt(timeTaken)) if parseInt(timeTaken) == 1 then gameEvents.addEvent(new event 'Selling Pictures.', gameTime.getFormatted(), 'It took ' + parseInt(timeTaken) + ' day to finally sell everything. Earned $' + earningsAct + ' from selling ' + photosSold + ' Photo/s.') else gameEvents.addEvent(new event 'Selling Pictures.', gameTime.getFormatted(), 'It took ' + parseInt(timeTaken) + ' days to finally sell everything. Earned $' + earningsAct + ' from selling ' + photosSold + ' Photo/s.') ### Blocks the game when a overlay/interface is active. ### $('#actions button').click -> if $(this).attr('id') != 'takeDrink' then $('#blockOverlay').show() ### Closes the overlay. ### $('.confirm, .close').click -> closeParent(this) ### Saves the DOM element to the player's collection. ### $('#confirmSavePic').click -> saveItem $('#savePicOverlay .img img').attr('src'), $('#savePicOverlay .title').text() $(this).prop 'disabled', true ### Closes the parent of the original DOM element @param {DOMElement} self The element whose parent should be hidden. ### closeParent = (self) -> $(self).parent().hide() $('#blockOverlay').hide() $('.status').text '' ### jQuery UI draggable handler. ### $('#actions').draggable() $('#actions').mousedown -> $('#actions p').text 'Actions' ### Saves the current user score. ### $('#saveScore').click -> currentGame.saveScore() ### Binds the generated buttons to the click event. ### $('body').on 'click', '.tutorial .next', -> gameTutorial.next() $('body').on 'click', '.tutorial .prev', -> gameTutorial.prev() ### Handles new Plus mode mechanics ### $('#randomEventOverlay .break').click -> gameTime.incrementDays(5) gameEvents.addEvent new event 'You take sometime off...', gameTime.getFormatted(), '' gameInsanity.setBar gameInsanity.value*0.75 $('#randomEventOverlay .seeDoc').click -> gameTime.incrementDays(2) newStats = player.stats newStats.CAB -= 500 player.updateStats newStats gameEvents.addEvent new event 'You visit a nearby doctor...', gameTime.getFormatted(), '' gameInsanity.setBar gameInsanity.value*0.25 gameGlobal.eventOccurrence = -1 $('#takeDrink').hide() $('#takeDrink').click -> $('#takePic').hide() $(this).hide() gameEvents.addEvent new event 'You go to a nearby pub', gameTime.getFormatted(), 'You spend $50 on some shots. It relieves some of your stress...' newStats = player.stats newStats.CAB -= 50 player.updateStats newStats gameInsanity.updateBar -5
[ { "context": "#\n# Commands:\n# git help <topic>\n#\n# Author:\n# vquaiato, Jens Jahnke\n\njsdom = require(\"jsdom\").jsdom\n\nmod", "end": 175, "score": 0.9995734691619873, "start": 167, "tag": "USERNAME", "value": "vquaiato" }, { "context": "ds:\n# git help <topic>\n#\n# Auth...
src/scripts/git-help.coffee
contolini/hubot-scripts
1,450
# Description: # Show some help to git noobies # # Dependencies: # jsdom # jquery # # Configuration: # None # # Commands: # git help <topic> # # Author: # vquaiato, Jens Jahnke jsdom = require("jsdom").jsdom module.exports = (robot) -> robot.respond /git help (.+)$/i, (msg) -> topic = msg.match[1].toLowerCase() url = 'http://git-scm.com/docs/git-' + topic msg.http(url).get() (err, res, body) -> window = (jsdom body, null, features: FetchExternalResources: false ProcessExternalResources: false MutationEvents: false QuerySelector: false ).createWindow() $ = require("jquery").create(window) name = $.trim $('#header .sectionbody .paragraph').text() desc = $.trim $('#_synopsis + .verseblock > .content').text() if name and desc msg.send name msg.send desc msg.send "See #{url} for details." else msg.send "No git help page found for #{topic}."
90607
# Description: # Show some help to git noobies # # Dependencies: # jsdom # jquery # # Configuration: # None # # Commands: # git help <topic> # # Author: # vquaiato, <NAME> jsdom = require("jsdom").jsdom module.exports = (robot) -> robot.respond /git help (.+)$/i, (msg) -> topic = msg.match[1].toLowerCase() url = 'http://git-scm.com/docs/git-' + topic msg.http(url).get() (err, res, body) -> window = (jsdom body, null, features: FetchExternalResources: false ProcessExternalResources: false MutationEvents: false QuerySelector: false ).createWindow() $ = require("jquery").create(window) name = $.trim $('#header .sectionbody .paragraph').text() desc = $.trim $('#_synopsis + .verseblock > .content').text() if name and desc msg.send name msg.send desc msg.send "See #{url} for details." else msg.send "No git help page found for #{topic}."
true
# Description: # Show some help to git noobies # # Dependencies: # jsdom # jquery # # Configuration: # None # # Commands: # git help <topic> # # Author: # vquaiato, PI:NAME:<NAME>END_PI jsdom = require("jsdom").jsdom module.exports = (robot) -> robot.respond /git help (.+)$/i, (msg) -> topic = msg.match[1].toLowerCase() url = 'http://git-scm.com/docs/git-' + topic msg.http(url).get() (err, res, body) -> window = (jsdom body, null, features: FetchExternalResources: false ProcessExternalResources: false MutationEvents: false QuerySelector: false ).createWindow() $ = require("jquery").create(window) name = $.trim $('#header .sectionbody .paragraph').text() desc = $.trim $('#_synopsis + .verseblock > .content').text() if name and desc msg.send name msg.send desc msg.send "See #{url} for details." else msg.send "No git help page found for #{topic}."
[ { "context": "id: 'thank-you-for-considering'\n token: 'this-will-not-work'\n @datastore.insert record, done\n\n be", "end": 1700, "score": 0.9981221556663513, "start": 1682, "tag": "PASSWORD", "value": "this-will-not-work" }, { "context": "Id: 'axed'\n ...
test/check-root-token-spec.coffee
octoblu/meshblu-core-task-check-root-token
0
Datastore = require 'meshblu-core-datastore' mongojs = require 'mongojs' RootTokenManager = require 'meshblu-core-manager-root-token' CheckRootToken = require '../' describe 'CheckRootToken', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['devices'] @datastore = new Datastore database: database collection: 'devices' database.devices.remove done beforeEach -> @rootTokenManager = new RootTokenManager { @datastore, @uuidAliasResolver } @sut = new CheckRootToken { @datastore, @uuidAliasResolver } describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' @datastore.insert record, done beforeEach (done) -> @rootTokenManager.generateAndStoreToken { uuid: 'thank-you-for-considering' }, (error, @generatedToken) => done error beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' auth: uuid: 'thank-you-for-considering' token: @generatedToken @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a invalid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' token: 'this-will-not-work' @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'axed' auth: uuid: 'hatcheted' token: 'bodysprayed' @sut.do request, (error, @response) => done error it 'should respond with a 401', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse context 'when given an invalid auth object', -> beforeEach (done) -> request = metadata: responseId: 'axed' @sut.do request, (error, @response) => done error it 'should respond with a 422', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse
50702
Datastore = require 'meshblu-core-datastore' mongojs = require 'mongojs' RootTokenManager = require 'meshblu-core-manager-root-token' CheckRootToken = require '../' describe 'CheckRootToken', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['devices'] @datastore = new Datastore database: database collection: 'devices' database.devices.remove done beforeEach -> @rootTokenManager = new RootTokenManager { @datastore, @uuidAliasResolver } @sut = new CheckRootToken { @datastore, @uuidAliasResolver } describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' @datastore.insert record, done beforeEach (done) -> @rootTokenManager.generateAndStoreToken { uuid: 'thank-you-for-considering' }, (error, @generatedToken) => done error beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' auth: uuid: 'thank-you-for-considering' token: @generatedToken @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a invalid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' token: '<PASSWORD>' @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'axed' auth: uuid: 'hatcheted' token: '<PASSWORD>' @sut.do request, (error, @response) => done error it 'should respond with a 401', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse context 'when given an invalid auth object', -> beforeEach (done) -> request = metadata: responseId: 'axed' @sut.do request, (error, @response) => done error it 'should respond with a 422', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse
true
Datastore = require 'meshblu-core-datastore' mongojs = require 'mongojs' RootTokenManager = require 'meshblu-core-manager-root-token' CheckRootToken = require '../' describe 'CheckRootToken', -> beforeEach (done) -> @uuidAliasResolver = resolve: (uuid, callback) => callback null, uuid database = mongojs 'meshblu-core-task-check-token', ['devices'] @datastore = new Datastore database: database collection: 'devices' database.devices.remove done beforeEach -> @rootTokenManager = new RootTokenManager { @datastore, @uuidAliasResolver } @sut = new CheckRootToken { @datastore, @uuidAliasResolver } describe '->do', -> context 'when given a valid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' @datastore.insert record, done beforeEach (done) -> @rootTokenManager.generateAndStoreToken { uuid: 'thank-you-for-considering' }, (error, @generatedToken) => done error beforeEach (done) -> request = metadata: responseId: 'used-as-biofuel' auth: uuid: 'thank-you-for-considering' token: @generatedToken @sut.do request, (error, @response) => done error it 'should respond with a 204', -> expectedResponse = metadata: responseId: 'used-as-biofuel' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'when given a invalid token', -> beforeEach (done) -> record = uuid: 'thank-you-for-considering' token: 'PI:PASSWORD:<PASSWORD>END_PI' @datastore.insert record, done beforeEach (done) -> request = metadata: responseId: 'axed' auth: uuid: 'hatcheted' token: 'PI:PASSWORD:<PASSWORD>END_PI' @sut.do request, (error, @response) => done error it 'should respond with a 401', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse context 'when given an invalid auth object', -> beforeEach (done) -> request = metadata: responseId: 'axed' @sut.do request, (error, @response) => done error it 'should respond with a 422', -> expectedResponse = metadata: responseId: 'axed' code: 401 status: 'Unauthorized' expect(@response).to.deep.equal expectedResponse
[ { "context": "'clear-list text-center'>\n <li>Developed by JCJ</li>\n <li>Report bugs or suggestions to my", "end": 513, "score": 0.9826878905296326, "start": 510, "tag": "USERNAME", "value": "JCJ" }, { "context": " bugs or suggestions to my email</li>\n <li>juan...
components/About.react.coffee
juancjara/guitar-hero-firefox-os
0
React = require 'react' module.exports = About = React.createClass handleClick: (to) -> @props.changeTab('About', to) render: -> className = 'about tabs '+@props.show <div className = {className}> <div className = 'btn blue pull-left' onTouchEnd={@handleClick.bind(this, 'MainMenu')}> Menu </div> <div className = 'clear' ></div> <h2 className = 'text-center'>About</h2> <ul className = 'clear-list text-center'> <li>Developed by JCJ</li> <li>Report bugs or suggestions to my email</li> <li>juanc.jara@pucp.pe</li> <li>Music: <a href = 'http://www.bensound.com'>http://www.bensound.com</a> </li> </ul> </div>
61658
React = require 'react' module.exports = About = React.createClass handleClick: (to) -> @props.changeTab('About', to) render: -> className = 'about tabs '+@props.show <div className = {className}> <div className = 'btn blue pull-left' onTouchEnd={@handleClick.bind(this, 'MainMenu')}> Menu </div> <div className = 'clear' ></div> <h2 className = 'text-center'>About</h2> <ul className = 'clear-list text-center'> <li>Developed by JCJ</li> <li>Report bugs or suggestions to my email</li> <li><EMAIL></li> <li>Music: <a href = 'http://www.bensound.com'>http://www.bensound.com</a> </li> </ul> </div>
true
React = require 'react' module.exports = About = React.createClass handleClick: (to) -> @props.changeTab('About', to) render: -> className = 'about tabs '+@props.show <div className = {className}> <div className = 'btn blue pull-left' onTouchEnd={@handleClick.bind(this, 'MainMenu')}> Menu </div> <div className = 'clear' ></div> <h2 className = 'text-center'>About</h2> <ul className = 'clear-list text-center'> <li>Developed by JCJ</li> <li>Report bugs or suggestions to my email</li> <li>PI:EMAIL:<EMAIL>END_PI</li> <li>Music: <a href = 'http://www.bensound.com'>http://www.bensound.com</a> </li> </ul> </div>
[ { "context": "--------------\n# Copyright Joe Drago 2018.\n# Distributed under the Boost Softw", "end": 123, "score": 0.999818742275238, "start": 114, "tag": "NAME", "value": "Joe Drago" } ]
lib/templates/src/coffee/PixelsView.coffee
EwoutH/colorist
0
# --------------------------------------------------------------------------- # Copyright Joe Drago 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- React = require 'react' DOM = require 'react-dom' tags = require './tags' utils = require './utils' {el, div, table, tr, td, tbody} = require './tags' TopBar = require './TopBar' ImageRenderer = require './ImageRenderer' InfoPanel = require './InfoPanel' as8Bit = (v, depth) -> return utils.clamp(Math.round(v / ((1 << depth)-1) * 255), 0, 255) class PixelsView extends React.Component @defaultProps: app: null constructor: (props) -> super props @state = x: -1 y: -1 @rawPixels = @props.app.rawPixels @highlightInfos = @props.app.highlightInfos setPos: (x, y) -> @setState { x: x, y: y } render: -> elements = [] elements.push el TopBar, { key: "TopBar" app: @props.app } infoPanelWidth = 300 title = "Pixels" image = COLORIST_DATA.visual maxNits = COLORIST_DATA.icc.luminance if @props.name == 'srgb' title = "sRGB Highlight (#{COLORIST_DATA.srgb.highlightLuminance})" image = COLORIST_DATA.srgb.visual maxNits = COLORIST_DATA.srgb.highlightLuminance elements.push el ImageRenderer, { width: @props.width - infoPanelWidth height: @props.height url: image listener: this } sections = [] horseshoeX = -1 horseshoeY = -1 if (@state.x >= 0) and (@state.y >= 0) pixel = @rawPixels.get(@state.x, @state.y) sections.push { name: "Raw" rows: [ ["R", pixel.r, "", as8Bit(pixel.r, COLORIST_DATA.depth)] ["G", pixel.g, "", as8Bit(pixel.g, COLORIST_DATA.depth)] ["B", pixel.b, "", as8Bit(pixel.b, COLORIST_DATA.depth)] ["A", pixel.a, "", as8Bit(pixel.a, COLORIST_DATA.depth)] ] } @pixelInfos highlightInfo = @highlightInfos.get(@state.x, @state.y) xyY = [highlightInfo.x, highlightInfo.y, highlightInfo.Y] pixelLuminance = highlightInfo.nits maxPixelLuminance = highlightInfo.maxNits outofSRGB = highlightInfo.outOfGamut sections.push { name: "xyY" rows: [ ["x", utils.fr(xyY[0], 4)] ["y", utils.fr(xyY[1], 4)] ["Y", utils.fr(xyY[2], 4)] ["Nits:", utils.fr(pixelLuminance, 2), "/", utils.fr(maxPixelLuminance, 2)] ] } horseshoeX = xyY[0] horseshoeY = xyY[1] if @props.name != 'pixels' p = (pixelLuminance / maxPixelLuminance) REASONABLY_OVERBRIGHT = 0.0001 # this should match the constant in context_report.c's calcOverbright() if p > (1.0 + REASONABLY_OVERBRIGHT) luminancePercentage = utils.fr(p * 100, 2) + "%" else luminancePercentage = "--" if outofSRGB > 0 outofSRGB = utils.fr(100 * outofSRGB, 2) + "%" else outofSRGB = "--" sections.push { name: "sRGB Overranging (#{maxNits} nits)" rows: [ ["Luminance", luminancePercentage] ["Out Gamut", outofSRGB] ] } elements.push el InfoPanel, { title: title left: @props.width - infoPanelWidth width: infoPanelWidth height: @props.height url: COLORIST_DATA.uri sections: sections usesPixelPos: true x: @state.x y: @state.y horseshoeX: horseshoeX horseshoeY: horseshoeY } return elements module.exports = PixelsView
1019
# --------------------------------------------------------------------------- # Copyright <NAME> 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- React = require 'react' DOM = require 'react-dom' tags = require './tags' utils = require './utils' {el, div, table, tr, td, tbody} = require './tags' TopBar = require './TopBar' ImageRenderer = require './ImageRenderer' InfoPanel = require './InfoPanel' as8Bit = (v, depth) -> return utils.clamp(Math.round(v / ((1 << depth)-1) * 255), 0, 255) class PixelsView extends React.Component @defaultProps: app: null constructor: (props) -> super props @state = x: -1 y: -1 @rawPixels = @props.app.rawPixels @highlightInfos = @props.app.highlightInfos setPos: (x, y) -> @setState { x: x, y: y } render: -> elements = [] elements.push el TopBar, { key: "TopBar" app: @props.app } infoPanelWidth = 300 title = "Pixels" image = COLORIST_DATA.visual maxNits = COLORIST_DATA.icc.luminance if @props.name == 'srgb' title = "sRGB Highlight (#{COLORIST_DATA.srgb.highlightLuminance})" image = COLORIST_DATA.srgb.visual maxNits = COLORIST_DATA.srgb.highlightLuminance elements.push el ImageRenderer, { width: @props.width - infoPanelWidth height: @props.height url: image listener: this } sections = [] horseshoeX = -1 horseshoeY = -1 if (@state.x >= 0) and (@state.y >= 0) pixel = @rawPixels.get(@state.x, @state.y) sections.push { name: "Raw" rows: [ ["R", pixel.r, "", as8Bit(pixel.r, COLORIST_DATA.depth)] ["G", pixel.g, "", as8Bit(pixel.g, COLORIST_DATA.depth)] ["B", pixel.b, "", as8Bit(pixel.b, COLORIST_DATA.depth)] ["A", pixel.a, "", as8Bit(pixel.a, COLORIST_DATA.depth)] ] } @pixelInfos highlightInfo = @highlightInfos.get(@state.x, @state.y) xyY = [highlightInfo.x, highlightInfo.y, highlightInfo.Y] pixelLuminance = highlightInfo.nits maxPixelLuminance = highlightInfo.maxNits outofSRGB = highlightInfo.outOfGamut sections.push { name: "xyY" rows: [ ["x", utils.fr(xyY[0], 4)] ["y", utils.fr(xyY[1], 4)] ["Y", utils.fr(xyY[2], 4)] ["Nits:", utils.fr(pixelLuminance, 2), "/", utils.fr(maxPixelLuminance, 2)] ] } horseshoeX = xyY[0] horseshoeY = xyY[1] if @props.name != 'pixels' p = (pixelLuminance / maxPixelLuminance) REASONABLY_OVERBRIGHT = 0.0001 # this should match the constant in context_report.c's calcOverbright() if p > (1.0 + REASONABLY_OVERBRIGHT) luminancePercentage = utils.fr(p * 100, 2) + "%" else luminancePercentage = "--" if outofSRGB > 0 outofSRGB = utils.fr(100 * outofSRGB, 2) + "%" else outofSRGB = "--" sections.push { name: "sRGB Overranging (#{maxNits} nits)" rows: [ ["Luminance", luminancePercentage] ["Out Gamut", outofSRGB] ] } elements.push el InfoPanel, { title: title left: @props.width - infoPanelWidth width: infoPanelWidth height: @props.height url: COLORIST_DATA.uri sections: sections usesPixelPos: true x: @state.x y: @state.y horseshoeX: horseshoeX horseshoeY: horseshoeY } return elements module.exports = PixelsView
true
# --------------------------------------------------------------------------- # Copyright PI:NAME:<NAME>END_PI 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- React = require 'react' DOM = require 'react-dom' tags = require './tags' utils = require './utils' {el, div, table, tr, td, tbody} = require './tags' TopBar = require './TopBar' ImageRenderer = require './ImageRenderer' InfoPanel = require './InfoPanel' as8Bit = (v, depth) -> return utils.clamp(Math.round(v / ((1 << depth)-1) * 255), 0, 255) class PixelsView extends React.Component @defaultProps: app: null constructor: (props) -> super props @state = x: -1 y: -1 @rawPixels = @props.app.rawPixels @highlightInfos = @props.app.highlightInfos setPos: (x, y) -> @setState { x: x, y: y } render: -> elements = [] elements.push el TopBar, { key: "TopBar" app: @props.app } infoPanelWidth = 300 title = "Pixels" image = COLORIST_DATA.visual maxNits = COLORIST_DATA.icc.luminance if @props.name == 'srgb' title = "sRGB Highlight (#{COLORIST_DATA.srgb.highlightLuminance})" image = COLORIST_DATA.srgb.visual maxNits = COLORIST_DATA.srgb.highlightLuminance elements.push el ImageRenderer, { width: @props.width - infoPanelWidth height: @props.height url: image listener: this } sections = [] horseshoeX = -1 horseshoeY = -1 if (@state.x >= 0) and (@state.y >= 0) pixel = @rawPixels.get(@state.x, @state.y) sections.push { name: "Raw" rows: [ ["R", pixel.r, "", as8Bit(pixel.r, COLORIST_DATA.depth)] ["G", pixel.g, "", as8Bit(pixel.g, COLORIST_DATA.depth)] ["B", pixel.b, "", as8Bit(pixel.b, COLORIST_DATA.depth)] ["A", pixel.a, "", as8Bit(pixel.a, COLORIST_DATA.depth)] ] } @pixelInfos highlightInfo = @highlightInfos.get(@state.x, @state.y) xyY = [highlightInfo.x, highlightInfo.y, highlightInfo.Y] pixelLuminance = highlightInfo.nits maxPixelLuminance = highlightInfo.maxNits outofSRGB = highlightInfo.outOfGamut sections.push { name: "xyY" rows: [ ["x", utils.fr(xyY[0], 4)] ["y", utils.fr(xyY[1], 4)] ["Y", utils.fr(xyY[2], 4)] ["Nits:", utils.fr(pixelLuminance, 2), "/", utils.fr(maxPixelLuminance, 2)] ] } horseshoeX = xyY[0] horseshoeY = xyY[1] if @props.name != 'pixels' p = (pixelLuminance / maxPixelLuminance) REASONABLY_OVERBRIGHT = 0.0001 # this should match the constant in context_report.c's calcOverbright() if p > (1.0 + REASONABLY_OVERBRIGHT) luminancePercentage = utils.fr(p * 100, 2) + "%" else luminancePercentage = "--" if outofSRGB > 0 outofSRGB = utils.fr(100 * outofSRGB, 2) + "%" else outofSRGB = "--" sections.push { name: "sRGB Overranging (#{maxNits} nits)" rows: [ ["Luminance", luminancePercentage] ["Out Gamut", outofSRGB] ] } elements.push el InfoPanel, { title: title left: @props.width - infoPanelWidth width: infoPanelWidth height: @props.height url: COLORIST_DATA.uri sections: sections usesPixelPos: true x: @state.x y: @state.y horseshoeX: horseshoeX horseshoeY: horseshoeY } return elements module.exports = PixelsView
[ { "context": "cation_data'\n dialog.positiveLocalizableKey = 'common.no'\n dialog.negativeLocalizableKey = 'common.yes'", "end": 498, "score": 0.9990413784980774, "start": 489, "tag": "KEY", "value": "common.no" }, { "context": " 'common.no'\n dialog.negativeLocalizableKey =...
app/src/controllers/wallet/settings/tools/wallet_settings_tools_utilities_setting_view_controller.coffee
romanornr/ledger-wallet-crw
173
class @WalletSettingsToolsUtilitiesSettingViewController extends WalletSettingsSettingViewController renderSelector: "#protocols_table_container" openRegistration: -> window.open "https://www.ledgerwallet.com/wallet/register" @parentViewController.dismiss() resetApplicationData: -> dialog = new CommonDialogsConfirmationDialogViewController() dialog.setMessageLocalizableKey 'wallet.settings.tools.resetting_application_data' dialog.positiveLocalizableKey = 'common.no' dialog.negativeLocalizableKey = 'common.yes' dialog.once 'click:negative', => ledger.database.main.delete -> chrome.storage.local.clear() chrome.runtime.reload() dialog.show() signMessage: -> dialog = new WalletMessageIndexDialogViewController({ path: "44'/#{ledger.config.network.bip44_coin_type}'/0/0" message: "" editable: yes }) dialog.show() @parentViewController.dismiss()
36081
class @WalletSettingsToolsUtilitiesSettingViewController extends WalletSettingsSettingViewController renderSelector: "#protocols_table_container" openRegistration: -> window.open "https://www.ledgerwallet.com/wallet/register" @parentViewController.dismiss() resetApplicationData: -> dialog = new CommonDialogsConfirmationDialogViewController() dialog.setMessageLocalizableKey 'wallet.settings.tools.resetting_application_data' dialog.positiveLocalizableKey = '<KEY>' dialog.negativeLocalizableKey = '<KEY>' dialog.once 'click:negative', => ledger.database.main.delete -> chrome.storage.local.clear() chrome.runtime.reload() dialog.show() signMessage: -> dialog = new WalletMessageIndexDialogViewController({ path: "44'/#{ledger.config.network.bip44_coin_type}'/0/0" message: "" editable: yes }) dialog.show() @parentViewController.dismiss()
true
class @WalletSettingsToolsUtilitiesSettingViewController extends WalletSettingsSettingViewController renderSelector: "#protocols_table_container" openRegistration: -> window.open "https://www.ledgerwallet.com/wallet/register" @parentViewController.dismiss() resetApplicationData: -> dialog = new CommonDialogsConfirmationDialogViewController() dialog.setMessageLocalizableKey 'wallet.settings.tools.resetting_application_data' dialog.positiveLocalizableKey = 'PI:KEY:<KEY>END_PI' dialog.negativeLocalizableKey = 'PI:KEY:<KEY>END_PI' dialog.once 'click:negative', => ledger.database.main.delete -> chrome.storage.local.clear() chrome.runtime.reload() dialog.show() signMessage: -> dialog = new WalletMessageIndexDialogViewController({ path: "44'/#{ledger.config.network.bip44_coin_type}'/0/0" message: "" editable: yes }) dialog.show() @parentViewController.dismiss()
[ { "context": "SON.stringify(metadata) isnt '{}'\n return res\n\n\n# Yi-Jeng Chen. (2016). Young Children's Collaboration on the Co", "end": 9582, "score": 0.9998445510864258, "start": 9570, "tag": "NAME", "value": "Yi-Jeng Chen" }, { "context": "tp://www.jstor.org/stable/jeductechso...
worker/src/svc/oaworks/find.coffee
oaworks/paradigm
1
P.svc.oaworks.metadata = (doi) -> res = await @svc.oaworks.find doi # may not be a DOI, but most likely thing return res?.metadata P.svc.oaworks.find = (options, metadata={}, content) -> res = {} _metadata = (input) => ct = await @svc.oaworks.citation input for k of ct if k in ['url', 'paywall'] res[k] ?= ct[k] else metadata[k] ?= ct[k] return true options = {doi: options} if typeof options is 'string' try options ?= @copy @params options ?= {} content ?= options.dom ? (if typeof @body is 'string' then @body else undefined) options.find = options.metadata if options.metadata if options.find if options.find.indexOf('10.') is 0 and options.find.indexOf('/') isnt -1 options.doi = options.find else options.url = options.find delete options.find options.url ?= options.q ? options.id if options.url options.url = options.url.toString() if typeof options.url is 'number' if options.url.indexOf('/10.') isnt -1 # we don't use a regex to try to pattern match a DOI because people often make mistakes typing them, so instead try to find one # in ways that may still match even with different expressions (as long as the DOI portion itself is still correct after extraction we can match it) dd = '10.' + options.url.split('/10.')[1].split('&')[0].split('#')[0] if dd.indexOf('/') isnt -1 and dd.split('/')[0].length > 6 and dd.length > 8 dps = dd.split('/') dd = dps.join('/') if dps.length > 2 metadata.doi ?= dd if options.url.replace('doi:','').replace('doi.org/','').trim().indexOf('10.') is 0 metadata.doi ?= options.url.replace('doi:','').replace('doi.org/','').trim() options.url = 'https://doi.org/' + metadata.doi else if options.url.toLowerCase().indexOf('pmc') is 0 metadata.pmcid ?= options.url.toLowerCase().replace('pmcid','').replace('pmc','') options.url = 'http://europepmc.org/articles/PMC' + metadata.pmcid else if options.url.replace(/pmid/i,'').replace(':','').length < 10 and options.url.indexOf('.') is -1 and not isNaN(parseInt(options.url.replace(/pmid/i,'').replace(':','').trim())) metadata.pmid ?= options.url.replace(/pmid/i,'').replace(':','').trim() options.url = 'https://www.ncbi.nlm.nih.gov/pubmed/' + metadata.pmid else if not metadata.title? and options.url.indexOf('http') isnt 0 if options.url.indexOf('{') isnt -1 or (options.url.replace('...','').match(/\./gi) ? []).length > 3 or (options.url.match(/\(/gi) ? []).length > 2 options.citation = options.url else metadata.title = options.url delete options.url if options.url.indexOf('http') isnt 0 or options.url.indexOf('.') is -1 if typeof options.title is 'string' and (options.title.indexOf('{') isnt -1 or (options.title.replace('...','').match(/\./gi) ? []).length > 3 or (options.title.match(/\(/gi) ? []).length > 2) options.citation = options.title # titles that look like citations delete options.title metadata.doi ?= options.doi metadata.title ?= options.title metadata.pmid ?= options.pmid metadata.pmcid ?= options.pmcid ? options.pmc await _metadata(options.citation) if options.citation try metadata.title = metadata.title.replace(/(<([^>]+)>)/g,'').replace(/\+/g,' ').trim() try metadata.title = await @decode metadata.title try metadata.doi = metadata.doi.split(' ')[0].replace('http://','').replace('https://','').replace('doi.org/','').replace('doi:','').trim() delete metadata.doi if typeof metadata.doi isnt 'string' or metadata.doi.indexOf('10.') isnt 0 # switch exlibris URLs for titles, which the scraper knows how to extract, because the exlibris url would always be the same if not metadata.title and content and typeof options.url is 'string' and (options.url.indexOf('alma.exlibrisgroup.com') isnt -1 or options.url.indexOf('/exlibristest') isnt -1) delete options.url # set a demo tag in certain cases # e.g. for instantill/shareyourpaper/other demos - dev and live demo accounts res.demo = options.demo if options.demo? res.demo ?= true if (metadata.doi is '10.1234/567890' or (metadata.doi? and metadata.doi.indexOf('10.1234/oab-syp-') is 0)) or metadata.title is 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL' or options.from in ['qZooaHWRz9NLFNcgR','eZwJ83xp3oZDaec86'] res.test ?= true if res.demo # don't save things coming from the demo accounts into the catalogue later _searches = () => if (content? or options.url?) and not (metadata.doi or metadata.pmid? or metadata.pmcid? or metadata.title?) scraped = await @svc.oaworks.scrape content ? options.url await _metadata scraped if not metadata.doi if metadata.pmid or metadata.pmcid epmc = await @src.epmc[if metadata.pmcid then 'pmc' else 'pmid'] (metadata.pmcid ? metadata.pmid) await _metadata epmc if not metadata.doi and metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1 metadata.title = metadata.title.replace /\+/g, ' ' # some+titles+come+in+like+this cr = await @src.crossref.works.title metadata.title if cr?.type and cr?.DOI await _metadata cr if not metadata.doi mag = await @src.microsoft.graph metadata.title if mag?.PaperTitle await _metadata mag if not metadata.doi and not epmc? # run this only if we don't find in our own stores epmc = await @src.epmc.title metadata.title await _metadata epmc if metadata.doi _fatcat = () => fat = await @src.fatcat metadata.doi if fat?.files? for f in fat.files # there are also hashes and revision IDs, but without knowing details about which is most recent just grab the first # looks like the URLs are timestamped, and looks like first is most recent, so let's just assume that. if f.mimetype.toLowerCase().indexOf('pdf') isnt -1 and f.state is 'active' # presumably worth knowing... for fu in f.urls if fu.url and fu.rel is 'webarchive' # would we want the web or the webarchive version? res.url = fu.url break return true _oad = () => oad = await @src.oadoi metadata.doi res.doi_not_in_oadoi = metadata.doi if not oad? await _metadata(oad) if oad?.doi and metadata?.doi and oad.doi.toLowerCase() is metadata.doi.toLowerCase() # check again for doi in case removed by failed crossref lookup return true _crd = () => cr = await @src.crossref.works metadata.doi if not cr?.type res.doi_not_in_crossref = metadata.doi else # temporary fix of date info until crossref index reloaded try cr.published = await @src.crossref.works.published cr try cr.year = cr.published.split('-')[0] try cr.year = parseInt cr.year try cr.publishedAt = await @epoch cr.published await _metadata cr return true await Promise.all [_oad(), _crd()] # _fatcat(), return true await _searches() # if nothing useful can be found and still only have title try using bing - or drop this ability? # TODO what to do if this finds anything? re-call the whole find? if not metadata.doi and not content and not options.url and not epmc? and metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1 try mct = unidecode(metadata.title.toLowerCase()).replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ') bong = await @src.microsoft.bing.search mct if bong?.data bct = unidecode(bong.data[0].name.toLowerCase()).replace('(pdf)','').replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ') if mct.replace(/ /g,'').indexOf(bct.replace(/ /g,'')) is 0 #and not await @svc.oaworks.blacklist bong.data[0].url # if the URL is usable and tidy bing title is a partial match to the start of the provided title, try using it options.url = bong.data[0].url.replace /"/g, '' metadata.pmid = options.url.replace(/\/$/,'').split('/').pop() if typeof options.url is 'string' and options.url.indexOf('pubmed.ncbi') isnt -1 metadata.doi ?= '10.' + options.url.split('/10.')[1] if typeof options.url is 'string' and options.url.indexOf('/10.') isnt -1 if metadata.doi or metadata.pmid or options.url await _searches() # run again if anything more useful found _ill = () => if (metadata.doi or (metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1)) and (options.from or options.config?) and (options.plugin is 'instantill' or options.ill is true) try res.ill ?= subscription: await @svc.oaworks.ill.subscription (options.config ? options.from), metadata return true _permissions = () => if metadata.doi and (options.permissions or options.plugin is 'shareyourpaper') res.permissions ?= await @svc.oaworks.permissions metadata, options.config?.ror, false return true await Promise.all [_ill(), _permissions()] # certain user-provided search values are allowed to override any that we could find ourselves # TODO is this ONLY relevant to ILL? or anything else? for uo in ['title','journal','year','doi'] metadata[uo] = options[uo] if options[uo] and options[uo] isnt metadata[uo] res.metadata = metadata # if JSON.stringify(metadata) isnt '{}' return res # Yi-Jeng Chen. (2016). Young Children's Collaboration on the Computer with Friends and Acquaintances. Journal of Educational Technology & Society, 19(1), 158-170. Retrieved November 19, 2020, from http://www.jstor.org/stable/jeductechsoci.19.1.158 # Baker, T. S., Eisenberg, D., & Eiserling, F. (1977). Ribulose Bisphosphate Carboxylase: A Two-Layered, Square-Shaped Molecule of Symmetry 422. Science, 196(4287), 293-295. doi:10.1126/science.196.4287.293 P.svc.oaworks.citation = (citation) -> res = {} try citation ?= @params.citation ? @params if typeof citation is 'string' and (citation.indexOf('{') is 0 or citation.indexOf('[') is 0) try citation = JSON.parse citation if typeof citation is 'object' res.doi = citation.DOI ? citation.doi res.pmid = citation.pmid if citation.pmid res.pmcid = citation.pmcid if citation.pmcid try res.type = citation.type ? citation.genre res.issn ?= citation.ISSN ? citation.issn ? citation.journalInfo?.journal?.issn ? citation.journal?.issn if citation.journalInfo?.journal?.eissn? res.issn ?= [] res.issn = [res.issn] if typeof res.issn is 'string' res.issn.push citation.journalInfo.journal.eissn res.issn ?= citation.journal_issns.split(',') if citation.journal_issns try res.title ?= citation.title[0] if Array.isArray citation.title try if citation.subtitle? and citation.subtitle.length and citation.subtitle[0].length res.title += ': ' + citation.subtitle[0] res.title ?= citation.dctitle ? citation.bibjson?.title res.title ?= citation.title if citation.title not in [404,'404'] res.title = res.title.replace(/\s\s+/g,' ').trim() if typeof res.title is 'string' try res.journal ?= citation['container-title'][0] try res.shortname = citation['short-container-title'][0] try res.shortname = citation.journalInfo.journal.isoabbreviation ? citation.journalInfo.journal.medlineAbbreviation res.journal ?= citation.journal_name ? citation.journalInfo?.journal?.title ? citation.journal?.title res.journal = citation.journal.split('(')[0].trim() if citation.journal try res[key] = res[key].charAt(0).toUpperCase() + res[key].slice(1) for key in ['title','journal'] res.publisher ?= citation.publisher res.publisher = res.publisher.trim() if res.publisher try res.issue ?= citation.issue if citation.issue? try res.issue ?= citation.journalInfo.issue if citation.journalInfo?.issue try res.volume ?= citation.volume if citation.volume? try res.volume ?= citation.journalInfo.volume if citation.journalInfo?.volume try res.page ?= citation.page.toString() if citation.page? res.page = citation.pageInfo.toString() if citation.pageInfo res.abstract = citation.abstract ? citation.abstractText if citation.abstract or citation.abstractText try res.abstract = @convert.html2txt(res.abstract).replace(/\n/g,' ').replace('Abstract ','') if res.abstract for p in ['published-print', 'journal-issue.published-print', 'journalInfo.printPublicationDate', 'firstPublicationDate', 'journalInfo.electronicPublicationDate', 'published', 'published_date', 'issued', 'published-online', 'created', 'deposited'] if typeof res.published isnt 'string' if rt = citation[p] ? citation['journal-issue']?[p.replace('journal-issue.','')] ? citation['journalInfo']?[p.replace('journalInfo.','')] rt = rt.toString() if typeof rt is 'number' try rt = rt['date-time'].toString() if typeof rt isnt 'string' if typeof rt isnt 'string' try for k of rt['date-parts'][0] rt['date-parts'][0][k] = '01' if typeof rt['date-parts'][0][k] not in ['number', 'string'] rt = rt['date-parts'][0].join '-' if typeof rt is 'string' res.published = if rt.indexOf('T') isnt -1 then rt.split('T')[0] else rt res.published = res.published.replace(/\//g, '-').replace(/-(\d)-/g, "-0$1-").replace /-(\d)$/, "-0$1" res.published += '-01' if res.published.indexOf('-') is -1 res.published += '-01' if res.published.split('-').length isnt 3 res.year ?= res.published.split('-')[0] delete res.published if res.published.split('-').length isnt 3 delete res.year if res.year.toString().length isnt 4 break if res.published res.year ?= citation.year if citation.year try res.year ?= citation.journalInfo.yearOfPublication.trim() if not res.author? and (citation.author? or citation.z_authors? or citation.authorList?.author) res.author ?= [] try for a in citation.author ? citation.z_authors ? citation.authorList.author if typeof a is 'string' res.author.push name: a else au = {} au.given = a.given ? a.firstName au.family = a.family ? a.lastName au.name = (if au.given then au.given + ' ' else '') + (au.family ? '') if a.affiliation? try for aff in (if au.affiliation then (if Array.isArray(a.affiliation) then a.affiliation else [a.affiliation]) else au.authorAffiliationDetailsList.authorAffiliation) if typeof aff is 'string' au.affiliation ?= [] au.affiliation.push name: aff.replace(/\s\s+/g,' ').trim() else if typeof aff is 'object' and (aff.name or aff.affiliation) au.affiliation ?= [] au.affiliation.push name: (aff.name ? aff.affiliation).replace(/\s\s+/g,' ').trim() res.author.push au try res.subject = citation.subject if citation.subject? and citation.subject.length and typeof citation.subject[0] is 'string' try res.keyword = citation.keywordList.keyword if citation.keywordList?.keyword? and citation.keywordList.keyword.length and typeof citation.keywordList.keyword[0] is 'string' try for m in [...(citation.meshHeadingList?.meshHeading ? []), ...(citation.chemicalList?.chemical ? [])] res.keyword ?= [] mn = if typeof m is 'string' then m else m.name ? m.descriptorName res.keyword.push mn if typeof mn is 'string' and mn and mn not in res.keyword res.licence = citation.license.trim().replace(/ /g,'-') if typeof citation.license is 'string' res.licence = citation.licence.trim().replace(/ /g,'-') if typeof citation.licence is 'string' try res.licence ?= citation.best_oa_location.license if citation.best_oa_location?.license and citation.best_oa_location?.license isnt null if not res.licence if Array.isArray citation.assertion for a in citation.assertion if a.label is 'OPEN ACCESS' and a.URL and a.URL.indexOf('creativecommons') isnt -1 res.licence ?= a.URL # and if the record has a URL, it can be used as an open URL rather than a paywall URL, or the DOI can be used if Array.isArray citation.license for l in citation.license ? [] if l.URL and l.URL.indexOf('creativecommons') isnt -1 and (not res.licence or res.licence.indexOf('creativecommons') is -1) res.licence ?= l.URL if typeof res.licence is 'string' and res.licence.indexOf('/licenses/') isnt -1 res.licence = 'cc-' + res.licence.split('/licenses/')[1].replace(/$\//,'').replace(/\//g, '-').replace(/-$/, '') # if there is a URL to use but not open, store it as res.paywall res.url ?= citation.best_oa_location?.url_for_pdf ? citation.best_oa_location?.url #? citation.url # is this always an open URL? check the sources, and check where else the open URL could be. Should it be blacklist checked and dereferenced? if not res.url and citation.fullTextUrlList?.fullTextUrl? # epmc fulltexts for cf in citation.fullTextUrlList.fullTextUrl if cf.availabilityCode.toLowerCase() in ['oa','f'] and (not res.url or (cf.documentStyle is 'pdf' and res.url.indexOf('pdf') is -1)) res.url = cf.url else if typeof citation is 'string' try citation = citation.replace(/citation\:/gi,'').trim() citation = citation.split('title')[1].trim() if citation.indexOf('title') isnt -1 citation = citation.replace(/^"/,'').replace(/^'/,'').replace(/"$/,'').replace(/'$/,'') res.doi = citation.split('doi:')[1].split(',')[0].split(' ')[0].trim() if citation.indexOf('doi:') isnt -1 res.doi = citation.split('doi.org/')[1].split(',')[0].split(' ')[0].trim() if citation.indexOf('doi.org/') isnt -1 if not res.doi and citation.indexOf('http') isnt -1 res.url = 'http' + citation.split('http')[1].split(' ')[0].trim() try if citation.indexOf('|') isnt -1 or citation.indexOf('}') isnt -1 res.title = citation.split('|')[0].split('}')[0].trim() if citation.split('"').length > 2 res.title = citation.split('"')[1].trim() else if citation.split("'").length > 2 res.title ?= citation.split("'")[1].trim() try pts = citation.replace(/,\./g,' ').split ' ' for pt in pts if not res.year pt = pt.replace /[^0-9]/g,'' if pt.length is 4 sy = parseInt pt res.year = sy if typeof sy is 'number' and not isNaN sy try if not res.title and res.year and citation.indexOf(res.year) < (citation.length/4) res.title = citation.split(res.year)[1].trim() res.title = res.title.replace(')','') if res.title.indexOf('(') is -1 or res.title.indexOf(')') < res.title.indexOf('(') res.title = res.title.replace('.','') if res.title.indexOf('.') < 3 res.title = res.title.replace(',','') if res.title.indexOf(',') < 3 res.title = res.title.trim() if res.title.indexOf('.') isnt -1 res.title = res.title.split('.')[0] else if res.title.indexOf(',') isnt -1 res.title = res.title.split(',')[0] if res.title try bt = citation.split(res.title)[0] bt = bt.split(res.year)[0] if res.year and bt.indexOf(res.year) isnt -1 bt = bt.split(res.url)[0] if res.url and bt.indexOf(res.url) > 0 bt = bt.replace(res.url) if res.url and bt.indexOf(res.url) is 0 bt = bt.replace(res.doi) if res.doi and bt.indexOf(res.doi) is 0 bt = bt.replace('.','') if bt.indexOf('.') < 3 bt = bt.replace(',','') if bt.indexOf(',') < 3 bt = bt.substring(0,bt.lastIndexOf('(')) if bt.lastIndexOf('(') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf(')')) if bt.lastIndexOf(')') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf(',')) if bt.lastIndexOf(',') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf('.')) if bt.lastIndexOf('.') > (bt.length-3) bt = bt.trim() if bt.length > 6 if bt.indexOf(',') isnt -1 res.author = [] res.author.push({name: ak}) for ak in bt.split(',') else res.author = [{name: bt}] try rmn = citation.split(res.title)[1] rmn = rmn.replace(res.url) if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.replace(res.doi) if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.replace('.','') if rmn.indexOf('.') < 3 rmn = rmn.replace(',','') if rmn.indexOf(',') < 3 rmn = rmn.trim() if rmn.length > 6 res.journal = rmn res.journal = res.journal.split(',')[0].replace(/in /gi,'').trim() if rmn.indexOf(',') isnt -1 res.journal = res.journal.replace('.','') if res.journal.indexOf('.') < 3 res.journal = res.journal.replace(',','') if res.journal.indexOf(',') < 3 res.journal = res.journal.trim() try if res.journal rmn = citation.split(res.journal)[1] rmn = rmn.replace(res.url) if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.replace(res.doi) if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.replace('.','') if rmn.indexOf('.') < 3 rmn = rmn.replace(',','') if rmn.indexOf(',') < 3 rmn = rmn.trim() if rmn.length > 4 rmn = rmn.split('retrieved')[0] if rmn.indexOf('retrieved') isnt -1 rmn = rmn.split('Retrieved')[0] if rmn.indexOf('Retrieved') isnt -1 res.volume = rmn if res.volume.indexOf('(') isnt -1 res.volume = res.volume.split('(')[0] res.volume = res.volume.trim() try res.issue = rmn.split('(')[1].split(')')[0] res.issue = res.issue.trim() if res.volume.indexOf(',') isnt -1 res.volume = res.volume.split(',')[0] res.volume = res.volume.trim() try res.issue = rmn.split(',')[1] res.issue = res.issue.trim() if res.volume try delete res.volume if isNaN parseInt res.volume if res.issue if res.issue.indexOf(',') isnt -1 res.issue = res.issue.split(',')[0].trim() try delete res.issue if isNaN parseInt res.issue if res.volume and res.issue try rmn = citation.split(res.journal)[1] rmn = rmn.split('retriev')[0] if rmn.indexOf('retriev') isnt -1 rmn = rmn.split('Retriev')[0] if rmn.indexOf('Retriev') isnt -1 rmn = rmn.split(res.url)[0] if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.split(res.doi)[0] if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.substring(rmn.indexOf(res.volume)+(res.volume+'').length) rmn = rmn.substring(rmn.indexOf(res.issue)+(res.issue+'').length) rmn = rmn.replace('.','') if rmn.indexOf('.') < 2 rmn = rmn.replace(',','') if rmn.indexOf(',') < 2 rmn = rmn.replace(')','') if rmn.indexOf(')') < 2 rmn = rmn.trim() if not isNaN parseInt rmn.substring(0,1) res.pages = rmn.split(' ')[0].split('.')[0].trim() res.pages = res.pages.split(', ')[0] if res.pages.length > 5 if not res.author and citation.indexOf('et al') isnt -1 cn = citation.split('et al')[0].trim() if citation.indexOf(cn) is 0 res.author = [{name: cn + 'et al'}] if res.title and not res.volume try clc = citation.split(res.title)[1].toLowerCase().replace('volume','vol').replace('vol.','vol').replace('issue','iss').replace('iss.','iss').replace('pages','page').replace('pp','page') if clc.indexOf('vol') isnt -1 res.volume = clc.split('vol')[1].split(',')[0].split('(')[0].split('.')[0].split(' ')[0].trim() if not res.issue and clc.indexOf('iss') isnt -1 res.issue = clc.split('iss')[1].split(',')[0].split('.')[0].split(' ')[0].trim() if not res.pages and clc.indexOf('page') isnt -1 res.pages = clc.split('page')[1].split('.')[0].split(', ')[0].split(' ')[0].trim() res.year = res.year.toString() if typeof res.year is 'number' return res # temporary legacy wrapper for old site front page availability check # that page should be moved to use the new embed, like shareyourpaper P.svc.oaworks.availability = (params, v2) -> params ?= @copy @params delete @params.dom if params.availability if params.availability.startsWith('10.') and params.availability.indexOf('/') isnt -1 params.doi = params.availability else if params.availability.indexOf(' ') isnt -1 params.title = params.availability else params.id = params.availability delete params.availability params.url = params.url[0] if Array.isArray params.url if not params.test and params.url and false #await @svc.oaworks.blacklist params.url params.dom = 'redacted' if params.dom return status: 400 else afnd = {data: {availability: [], requests: [], accepts: [], meta: {article: {}, data: {}}}} if params? afnd.data.match = params.doi ? params.pmid ? params.pmc ? params.pmcid ? params.title ? params.url ? params.id ? params.citation ? params.q afnd.v2 = v2 if typeof v2 is 'object' and JSON.stringify(v2) isnt '{}' and v2.metadata? afnd.v2 ?= await @svc.oaworks.find params if afnd.v2? afnd.data.match ?= afnd.v2.input ? afnd.v2.metadata?.doi ? afnd.v2.metadata?.title ? afnd.v2.metadata?.pmid ? afnd.v2.metadata?.pmc ? afnd.v2.metadata?.pmcid ? afnd.v2.metadata?.url afnd.data.match = afnd.data.match[0] if Array.isArray afnd.data.match try afnd.data.ill = afnd.v2.ill afnd.data.meta.article = JSON.parse(JSON.stringify(afnd.v2.metadata)) if afnd.v2.metadata? afnd.data.meta.article.url = afnd.data.meta.article.url[0] if Array.isArray afnd.data.meta.article.url if afnd.v2.url? and not afnd.data.meta.article.source? afnd.data.meta.article.source = 'oaworks' # source doesn't play significant role any more, could prob just remove this if not used anywhere if afnd.v2.url afnd.data.availability.push type: 'article', url: (if Array.isArray(afnd.v2.url) then afnd.v2.url[0] else afnd.v2.url) try if afnd.data.availability.length is 0 and (afnd.v2.metadata.doi or afnd.v2.metadata.title or afnd.v2.meadata.url) if afnd.v2.metadata.doi qry = 'doi.exact:"' + afnd.v2.metadata.doi + '"' else if afnd.v2.metadata.title qry = 'title.exact:"' + afnd.v2.metadata.title + '"' else qry = 'url.exact:"' + (if Array.isArray(afnd.v2.metadata.url) then afnd.v2.metadata.url[0] else afnd.v2.metadata.url) + '"' if qry # ' + (if @S.dev then 'dev.' else '') + ' resp = await @fetch 'https://api.cottagelabs.com/service/oab/requests?q=' + qry + ' AND type:article&sort=createdAt:desc' if resp?.hits?.total request = resp.hits.hits[0]._source rq = type: 'article', _id: request._id rq.ucreated = if params.uid and request.user?.id is params.uid then true else false afnd.data.requests.push rq afnd.data.accepts.push({type:'article'}) if afnd.data.availability.length is 0 and afnd.data.requests.length is 0 return afnd P.svc.oaworks.availability._hide = true
127676
P.svc.oaworks.metadata = (doi) -> res = await @svc.oaworks.find doi # may not be a DOI, but most likely thing return res?.metadata P.svc.oaworks.find = (options, metadata={}, content) -> res = {} _metadata = (input) => ct = await @svc.oaworks.citation input for k of ct if k in ['url', 'paywall'] res[k] ?= ct[k] else metadata[k] ?= ct[k] return true options = {doi: options} if typeof options is 'string' try options ?= @copy @params options ?= {} content ?= options.dom ? (if typeof @body is 'string' then @body else undefined) options.find = options.metadata if options.metadata if options.find if options.find.indexOf('10.') is 0 and options.find.indexOf('/') isnt -1 options.doi = options.find else options.url = options.find delete options.find options.url ?= options.q ? options.id if options.url options.url = options.url.toString() if typeof options.url is 'number' if options.url.indexOf('/10.') isnt -1 # we don't use a regex to try to pattern match a DOI because people often make mistakes typing them, so instead try to find one # in ways that may still match even with different expressions (as long as the DOI portion itself is still correct after extraction we can match it) dd = '10.' + options.url.split('/10.')[1].split('&')[0].split('#')[0] if dd.indexOf('/') isnt -1 and dd.split('/')[0].length > 6 and dd.length > 8 dps = dd.split('/') dd = dps.join('/') if dps.length > 2 metadata.doi ?= dd if options.url.replace('doi:','').replace('doi.org/','').trim().indexOf('10.') is 0 metadata.doi ?= options.url.replace('doi:','').replace('doi.org/','').trim() options.url = 'https://doi.org/' + metadata.doi else if options.url.toLowerCase().indexOf('pmc') is 0 metadata.pmcid ?= options.url.toLowerCase().replace('pmcid','').replace('pmc','') options.url = 'http://europepmc.org/articles/PMC' + metadata.pmcid else if options.url.replace(/pmid/i,'').replace(':','').length < 10 and options.url.indexOf('.') is -1 and not isNaN(parseInt(options.url.replace(/pmid/i,'').replace(':','').trim())) metadata.pmid ?= options.url.replace(/pmid/i,'').replace(':','').trim() options.url = 'https://www.ncbi.nlm.nih.gov/pubmed/' + metadata.pmid else if not metadata.title? and options.url.indexOf('http') isnt 0 if options.url.indexOf('{') isnt -1 or (options.url.replace('...','').match(/\./gi) ? []).length > 3 or (options.url.match(/\(/gi) ? []).length > 2 options.citation = options.url else metadata.title = options.url delete options.url if options.url.indexOf('http') isnt 0 or options.url.indexOf('.') is -1 if typeof options.title is 'string' and (options.title.indexOf('{') isnt -1 or (options.title.replace('...','').match(/\./gi) ? []).length > 3 or (options.title.match(/\(/gi) ? []).length > 2) options.citation = options.title # titles that look like citations delete options.title metadata.doi ?= options.doi metadata.title ?= options.title metadata.pmid ?= options.pmid metadata.pmcid ?= options.pmcid ? options.pmc await _metadata(options.citation) if options.citation try metadata.title = metadata.title.replace(/(<([^>]+)>)/g,'').replace(/\+/g,' ').trim() try metadata.title = await @decode metadata.title try metadata.doi = metadata.doi.split(' ')[0].replace('http://','').replace('https://','').replace('doi.org/','').replace('doi:','').trim() delete metadata.doi if typeof metadata.doi isnt 'string' or metadata.doi.indexOf('10.') isnt 0 # switch exlibris URLs for titles, which the scraper knows how to extract, because the exlibris url would always be the same if not metadata.title and content and typeof options.url is 'string' and (options.url.indexOf('alma.exlibrisgroup.com') isnt -1 or options.url.indexOf('/exlibristest') isnt -1) delete options.url # set a demo tag in certain cases # e.g. for instantill/shareyourpaper/other demos - dev and live demo accounts res.demo = options.demo if options.demo? res.demo ?= true if (metadata.doi is '10.1234/567890' or (metadata.doi? and metadata.doi.indexOf('10.1234/oab-syp-') is 0)) or metadata.title is 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL' or options.from in ['qZooaHWRz9NLFNcgR','eZwJ83xp3oZDaec86'] res.test ?= true if res.demo # don't save things coming from the demo accounts into the catalogue later _searches = () => if (content? or options.url?) and not (metadata.doi or metadata.pmid? or metadata.pmcid? or metadata.title?) scraped = await @svc.oaworks.scrape content ? options.url await _metadata scraped if not metadata.doi if metadata.pmid or metadata.pmcid epmc = await @src.epmc[if metadata.pmcid then 'pmc' else 'pmid'] (metadata.pmcid ? metadata.pmid) await _metadata epmc if not metadata.doi and metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1 metadata.title = metadata.title.replace /\+/g, ' ' # some+titles+come+in+like+this cr = await @src.crossref.works.title metadata.title if cr?.type and cr?.DOI await _metadata cr if not metadata.doi mag = await @src.microsoft.graph metadata.title if mag?.PaperTitle await _metadata mag if not metadata.doi and not epmc? # run this only if we don't find in our own stores epmc = await @src.epmc.title metadata.title await _metadata epmc if metadata.doi _fatcat = () => fat = await @src.fatcat metadata.doi if fat?.files? for f in fat.files # there are also hashes and revision IDs, but without knowing details about which is most recent just grab the first # looks like the URLs are timestamped, and looks like first is most recent, so let's just assume that. if f.mimetype.toLowerCase().indexOf('pdf') isnt -1 and f.state is 'active' # presumably worth knowing... for fu in f.urls if fu.url and fu.rel is 'webarchive' # would we want the web or the webarchive version? res.url = fu.url break return true _oad = () => oad = await @src.oadoi metadata.doi res.doi_not_in_oadoi = metadata.doi if not oad? await _metadata(oad) if oad?.doi and metadata?.doi and oad.doi.toLowerCase() is metadata.doi.toLowerCase() # check again for doi in case removed by failed crossref lookup return true _crd = () => cr = await @src.crossref.works metadata.doi if not cr?.type res.doi_not_in_crossref = metadata.doi else # temporary fix of date info until crossref index reloaded try cr.published = await @src.crossref.works.published cr try cr.year = cr.published.split('-')[0] try cr.year = parseInt cr.year try cr.publishedAt = await @epoch cr.published await _metadata cr return true await Promise.all [_oad(), _crd()] # _fatcat(), return true await _searches() # if nothing useful can be found and still only have title try using bing - or drop this ability? # TODO what to do if this finds anything? re-call the whole find? if not metadata.doi and not content and not options.url and not epmc? and metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1 try mct = unidecode(metadata.title.toLowerCase()).replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ') bong = await @src.microsoft.bing.search mct if bong?.data bct = unidecode(bong.data[0].name.toLowerCase()).replace('(pdf)','').replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ') if mct.replace(/ /g,'').indexOf(bct.replace(/ /g,'')) is 0 #and not await @svc.oaworks.blacklist bong.data[0].url # if the URL is usable and tidy bing title is a partial match to the start of the provided title, try using it options.url = bong.data[0].url.replace /"/g, '' metadata.pmid = options.url.replace(/\/$/,'').split('/').pop() if typeof options.url is 'string' and options.url.indexOf('pubmed.ncbi') isnt -1 metadata.doi ?= '10.' + options.url.split('/10.')[1] if typeof options.url is 'string' and options.url.indexOf('/10.') isnt -1 if metadata.doi or metadata.pmid or options.url await _searches() # run again if anything more useful found _ill = () => if (metadata.doi or (metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1)) and (options.from or options.config?) and (options.plugin is 'instantill' or options.ill is true) try res.ill ?= subscription: await @svc.oaworks.ill.subscription (options.config ? options.from), metadata return true _permissions = () => if metadata.doi and (options.permissions or options.plugin is 'shareyourpaper') res.permissions ?= await @svc.oaworks.permissions metadata, options.config?.ror, false return true await Promise.all [_ill(), _permissions()] # certain user-provided search values are allowed to override any that we could find ourselves # TODO is this ONLY relevant to ILL? or anything else? for uo in ['title','journal','year','doi'] metadata[uo] = options[uo] if options[uo] and options[uo] isnt metadata[uo] res.metadata = metadata # if JSON.stringify(metadata) isnt '{}' return res # <NAME>. (2016). Young Children's Collaboration on the Computer with Friends and Acquaintances. Journal of Educational Technology & Society, 19(1), 158-170. Retrieved November 19, 2020, from http://www.jstor.org/stable/jeductechsoci.19.1.158 # <NAME>., <NAME>., & <NAME>. (1977). Ribulose Bisphosphate Carboxylase: A Two-Layered, Square-Shaped Molecule of Symmetry 422. Science, 196(4287), 293-295. doi:10.1126/science.196.4287.293 P.svc.oaworks.citation = (citation) -> res = {} try citation ?= @params.citation ? @params if typeof citation is 'string' and (citation.indexOf('{') is 0 or citation.indexOf('[') is 0) try citation = JSON.parse citation if typeof citation is 'object' res.doi = citation.DOI ? citation.doi res.pmid = citation.pmid if citation.pmid res.pmcid = citation.pmcid if citation.pmcid try res.type = citation.type ? citation.genre res.issn ?= citation.ISSN ? citation.issn ? citation.journalInfo?.journal?.issn ? citation.journal?.issn if citation.journalInfo?.journal?.eissn? res.issn ?= [] res.issn = [res.issn] if typeof res.issn is 'string' res.issn.push citation.journalInfo.journal.eissn res.issn ?= citation.journal_issns.split(',') if citation.journal_issns try res.title ?= citation.title[0] if Array.isArray citation.title try if citation.subtitle? and citation.subtitle.length and citation.subtitle[0].length res.title += ': ' + citation.subtitle[0] res.title ?= citation.dctitle ? citation.bibjson?.title res.title ?= citation.title if citation.title not in [404,'404'] res.title = res.title.replace(/\s\s+/g,' ').trim() if typeof res.title is 'string' try res.journal ?= citation['container-title'][0] try res.shortname = citation['short-container-title'][0] try res.shortname = citation.journalInfo.journal.isoabbreviation ? citation.journalInfo.journal.medlineAbbreviation res.journal ?= citation.journal_name ? citation.journalInfo?.journal?.title ? citation.journal?.title res.journal = citation.journal.split('(')[0].trim() if citation.journal try res[key] = res[key].charAt(0).toUpperCase() + res[key].slice(1) for key in ['title','journal'] res.publisher ?= citation.publisher res.publisher = res.publisher.trim() if res.publisher try res.issue ?= citation.issue if citation.issue? try res.issue ?= citation.journalInfo.issue if citation.journalInfo?.issue try res.volume ?= citation.volume if citation.volume? try res.volume ?= citation.journalInfo.volume if citation.journalInfo?.volume try res.page ?= citation.page.toString() if citation.page? res.page = citation.pageInfo.toString() if citation.pageInfo res.abstract = citation.abstract ? citation.abstractText if citation.abstract or citation.abstractText try res.abstract = @convert.html2txt(res.abstract).replace(/\n/g,' ').replace('Abstract ','') if res.abstract for p in ['published-print', 'journal-issue.published-print', 'journalInfo.printPublicationDate', 'firstPublicationDate', 'journalInfo.electronicPublicationDate', 'published', 'published_date', 'issued', 'published-online', 'created', 'deposited'] if typeof res.published isnt 'string' if rt = citation[p] ? citation['journal-issue']?[p.replace('journal-issue.','')] ? citation['journalInfo']?[p.replace('journalInfo.','')] rt = rt.toString() if typeof rt is 'number' try rt = rt['date-time'].toString() if typeof rt isnt 'string' if typeof rt isnt 'string' try for k of rt['date-parts'][0] rt['date-parts'][0][k] = '01' if typeof rt['date-parts'][0][k] not in ['number', 'string'] rt = rt['date-parts'][0].join '-' if typeof rt is 'string' res.published = if rt.indexOf('T') isnt -1 then rt.split('T')[0] else rt res.published = res.published.replace(/\//g, '-').replace(/-(\d)-/g, "-0$1-").replace /-(\d)$/, "-0$1" res.published += '-01' if res.published.indexOf('-') is -1 res.published += '-01' if res.published.split('-').length isnt 3 res.year ?= res.published.split('-')[0] delete res.published if res.published.split('-').length isnt 3 delete res.year if res.year.toString().length isnt 4 break if res.published res.year ?= citation.year if citation.year try res.year ?= citation.journalInfo.yearOfPublication.trim() if not res.author? and (citation.author? or citation.z_authors? or citation.authorList?.author) res.author ?= [] try for a in citation.author ? citation.z_authors ? citation.authorList.author if typeof a is 'string' res.author.push name: a else au = {} au.given = a.given ? a.firstName au.family = a.family ? a.lastName au.name = (if au.given then au.given + ' ' else '') + (au.family ? '') if a.affiliation? try for aff in (if au.affiliation then (if Array.isArray(a.affiliation) then a.affiliation else [a.affiliation]) else au.authorAffiliationDetailsList.authorAffiliation) if typeof aff is 'string' au.affiliation ?= [] au.affiliation.push name: aff.replace(/\s\s+/g,' ').trim() else if typeof aff is 'object' and (aff.name or aff.affiliation) au.affiliation ?= [] au.affiliation.push name: (aff.name ? aff.affiliation).replace(/\s\s+/g,' ').trim() res.author.push au try res.subject = citation.subject if citation.subject? and citation.subject.length and typeof citation.subject[0] is 'string' try res.keyword = citation.keywordList.keyword if citation.keywordList?.keyword? and citation.keywordList.keyword.length and typeof citation.keywordList.keyword[0] is 'string' try for m in [...(citation.meshHeadingList?.meshHeading ? []), ...(citation.chemicalList?.chemical ? [])] res.keyword ?= [] mn = if typeof m is 'string' then m else m.name ? m.descriptorName res.keyword.push mn if typeof mn is 'string' and mn and mn not in res.keyword res.licence = citation.license.trim().replace(/ /g,'-') if typeof citation.license is 'string' res.licence = citation.licence.trim().replace(/ /g,'-') if typeof citation.licence is 'string' try res.licence ?= citation.best_oa_location.license if citation.best_oa_location?.license and citation.best_oa_location?.license isnt null if not res.licence if Array.isArray citation.assertion for a in citation.assertion if a.label is 'OPEN ACCESS' and a.URL and a.URL.indexOf('creativecommons') isnt -1 res.licence ?= a.URL # and if the record has a URL, it can be used as an open URL rather than a paywall URL, or the DOI can be used if Array.isArray citation.license for l in citation.license ? [] if l.URL and l.URL.indexOf('creativecommons') isnt -1 and (not res.licence or res.licence.indexOf('creativecommons') is -1) res.licence ?= l.URL if typeof res.licence is 'string' and res.licence.indexOf('/licenses/') isnt -1 res.licence = 'cc-' + res.licence.split('/licenses/')[1].replace(/$\//,'').replace(/\//g, '-').replace(/-$/, '') # if there is a URL to use but not open, store it as res.paywall res.url ?= citation.best_oa_location?.url_for_pdf ? citation.best_oa_location?.url #? citation.url # is this always an open URL? check the sources, and check where else the open URL could be. Should it be blacklist checked and dereferenced? if not res.url and citation.fullTextUrlList?.fullTextUrl? # epmc fulltexts for cf in citation.fullTextUrlList.fullTextUrl if cf.availabilityCode.toLowerCase() in ['oa','f'] and (not res.url or (cf.documentStyle is 'pdf' and res.url.indexOf('pdf') is -1)) res.url = cf.url else if typeof citation is 'string' try citation = citation.replace(/citation\:/gi,'').trim() citation = citation.split('title')[1].trim() if citation.indexOf('title') isnt -1 citation = citation.replace(/^"/,'').replace(/^'/,'').replace(/"$/,'').replace(/'$/,'') res.doi = citation.split('doi:')[1].split(',')[0].split(' ')[0].trim() if citation.indexOf('doi:') isnt -1 res.doi = citation.split('doi.org/')[1].split(',')[0].split(' ')[0].trim() if citation.indexOf('doi.org/') isnt -1 if not res.doi and citation.indexOf('http') isnt -1 res.url = 'http' + citation.split('http')[1].split(' ')[0].trim() try if citation.indexOf('|') isnt -1 or citation.indexOf('}') isnt -1 res.title = citation.split('|')[0].split('}')[0].trim() if citation.split('"').length > 2 res.title = citation.split('"')[1].trim() else if citation.split("'").length > 2 res.title ?= citation.split("'")[1].trim() try pts = citation.replace(/,\./g,' ').split ' ' for pt in pts if not res.year pt = pt.replace /[^0-9]/g,'' if pt.length is 4 sy = parseInt pt res.year = sy if typeof sy is 'number' and not isNaN sy try if not res.title and res.year and citation.indexOf(res.year) < (citation.length/4) res.title = citation.split(res.year)[1].trim() res.title = res.title.replace(')','') if res.title.indexOf('(') is -1 or res.title.indexOf(')') < res.title.indexOf('(') res.title = res.title.replace('.','') if res.title.indexOf('.') < 3 res.title = res.title.replace(',','') if res.title.indexOf(',') < 3 res.title = res.title.trim() if res.title.indexOf('.') isnt -1 res.title = res.title.split('.')[0] else if res.title.indexOf(',') isnt -1 res.title = res.title.split(',')[0] if res.title try bt = citation.split(res.title)[0] bt = bt.split(res.year)[0] if res.year and bt.indexOf(res.year) isnt -1 bt = bt.split(res.url)[0] if res.url and bt.indexOf(res.url) > 0 bt = bt.replace(res.url) if res.url and bt.indexOf(res.url) is 0 bt = bt.replace(res.doi) if res.doi and bt.indexOf(res.doi) is 0 bt = bt.replace('.','') if bt.indexOf('.') < 3 bt = bt.replace(',','') if bt.indexOf(',') < 3 bt = bt.substring(0,bt.lastIndexOf('(')) if bt.lastIndexOf('(') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf(')')) if bt.lastIndexOf(')') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf(',')) if bt.lastIndexOf(',') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf('.')) if bt.lastIndexOf('.') > (bt.length-3) bt = bt.trim() if bt.length > 6 if bt.indexOf(',') isnt -1 res.author = [] res.author.push({name: ak}) for ak in bt.split(',') else res.author = [{name: bt}] try rmn = citation.split(res.title)[1] rmn = rmn.replace(res.url) if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.replace(res.doi) if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.replace('.','') if rmn.indexOf('.') < 3 rmn = rmn.replace(',','') if rmn.indexOf(',') < 3 rmn = rmn.trim() if rmn.length > 6 res.journal = rmn res.journal = res.journal.split(',')[0].replace(/in /gi,'').trim() if rmn.indexOf(',') isnt -1 res.journal = res.journal.replace('.','') if res.journal.indexOf('.') < 3 res.journal = res.journal.replace(',','') if res.journal.indexOf(',') < 3 res.journal = res.journal.trim() try if res.journal rmn = citation.split(res.journal)[1] rmn = rmn.replace(res.url) if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.replace(res.doi) if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.replace('.','') if rmn.indexOf('.') < 3 rmn = rmn.replace(',','') if rmn.indexOf(',') < 3 rmn = rmn.trim() if rmn.length > 4 rmn = rmn.split('retrieved')[0] if rmn.indexOf('retrieved') isnt -1 rmn = rmn.split('Retrieved')[0] if rmn.indexOf('Retrieved') isnt -1 res.volume = rmn if res.volume.indexOf('(') isnt -1 res.volume = res.volume.split('(')[0] res.volume = res.volume.trim() try res.issue = rmn.split('(')[1].split(')')[0] res.issue = res.issue.trim() if res.volume.indexOf(',') isnt -1 res.volume = res.volume.split(',')[0] res.volume = res.volume.trim() try res.issue = rmn.split(',')[1] res.issue = res.issue.trim() if res.volume try delete res.volume if isNaN parseInt res.volume if res.issue if res.issue.indexOf(',') isnt -1 res.issue = res.issue.split(',')[0].trim() try delete res.issue if isNaN parseInt res.issue if res.volume and res.issue try rmn = citation.split(res.journal)[1] rmn = rmn.split('retriev')[0] if rmn.indexOf('retriev') isnt -1 rmn = rmn.split('Retriev')[0] if rmn.indexOf('Retriev') isnt -1 rmn = rmn.split(res.url)[0] if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.split(res.doi)[0] if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.substring(rmn.indexOf(res.volume)+(res.volume+'').length) rmn = rmn.substring(rmn.indexOf(res.issue)+(res.issue+'').length) rmn = rmn.replace('.','') if rmn.indexOf('.') < 2 rmn = rmn.replace(',','') if rmn.indexOf(',') < 2 rmn = rmn.replace(')','') if rmn.indexOf(')') < 2 rmn = rmn.trim() if not isNaN parseInt rmn.substring(0,1) res.pages = rmn.split(' ')[0].split('.')[0].trim() res.pages = res.pages.split(', ')[0] if res.pages.length > 5 if not res.author and citation.indexOf('et al') isnt -1 cn = citation.split('et al')[0].trim() if citation.indexOf(cn) is 0 res.author = [{name: cn + 'et al'}] if res.title and not res.volume try clc = citation.split(res.title)[1].toLowerCase().replace('volume','vol').replace('vol.','vol').replace('issue','iss').replace('iss.','iss').replace('pages','page').replace('pp','page') if clc.indexOf('vol') isnt -1 res.volume = clc.split('vol')[1].split(',')[0].split('(')[0].split('.')[0].split(' ')[0].trim() if not res.issue and clc.indexOf('iss') isnt -1 res.issue = clc.split('iss')[1].split(',')[0].split('.')[0].split(' ')[0].trim() if not res.pages and clc.indexOf('page') isnt -1 res.pages = clc.split('page')[1].split('.')[0].split(', ')[0].split(' ')[0].trim() res.year = res.year.toString() if typeof res.year is 'number' return res # temporary legacy wrapper for old site front page availability check # that page should be moved to use the new embed, like shareyourpaper P.svc.oaworks.availability = (params, v2) -> params ?= @copy @params delete @params.dom if params.availability if params.availability.startsWith('10.') and params.availability.indexOf('/') isnt -1 params.doi = params.availability else if params.availability.indexOf(' ') isnt -1 params.title = params.availability else params.id = params.availability delete params.availability params.url = params.url[0] if Array.isArray params.url if not params.test and params.url and false #await @svc.oaworks.blacklist params.url params.dom = 'redacted' if params.dom return status: 400 else afnd = {data: {availability: [], requests: [], accepts: [], meta: {article: {}, data: {}}}} if params? afnd.data.match = params.doi ? params.pmid ? params.pmc ? params.pmcid ? params.title ? params.url ? params.id ? params.citation ? params.q afnd.v2 = v2 if typeof v2 is 'object' and JSON.stringify(v2) isnt '{}' and v2.metadata? afnd.v2 ?= await @svc.oaworks.find params if afnd.v2? afnd.data.match ?= afnd.v2.input ? afnd.v2.metadata?.doi ? afnd.v2.metadata?.title ? afnd.v2.metadata?.pmid ? afnd.v2.metadata?.pmc ? afnd.v2.metadata?.pmcid ? afnd.v2.metadata?.url afnd.data.match = afnd.data.match[0] if Array.isArray afnd.data.match try afnd.data.ill = afnd.v2.ill afnd.data.meta.article = JSON.parse(JSON.stringify(afnd.v2.metadata)) if afnd.v2.metadata? afnd.data.meta.article.url = afnd.data.meta.article.url[0] if Array.isArray afnd.data.meta.article.url if afnd.v2.url? and not afnd.data.meta.article.source? afnd.data.meta.article.source = 'oaworks' # source doesn't play significant role any more, could prob just remove this if not used anywhere if afnd.v2.url afnd.data.availability.push type: 'article', url: (if Array.isArray(afnd.v2.url) then afnd.v2.url[0] else afnd.v2.url) try if afnd.data.availability.length is 0 and (afnd.v2.metadata.doi or afnd.v2.metadata.title or afnd.v2.meadata.url) if afnd.v2.metadata.doi qry = 'doi.exact:"' + afnd.v2.metadata.doi + '"' else if afnd.v2.metadata.title qry = 'title.exact:"' + afnd.v2.metadata.title + '"' else qry = 'url.exact:"' + (if Array.isArray(afnd.v2.metadata.url) then afnd.v2.metadata.url[0] else afnd.v2.metadata.url) + '"' if qry # ' + (if @S.dev then 'dev.' else '') + ' resp = await @fetch 'https://api.cottagelabs.com/service/oab/requests?q=' + qry + ' AND type:article&sort=createdAt:desc' if resp?.hits?.total request = resp.hits.hits[0]._source rq = type: 'article', _id: request._id rq.ucreated = if params.uid and request.user?.id is params.uid then true else false afnd.data.requests.push rq afnd.data.accepts.push({type:'article'}) if afnd.data.availability.length is 0 and afnd.data.requests.length is 0 return afnd P.svc.oaworks.availability._hide = true
true
P.svc.oaworks.metadata = (doi) -> res = await @svc.oaworks.find doi # may not be a DOI, but most likely thing return res?.metadata P.svc.oaworks.find = (options, metadata={}, content) -> res = {} _metadata = (input) => ct = await @svc.oaworks.citation input for k of ct if k in ['url', 'paywall'] res[k] ?= ct[k] else metadata[k] ?= ct[k] return true options = {doi: options} if typeof options is 'string' try options ?= @copy @params options ?= {} content ?= options.dom ? (if typeof @body is 'string' then @body else undefined) options.find = options.metadata if options.metadata if options.find if options.find.indexOf('10.') is 0 and options.find.indexOf('/') isnt -1 options.doi = options.find else options.url = options.find delete options.find options.url ?= options.q ? options.id if options.url options.url = options.url.toString() if typeof options.url is 'number' if options.url.indexOf('/10.') isnt -1 # we don't use a regex to try to pattern match a DOI because people often make mistakes typing them, so instead try to find one # in ways that may still match even with different expressions (as long as the DOI portion itself is still correct after extraction we can match it) dd = '10.' + options.url.split('/10.')[1].split('&')[0].split('#')[0] if dd.indexOf('/') isnt -1 and dd.split('/')[0].length > 6 and dd.length > 8 dps = dd.split('/') dd = dps.join('/') if dps.length > 2 metadata.doi ?= dd if options.url.replace('doi:','').replace('doi.org/','').trim().indexOf('10.') is 0 metadata.doi ?= options.url.replace('doi:','').replace('doi.org/','').trim() options.url = 'https://doi.org/' + metadata.doi else if options.url.toLowerCase().indexOf('pmc') is 0 metadata.pmcid ?= options.url.toLowerCase().replace('pmcid','').replace('pmc','') options.url = 'http://europepmc.org/articles/PMC' + metadata.pmcid else if options.url.replace(/pmid/i,'').replace(':','').length < 10 and options.url.indexOf('.') is -1 and not isNaN(parseInt(options.url.replace(/pmid/i,'').replace(':','').trim())) metadata.pmid ?= options.url.replace(/pmid/i,'').replace(':','').trim() options.url = 'https://www.ncbi.nlm.nih.gov/pubmed/' + metadata.pmid else if not metadata.title? and options.url.indexOf('http') isnt 0 if options.url.indexOf('{') isnt -1 or (options.url.replace('...','').match(/\./gi) ? []).length > 3 or (options.url.match(/\(/gi) ? []).length > 2 options.citation = options.url else metadata.title = options.url delete options.url if options.url.indexOf('http') isnt 0 or options.url.indexOf('.') is -1 if typeof options.title is 'string' and (options.title.indexOf('{') isnt -1 or (options.title.replace('...','').match(/\./gi) ? []).length > 3 or (options.title.match(/\(/gi) ? []).length > 2) options.citation = options.title # titles that look like citations delete options.title metadata.doi ?= options.doi metadata.title ?= options.title metadata.pmid ?= options.pmid metadata.pmcid ?= options.pmcid ? options.pmc await _metadata(options.citation) if options.citation try metadata.title = metadata.title.replace(/(<([^>]+)>)/g,'').replace(/\+/g,' ').trim() try metadata.title = await @decode metadata.title try metadata.doi = metadata.doi.split(' ')[0].replace('http://','').replace('https://','').replace('doi.org/','').replace('doi:','').trim() delete metadata.doi if typeof metadata.doi isnt 'string' or metadata.doi.indexOf('10.') isnt 0 # switch exlibris URLs for titles, which the scraper knows how to extract, because the exlibris url would always be the same if not metadata.title and content and typeof options.url is 'string' and (options.url.indexOf('alma.exlibrisgroup.com') isnt -1 or options.url.indexOf('/exlibristest') isnt -1) delete options.url # set a demo tag in certain cases # e.g. for instantill/shareyourpaper/other demos - dev and live demo accounts res.demo = options.demo if options.demo? res.demo ?= true if (metadata.doi is '10.1234/567890' or (metadata.doi? and metadata.doi.indexOf('10.1234/oab-syp-') is 0)) or metadata.title is 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL' or options.from in ['qZooaHWRz9NLFNcgR','eZwJ83xp3oZDaec86'] res.test ?= true if res.demo # don't save things coming from the demo accounts into the catalogue later _searches = () => if (content? or options.url?) and not (metadata.doi or metadata.pmid? or metadata.pmcid? or metadata.title?) scraped = await @svc.oaworks.scrape content ? options.url await _metadata scraped if not metadata.doi if metadata.pmid or metadata.pmcid epmc = await @src.epmc[if metadata.pmcid then 'pmc' else 'pmid'] (metadata.pmcid ? metadata.pmid) await _metadata epmc if not metadata.doi and metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1 metadata.title = metadata.title.replace /\+/g, ' ' # some+titles+come+in+like+this cr = await @src.crossref.works.title metadata.title if cr?.type and cr?.DOI await _metadata cr if not metadata.doi mag = await @src.microsoft.graph metadata.title if mag?.PaperTitle await _metadata mag if not metadata.doi and not epmc? # run this only if we don't find in our own stores epmc = await @src.epmc.title metadata.title await _metadata epmc if metadata.doi _fatcat = () => fat = await @src.fatcat metadata.doi if fat?.files? for f in fat.files # there are also hashes and revision IDs, but without knowing details about which is most recent just grab the first # looks like the URLs are timestamped, and looks like first is most recent, so let's just assume that. if f.mimetype.toLowerCase().indexOf('pdf') isnt -1 and f.state is 'active' # presumably worth knowing... for fu in f.urls if fu.url and fu.rel is 'webarchive' # would we want the web or the webarchive version? res.url = fu.url break return true _oad = () => oad = await @src.oadoi metadata.doi res.doi_not_in_oadoi = metadata.doi if not oad? await _metadata(oad) if oad?.doi and metadata?.doi and oad.doi.toLowerCase() is metadata.doi.toLowerCase() # check again for doi in case removed by failed crossref lookup return true _crd = () => cr = await @src.crossref.works metadata.doi if not cr?.type res.doi_not_in_crossref = metadata.doi else # temporary fix of date info until crossref index reloaded try cr.published = await @src.crossref.works.published cr try cr.year = cr.published.split('-')[0] try cr.year = parseInt cr.year try cr.publishedAt = await @epoch cr.published await _metadata cr return true await Promise.all [_oad(), _crd()] # _fatcat(), return true await _searches() # if nothing useful can be found and still only have title try using bing - or drop this ability? # TODO what to do if this finds anything? re-call the whole find? if not metadata.doi and not content and not options.url and not epmc? and metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1 try mct = unidecode(metadata.title.toLowerCase()).replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ') bong = await @src.microsoft.bing.search mct if bong?.data bct = unidecode(bong.data[0].name.toLowerCase()).replace('(pdf)','').replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ') if mct.replace(/ /g,'').indexOf(bct.replace(/ /g,'')) is 0 #and not await @svc.oaworks.blacklist bong.data[0].url # if the URL is usable and tidy bing title is a partial match to the start of the provided title, try using it options.url = bong.data[0].url.replace /"/g, '' metadata.pmid = options.url.replace(/\/$/,'').split('/').pop() if typeof options.url is 'string' and options.url.indexOf('pubmed.ncbi') isnt -1 metadata.doi ?= '10.' + options.url.split('/10.')[1] if typeof options.url is 'string' and options.url.indexOf('/10.') isnt -1 if metadata.doi or metadata.pmid or options.url await _searches() # run again if anything more useful found _ill = () => if (metadata.doi or (metadata.title and metadata.title.length > 8 and metadata.title.split(' ').length > 1)) and (options.from or options.config?) and (options.plugin is 'instantill' or options.ill is true) try res.ill ?= subscription: await @svc.oaworks.ill.subscription (options.config ? options.from), metadata return true _permissions = () => if metadata.doi and (options.permissions or options.plugin is 'shareyourpaper') res.permissions ?= await @svc.oaworks.permissions metadata, options.config?.ror, false return true await Promise.all [_ill(), _permissions()] # certain user-provided search values are allowed to override any that we could find ourselves # TODO is this ONLY relevant to ILL? or anything else? for uo in ['title','journal','year','doi'] metadata[uo] = options[uo] if options[uo] and options[uo] isnt metadata[uo] res.metadata = metadata # if JSON.stringify(metadata) isnt '{}' return res # PI:NAME:<NAME>END_PI. (2016). Young Children's Collaboration on the Computer with Friends and Acquaintances. Journal of Educational Technology & Society, 19(1), 158-170. Retrieved November 19, 2020, from http://www.jstor.org/stable/jeductechsoci.19.1.158 # PI:NAME:<NAME>END_PI., PI:NAME:<NAME>END_PI., & PI:NAME:<NAME>END_PI. (1977). Ribulose Bisphosphate Carboxylase: A Two-Layered, Square-Shaped Molecule of Symmetry 422. Science, 196(4287), 293-295. doi:10.1126/science.196.4287.293 P.svc.oaworks.citation = (citation) -> res = {} try citation ?= @params.citation ? @params if typeof citation is 'string' and (citation.indexOf('{') is 0 or citation.indexOf('[') is 0) try citation = JSON.parse citation if typeof citation is 'object' res.doi = citation.DOI ? citation.doi res.pmid = citation.pmid if citation.pmid res.pmcid = citation.pmcid if citation.pmcid try res.type = citation.type ? citation.genre res.issn ?= citation.ISSN ? citation.issn ? citation.journalInfo?.journal?.issn ? citation.journal?.issn if citation.journalInfo?.journal?.eissn? res.issn ?= [] res.issn = [res.issn] if typeof res.issn is 'string' res.issn.push citation.journalInfo.journal.eissn res.issn ?= citation.journal_issns.split(',') if citation.journal_issns try res.title ?= citation.title[0] if Array.isArray citation.title try if citation.subtitle? and citation.subtitle.length and citation.subtitle[0].length res.title += ': ' + citation.subtitle[0] res.title ?= citation.dctitle ? citation.bibjson?.title res.title ?= citation.title if citation.title not in [404,'404'] res.title = res.title.replace(/\s\s+/g,' ').trim() if typeof res.title is 'string' try res.journal ?= citation['container-title'][0] try res.shortname = citation['short-container-title'][0] try res.shortname = citation.journalInfo.journal.isoabbreviation ? citation.journalInfo.journal.medlineAbbreviation res.journal ?= citation.journal_name ? citation.journalInfo?.journal?.title ? citation.journal?.title res.journal = citation.journal.split('(')[0].trim() if citation.journal try res[key] = res[key].charAt(0).toUpperCase() + res[key].slice(1) for key in ['title','journal'] res.publisher ?= citation.publisher res.publisher = res.publisher.trim() if res.publisher try res.issue ?= citation.issue if citation.issue? try res.issue ?= citation.journalInfo.issue if citation.journalInfo?.issue try res.volume ?= citation.volume if citation.volume? try res.volume ?= citation.journalInfo.volume if citation.journalInfo?.volume try res.page ?= citation.page.toString() if citation.page? res.page = citation.pageInfo.toString() if citation.pageInfo res.abstract = citation.abstract ? citation.abstractText if citation.abstract or citation.abstractText try res.abstract = @convert.html2txt(res.abstract).replace(/\n/g,' ').replace('Abstract ','') if res.abstract for p in ['published-print', 'journal-issue.published-print', 'journalInfo.printPublicationDate', 'firstPublicationDate', 'journalInfo.electronicPublicationDate', 'published', 'published_date', 'issued', 'published-online', 'created', 'deposited'] if typeof res.published isnt 'string' if rt = citation[p] ? citation['journal-issue']?[p.replace('journal-issue.','')] ? citation['journalInfo']?[p.replace('journalInfo.','')] rt = rt.toString() if typeof rt is 'number' try rt = rt['date-time'].toString() if typeof rt isnt 'string' if typeof rt isnt 'string' try for k of rt['date-parts'][0] rt['date-parts'][0][k] = '01' if typeof rt['date-parts'][0][k] not in ['number', 'string'] rt = rt['date-parts'][0].join '-' if typeof rt is 'string' res.published = if rt.indexOf('T') isnt -1 then rt.split('T')[0] else rt res.published = res.published.replace(/\//g, '-').replace(/-(\d)-/g, "-0$1-").replace /-(\d)$/, "-0$1" res.published += '-01' if res.published.indexOf('-') is -1 res.published += '-01' if res.published.split('-').length isnt 3 res.year ?= res.published.split('-')[0] delete res.published if res.published.split('-').length isnt 3 delete res.year if res.year.toString().length isnt 4 break if res.published res.year ?= citation.year if citation.year try res.year ?= citation.journalInfo.yearOfPublication.trim() if not res.author? and (citation.author? or citation.z_authors? or citation.authorList?.author) res.author ?= [] try for a in citation.author ? citation.z_authors ? citation.authorList.author if typeof a is 'string' res.author.push name: a else au = {} au.given = a.given ? a.firstName au.family = a.family ? a.lastName au.name = (if au.given then au.given + ' ' else '') + (au.family ? '') if a.affiliation? try for aff in (if au.affiliation then (if Array.isArray(a.affiliation) then a.affiliation else [a.affiliation]) else au.authorAffiliationDetailsList.authorAffiliation) if typeof aff is 'string' au.affiliation ?= [] au.affiliation.push name: aff.replace(/\s\s+/g,' ').trim() else if typeof aff is 'object' and (aff.name or aff.affiliation) au.affiliation ?= [] au.affiliation.push name: (aff.name ? aff.affiliation).replace(/\s\s+/g,' ').trim() res.author.push au try res.subject = citation.subject if citation.subject? and citation.subject.length and typeof citation.subject[0] is 'string' try res.keyword = citation.keywordList.keyword if citation.keywordList?.keyword? and citation.keywordList.keyword.length and typeof citation.keywordList.keyword[0] is 'string' try for m in [...(citation.meshHeadingList?.meshHeading ? []), ...(citation.chemicalList?.chemical ? [])] res.keyword ?= [] mn = if typeof m is 'string' then m else m.name ? m.descriptorName res.keyword.push mn if typeof mn is 'string' and mn and mn not in res.keyword res.licence = citation.license.trim().replace(/ /g,'-') if typeof citation.license is 'string' res.licence = citation.licence.trim().replace(/ /g,'-') if typeof citation.licence is 'string' try res.licence ?= citation.best_oa_location.license if citation.best_oa_location?.license and citation.best_oa_location?.license isnt null if not res.licence if Array.isArray citation.assertion for a in citation.assertion if a.label is 'OPEN ACCESS' and a.URL and a.URL.indexOf('creativecommons') isnt -1 res.licence ?= a.URL # and if the record has a URL, it can be used as an open URL rather than a paywall URL, or the DOI can be used if Array.isArray citation.license for l in citation.license ? [] if l.URL and l.URL.indexOf('creativecommons') isnt -1 and (not res.licence or res.licence.indexOf('creativecommons') is -1) res.licence ?= l.URL if typeof res.licence is 'string' and res.licence.indexOf('/licenses/') isnt -1 res.licence = 'cc-' + res.licence.split('/licenses/')[1].replace(/$\//,'').replace(/\//g, '-').replace(/-$/, '') # if there is a URL to use but not open, store it as res.paywall res.url ?= citation.best_oa_location?.url_for_pdf ? citation.best_oa_location?.url #? citation.url # is this always an open URL? check the sources, and check where else the open URL could be. Should it be blacklist checked and dereferenced? if not res.url and citation.fullTextUrlList?.fullTextUrl? # epmc fulltexts for cf in citation.fullTextUrlList.fullTextUrl if cf.availabilityCode.toLowerCase() in ['oa','f'] and (not res.url or (cf.documentStyle is 'pdf' and res.url.indexOf('pdf') is -1)) res.url = cf.url else if typeof citation is 'string' try citation = citation.replace(/citation\:/gi,'').trim() citation = citation.split('title')[1].trim() if citation.indexOf('title') isnt -1 citation = citation.replace(/^"/,'').replace(/^'/,'').replace(/"$/,'').replace(/'$/,'') res.doi = citation.split('doi:')[1].split(',')[0].split(' ')[0].trim() if citation.indexOf('doi:') isnt -1 res.doi = citation.split('doi.org/')[1].split(',')[0].split(' ')[0].trim() if citation.indexOf('doi.org/') isnt -1 if not res.doi and citation.indexOf('http') isnt -1 res.url = 'http' + citation.split('http')[1].split(' ')[0].trim() try if citation.indexOf('|') isnt -1 or citation.indexOf('}') isnt -1 res.title = citation.split('|')[0].split('}')[0].trim() if citation.split('"').length > 2 res.title = citation.split('"')[1].trim() else if citation.split("'").length > 2 res.title ?= citation.split("'")[1].trim() try pts = citation.replace(/,\./g,' ').split ' ' for pt in pts if not res.year pt = pt.replace /[^0-9]/g,'' if pt.length is 4 sy = parseInt pt res.year = sy if typeof sy is 'number' and not isNaN sy try if not res.title and res.year and citation.indexOf(res.year) < (citation.length/4) res.title = citation.split(res.year)[1].trim() res.title = res.title.replace(')','') if res.title.indexOf('(') is -1 or res.title.indexOf(')') < res.title.indexOf('(') res.title = res.title.replace('.','') if res.title.indexOf('.') < 3 res.title = res.title.replace(',','') if res.title.indexOf(',') < 3 res.title = res.title.trim() if res.title.indexOf('.') isnt -1 res.title = res.title.split('.')[0] else if res.title.indexOf(',') isnt -1 res.title = res.title.split(',')[0] if res.title try bt = citation.split(res.title)[0] bt = bt.split(res.year)[0] if res.year and bt.indexOf(res.year) isnt -1 bt = bt.split(res.url)[0] if res.url and bt.indexOf(res.url) > 0 bt = bt.replace(res.url) if res.url and bt.indexOf(res.url) is 0 bt = bt.replace(res.doi) if res.doi and bt.indexOf(res.doi) is 0 bt = bt.replace('.','') if bt.indexOf('.') < 3 bt = bt.replace(',','') if bt.indexOf(',') < 3 bt = bt.substring(0,bt.lastIndexOf('(')) if bt.lastIndexOf('(') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf(')')) if bt.lastIndexOf(')') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf(',')) if bt.lastIndexOf(',') > (bt.length-3) bt = bt.substring(0,bt.lastIndexOf('.')) if bt.lastIndexOf('.') > (bt.length-3) bt = bt.trim() if bt.length > 6 if bt.indexOf(',') isnt -1 res.author = [] res.author.push({name: ak}) for ak in bt.split(',') else res.author = [{name: bt}] try rmn = citation.split(res.title)[1] rmn = rmn.replace(res.url) if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.replace(res.doi) if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.replace('.','') if rmn.indexOf('.') < 3 rmn = rmn.replace(',','') if rmn.indexOf(',') < 3 rmn = rmn.trim() if rmn.length > 6 res.journal = rmn res.journal = res.journal.split(',')[0].replace(/in /gi,'').trim() if rmn.indexOf(',') isnt -1 res.journal = res.journal.replace('.','') if res.journal.indexOf('.') < 3 res.journal = res.journal.replace(',','') if res.journal.indexOf(',') < 3 res.journal = res.journal.trim() try if res.journal rmn = citation.split(res.journal)[1] rmn = rmn.replace(res.url) if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.replace(res.doi) if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.replace('.','') if rmn.indexOf('.') < 3 rmn = rmn.replace(',','') if rmn.indexOf(',') < 3 rmn = rmn.trim() if rmn.length > 4 rmn = rmn.split('retrieved')[0] if rmn.indexOf('retrieved') isnt -1 rmn = rmn.split('Retrieved')[0] if rmn.indexOf('Retrieved') isnt -1 res.volume = rmn if res.volume.indexOf('(') isnt -1 res.volume = res.volume.split('(')[0] res.volume = res.volume.trim() try res.issue = rmn.split('(')[1].split(')')[0] res.issue = res.issue.trim() if res.volume.indexOf(',') isnt -1 res.volume = res.volume.split(',')[0] res.volume = res.volume.trim() try res.issue = rmn.split(',')[1] res.issue = res.issue.trim() if res.volume try delete res.volume if isNaN parseInt res.volume if res.issue if res.issue.indexOf(',') isnt -1 res.issue = res.issue.split(',')[0].trim() try delete res.issue if isNaN parseInt res.issue if res.volume and res.issue try rmn = citation.split(res.journal)[1] rmn = rmn.split('retriev')[0] if rmn.indexOf('retriev') isnt -1 rmn = rmn.split('Retriev')[0] if rmn.indexOf('Retriev') isnt -1 rmn = rmn.split(res.url)[0] if res.url and rmn.indexOf(res.url) isnt -1 rmn = rmn.split(res.doi)[0] if res.doi and rmn.indexOf(res.doi) isnt -1 rmn = rmn.substring(rmn.indexOf(res.volume)+(res.volume+'').length) rmn = rmn.substring(rmn.indexOf(res.issue)+(res.issue+'').length) rmn = rmn.replace('.','') if rmn.indexOf('.') < 2 rmn = rmn.replace(',','') if rmn.indexOf(',') < 2 rmn = rmn.replace(')','') if rmn.indexOf(')') < 2 rmn = rmn.trim() if not isNaN parseInt rmn.substring(0,1) res.pages = rmn.split(' ')[0].split('.')[0].trim() res.pages = res.pages.split(', ')[0] if res.pages.length > 5 if not res.author and citation.indexOf('et al') isnt -1 cn = citation.split('et al')[0].trim() if citation.indexOf(cn) is 0 res.author = [{name: cn + 'et al'}] if res.title and not res.volume try clc = citation.split(res.title)[1].toLowerCase().replace('volume','vol').replace('vol.','vol').replace('issue','iss').replace('iss.','iss').replace('pages','page').replace('pp','page') if clc.indexOf('vol') isnt -1 res.volume = clc.split('vol')[1].split(',')[0].split('(')[0].split('.')[0].split(' ')[0].trim() if not res.issue and clc.indexOf('iss') isnt -1 res.issue = clc.split('iss')[1].split(',')[0].split('.')[0].split(' ')[0].trim() if not res.pages and clc.indexOf('page') isnt -1 res.pages = clc.split('page')[1].split('.')[0].split(', ')[0].split(' ')[0].trim() res.year = res.year.toString() if typeof res.year is 'number' return res # temporary legacy wrapper for old site front page availability check # that page should be moved to use the new embed, like shareyourpaper P.svc.oaworks.availability = (params, v2) -> params ?= @copy @params delete @params.dom if params.availability if params.availability.startsWith('10.') and params.availability.indexOf('/') isnt -1 params.doi = params.availability else if params.availability.indexOf(' ') isnt -1 params.title = params.availability else params.id = params.availability delete params.availability params.url = params.url[0] if Array.isArray params.url if not params.test and params.url and false #await @svc.oaworks.blacklist params.url params.dom = 'redacted' if params.dom return status: 400 else afnd = {data: {availability: [], requests: [], accepts: [], meta: {article: {}, data: {}}}} if params? afnd.data.match = params.doi ? params.pmid ? params.pmc ? params.pmcid ? params.title ? params.url ? params.id ? params.citation ? params.q afnd.v2 = v2 if typeof v2 is 'object' and JSON.stringify(v2) isnt '{}' and v2.metadata? afnd.v2 ?= await @svc.oaworks.find params if afnd.v2? afnd.data.match ?= afnd.v2.input ? afnd.v2.metadata?.doi ? afnd.v2.metadata?.title ? afnd.v2.metadata?.pmid ? afnd.v2.metadata?.pmc ? afnd.v2.metadata?.pmcid ? afnd.v2.metadata?.url afnd.data.match = afnd.data.match[0] if Array.isArray afnd.data.match try afnd.data.ill = afnd.v2.ill afnd.data.meta.article = JSON.parse(JSON.stringify(afnd.v2.metadata)) if afnd.v2.metadata? afnd.data.meta.article.url = afnd.data.meta.article.url[0] if Array.isArray afnd.data.meta.article.url if afnd.v2.url? and not afnd.data.meta.article.source? afnd.data.meta.article.source = 'oaworks' # source doesn't play significant role any more, could prob just remove this if not used anywhere if afnd.v2.url afnd.data.availability.push type: 'article', url: (if Array.isArray(afnd.v2.url) then afnd.v2.url[0] else afnd.v2.url) try if afnd.data.availability.length is 0 and (afnd.v2.metadata.doi or afnd.v2.metadata.title or afnd.v2.meadata.url) if afnd.v2.metadata.doi qry = 'doi.exact:"' + afnd.v2.metadata.doi + '"' else if afnd.v2.metadata.title qry = 'title.exact:"' + afnd.v2.metadata.title + '"' else qry = 'url.exact:"' + (if Array.isArray(afnd.v2.metadata.url) then afnd.v2.metadata.url[0] else afnd.v2.metadata.url) + '"' if qry # ' + (if @S.dev then 'dev.' else '') + ' resp = await @fetch 'https://api.cottagelabs.com/service/oab/requests?q=' + qry + ' AND type:article&sort=createdAt:desc' if resp?.hits?.total request = resp.hits.hits[0]._source rq = type: 'article', _id: request._id rq.ucreated = if params.uid and request.user?.id is params.uid then true else false afnd.data.requests.push rq afnd.data.accepts.push({type:'article'}) if afnd.data.availability.length is 0 and afnd.data.requests.length is 0 return afnd P.svc.oaworks.availability._hide = true
[ { "context": " create user with specific role: create nexus user testuser1 with any-all-view role\n#to get details of user: p", "end": 1041, "score": 0.9994258284568787, "start": 1032, "tag": "USERNAME", "value": "testuser1" }, { "context": "iew role\n#to get details of user: print n...
scripts/nexus/scripts-slack/Nexus.coffee
akash1233/OnBot_Demo
0
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # 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. #------------------------------------------------------------------------------- #Set of bot commands for nexus #to create new nexus repository: create nexus repo test1 #to get details of repository: print nexus repo test1 #to get list of all repositories: list nexus repos #to create user with specific role: create nexus user testuser1 with any-all-view role #to get details of user: print nexus user testuser1@cognizant.com #to get list of all users: list nexus users #to delete a nexus user: delete nexus user testuser1@cognizant.com #to delete a nexus repository: delete nexus repo test1 #Env variables to set: # NEXUS_URL # NEXUS_USER_ID # NEXUS_PASSWORD # HUBOT_NAME #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ nexus_url = process.env.NEXUS_URL nexus_user_id = process.env.NEXUS_USER_ID nexus_password = process.env.NEXUS_PASSWORD botname = process.BOT_NAME pod_ip = process.env.MY_POD_IP; create_repo = require('./create_repo.js'); delete_repo = require('./delete_repo.js'); create_user = require('./create_user.js'); get_all_repo = require('./get_all_repo.js'); get_given_repo = require('./get_given_repo.js'); get_all_user = require('./get_all_user.js'); get_all_privileges = require('./get_all_privileges.js'); get_given_privilege = require('./get_given_privilege.js'); create_privilege = require('./create_privilege.js'); get_privileges_details = require('./get_privileges_details.js'); get_given_user = require('./get_given_user.js'); delete_user = require('./delete_user.js'); request = require('request'); readjson = require './readjson.js' generate_id = require('./mongoConnt') index = require('./index.js') uniqueId = (length=8) -> id = "" id += Math.random().toString(36).substr(2) while id.length < length id.substr 0, length module.exports = (robot) -> robot.respond /help/i, (msg) -> dt = 'list nexus repos\nlist nexus users\nlist nexus repo <repo-id>\nlist nexus user <user-id>\ncreate nexus repo <repo-name>\ndelete nexus repo <repo-id>\ncreate nexus user <user-name> with <role-name> role\nshow artifacts in <groupId>\ndelete nexus user <user-id>\nlist nexus privileges\ncreate privilege <privilege name> <tagged repo id>'; msg.send dt setTimeout (->index.passData dt),1000 robot.router.post '/createnexusrepo', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_repo.repo_create nexus_url, nexus_user_id, nexus_password, data_http.repoid, data_http.repo_name, (error, stdout, stderr) -> if error == null dt = 'Nexus repo created with ID : '.concat(data_http.repoid) setTimeout (->index.passData dt),1000 actionmsg = 'Nexus repo created' statusmsg = 'Success'; dt = 'Nexus repo created with ID : '.concat(data_http.repoid) index.wallData botname, data_http.message, actionmsg, statusmsg; robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create nexus repo (.*)/i, (msg) -> message = msg.match[0] actionmsg = "" statusmsg = "" repoid = msg.match[1] repo_name = repoid unique_id = uniqueId(5); repoid = repoid.concat(unique_id); readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexusrepo.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusrepo.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,repo_name:repo_name,callback_id: 'createnexusrepo',tckid:tckid}; data = {text: 'Approve Request for create nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexusrepo.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexusrepo.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_repo.repo_create nexus_url, nexus_user_id, nexus_password, repoid, repo_name, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo created' statusmsg= 'Success'; dt = 'Nexus repo created with ID : '.concat(repoid) msg.send dt setTimeout (->index.passData dt),1000 index.wallData botname, message, actionmsg, statusmsg; else msg.send error; setTimeout (->index.passData message2),1000 robot.router.post '/deletenexusrepo', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo deleted' statusmsg = 'Success'; dt = 'Nexus repo deleted with ID : '.concat(data_http.repoid) index.wallData botname, data_http.message, actionmsg, statusmsg; robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /delete nexus repo (.*)/i, (msg) -> message =msg.match[0] actionmsg = "" statusmsg = "" repoid = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.deletenexusrepo.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexusrepo.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,callback_id: 'deletenexusrepo',tckid:tckid}; data = {text: 'Approve Request for delete nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'deletenexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.deletenexusrepo.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.deletenexusrepo.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo deleted' statusmsg= 'Success'; dt = 'Nexus repo deleted with ID : '.concat(repoid) msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusreposome', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /list nexus repo (.*)/i, (msg) -> repoid = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusreposome.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusreposome.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,callback_id: 'listnexusreposome',tckid:tckid}; data = {text: 'Approve Request for print nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusreposome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusreposome.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusreposome.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusrepos', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus repos/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusrepos.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexusrepos.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusrepos',tckid:tckid}; data = {text: 'Approve Request for print nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusrepos',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusrepos.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusrepos.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexususersome', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, data_http.userid_nexus, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus user (.*)/i, (msg) -> userid_nexus = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexususersome.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususersome.admin,podIp:pod_ip,message:msg.message.text,userid_nexus:userid_nexus,callback_id: 'listnexususersome',tckid:tckid}; data = {text: 'Approve Request for print nexus user',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexususersome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexususersome.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexususersome.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, userid_nexus, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus users/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususer.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexususer',tckid:tckid}; data = {text: 'Approve Request for print nexus users',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/createnexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_user.create_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, data_http.roleid, data_http.password, (error, stdout, stderr) -> if error == null dt = 'Nexus user created with password : '.concat(data_http.password) setTimeout (->index.passData dt),1000 actionmsg = 'Nexus user created'; statusmsg = 'Success'; dt = 'Nexus user created with password : '.concat(data_http.password) robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 index.wallData botname, data_http.message, actionmsg, statusmsg; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create nexus user (.*) with (.*) role/i, (msg) -> message = msg.match[1] actionmsg = "" statusmsg = "" user_id = msg.match[1] roleid = msg.match[2] password = uniqueId(8); readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.createnexususer.admin,podIp:pod_ip,message:msg.message.text,user_id:user_id,roleid:roleid,password:password,callback_id: 'createnexususer',tckid:tckid}; data = {text: 'Approve Request for create nexus user',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid},{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_user.create_user nexus_url, nexus_user_id, nexus_password, user_id, roleid, password, (error, stdout, stderr) -> if error == null dt = 'Nexus user created with password : '.concat(password) actionmsg = 'Nexus user created'; statusmsg= 'Success'; msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/deletenexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' delete_user.delete_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus user deleted' statusmsg = 'Success'; dt = 'Nexus user deleted with ID : '.concat(data_http.user_id) robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 index.wallData botname, data_http.message, actionmsg, statusmsg; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /delete nexus user (.*)/i, (msg) -> message = msg.match[0] actionmsg = "" statusmsg = "" user_id = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.deletenexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.deletenexususer.admin,podIp:pod_ip,message:msg.message.text,user_id:user_id,callback_id: 'deletenexususer',tckid:tckid}; data = {text: 'Approve Request for delete nexus user'+payload.user_id,attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'deletenexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.deletenexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.deletenexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else delete_user.delete_user nexus_url, nexus_user_id, nexus_password, user_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus user deleted' statusmsg= 'Success'; dt = 'Nexus user deleted with ID : '.concat(user_id) msg.send dt setTimeout (->index.passData dt),1000 index.wallData botname, message, actionmsg, statusmsg; else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusprivilege', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus privileges/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusprivilege.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusprivilege',tckid:tckid}; data = {text: 'Approve Request for see nexus privileges',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusprivilege.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusprivilege.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.respond /get nexus privilege (.*)/i, (msg) -> userid = msg.match[1] get_given_privilege.get_given_privilege nexus_url, nexus_user_id, nexus_password, userid, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 msg.send stdout; else setTimeout (->index.passData error),1000 msg.send error; robot.respond /search pri name (.*)/i, (msg) -> name = msg.match[1] msg.send name get_privileges_details.get_privileges_details nexus_url, nexus_user_id, nexus_password, name, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 msg.send stdout; else setTimeout (->index.passData error),1000 msg.send error; robot.router.post '/createnexusprivilege', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, data_http.pri_name, data_http.repo_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus privilege(s) created' statusmsg = 'Success' dt = stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id) robot.messageRoom data_http.userid, dt index.wallData botname, data_http.message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create privilege (.*)/i, (msg) -> array_command = msg.match[1].split " ", 2 pri_name = array_command[0] repo_id = array_command[1] message = msg.match[0] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexusprivilege.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.createnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,repo_id:repo_id,pri_name:pri_name,callback_id: 'createnexusprivilege',tckid:tckid}; data = {text: 'Approve Request for create nexus privilege',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexusprivilege.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexusprivilege.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, pri_name, repo_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus privilege(s) created' statusmsg = 'Success' dt = stdout.concat(' with name : ').concat(pri_name).concat(' tagged with repo : ').concat(repo_id); msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.respond /show artifacts in (.*)/i, (msg) -> url=nexus_url+'/service/local/lucene/search?g='+msg.match[1]+'' options = { auth: { 'user': nexus_user_id, 'pass': nexus_password }, method: 'GET', url: url } request options, (error, response, body) -> result = body.split('<artifact>') if(result.length==1) dt = 'No artifacts found for groupId: '+msg.match[1] else dt = '*No.*\t\t\t*Group Id*\t\t\t*Artifact Id*\t\t\t*Version*\t\t\t\t*RepoId*\n' for i in [1...result.length] if(result[i].indexOf('latestReleaseRepositoryId')!=-1) dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestReleaseRepositoryId>')[1].split('</latestReleaseRepositoryId>')[0]+'\n' else dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestSnapshotRepositoryId>')[1].split('</latestSnapshotRepositoryId>')[0]+'\n' msg.send dt setTimeout (->index.passData dt),1000
140237
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # 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. #------------------------------------------------------------------------------- #Set of bot commands for nexus #to create new nexus repository: create nexus repo test1 #to get details of repository: print nexus repo test1 #to get list of all repositories: list nexus repos #to create user with specific role: create nexus user testuser1 with any-all-view role #to get details of user: print nexus user <EMAIL> #to get list of all users: list nexus users #to delete a nexus user: delete nexus user <EMAIL> #to delete a nexus repository: delete nexus repo test1 #Env variables to set: # NEXUS_URL # NEXUS_USER_ID # NEXUS_PASSWORD # HUBOT_NAME #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ nexus_url = process.env.NEXUS_URL nexus_user_id = process.env.NEXUS_USER_ID nexus_password = <PASSWORD> botname = process.BOT_NAME pod_ip = process.env.MY_POD_IP; create_repo = require('./create_repo.js'); delete_repo = require('./delete_repo.js'); create_user = require('./create_user.js'); get_all_repo = require('./get_all_repo.js'); get_given_repo = require('./get_given_repo.js'); get_all_user = require('./get_all_user.js'); get_all_privileges = require('./get_all_privileges.js'); get_given_privilege = require('./get_given_privilege.js'); create_privilege = require('./create_privilege.js'); get_privileges_details = require('./get_privileges_details.js'); get_given_user = require('./get_given_user.js'); delete_user = require('./delete_user.js'); request = require('request'); readjson = require './readjson.js' generate_id = require('./mongoConnt') index = require('./index.js') uniqueId = (length=8) -> id = "" id += Math.random().toString(36).substr(2) while id.length < length id.substr 0, length module.exports = (robot) -> robot.respond /help/i, (msg) -> dt = 'list nexus repos\nlist nexus users\nlist nexus repo <repo-id>\nlist nexus user <user-id>\ncreate nexus repo <repo-name>\ndelete nexus repo <repo-id>\ncreate nexus user <user-name> with <role-name> role\nshow artifacts in <groupId>\ndelete nexus user <user-id>\nlist nexus privileges\ncreate privilege <privilege name> <tagged repo id>'; msg.send dt setTimeout (->index.passData dt),1000 robot.router.post '/createnexusrepo', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_repo.repo_create nexus_url, nexus_user_id, nexus_password, data_http.repoid, data_http.repo_name, (error, stdout, stderr) -> if error == null dt = 'Nexus repo created with ID : '.concat(data_http.repoid) setTimeout (->index.passData dt),1000 actionmsg = 'Nexus repo created' statusmsg = 'Success'; dt = 'Nexus repo created with ID : '.concat(data_http.repoid) index.wallData botname, data_http.message, actionmsg, statusmsg; robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create nexus repo (.*)/i, (msg) -> message = msg.match[0] actionmsg = "" statusmsg = "" repoid = msg.match[1] repo_name = repoid unique_id = uniqueId(5); repoid = repoid.concat(unique_id); readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexusrepo.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusrepo.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,repo_name:repo_name,callback_id: 'createnexusrepo',tckid:tckid}; data = {text: 'Approve Request for create nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexusrepo.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexusrepo.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_repo.repo_create nexus_url, nexus_user_id, nexus_password, repoid, repo_name, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo created' statusmsg= 'Success'; dt = 'Nexus repo created with ID : '.concat(repoid) msg.send dt setTimeout (->index.passData dt),1000 index.wallData botname, message, actionmsg, statusmsg; else msg.send error; setTimeout (->index.passData message2),1000 robot.router.post '/deletenexusrepo', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo deleted' statusmsg = 'Success'; dt = 'Nexus repo deleted with ID : '.concat(data_http.repoid) index.wallData botname, data_http.message, actionmsg, statusmsg; robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /delete nexus repo (.*)/i, (msg) -> message =msg.match[0] actionmsg = "" statusmsg = "" repoid = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.deletenexusrepo.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexusrepo.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,callback_id: 'deletenexusrepo',tckid:tckid}; data = {text: 'Approve Request for delete nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'deletenexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.deletenexusrepo.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.deletenexusrepo.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo deleted' statusmsg= 'Success'; dt = 'Nexus repo deleted with ID : '.concat(repoid) msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusreposome', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /list nexus repo (.*)/i, (msg) -> repoid = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusreposome.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusreposome.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,callback_id: 'listnexusreposome',tckid:tckid}; data = {text: 'Approve Request for print nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusreposome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusreposome.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusreposome.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusrepos', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus repos/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusrepos.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexusrepos.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusrepos',tckid:tckid}; data = {text: 'Approve Request for print nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusrepos',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusrepos.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusrepos.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexususersome', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, data_http.userid_nexus, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus user (.*)/i, (msg) -> userid_nexus = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexususersome.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususersome.admin,podIp:pod_ip,message:msg.message.text,userid_nexus:userid_nexus,callback_id: 'listnexususersome',tckid:tckid}; data = {text: 'Approve Request for print nexus user',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexususersome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexususersome.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexususersome.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, userid_nexus, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus users/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususer.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexususer',tckid:tckid}; data = {text: 'Approve Request for print nexus users',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/createnexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_user.create_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, data_http.roleid, data_http.password, (error, stdout, stderr) -> if error == null dt = 'Nexus user created with password : '.concat(data_http.password) setTimeout (->index.passData dt),1000 actionmsg = 'Nexus user created'; statusmsg = 'Success'; dt = 'Nexus user created with password : '.concat(data_http.password) robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 index.wallData botname, data_http.message, actionmsg, statusmsg; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create nexus user (.*) with (.*) role/i, (msg) -> message = msg.match[1] actionmsg = "" statusmsg = "" user_id = msg.match[1] roleid = msg.match[2] password = <PASSWORD>(<PASSWORD>); readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.createnexususer.admin,podIp:pod_ip,message:msg.message.text,user_id:user_id,roleid:roleid,password:<PASSWORD>,callback_id: 'createnexususer',tckid:tckid}; data = {text: 'Approve Request for create nexus user',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid},{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_user.create_user nexus_url, nexus_user_id, nexus_password, user_id, roleid, password, (error, stdout, stderr) -> if error == null dt = 'Nexus user created with password : '.concat(password) actionmsg = 'Nexus user created'; statusmsg= 'Success'; msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/deletenexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' delete_user.delete_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus user deleted' statusmsg = 'Success'; dt = 'Nexus user deleted with ID : '.concat(data_http.user_id) robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 index.wallData botname, data_http.message, actionmsg, statusmsg; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /delete nexus user (.*)/i, (msg) -> message = msg.match[0] actionmsg = "" statusmsg = "" user_id = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.deletenexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.deletenexususer.admin,podIp:pod_ip,message:msg.message.text,user_id:user_id,callback_id: 'deletenexususer',tckid:tckid}; data = {text: 'Approve Request for delete nexus user'+payload.user_id,attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'deletenexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.deletenexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.deletenexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else delete_user.delete_user nexus_url, nexus_user_id, nexus_password, user_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus user deleted' statusmsg= 'Success'; dt = 'Nexus user deleted with ID : '.concat(user_id) msg.send dt setTimeout (->index.passData dt),1000 index.wallData botname, message, actionmsg, statusmsg; else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusprivilege', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus privileges/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusprivilege.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusprivilege',tckid:tckid}; data = {text: 'Approve Request for see nexus privileges',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusprivilege.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusprivilege.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.respond /get nexus privilege (.*)/i, (msg) -> userid = msg.match[1] get_given_privilege.get_given_privilege nexus_url, nexus_user_id, nexus_password, userid, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 msg.send stdout; else setTimeout (->index.passData error),1000 msg.send error; robot.respond /search pri name (.*)/i, (msg) -> name = msg.match[1] msg.send name get_privileges_details.get_privileges_details nexus_url, nexus_user_id, nexus_password, name, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 msg.send stdout; else setTimeout (->index.passData error),1000 msg.send error; robot.router.post '/createnexusprivilege', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, data_http.pri_name, data_http.repo_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus privilege(s) created' statusmsg = 'Success' dt = stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id) robot.messageRoom data_http.userid, dt index.wallData botname, data_http.message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create privilege (.*)/i, (msg) -> array_command = msg.match[1].split " ", 2 pri_name = array_command[0] repo_id = array_command[1] message = msg.match[0] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexusprivilege.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.createnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,repo_id:repo_id,pri_name:pri_name,callback_id: 'createnexusprivilege',tckid:tckid}; data = {text: 'Approve Request for create nexus privilege',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexusprivilege.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexusprivilege.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, pri_name, repo_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus privilege(s) created' statusmsg = 'Success' dt = stdout.concat(' with name : ').concat(pri_name).concat(' tagged with repo : ').concat(repo_id); msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.respond /show artifacts in (.*)/i, (msg) -> url=nexus_url+'/service/local/lucene/search?g='+msg.match[1]+'' options = { auth: { 'user': nexus_user_id, 'pass': <PASSWORD> }, method: 'GET', url: url } request options, (error, response, body) -> result = body.split('<artifact>') if(result.length==1) dt = 'No artifacts found for groupId: '+msg.match[1] else dt = '*No.*\t\t\t*Group Id*\t\t\t*Artifact Id*\t\t\t*Version*\t\t\t\t*RepoId*\n' for i in [1...result.length] if(result[i].indexOf('latestReleaseRepositoryId')!=-1) dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestReleaseRepositoryId>')[1].split('</latestReleaseRepositoryId>')[0]+'\n' else dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestSnapshotRepositoryId>')[1].split('</latestSnapshotRepositoryId>')[0]+'\n' msg.send dt setTimeout (->index.passData dt),1000
true
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # 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. #------------------------------------------------------------------------------- #Set of bot commands for nexus #to create new nexus repository: create nexus repo test1 #to get details of repository: print nexus repo test1 #to get list of all repositories: list nexus repos #to create user with specific role: create nexus user testuser1 with any-all-view role #to get details of user: print nexus user PI:EMAIL:<EMAIL>END_PI #to get list of all users: list nexus users #to delete a nexus user: delete nexus user PI:EMAIL:<EMAIL>END_PI #to delete a nexus repository: delete nexus repo test1 #Env variables to set: # NEXUS_URL # NEXUS_USER_ID # NEXUS_PASSWORD # HUBOT_NAME #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ nexus_url = process.env.NEXUS_URL nexus_user_id = process.env.NEXUS_USER_ID nexus_password = PI:PASSWORD:<PASSWORD>END_PI botname = process.BOT_NAME pod_ip = process.env.MY_POD_IP; create_repo = require('./create_repo.js'); delete_repo = require('./delete_repo.js'); create_user = require('./create_user.js'); get_all_repo = require('./get_all_repo.js'); get_given_repo = require('./get_given_repo.js'); get_all_user = require('./get_all_user.js'); get_all_privileges = require('./get_all_privileges.js'); get_given_privilege = require('./get_given_privilege.js'); create_privilege = require('./create_privilege.js'); get_privileges_details = require('./get_privileges_details.js'); get_given_user = require('./get_given_user.js'); delete_user = require('./delete_user.js'); request = require('request'); readjson = require './readjson.js' generate_id = require('./mongoConnt') index = require('./index.js') uniqueId = (length=8) -> id = "" id += Math.random().toString(36).substr(2) while id.length < length id.substr 0, length module.exports = (robot) -> robot.respond /help/i, (msg) -> dt = 'list nexus repos\nlist nexus users\nlist nexus repo <repo-id>\nlist nexus user <user-id>\ncreate nexus repo <repo-name>\ndelete nexus repo <repo-id>\ncreate nexus user <user-name> with <role-name> role\nshow artifacts in <groupId>\ndelete nexus user <user-id>\nlist nexus privileges\ncreate privilege <privilege name> <tagged repo id>'; msg.send dt setTimeout (->index.passData dt),1000 robot.router.post '/createnexusrepo', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_repo.repo_create nexus_url, nexus_user_id, nexus_password, data_http.repoid, data_http.repo_name, (error, stdout, stderr) -> if error == null dt = 'Nexus repo created with ID : '.concat(data_http.repoid) setTimeout (->index.passData dt),1000 actionmsg = 'Nexus repo created' statusmsg = 'Success'; dt = 'Nexus repo created with ID : '.concat(data_http.repoid) index.wallData botname, data_http.message, actionmsg, statusmsg; robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create nexus repo (.*)/i, (msg) -> message = msg.match[0] actionmsg = "" statusmsg = "" repoid = msg.match[1] repo_name = repoid unique_id = uniqueId(5); repoid = repoid.concat(unique_id); readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexusrepo.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.createnexusrepo.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,repo_name:repo_name,callback_id: 'createnexusrepo',tckid:tckid}; data = {text: 'Approve Request for create nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexusrepo.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexusrepo.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_repo.repo_create nexus_url, nexus_user_id, nexus_password, repoid, repo_name, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo created' statusmsg= 'Success'; dt = 'Nexus repo created with ID : '.concat(repoid) msg.send dt setTimeout (->index.passData dt),1000 index.wallData botname, message, actionmsg, statusmsg; else msg.send error; setTimeout (->index.passData message2),1000 robot.router.post '/deletenexusrepo', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo deleted' statusmsg = 'Success'; dt = 'Nexus repo deleted with ID : '.concat(data_http.repoid) index.wallData botname, data_http.message, actionmsg, statusmsg; robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /delete nexus repo (.*)/i, (msg) -> message =msg.match[0] actionmsg = "" statusmsg = "" repoid = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.deletenexusrepo.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.deletenexusrepo.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,callback_id: 'deletenexusrepo',tckid:tckid}; data = {text: 'Approve Request for delete nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'deletenexusrepo',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.deletenexusrepo.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.deletenexusrepo.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else delete_repo.repo_delete nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus repo deleted' statusmsg= 'Success'; dt = 'Nexus repo deleted with ID : '.concat(repoid) msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusreposome', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, data_http.repoid, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /list nexus repo (.*)/i, (msg) -> repoid = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusreposome.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusreposome.admin,podIp:pod_ip,message:msg.message.text,repoid:repoid,callback_id: 'listnexusreposome',tckid:tckid}; data = {text: 'Approve Request for print nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusreposome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusreposome.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusreposome.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_given_repo.get_given_repo nexus_url, nexus_user_id, nexus_password, repoid, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusrepos', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus repos/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusrepos.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexusrepos.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusrepos',tckid:tckid}; data = {text: 'Approve Request for print nexus repo',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusrepos',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusrepos.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusrepos.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_repo.get_all_repo nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexususersome', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, data_http.userid_nexus, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus user (.*)/i, (msg) -> userid_nexus = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexususersome.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususersome.admin,podIp:pod_ip,message:msg.message.text,userid_nexus:userid_nexus,callback_id: 'listnexususersome',tckid:tckid}; data = {text: 'Approve Request for print nexus user',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexususersome',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexususersome.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexususersome.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_given_user.get_given_user nexus_url, nexus_user_id, nexus_password, userid_nexus, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus users/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.room,approver:stdout.listnexususer.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexususer',tckid:tckid}; data = {text: 'Approve Request for print nexus users',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_user.get_all_user nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/createnexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_user.create_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, data_http.roleid, data_http.password, (error, stdout, stderr) -> if error == null dt = 'Nexus user created with password : '.concat(data_http.password) setTimeout (->index.passData dt),1000 actionmsg = 'Nexus user created'; statusmsg = 'Success'; dt = 'Nexus user created with password : '.concat(data_http.password) robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 index.wallData botname, data_http.message, actionmsg, statusmsg; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create nexus user (.*) with (.*) role/i, (msg) -> message = msg.match[1] actionmsg = "" statusmsg = "" user_id = msg.match[1] roleid = msg.match[2] password = PI:PASSWORD:<PASSWORD>END_PI(PI:PASSWORD:<PASSWORD>END_PI); readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.createnexususer.admin,podIp:pod_ip,message:msg.message.text,user_id:user_id,roleid:roleid,password:PI:PASSWORD:<PASSWORD>END_PI,callback_id: 'createnexususer',tckid:tckid}; data = {text: 'Approve Request for create nexus user',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid},{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_user.create_user nexus_url, nexus_user_id, nexus_password, user_id, roleid, password, (error, stdout, stderr) -> if error == null dt = 'Nexus user created with password : '.concat(password) actionmsg = 'Nexus user created'; statusmsg= 'Success'; msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/deletenexususer', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' delete_user.delete_user nexus_url, nexus_user_id, nexus_password, data_http.user_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus user deleted' statusmsg = 'Success'; dt = 'Nexus user deleted with ID : '.concat(data_http.user_id) robot.messageRoom data_http.userid, dt setTimeout (->index.passData dt),1000 index.wallData botname, data_http.message, actionmsg, statusmsg; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /delete nexus user (.*)/i, (msg) -> message = msg.match[0] actionmsg = "" statusmsg = "" user_id = msg.match[1] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.deletenexususer.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.deletenexususer.admin,podIp:pod_ip,message:msg.message.text,user_id:user_id,callback_id: 'deletenexususer',tckid:tckid}; data = {text: 'Approve Request for delete nexus user'+payload.user_id,attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'deletenexususer',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.deletenexususer.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.deletenexususer.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else delete_user.delete_user nexus_url, nexus_user_id, nexus_password, user_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus user deleted' statusmsg= 'Success'; dt = 'Nexus user deleted with ID : '.concat(user_id) msg.send dt setTimeout (->index.passData dt),1000 index.wallData botname, message, actionmsg, statusmsg; else msg.send error; setTimeout (->index.passData error),1000 robot.router.post '/listnexusprivilege', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 robot.messageRoom data_http.userid, stdout; else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else robot.messageRoom data_http.userid, 'You are not authorized.'; robot.respond /list nexus privileges/i, (msg) -> readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.listnexusprivilege.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.listnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,callback_id: 'listnexusprivilege',tckid:tckid}; data = {text: 'Approve Request for see nexus privileges',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'listnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.listnexusprivilege.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.listnexusprivilege.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else get_all_privileges.get_all_privileges nexus_url, nexus_user_id, nexus_password, (error, stdout, stderr) -> if error == null msg.send stdout; setTimeout (->index.passData stdout),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.respond /get nexus privilege (.*)/i, (msg) -> userid = msg.match[1] get_given_privilege.get_given_privilege nexus_url, nexus_user_id, nexus_password, userid, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 msg.send stdout; else setTimeout (->index.passData error),1000 msg.send error; robot.respond /search pri name (.*)/i, (msg) -> name = msg.match[1] msg.send name get_privileges_details.get_privileges_details nexus_url, nexus_user_id, nexus_password, name, (error, stdout, stderr) -> if error == null setTimeout (->index.passData stdout),1000 msg.send stdout; else setTimeout (->index.passData error),1000 msg.send error; robot.router.post '/createnexusprivilege', (request, response) -> data_http = if request.body.payload? then JSON.parse request.body.payload else request.body if data_http.action == 'Approve' create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, data_http.pri_name, data_http.repo_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus privilege(s) created' statusmsg = 'Success' dt = stdout.concat(' with name : ').concat(data_http.pri_name).concat(' tagged with repo : ').concat(data_http.repo_id) robot.messageRoom data_http.userid, dt index.wallData botname, data_http.message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else setTimeout (->index.passData error),1000 robot.messageRoom data_http.userid, error; else dt = 'You are not authorized.' robot.messageRoom data_http.userid, dt; setTimeout (->index.passData dt),1000 robot.respond /create privilege (.*)/i, (msg) -> array_command = msg.match[1].split " ", 2 pri_name = array_command[0] repo_id = array_command[1] message = msg.match[0] readjson.readworkflow_coffee (error,stdout,stderr) -> if stdout.createnexusprivilege.workflowflag == true generate_id.getNextSequence (err,id) -> tckid=id payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,approver:stdout.createnexusprivilege.admin,podIp:pod_ip,message:msg.message.text,repo_id:repo_id,pri_name:pri_name,callback_id: 'createnexusprivilege',tckid:tckid}; data = {text: 'Approve Request for create nexus privilege',attachments: [{text: 'click yes to approve',fallback: 'Yes or No?',callback_id: 'createnexusprivilege',color: '#3AA3E3',attachment_type: 'default',actions: [{ name: 'Approve', text: 'Approve', type: 'button', value: tckid },{ name: 'Reject', text: 'Reject', type: 'button', value: tckid,confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]} robot.messageRoom stdout.createnexusprivilege.adminid, data; msg.send 'Your approval request is waiting from '.concat(stdout.createnexusprivilege.admin); dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""} generate_id.add_in_mongo dataToInsert else create_privilege.create_privilege nexus_url, nexus_user_id, nexus_password, pri_name, repo_id, (error, stdout, stderr) -> if error == null actionmsg = 'Nexus privilege(s) created' statusmsg = 'Success' dt = stdout.concat(' with name : ').concat(pri_name).concat(' tagged with repo : ').concat(repo_id); msg.send dt index.wallData botname, message, actionmsg, statusmsg; setTimeout (->index.passData dt),1000 else msg.send error; setTimeout (->index.passData error),1000 robot.respond /show artifacts in (.*)/i, (msg) -> url=nexus_url+'/service/local/lucene/search?g='+msg.match[1]+'' options = { auth: { 'user': nexus_user_id, 'pass': PI:PASSWORD:<PASSWORD>END_PI }, method: 'GET', url: url } request options, (error, response, body) -> result = body.split('<artifact>') if(result.length==1) dt = 'No artifacts found for groupId: '+msg.match[1] else dt = '*No.*\t\t\t*Group Id*\t\t\t*Artifact Id*\t\t\t*Version*\t\t\t\t*RepoId*\n' for i in [1...result.length] if(result[i].indexOf('latestReleaseRepositoryId')!=-1) dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestReleaseRepositoryId>')[1].split('</latestReleaseRepositoryId>')[0]+'\n' else dt = dt + i+'\t\t\t'+result[i].split('<groupId>')[1].split('</groupId>')[0]+'\t\t'+result[i].split('<artifactId>')[1].split('</artifactId>')[0]+'\t\t'+result[i].split('<version>')[1].split('</version>')[0]+'\t\t'+result[i].split('<latestSnapshotRepositoryId>')[1].split('</latestSnapshotRepositoryId>')[0]+'\n' msg.send dt setTimeout (->index.passData dt),1000
[ { "context": " .post('/v1/rooms/message?format=json&auth_token=testtoken', {\n message_format: 'html',\n c", "end": 2878, "score": 0.5358365774154663, "start": 2869, "tag": "KEY", "value": "testtoken" }, { "context": ",\n room_id: 'testchan',\n fr...
test/utils.coffee
boxuk/albot
0
Require = require('covershot').require.bind(null, require) should = require('chai').should() Utils = Require '../lib/utils' Nock = require 'nock' describe 'Utils', () -> describe '#format_term()', () -> it 'should have styled status', () -> ok = Utils.format_term("title", null, "infos", "comments", true) ok.should.equal "\u001b[32m✓\u001b[0m title - \u001b[1minfos\u001b[0m - \u001b[3mcomments\u001b[0m" nok = Utils.format_term("title", null, "infos", "comments", false) nok.should.equal "\u001b[31m✘\u001b[0m title - \u001b[1minfos\u001b[0m - \u001b[3mcomments\u001b[0m" it 'should have only title mandatory', () -> text = Utils.format_term("title") text.should.equal "\u001b[33m●\u001b[0m title" it 'should have tails on multi lines', () -> tail = ["Once", "Twice", "Thrice"] text = Utils.format_term("title", null, null, null, null, null, tail) text.should.equal "\u001b[33m●\u001b[0m title\n\t ↳ Once\n\t ↳ Twice\n\t ↳ Thrice" describe '#format_html()', () -> it 'should be nicely formatted', () -> ok = Utils.format_html("title", "http://google.fr", "infos", "comments", true) ok.should.equal "✓ <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" nok = Utils.format_html("title", "http://google.fr", "infos", "comments", false) nok.should.equal "✘ <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should have only title mandatory', () -> text = Utils.format_html("title") text.should.equal "● title" it 'should be able to display gravatars', () -> test = Utils.format_html("title", "http://google.fr", "infos", "comments", false, "205e460b479e2e5b48aec07710c08d50") test.should.equal "✘ <img src='http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=20' /> - <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should be able to display avatar urls', () -> test = Utils.format_html("title", "http://google.fr", "infos", "comments", false, "http://my.awesome.avatar.com") test.should.equal "✘ <img src='http://my.awesome.avatar.com' height='20px' width='20px' /> - <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should display tails as multi-line', () -> test = Utils.format_html("title", null, "infos", "comments", false, null, ["this is not a tail recursion"]) test.should.equal "✘ title - <strong>infos</strong> - <i>comments</i><br />&nbsp; ↳ this is not a tail recursion" describe '#render()', () -> it 'should send a message to the Hipchat API', () -> nock = Nock('http://api.hipchat.com') .matchHeader('Content-Type', 'application/x-www-form-urlencoded') .post('/v1/rooms/message?format=json&auth_token=testtoken', { message_format: 'html', color: 'yellow', room_id: 'testchan', from: 'testbot', message: '● test message' }) .reply(200, { "status": "sent" }) Utils.render { title: "test message" } nock.done() describe '#fallback_printList()', () -> it 'should handle an empty list', (done) -> Utils.fallback_printList (object) -> object.title.should.be.equal "No result for your request" done() , []
21187
Require = require('covershot').require.bind(null, require) should = require('chai').should() Utils = Require '../lib/utils' Nock = require 'nock' describe 'Utils', () -> describe '#format_term()', () -> it 'should have styled status', () -> ok = Utils.format_term("title", null, "infos", "comments", true) ok.should.equal "\u001b[32m✓\u001b[0m title - \u001b[1minfos\u001b[0m - \u001b[3mcomments\u001b[0m" nok = Utils.format_term("title", null, "infos", "comments", false) nok.should.equal "\u001b[31m✘\u001b[0m title - \u001b[1minfos\u001b[0m - \u001b[3mcomments\u001b[0m" it 'should have only title mandatory', () -> text = Utils.format_term("title") text.should.equal "\u001b[33m●\u001b[0m title" it 'should have tails on multi lines', () -> tail = ["Once", "Twice", "Thrice"] text = Utils.format_term("title", null, null, null, null, null, tail) text.should.equal "\u001b[33m●\u001b[0m title\n\t ↳ Once\n\t ↳ Twice\n\t ↳ Thrice" describe '#format_html()', () -> it 'should be nicely formatted', () -> ok = Utils.format_html("title", "http://google.fr", "infos", "comments", true) ok.should.equal "✓ <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" nok = Utils.format_html("title", "http://google.fr", "infos", "comments", false) nok.should.equal "✘ <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should have only title mandatory', () -> text = Utils.format_html("title") text.should.equal "● title" it 'should be able to display gravatars', () -> test = Utils.format_html("title", "http://google.fr", "infos", "comments", false, "205e460b479e2e5b48aec07710c08d50") test.should.equal "✘ <img src='http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=20' /> - <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should be able to display avatar urls', () -> test = Utils.format_html("title", "http://google.fr", "infos", "comments", false, "http://my.awesome.avatar.com") test.should.equal "✘ <img src='http://my.awesome.avatar.com' height='20px' width='20px' /> - <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should display tails as multi-line', () -> test = Utils.format_html("title", null, "infos", "comments", false, null, ["this is not a tail recursion"]) test.should.equal "✘ title - <strong>infos</strong> - <i>comments</i><br />&nbsp; ↳ this is not a tail recursion" describe '#render()', () -> it 'should send a message to the Hipchat API', () -> nock = Nock('http://api.hipchat.com') .matchHeader('Content-Type', 'application/x-www-form-urlencoded') .post('/v1/rooms/message?format=json&auth_token=<KEY>', { message_format: 'html', color: 'yellow', room_id: 'testchan', from: 'testbot', message: '● test message' }) .reply(200, { "status": "sent" }) Utils.render { title: "test message" } nock.done() describe '#fallback_printList()', () -> it 'should handle an empty list', (done) -> Utils.fallback_printList (object) -> object.title.should.be.equal "No result for your request" done() , []
true
Require = require('covershot').require.bind(null, require) should = require('chai').should() Utils = Require '../lib/utils' Nock = require 'nock' describe 'Utils', () -> describe '#format_term()', () -> it 'should have styled status', () -> ok = Utils.format_term("title", null, "infos", "comments", true) ok.should.equal "\u001b[32m✓\u001b[0m title - \u001b[1minfos\u001b[0m - \u001b[3mcomments\u001b[0m" nok = Utils.format_term("title", null, "infos", "comments", false) nok.should.equal "\u001b[31m✘\u001b[0m title - \u001b[1minfos\u001b[0m - \u001b[3mcomments\u001b[0m" it 'should have only title mandatory', () -> text = Utils.format_term("title") text.should.equal "\u001b[33m●\u001b[0m title" it 'should have tails on multi lines', () -> tail = ["Once", "Twice", "Thrice"] text = Utils.format_term("title", null, null, null, null, null, tail) text.should.equal "\u001b[33m●\u001b[0m title\n\t ↳ Once\n\t ↳ Twice\n\t ↳ Thrice" describe '#format_html()', () -> it 'should be nicely formatted', () -> ok = Utils.format_html("title", "http://google.fr", "infos", "comments", true) ok.should.equal "✓ <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" nok = Utils.format_html("title", "http://google.fr", "infos", "comments", false) nok.should.equal "✘ <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should have only title mandatory', () -> text = Utils.format_html("title") text.should.equal "● title" it 'should be able to display gravatars', () -> test = Utils.format_html("title", "http://google.fr", "infos", "comments", false, "205e460b479e2e5b48aec07710c08d50") test.should.equal "✘ <img src='http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=20' /> - <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should be able to display avatar urls', () -> test = Utils.format_html("title", "http://google.fr", "infos", "comments", false, "http://my.awesome.avatar.com") test.should.equal "✘ <img src='http://my.awesome.avatar.com' height='20px' width='20px' /> - <a href='http://google.fr'>title</a> - <strong>infos</strong> - <i>comments</i>" it 'should display tails as multi-line', () -> test = Utils.format_html("title", null, "infos", "comments", false, null, ["this is not a tail recursion"]) test.should.equal "✘ title - <strong>infos</strong> - <i>comments</i><br />&nbsp; ↳ this is not a tail recursion" describe '#render()', () -> it 'should send a message to the Hipchat API', () -> nock = Nock('http://api.hipchat.com') .matchHeader('Content-Type', 'application/x-www-form-urlencoded') .post('/v1/rooms/message?format=json&auth_token=PI:KEY:<KEY>END_PI', { message_format: 'html', color: 'yellow', room_id: 'testchan', from: 'testbot', message: '● test message' }) .reply(200, { "status": "sent" }) Utils.render { title: "test message" } nock.done() describe '#fallback_printList()', () -> it 'should handle an empty list', (done) -> Utils.fallback_printList (object) -> object.title.should.be.equal "No result for your request" done() , []
[ { "context": "ype extensions for javascript strings \n Author: Cody Kochmann\n\n To do list:\n [X] - contains\n [X] - rem", "end": 78, "score": 0.9996813535690308, "start": 65, "tag": "NAME", "value": "Cody Kochmann" } ]
strings_extensions.coffee
CodyKochmann/enhancing_javascript
0
### Prototype extensions for javascript strings Author: Cody Kochmann To do list: [X] - contains [X] - remove_all [X] - word_count [X] - base64_encode [X] - base64_decode [ ] - find_all [ ] - count_sentences [ ] - longest_word [ ] - most_common_word [ ] - most_common_pattern [ ] - is_multi_line [ ] - find_lines_containing [ ] - spell_check [ ] - reading_level [ ] - estimate_type ### String::contains = (search_str) -> # checks if a substring is in the string if @indexOf(search_str) == -1 return false true String::remove_all = (target) -> # removes every instance of a string in a string if @indexOf(target) != -1 @split(target).join '' return String::word_count = -> # returns the word count of a string i=0 count = 0 # filter everything out that isno a letter or a space letters = 'abcdefghijklmnopqrstuvwxyz ' letters += letters.toUpperCase() tmp_array = @split('') for i of tmp_array if letters.indexOf(tmp_array[i]) == -1 @split(tmp_array[i]).join '' # filter out empty spaces while @indexOf(' ') != -1 @replace(' ').join ' ' split = @split(' ') for i of split if split[i].length > 0 and split[i] != ' ' count += 1 count String::base64_encode = () -> window.btoa unescape(encodeURIComponent(this)) String::base64_decode=()-> decodeURIComponent escape(window.atob(this))
59770
### Prototype extensions for javascript strings Author: <NAME> To do list: [X] - contains [X] - remove_all [X] - word_count [X] - base64_encode [X] - base64_decode [ ] - find_all [ ] - count_sentences [ ] - longest_word [ ] - most_common_word [ ] - most_common_pattern [ ] - is_multi_line [ ] - find_lines_containing [ ] - spell_check [ ] - reading_level [ ] - estimate_type ### String::contains = (search_str) -> # checks if a substring is in the string if @indexOf(search_str) == -1 return false true String::remove_all = (target) -> # removes every instance of a string in a string if @indexOf(target) != -1 @split(target).join '' return String::word_count = -> # returns the word count of a string i=0 count = 0 # filter everything out that isno a letter or a space letters = 'abcdefghijklmnopqrstuvwxyz ' letters += letters.toUpperCase() tmp_array = @split('') for i of tmp_array if letters.indexOf(tmp_array[i]) == -1 @split(tmp_array[i]).join '' # filter out empty spaces while @indexOf(' ') != -1 @replace(' ').join ' ' split = @split(' ') for i of split if split[i].length > 0 and split[i] != ' ' count += 1 count String::base64_encode = () -> window.btoa unescape(encodeURIComponent(this)) String::base64_decode=()-> decodeURIComponent escape(window.atob(this))
true
### Prototype extensions for javascript strings Author: PI:NAME:<NAME>END_PI To do list: [X] - contains [X] - remove_all [X] - word_count [X] - base64_encode [X] - base64_decode [ ] - find_all [ ] - count_sentences [ ] - longest_word [ ] - most_common_word [ ] - most_common_pattern [ ] - is_multi_line [ ] - find_lines_containing [ ] - spell_check [ ] - reading_level [ ] - estimate_type ### String::contains = (search_str) -> # checks if a substring is in the string if @indexOf(search_str) == -1 return false true String::remove_all = (target) -> # removes every instance of a string in a string if @indexOf(target) != -1 @split(target).join '' return String::word_count = -> # returns the word count of a string i=0 count = 0 # filter everything out that isno a letter or a space letters = 'abcdefghijklmnopqrstuvwxyz ' letters += letters.toUpperCase() tmp_array = @split('') for i of tmp_array if letters.indexOf(tmp_array[i]) == -1 @split(tmp_array[i]).join '' # filter out empty spaces while @indexOf(' ') != -1 @replace(' ').join ' ' split = @split(' ') for i of split if split[i].length > 0 and split[i] != ' ' count += 1 count String::base64_encode = () -> window.btoa unescape(encodeURIComponent(this)) String::base64_decode=()-> decodeURIComponent escape(window.atob(this))
[ { "context": "\t\t\t\t\tparams:\n\t\t\t\t\t\t\tBucket: bucket\n\t\t\t\t\t\t\tKey: key.get()\n\t\t\t\t\t\t\tBody: readStream\n\t\t\t\t\t\t\tACL: 'private'\n\t", "end": 5056, "score": 0.7797527313232422, "start": 5053, "tag": "KEY", "value": "get" }, { "context": "ql\n\t\t\t\t\t\tparam...
lib/tests/s3/S3Artifactory.tests.coffee
NiteoSoftware/s3artifactor
3
path = require 'path' should = require 'should' aws = require 'aws-sdk' Q = require 'q' _ = require 'lodash' sinon = require 'sinon' events = require 'events' s3Key = require path.join( __dirname, "../../s3/s3Key.js") s3artifactory = require path.join( __dirname, "../../s3/s3Artifactory.js") collection = aws = fs = region = bucket = id = null describe 's3Artifactory', -> stockArtifacts = [ { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "1" Version: "0.0.1" } { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "2" Version: "0.0.2" } { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "3" Version: "3" } { Region: region Bucket: bucket Id: id IsLatest: true VersionId: "4" Version: "0.0.4" } ] sourceArtifacts = null beforeEachFunction = () -> sourceArtifacts = JSON.parse(JSON.stringify(stockArtifacts)) collection = get: (version) -> if version? Q.resolve(_.find sourceArtifacts, { Version: version }) else Q.resolve sourceArtifacts getLatest: () -> Q.resolve(_.find sourceArtifacts, { IsLatest: true }) aws = { } fs = { } region = "Some Region" bucket = "Some Bucket" id = "Some Id" getTarget = (innerCollection) -> if innerCollection? collection.get = () -> Q.resolve innerCollection new s3artifactory(collection, aws, fs, region, bucket, id) beforeEach beforeEachFunction describe '#constructor', -> it 'should raise an error if collection is null.', -> collection = null (() -> getTarget()).should.throw() it 'should raise an error if collection is undefined.', -> collection = undefined (() -> getTarget()).should.throw() it 'should raise an error if aws is null.', -> aws = null (() -> getTarget()).should.throw() it 'should raise an error if aws is undefined.', -> aws = undefined (() -> getTarget()).should.throw() it 'should raise an error if fs is null.', -> fs = null (() -> getTarget()).should.throw() it 'should raise an error if fs is undefined.', -> fs = undefined (() -> getTarget()).should.throw() it 'should raise an error if region is null.', -> region = null (() -> getTarget()).should.throw() it 'should raise an error if region is undefined.', -> region = undefined (() -> getTarget()).should.throw() it 'should raise an error if bucket is null.', -> bucket = null (() -> getTarget()).should.throw() it 'should raise an error if bucket is undefined.', -> bucket = undefined (() -> getTarget()).should.throw() it 'should raise an error if id is null.', -> id = null (() -> getTarget()).should.throw() it 'should raise an error if id is undefined.', -> id = undefined (() -> getTarget()).should.throw() it 'key should be set.', -> id = "Some Id" key = new s3Key id getTarget().key.should.eql key describe '#pushArtifact(sourcePath, version, isPublic, isEncrypted, overwrite)', -> it 'should raise an error if sourcePath is null.', (done) -> getTarget().pushArtifact null, '0.0.5' .catch (err) -> done() it 'should raise an error if sourcePath is undefined.', (done) -> getTarget().pushArtifact undefined, '0.0.5' .catch (err) -> done() it 'should raise an error if version is null.', (done) -> getTarget().pushArtifact 'path', null .catch (err) -> done() it 'should raise an error if version is undefined.', (done) -> getTarget().pushArtifact 'path', undefined .catch (err) -> done() it 'should raise an error if the version already exists.', (done) -> getTarget().pushArtifact 'path', '0.0.4' .catch (err) -> done() it 'should open the correct file.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact "some Path", "0.0.5" .done (data) -> fs.createReadStream.calledOnce.should.be.true fs.createReadStream.alwaysCalledWithExactly("some Path").should.be.true done() it 'should send the correct options to managed upload.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.get() Body: readStream ACL: 'private' Metadata: version: '0.0.6' done() it 'should delete the latest if overwrite is true', (done) -> readStream = { } actualManagedUploadOptions = null deleteOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: class deleteObject: (options, callback) => deleteOptions = options sourceArtifacts = _.filter sourceArtifacts, (item) -> item.VersionId != options.VersionId callback null, { } aws.S3.ManagedUpload = class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.4', false, false, true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.get() Body: readStream ACL: 'private' Metadata: version: '0.0.4' deleteOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it 'should raise an exception if overwrite is true and the version is not the latest version', (done) -> readStream = { } actualManagedUploadOptions = null deleteOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: class deleteObject: (options, callback) => deleteOptions = options sourceArtifacts = _.filter sourceArtifacts, (item) -> item.VersionId != options.VersionId callback null, { } aws.S3.ManagedUpload = class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.2', false, false, true .catch (err) -> done() it 'should set the correct ACL when isPublic is set to true.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6', true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.get() Body: readStream ACL: 'public-read' Metadata: version: '0.0.6' done() it 'should set the correct SSE when isEncrypted is set to true.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6', false, true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.get() Body: readStream ACL: 'private' Metadata: version: '0.0.6' ServerSideEncryption: 'AES256' done() it 'should raise an error if managedUpload.send does so.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback "someError", null on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .catch (error) -> done() it 'should data returned from managedUpload.send.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id returnResult = { } fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, returnResult on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .done (data) -> data.should.equal returnResult done() describe '#getArtifact(destPath, version)', -> it 'should raise an error if destPath is null.', (done) -> getTarget().getArtifact null, '0.0.4' .catch (err) -> done() it 'should raise an error if destPath is undefined.', (done) -> getTarget().getArtifact undefined, '0.0.4' .catch (err) -> done() it 'should raise an error if the version does not exists.', (done) -> getTarget().getArtifact 'path', '0.0.5' .catch (err) -> done() it 'should open the correct file.', (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "0.0.4" promise.done (data) -> createWriteStreamStub.alwaysCalledWithExactly("some Path").should.be.true done() it 'should pass the correct options.', (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "0.0.2" promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "2" done() it "'httpData' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpData').length.should.equal 1 done() it "'httpDone' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpDone').length.should.equal 1 done() it "'success' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('success').length.should.equal 1 done() it "'error' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('error').length.should.equal 1 done() it "'httpDownloadProgress' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpDownloadProgress').length.should.equal 1 done() it "'httpData' should write to the file.", (done) -> chunk = { } actualManagedUploadOptions = null writeStreamStub = write: sinon.stub() end: sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.emit('httpData', chunk) writeStreamStub.write.alwaysCalledWithExactly(chunk).should.be.true done() it "'httpDone' should end the file.", (done) -> writeStreamStub = write: sinon.stub() end: sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.emit('httpDone') writeStreamStub.end.calledOnce.should.be.true done() it "should get the latest version if 'Latest' is passed in for version id.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "Latest" promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it "should get the latest if version id is undefined.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", undefined promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it "should get the latest if version id is null.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", null promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() describe '#deleteArtifact(version)', -> it 'should raise an error if version is null.', (done) -> getTarget().deleteArtifact null .catch (err) -> done() it 'should raise an error if version is undefined.', (done) -> getTarget().deleteArtifact undefined .catch (err) -> done() it 'should raise an error if the version does not exists.', (done) -> getTarget().deleteArtifact '0.0.5' .catch (err) -> done() it 'should pass the correct options.', (done) -> actualOptions = null key = new s3Key id aws = S3: class deleteObject: (options, callback) -> actualOptions = options callback null, { } getTarget().deleteArtifact "0.0.4" .done (data) -> actualOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it 'should raise an error if one happens.', (done) -> aws = S3: class deleteObject: (options, callback) -> callback "Some Error", null getTarget().deleteArtifact "0.0.4" .catch (error) -> done() it 'should return success if everything is ok.', (done) -> aws = S3: class deleteObject: (options, callback) -> callback null, "Some Data" getTarget().deleteArtifact "0.0.4" .done (data) -> done()
93279
path = require 'path' should = require 'should' aws = require 'aws-sdk' Q = require 'q' _ = require 'lodash' sinon = require 'sinon' events = require 'events' s3Key = require path.join( __dirname, "../../s3/s3Key.js") s3artifactory = require path.join( __dirname, "../../s3/s3Artifactory.js") collection = aws = fs = region = bucket = id = null describe 's3Artifactory', -> stockArtifacts = [ { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "1" Version: "0.0.1" } { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "2" Version: "0.0.2" } { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "3" Version: "3" } { Region: region Bucket: bucket Id: id IsLatest: true VersionId: "4" Version: "0.0.4" } ] sourceArtifacts = null beforeEachFunction = () -> sourceArtifacts = JSON.parse(JSON.stringify(stockArtifacts)) collection = get: (version) -> if version? Q.resolve(_.find sourceArtifacts, { Version: version }) else Q.resolve sourceArtifacts getLatest: () -> Q.resolve(_.find sourceArtifacts, { IsLatest: true }) aws = { } fs = { } region = "Some Region" bucket = "Some Bucket" id = "Some Id" getTarget = (innerCollection) -> if innerCollection? collection.get = () -> Q.resolve innerCollection new s3artifactory(collection, aws, fs, region, bucket, id) beforeEach beforeEachFunction describe '#constructor', -> it 'should raise an error if collection is null.', -> collection = null (() -> getTarget()).should.throw() it 'should raise an error if collection is undefined.', -> collection = undefined (() -> getTarget()).should.throw() it 'should raise an error if aws is null.', -> aws = null (() -> getTarget()).should.throw() it 'should raise an error if aws is undefined.', -> aws = undefined (() -> getTarget()).should.throw() it 'should raise an error if fs is null.', -> fs = null (() -> getTarget()).should.throw() it 'should raise an error if fs is undefined.', -> fs = undefined (() -> getTarget()).should.throw() it 'should raise an error if region is null.', -> region = null (() -> getTarget()).should.throw() it 'should raise an error if region is undefined.', -> region = undefined (() -> getTarget()).should.throw() it 'should raise an error if bucket is null.', -> bucket = null (() -> getTarget()).should.throw() it 'should raise an error if bucket is undefined.', -> bucket = undefined (() -> getTarget()).should.throw() it 'should raise an error if id is null.', -> id = null (() -> getTarget()).should.throw() it 'should raise an error if id is undefined.', -> id = undefined (() -> getTarget()).should.throw() it 'key should be set.', -> id = "Some Id" key = new s3Key id getTarget().key.should.eql key describe '#pushArtifact(sourcePath, version, isPublic, isEncrypted, overwrite)', -> it 'should raise an error if sourcePath is null.', (done) -> getTarget().pushArtifact null, '0.0.5' .catch (err) -> done() it 'should raise an error if sourcePath is undefined.', (done) -> getTarget().pushArtifact undefined, '0.0.5' .catch (err) -> done() it 'should raise an error if version is null.', (done) -> getTarget().pushArtifact 'path', null .catch (err) -> done() it 'should raise an error if version is undefined.', (done) -> getTarget().pushArtifact 'path', undefined .catch (err) -> done() it 'should raise an error if the version already exists.', (done) -> getTarget().pushArtifact 'path', '0.0.4' .catch (err) -> done() it 'should open the correct file.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact "some Path", "0.0.5" .done (data) -> fs.createReadStream.calledOnce.should.be.true fs.createReadStream.alwaysCalledWithExactly("some Path").should.be.true done() it 'should send the correct options to managed upload.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.<KEY>() Body: readStream ACL: 'private' Metadata: version: '0.0.6' done() it 'should delete the latest if overwrite is true', (done) -> readStream = { } actualManagedUploadOptions = null deleteOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: class deleteObject: (options, callback) => deleteOptions = options sourceArtifacts = _.filter sourceArtifacts, (item) -> item.VersionId != options.VersionId callback null, { } aws.S3.ManagedUpload = class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.4', false, false, true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.get() Body: readStream ACL: 'private' Metadata: version: '0.0.4' deleteOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it 'should raise an exception if overwrite is true and the version is not the latest version', (done) -> readStream = { } actualManagedUploadOptions = null deleteOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: class deleteObject: (options, callback) => deleteOptions = options sourceArtifacts = _.filter sourceArtifacts, (item) -> item.VersionId != options.VersionId callback null, { } aws.S3.ManagedUpload = class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.2', false, false, true .catch (err) -> done() it 'should set the correct ACL when isPublic is set to true.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6', true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: <KEY> Body: readStream ACL: 'public-read' Metadata: version: '0.0.6' done() it 'should set the correct SSE when isEncrypted is set to true.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6', false, true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: <KEY> Body: readStream ACL: 'private' Metadata: version: '0.0.6' ServerSideEncryption: 'AES256' done() it 'should raise an error if managedUpload.send does so.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback "someError", null on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .catch (error) -> done() it 'should data returned from managedUpload.send.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id returnResult = { } fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, returnResult on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .done (data) -> data.should.equal returnResult done() describe '#getArtifact(destPath, version)', -> it 'should raise an error if destPath is null.', (done) -> getTarget().getArtifact null, '0.0.4' .catch (err) -> done() it 'should raise an error if destPath is undefined.', (done) -> getTarget().getArtifact undefined, '0.0.4' .catch (err) -> done() it 'should raise an error if the version does not exists.', (done) -> getTarget().getArtifact 'path', '0.0.5' .catch (err) -> done() it 'should open the correct file.', (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "0.0.4" promise.done (data) -> createWriteStreamStub.alwaysCalledWithExactly("some Path").should.be.true done() it 'should pass the correct options.', (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "0.0.2" promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "2" done() it "'httpData' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpData').length.should.equal 1 done() it "'httpDone' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpDone').length.should.equal 1 done() it "'success' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('success').length.should.equal 1 done() it "'error' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('error').length.should.equal 1 done() it "'httpDownloadProgress' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpDownloadProgress').length.should.equal 1 done() it "'httpData' should write to the file.", (done) -> chunk = { } actualManagedUploadOptions = null writeStreamStub = write: sinon.stub() end: sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.emit('httpData', chunk) writeStreamStub.write.alwaysCalledWithExactly(chunk).should.be.true done() it "'httpDone' should end the file.", (done) -> writeStreamStub = write: sinon.stub() end: sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.emit('httpDone') writeStreamStub.end.calledOnce.should.be.true done() it "should get the latest version if 'Latest' is passed in for version id.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "Latest" promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.<KEY>() VersionId: "4" done() it "should get the latest if version id is undefined.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", undefined promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.<KEY>() VersionId: "4" done() it "should get the latest if version id is null.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", null promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() describe '#deleteArtifact(version)', -> it 'should raise an error if version is null.', (done) -> getTarget().deleteArtifact null .catch (err) -> done() it 'should raise an error if version is undefined.', (done) -> getTarget().deleteArtifact undefined .catch (err) -> done() it 'should raise an error if the version does not exists.', (done) -> getTarget().deleteArtifact '0.0.5' .catch (err) -> done() it 'should pass the correct options.', (done) -> actualOptions = null key = new s3Key id aws = S3: class deleteObject: (options, callback) -> actualOptions = options callback null, { } getTarget().deleteArtifact "0.0.4" .done (data) -> actualOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it 'should raise an error if one happens.', (done) -> aws = S3: class deleteObject: (options, callback) -> callback "Some Error", null getTarget().deleteArtifact "0.0.4" .catch (error) -> done() it 'should return success if everything is ok.', (done) -> aws = S3: class deleteObject: (options, callback) -> callback null, "Some Data" getTarget().deleteArtifact "0.0.4" .done (data) -> done()
true
path = require 'path' should = require 'should' aws = require 'aws-sdk' Q = require 'q' _ = require 'lodash' sinon = require 'sinon' events = require 'events' s3Key = require path.join( __dirname, "../../s3/s3Key.js") s3artifactory = require path.join( __dirname, "../../s3/s3Artifactory.js") collection = aws = fs = region = bucket = id = null describe 's3Artifactory', -> stockArtifacts = [ { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "1" Version: "0.0.1" } { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "2" Version: "0.0.2" } { Region: region Bucket: bucket Id: id IsLatest: false VersionId: "3" Version: "3" } { Region: region Bucket: bucket Id: id IsLatest: true VersionId: "4" Version: "0.0.4" } ] sourceArtifacts = null beforeEachFunction = () -> sourceArtifacts = JSON.parse(JSON.stringify(stockArtifacts)) collection = get: (version) -> if version? Q.resolve(_.find sourceArtifacts, { Version: version }) else Q.resolve sourceArtifacts getLatest: () -> Q.resolve(_.find sourceArtifacts, { IsLatest: true }) aws = { } fs = { } region = "Some Region" bucket = "Some Bucket" id = "Some Id" getTarget = (innerCollection) -> if innerCollection? collection.get = () -> Q.resolve innerCollection new s3artifactory(collection, aws, fs, region, bucket, id) beforeEach beforeEachFunction describe '#constructor', -> it 'should raise an error if collection is null.', -> collection = null (() -> getTarget()).should.throw() it 'should raise an error if collection is undefined.', -> collection = undefined (() -> getTarget()).should.throw() it 'should raise an error if aws is null.', -> aws = null (() -> getTarget()).should.throw() it 'should raise an error if aws is undefined.', -> aws = undefined (() -> getTarget()).should.throw() it 'should raise an error if fs is null.', -> fs = null (() -> getTarget()).should.throw() it 'should raise an error if fs is undefined.', -> fs = undefined (() -> getTarget()).should.throw() it 'should raise an error if region is null.', -> region = null (() -> getTarget()).should.throw() it 'should raise an error if region is undefined.', -> region = undefined (() -> getTarget()).should.throw() it 'should raise an error if bucket is null.', -> bucket = null (() -> getTarget()).should.throw() it 'should raise an error if bucket is undefined.', -> bucket = undefined (() -> getTarget()).should.throw() it 'should raise an error if id is null.', -> id = null (() -> getTarget()).should.throw() it 'should raise an error if id is undefined.', -> id = undefined (() -> getTarget()).should.throw() it 'key should be set.', -> id = "Some Id" key = new s3Key id getTarget().key.should.eql key describe '#pushArtifact(sourcePath, version, isPublic, isEncrypted, overwrite)', -> it 'should raise an error if sourcePath is null.', (done) -> getTarget().pushArtifact null, '0.0.5' .catch (err) -> done() it 'should raise an error if sourcePath is undefined.', (done) -> getTarget().pushArtifact undefined, '0.0.5' .catch (err) -> done() it 'should raise an error if version is null.', (done) -> getTarget().pushArtifact 'path', null .catch (err) -> done() it 'should raise an error if version is undefined.', (done) -> getTarget().pushArtifact 'path', undefined .catch (err) -> done() it 'should raise an error if the version already exists.', (done) -> getTarget().pushArtifact 'path', '0.0.4' .catch (err) -> done() it 'should open the correct file.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact "some Path", "0.0.5" .done (data) -> fs.createReadStream.calledOnce.should.be.true fs.createReadStream.alwaysCalledWithExactly("some Path").should.be.true done() it 'should send the correct options to managed upload.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.PI:KEY:<KEY>END_PI() Body: readStream ACL: 'private' Metadata: version: '0.0.6' done() it 'should delete the latest if overwrite is true', (done) -> readStream = { } actualManagedUploadOptions = null deleteOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: class deleteObject: (options, callback) => deleteOptions = options sourceArtifacts = _.filter sourceArtifacts, (item) -> item.VersionId != options.VersionId callback null, { } aws.S3.ManagedUpload = class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.4', false, false, true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: key.get() Body: readStream ACL: 'private' Metadata: version: '0.0.4' deleteOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it 'should raise an exception if overwrite is true and the version is not the latest version', (done) -> readStream = { } actualManagedUploadOptions = null deleteOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: class deleteObject: (options, callback) => deleteOptions = options sourceArtifacts = _.filter sourceArtifacts, (item) -> item.VersionId != options.VersionId callback null, { } aws.S3.ManagedUpload = class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.2', false, false, true .catch (err) -> done() it 'should set the correct ACL when isPublic is set to true.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6', true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: PI:KEY:<KEY>END_PI Body: readStream ACL: 'public-read' Metadata: version: '0.0.6' done() it 'should set the correct SSE when isEncrypted is set to true.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, { } on: () -> getTarget().pushArtifact 'some Path', '0.0.6', false, true .done (data) -> actualManagedUploadOptions.should.eql params: Bucket: bucket Key: PI:KEY:<KEY>END_PI Body: readStream ACL: 'private' Metadata: version: '0.0.6' ServerSideEncryption: 'AES256' done() it 'should raise an error if managedUpload.send does so.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback "someError", null on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .catch (error) -> done() it 'should data returned from managedUpload.send.', (done) -> readStream = { } actualManagedUploadOptions = null createReadStreamStub = sinon.stub() createReadStreamStub.returns readStream key = new s3Key id returnResult = { } fs = createReadStream: createReadStreamStub aws = S3: ManagedUpload: class constructor: (options) -> actualManagedUploadOptions = options send: (callback) -> callback null, returnResult on: () -> getTarget().pushArtifact 'some Path', '0.0.6' .done (data) -> data.should.equal returnResult done() describe '#getArtifact(destPath, version)', -> it 'should raise an error if destPath is null.', (done) -> getTarget().getArtifact null, '0.0.4' .catch (err) -> done() it 'should raise an error if destPath is undefined.', (done) -> getTarget().getArtifact undefined, '0.0.4' .catch (err) -> done() it 'should raise an error if the version does not exists.', (done) -> getTarget().getArtifact 'path', '0.0.5' .catch (err) -> done() it 'should open the correct file.', (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "0.0.4" promise.done (data) -> createWriteStreamStub.alwaysCalledWithExactly("some Path").should.be.true done() it 'should pass the correct options.', (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "0.0.2" promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "2" done() it "'httpData' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpData').length.should.equal 1 done() it "'httpDone' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpDone').length.should.equal 1 done() it "'success' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('success').length.should.equal 1 done() it "'error' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('error').length.should.equal 1 done() it "'httpDownloadProgress' should have been registered.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.listeners('httpDownloadProgress').length.should.equal 1 done() it "'httpData' should write to the file.", (done) -> chunk = { } actualManagedUploadOptions = null writeStreamStub = write: sinon.stub() end: sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.emit('httpData', chunk) writeStreamStub.write.alwaysCalledWithExactly(chunk).should.be.true done() it "'httpDone' should end the file.", (done) -> writeStreamStub = write: sinon.stub() end: sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> request getTarget().getArtifact "some Path", "0.0.4" .done (data) -> request.emit('httpDone') writeStreamStub.end.calledOnce.should.be.true done() it "should get the latest version if 'Latest' is passed in for version id.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", "Latest" promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.PI:KEY:<KEY>END_PI() VersionId: "4" done() it "should get the latest if version id is undefined.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", undefined promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.PI:KEY:<KEY>END_PI() VersionId: "4" done() it "should get the latest if version id is null.", (done) -> actualManagedUploadOptions = null writeStreamStub = sinon.stub() createWriteStreamStub = sinon.stub() createWriteStreamStub.returns writeStreamStub key = new s3Key id requestDef = class extends events.EventEmitter send: () -> @emit 'success' request = new requestDef fs = createWriteStream: createWriteStreamStub aws = S3: class getObject: (options) -> actualManagedUploadOptions = options request promise = getTarget().getArtifact "some Path", null promise.done (data) -> actualManagedUploadOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() describe '#deleteArtifact(version)', -> it 'should raise an error if version is null.', (done) -> getTarget().deleteArtifact null .catch (err) -> done() it 'should raise an error if version is undefined.', (done) -> getTarget().deleteArtifact undefined .catch (err) -> done() it 'should raise an error if the version does not exists.', (done) -> getTarget().deleteArtifact '0.0.5' .catch (err) -> done() it 'should pass the correct options.', (done) -> actualOptions = null key = new s3Key id aws = S3: class deleteObject: (options, callback) -> actualOptions = options callback null, { } getTarget().deleteArtifact "0.0.4" .done (data) -> actualOptions.should.eql Bucket: bucket Key: key.get() VersionId: "4" done() it 'should raise an error if one happens.', (done) -> aws = S3: class deleteObject: (options, callback) -> callback "Some Error", null getTarget().deleteArtifact "0.0.4" .catch (error) -> done() it 'should return success if everything is ok.', (done) -> aws = S3: class deleteObject: (options, callback) -> callback null, "Some Data" getTarget().deleteArtifact "0.0.4" .done (data) -> done()
[ { "context": "###\nCopyright (C) 2013, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(", "end": 36, "score": 0.9998370409011841, "start": 24, "tag": "NAME", "value": "Bill Burdick" }, { "context": ", Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(lic...
METEOR-OLD/client/15-base.coffee
zot/Leisure
58
### Copyright (C) 2013, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### (window ? global).Leisure = root = (module ? {}).exports = (global?.Leisure ? module?.exports ? window?.Leisure) root.currentNameSpace = 'core' root.nameSpacePath = ['core'] #root.shouldNsLog = true root.shouldNsLog = false root.nsLog = (args...)-> if root.shouldNsLog then console.log args... (window ? global).verbose = {} verboseMsg = (label, msg...)-> if (window ? global).verbose[label] then console.log msg... if !btoa? then (window ? global).btoa = require 'btoa' defaultEnv = presentValue: (x)-> String(x) + '\n' values: {} errorHandlers: [] prompt: -> rz = (window ? global).resolve = (value)-> if typeof value == 'function' if typeof value.memo != 'undefined' then value.memo else if value.creationStack then value.creationStack = null if value.args then value.args = null value.memo = value() else value #global.lazy = (l)-> ->l #global.lazy = (l)-> if typeof l == 'function' # count=0 # -> # if count++ > 0 then console.log "EXTRA EXECUTION OF #{l}, #{new Error('stack').stack}" # l #else l (window ? global).lazy = (l)-> if typeof l == 'function' then l.memo = l else l readFile = (fileName, cont)-> defaultEnv.readFile fileName, cont writeFile = (fileName, data, cont)-> defaultEnv.writeFile fileName, data, cont readDir = (fileName, cont)-> defaultEnv.readDir fileName, cont statFile = (fileName, cont)-> defaultEnv.statFile fileName, cont root.trackCreation = false #root.trackVars = false #root.trackCreation = true root.trackVars = true funcInfo = (func)-> if func.leisureInfoNew then primConsFrom func.leisureInfoNew, 0 else if func.leisureInfo (window ? global).FUNC = func info = [] callInfo = func.leisureInfo while callInfo info.push resolve callInfo.arg if callInfo.name info.push callInfo.name break callInfo = callInfo.parent root.consFrom info.reverse() else rz L_nil primConsFrom = (array, index)-> if index >= array.length then rz L_nil else root.primCons array[index], primConsFrom array, index + 1 class SimpyCons constructor: (@head, @tail)-> toArray: -> @_array ? ( h = @ array = [] while h != null array.push h.head h = h.tail @_array = array) simpyCons = (a, b)-> new SimpyCons a, b slice = Array.prototype.slice concat = Array.prototype.concat (window ? global).Leisure_call = leisureCall = (f)-> baseLeisureCall f, 1, arguments (window ? global).Leisure_primCall = baseLeisureCall = (f, pos, args)-> while pos < args.length if typeof f != 'function' then throw new Error "TypeError: #{typeof f} is not a function: #{f}" if f.length <= args.length - pos oldF = f switch f.length when 1 then f = f args[pos] when 2 then f = f args[pos], args[pos + 1] when 3 then f = f args[pos], args[pos + 1], args[pos + 2] when 4 then f = f args[pos], args[pos + 1], args[pos + 2], args[pos + 3] else if f.leisureInfo || (pos == 0 && f.length == args.length) return f.apply null, (if pos == 0 then args else slice.call(args, pos)) f = f.apply null, slice.call(args, pos, pos + f.length) pos += oldF.length else prev = slice.call args, pos partial = -> newArgs = concat.call prev, slice.call arguments if newArgs.length == f.length then f.apply null, newArgs else baseLeisureCall f, 0, newArgs partial.leisurePartial = true partial.leisureInfo = genInfo f, args, f.leisureInfo return lazy partial if pos != args.length then console.log "BAD FINAL POSITION IN LEISURE CALL, ARG LENGTH IS #{args.length} BUT POSITION IS #{pos}" f genInfo = (func, args, oldInfo)-> for arg in args if !oldInfo then oldInfo = {name: func.leisureName, arg} else oldInfo = {arg: arg, parent: oldInfo} oldInfo testCount = 0 errors = '' test = (expected, actual)-> if JSON.stringify(expected) != JSON.stringify(actual) if errors.length then errors += '\n' errors += "TEST #{testCount} FAILED, EXPECTED #{JSON.stringify(expected)} BUT GOT #{JSON.stringify(actual)}" testCount++ (window ? global).Leisure_test_call = -> test [1, 2, 3], Leisure_call ((a, b)->(c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3], Leisure_call ((a, b, c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3], Leisure_call ((a)->(b, c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3, 4], Leisure_call ((a)->(b, c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b, c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b)->(c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b)->(c, d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b, c, d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call (Leisure_call ((a, b, c, d)-> [a, b, c, d]), 1, 2), 3, 4 if errors.length then errors else null serverIncrement = (path, amount, cont)-> block = root.getBlockNamed path.split(/\./)[0] if block.origin != root.currentDocument._name return root.storeBlock block, -> serverIncrement path, amount, cont if typeof path == 'function' then cont "Error, no path given to serverIncrement" else if typeof amount == 'function' then cont "Error, no amount given to serverIncrement" else Meteor.call 'incrementField', root.currentDocument.leisure.name, path, amount, cont root.serverIncrement = serverIncrement root.defaultEnv = defaultEnv root.readFile = readFile root.readDir = readDir root.writeFile = writeFile root.statFile = statFile root.SimpyCons = SimpyCons root.simpyCons = simpyCons root.resolve = resolve root.lazy = lazy root.verboseMsg = verboseMsg root.maxInt = 9007199254740992 root.minInt = -root.maxInt root.funcInfo = funcInfo
116230
### Copyright (C) 2013, <NAME>, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### (window ? global).Leisure = root = (module ? {}).exports = (global?.Leisure ? module?.exports ? window?.Leisure) root.currentNameSpace = 'core' root.nameSpacePath = ['core'] #root.shouldNsLog = true root.shouldNsLog = false root.nsLog = (args...)-> if root.shouldNsLog then console.log args... (window ? global).verbose = {} verboseMsg = (label, msg...)-> if (window ? global).verbose[label] then console.log msg... if !btoa? then (window ? global).btoa = require 'btoa' defaultEnv = presentValue: (x)-> String(x) + '\n' values: {} errorHandlers: [] prompt: -> rz = (window ? global).resolve = (value)-> if typeof value == 'function' if typeof value.memo != 'undefined' then value.memo else if value.creationStack then value.creationStack = null if value.args then value.args = null value.memo = value() else value #global.lazy = (l)-> ->l #global.lazy = (l)-> if typeof l == 'function' # count=0 # -> # if count++ > 0 then console.log "EXTRA EXECUTION OF #{l}, #{new Error('stack').stack}" # l #else l (window ? global).lazy = (l)-> if typeof l == 'function' then l.memo = l else l readFile = (fileName, cont)-> defaultEnv.readFile fileName, cont writeFile = (fileName, data, cont)-> defaultEnv.writeFile fileName, data, cont readDir = (fileName, cont)-> defaultEnv.readDir fileName, cont statFile = (fileName, cont)-> defaultEnv.statFile fileName, cont root.trackCreation = false #root.trackVars = false #root.trackCreation = true root.trackVars = true funcInfo = (func)-> if func.leisureInfoNew then primConsFrom func.leisureInfoNew, 0 else if func.leisureInfo (window ? global).FUNC = func info = [] callInfo = func.leisureInfo while callInfo info.push resolve callInfo.arg if callInfo.name info.push callInfo.name break callInfo = callInfo.parent root.consFrom info.reverse() else rz L_nil primConsFrom = (array, index)-> if index >= array.length then rz L_nil else root.primCons array[index], primConsFrom array, index + 1 class SimpyCons constructor: (@head, @tail)-> toArray: -> @_array ? ( h = @ array = [] while h != null array.push h.head h = h.tail @_array = array) simpyCons = (a, b)-> new SimpyCons a, b slice = Array.prototype.slice concat = Array.prototype.concat (window ? global).Leisure_call = leisureCall = (f)-> baseLeisureCall f, 1, arguments (window ? global).Leisure_primCall = baseLeisureCall = (f, pos, args)-> while pos < args.length if typeof f != 'function' then throw new Error "TypeError: #{typeof f} is not a function: #{f}" if f.length <= args.length - pos oldF = f switch f.length when 1 then f = f args[pos] when 2 then f = f args[pos], args[pos + 1] when 3 then f = f args[pos], args[pos + 1], args[pos + 2] when 4 then f = f args[pos], args[pos + 1], args[pos + 2], args[pos + 3] else if f.leisureInfo || (pos == 0 && f.length == args.length) return f.apply null, (if pos == 0 then args else slice.call(args, pos)) f = f.apply null, slice.call(args, pos, pos + f.length) pos += oldF.length else prev = slice.call args, pos partial = -> newArgs = concat.call prev, slice.call arguments if newArgs.length == f.length then f.apply null, newArgs else baseLeisureCall f, 0, newArgs partial.leisurePartial = true partial.leisureInfo = genInfo f, args, f.leisureInfo return lazy partial if pos != args.length then console.log "BAD FINAL POSITION IN LEISURE CALL, ARG LENGTH IS #{args.length} BUT POSITION IS #{pos}" f genInfo = (func, args, oldInfo)-> for arg in args if !oldInfo then oldInfo = {name: func.leisureName, arg} else oldInfo = {arg: arg, parent: oldInfo} oldInfo testCount = 0 errors = '' test = (expected, actual)-> if JSON.stringify(expected) != JSON.stringify(actual) if errors.length then errors += '\n' errors += "TEST #{testCount} FAILED, EXPECTED #{JSON.stringify(expected)} BUT GOT #{JSON.stringify(actual)}" testCount++ (window ? global).Leisure_test_call = -> test [1, 2, 3], Leisure_call ((a, b)->(c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3], Leisure_call ((a, b, c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3], Leisure_call ((a)->(b, c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3, 4], Leisure_call ((a)->(b, c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b, c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b)->(c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b)->(c, d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b, c, d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call (Leisure_call ((a, b, c, d)-> [a, b, c, d]), 1, 2), 3, 4 if errors.length then errors else null serverIncrement = (path, amount, cont)-> block = root.getBlockNamed path.split(/\./)[0] if block.origin != root.currentDocument._name return root.storeBlock block, -> serverIncrement path, amount, cont if typeof path == 'function' then cont "Error, no path given to serverIncrement" else if typeof amount == 'function' then cont "Error, no amount given to serverIncrement" else Meteor.call 'incrementField', root.currentDocument.leisure.name, path, amount, cont root.serverIncrement = serverIncrement root.defaultEnv = defaultEnv root.readFile = readFile root.readDir = readDir root.writeFile = writeFile root.statFile = statFile root.SimpyCons = SimpyCons root.simpyCons = simpyCons root.resolve = resolve root.lazy = lazy root.verboseMsg = verboseMsg root.maxInt = 9007199254740992 root.minInt = -root.maxInt root.funcInfo = funcInfo
true
### Copyright (C) 2013, PI:NAME:<NAME>END_PI, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### (window ? global).Leisure = root = (module ? {}).exports = (global?.Leisure ? module?.exports ? window?.Leisure) root.currentNameSpace = 'core' root.nameSpacePath = ['core'] #root.shouldNsLog = true root.shouldNsLog = false root.nsLog = (args...)-> if root.shouldNsLog then console.log args... (window ? global).verbose = {} verboseMsg = (label, msg...)-> if (window ? global).verbose[label] then console.log msg... if !btoa? then (window ? global).btoa = require 'btoa' defaultEnv = presentValue: (x)-> String(x) + '\n' values: {} errorHandlers: [] prompt: -> rz = (window ? global).resolve = (value)-> if typeof value == 'function' if typeof value.memo != 'undefined' then value.memo else if value.creationStack then value.creationStack = null if value.args then value.args = null value.memo = value() else value #global.lazy = (l)-> ->l #global.lazy = (l)-> if typeof l == 'function' # count=0 # -> # if count++ > 0 then console.log "EXTRA EXECUTION OF #{l}, #{new Error('stack').stack}" # l #else l (window ? global).lazy = (l)-> if typeof l == 'function' then l.memo = l else l readFile = (fileName, cont)-> defaultEnv.readFile fileName, cont writeFile = (fileName, data, cont)-> defaultEnv.writeFile fileName, data, cont readDir = (fileName, cont)-> defaultEnv.readDir fileName, cont statFile = (fileName, cont)-> defaultEnv.statFile fileName, cont root.trackCreation = false #root.trackVars = false #root.trackCreation = true root.trackVars = true funcInfo = (func)-> if func.leisureInfoNew then primConsFrom func.leisureInfoNew, 0 else if func.leisureInfo (window ? global).FUNC = func info = [] callInfo = func.leisureInfo while callInfo info.push resolve callInfo.arg if callInfo.name info.push callInfo.name break callInfo = callInfo.parent root.consFrom info.reverse() else rz L_nil primConsFrom = (array, index)-> if index >= array.length then rz L_nil else root.primCons array[index], primConsFrom array, index + 1 class SimpyCons constructor: (@head, @tail)-> toArray: -> @_array ? ( h = @ array = [] while h != null array.push h.head h = h.tail @_array = array) simpyCons = (a, b)-> new SimpyCons a, b slice = Array.prototype.slice concat = Array.prototype.concat (window ? global).Leisure_call = leisureCall = (f)-> baseLeisureCall f, 1, arguments (window ? global).Leisure_primCall = baseLeisureCall = (f, pos, args)-> while pos < args.length if typeof f != 'function' then throw new Error "TypeError: #{typeof f} is not a function: #{f}" if f.length <= args.length - pos oldF = f switch f.length when 1 then f = f args[pos] when 2 then f = f args[pos], args[pos + 1] when 3 then f = f args[pos], args[pos + 1], args[pos + 2] when 4 then f = f args[pos], args[pos + 1], args[pos + 2], args[pos + 3] else if f.leisureInfo || (pos == 0 && f.length == args.length) return f.apply null, (if pos == 0 then args else slice.call(args, pos)) f = f.apply null, slice.call(args, pos, pos + f.length) pos += oldF.length else prev = slice.call args, pos partial = -> newArgs = concat.call prev, slice.call arguments if newArgs.length == f.length then f.apply null, newArgs else baseLeisureCall f, 0, newArgs partial.leisurePartial = true partial.leisureInfo = genInfo f, args, f.leisureInfo return lazy partial if pos != args.length then console.log "BAD FINAL POSITION IN LEISURE CALL, ARG LENGTH IS #{args.length} BUT POSITION IS #{pos}" f genInfo = (func, args, oldInfo)-> for arg in args if !oldInfo then oldInfo = {name: func.leisureName, arg} else oldInfo = {arg: arg, parent: oldInfo} oldInfo testCount = 0 errors = '' test = (expected, actual)-> if JSON.stringify(expected) != JSON.stringify(actual) if errors.length then errors += '\n' errors += "TEST #{testCount} FAILED, EXPECTED #{JSON.stringify(expected)} BUT GOT #{JSON.stringify(actual)}" testCount++ (window ? global).Leisure_test_call = -> test [1, 2, 3], Leisure_call ((a, b)->(c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3], Leisure_call ((a, b, c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3], Leisure_call ((a)->(b, c)-> [a, b, c]), 1, 2, 3 test [1, 2, 3, 4], Leisure_call ((a)->(b, c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b, c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b)->(c)->(d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b)->(c, d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call ((a, b, c, d)-> [a, b, c, d]), 1, 2, 3, 4 test [1, 2, 3, 4], Leisure_call (Leisure_call ((a, b, c, d)-> [a, b, c, d]), 1, 2), 3, 4 if errors.length then errors else null serverIncrement = (path, amount, cont)-> block = root.getBlockNamed path.split(/\./)[0] if block.origin != root.currentDocument._name return root.storeBlock block, -> serverIncrement path, amount, cont if typeof path == 'function' then cont "Error, no path given to serverIncrement" else if typeof amount == 'function' then cont "Error, no amount given to serverIncrement" else Meteor.call 'incrementField', root.currentDocument.leisure.name, path, amount, cont root.serverIncrement = serverIncrement root.defaultEnv = defaultEnv root.readFile = readFile root.readDir = readDir root.writeFile = writeFile root.statFile = statFile root.SimpyCons = SimpyCons root.simpyCons = simpyCons root.resolve = resolve root.lazy = lazy root.verboseMsg = verboseMsg root.maxInt = 9007199254740992 root.minInt = -root.maxInt root.funcInfo = funcInfo
[ { "context": "ot of scantwo results (2-dim, 2-QTL genome scan)\n# Karl W Broman\n\niplotScantwo = (scantwo_data, pheno_and_geno, ch", "end": 94, "score": 0.9998127222061157, "start": 81, "tag": "NAME", "value": "Karl W Broman" } ]
inst/charts/iplotScantwo.coffee
FourchettesDeInterActive/qtlcharts
0
# iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan) # Karl W Broman iplotScantwo = (scantwo_data, pheno_and_geno, chartOpts) -> # chartOpts start pixelPerCell = chartOpts?.pixelPerCell ? null # pixels per cell in heat map chrGap = chartOpts?.chrGap ? 2 # gaps between chr in heat map wright = chartOpts?.wright ? 500 # width (in pixels) of right panels hbot = chartOpts?.hbot ? 150 # height (in pixels) of each of the lower panels margin = chartOpts?.margin ? {left:60, top:30, right:10, bottom: 40, inner: 5} # margins in each panel axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # axis positions in heatmap lightrect = chartOpts?.lightrect ? "#e6e6e6" # color for light rect in lower panels and backgrd in right panels darkrect = chartOpts?.darkrect ? "#c8c8c8" # dark rectangle in lower panels nullcolor = chartOpts?.nullcolor ? "#e6e6e6" # color of null pixels in heat map bordercolor = chartOpts?.bordercolor ? "black" # border color in heat map linecolor = chartOpts?.linecolor ? "slateblue" # line color in lower panels linewidth = chartOpts?.linewidth ? 2 # line width in lower panels pointsize = chartOpts?.pointsize ? 3 # point size in right panels pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle in right panels cicolors = chartOpts?.cicolors ? null # colors for CIs in QTL effect plot; also used for points in phe x gen plot color = chartOpts?.color ? "slateblue" # color for heat map oneAtTop = chartOpts?.oneAtTop ? false # whether to put chr 1 at top of heatmap zthresh = chartOpts?.zthresh ? 0 # LOD values below this threshold aren't shown (on LOD_full scale) # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' # size of heatmap region totmar = sumArray(scantwo_data.nmar) pixelPerCell = d3.max([2, Math.floor(600/totmar)]) unless pixelPerCell? w = chrGap*scantwo_data.chrnames.length + pixelPerCell*totmar heatmap_width = w + margin.left + margin.right heatmap_height = w + margin.top + margin.bottom hright = heatmap_height/2 - margin.top - margin.bottom totalw = heatmap_width + wright + margin.left + margin.right totalh = heatmap_height + (hbot + margin.top + margin.bottom)*2 # width of lower panels wbot = (totalw/2 - margin.left - margin.right) # selected LODs on left and right leftvalue = "int" rightvalue = "fv1" # cicolors: check they're the write length or estimate them if pheno_and_geno? gn = pheno_and_geno.genonames ncat = d3.max(gn[x].length for x of gn) if cicolors? # cicolors provided; expand to ncat cicolors = expand2vector(cicolors, ncat) n = cicolors.length if n < ncat # not enough, display error displayError("length(cicolors) (#{n}) < maximum no. genotypes (#{ncat})") cicolors = (cicolors[i % n] for i in [0...ncat]) else # not provided; select them cicolors = selectGroupColors(ncat, "dark") # drop-down menus options = ["full", "fv1", "int", "add", "av1"] div = d3.select("div##{chartdivid}") form = d3.select("body") .insert("div", "div##{chartdivid}") .attr("id", "form") left = form.append("div") .text(if oneAtTop then "bottom-left: " else "top-left: ") .style("float", "left") .style("margin-left", "150px") leftsel = left.append("select") .attr("id", "leftselect") .attr("name", "left") leftsel.selectAll("empty") .data(options) .enter() .append("option") .attr("value", (d) -> d) .text((d) -> d) .attr("selected", (d) -> return "selected" if d==leftvalue null) right = form.append("div") .text(if oneAtTop then "top-right: " else "bottom-right: ") .style("float", "left") .style("margin-left", "50px") rightsel = right.append("select") .attr("id", "rightselect") .attr("name", "right") rightsel.selectAll("empty") .data(options) .enter() .append("option") .attr("value", (d) -> d) .text((d) -> d) .attr("selected", (d) -> return "selected" if d==rightvalue null) submit = form.append("div") .style("float", "left") .style("margin-left", "50px") .append("button") .attr("name", "refresh") .text("Refresh") .on "click", () -> leftsel = document.getElementById('leftselect') leftvalue = leftsel.options[leftsel.selectedIndex].value rightsel = document.getElementById('rightselect') rightvalue = rightsel.options[rightsel.selectedIndex].value scantwo_data.z = lod_for_heatmap(scantwo_data, leftvalue, rightvalue) d3.select("g#chrheatmap svg").remove() d3.select("g#chrheatmap").datum(scantwo_data).call(mychrheatmap) add_cell_tooltips() d3.select("body") .insert("p", "div##{chartdivid}") # create SVG svg = d3.select("div##{chartdivid}") .append("svg") .attr("height", totalh) .attr("width", totalw) # add the full,add,int,fv1,av1 lod matrices to scantwo_data # (and remove the non-symmetric ones) scantwo_data = add_symmetric_lod(scantwo_data) scantwo_data.z = lod_for_heatmap(scantwo_data, leftvalue, rightvalue) mychrheatmap = chrheatmap().pixelPerCell(pixelPerCell) .chrGap(chrGap) .axispos(axispos) .rectcolor("white") .nullcolor(nullcolor) .bordercolor(bordercolor) .colors(["white",color]) .zlim([0, scantwo_data.max.full]) .zthresh(zthresh) .oneAtTop(oneAtTop) .hover(false) g_heatmap = svg.append("g") .attr("id", "chrheatmap") .datum(scantwo_data) .call(mychrheatmap) # function to add tool tips and handle clicking add_cell_tooltips = () -> d3.selectAll(".d3-tip").remove() celltip = d3.tip() .attr('class', 'd3-tip') .html((d) -> mari = scantwo_data.labels[d.i] marj = scantwo_data.labels[d.j] if +d.i > +d.j # +'s ensure number not string leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.i][d.j]) rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.j][d.i]) return "(#{marj} #{mari}) #{rightvalue} = #{rightlod}, #{leftvalue} = #{leftlod}" else if +d.j > +d.i leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.j][d.i]) rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.i][d.j]) return "(#{marj} #{mari}) #{leftvalue} = #{leftlod}, #{rightvalue} = #{rightlod}" else return mari ) .direction('e') .offset([0,10]) svg.call(celltip) cells = mychrheatmap.cellSelect() cells.on("mouseover", (d) -> celltip.show(d)) .on("mouseout", () -> celltip.hide()) .on "click", (d) -> mari = scantwo_data.labels[d.i] marj = scantwo_data.labels[d.j] return null if d.i == d.j # skip the diagonal case # plot the cross-sections as genome scans, below plot_scan(d.i, 0, 0, leftvalue) plot_scan(d.i, 1, 0, rightvalue) plot_scan(d.j, 0, 1, leftvalue) plot_scan(d.j, 1, 1, rightvalue) # plot the effect plot and phe x gen plot to right if pheno_and_geno? plot_effects(d.i, d.j) add_cell_tooltips() # to hold groups and positions of scan and effect plots g_scans = [[null,null], [null,null]] scans_hpos = [0, wbot+margin.left+margin.right] scans_vpos = [heatmap_height, heatmap_height+hbot+margin.top+margin.bottom] g_eff = [null, null] eff_hpos = [heatmap_width, heatmap_width] eff_vpos = [0, heatmap_height/2] plot_scan = (markerindex, panelrow, panelcol, lod) -> data = chrnames: scantwo_data.chrnames lodnames: ["lod"] chr: scantwo_data.chr pos: scantwo_data.pos lod: (x for x in scantwo_data[lod][markerindex]) markernames: scantwo_data.labels g_scans[panelrow][panelcol].remove() if g_scans[panelrow][panelcol]? mylodchart = lodchart().height(hbot) .width(wbot) .margin(margin) .axispos(axispos) .ylim([0.0, scantwo_data.max[lod]]) .lightrect(lightrect) .darkrect(darkrect) .linewidth(linewidth) .linecolor(linecolor) .pointsize(0) .pointcolor("") .pointstroke("") .lodvarname("lod") .xlab("") .title("#{data.markernames[markerindex]} : #{lod}") g_scans[panelrow][panelcol] = svg.append("g") .attr("id", "scan_#{panelrow+1}_#{panelcol+1}") .attr("transform", "translate(#{scans_hpos[panelcol]}, #{scans_vpos[panelrow]})") .datum(data) .call(mylodchart) plot_effects = (markerindex1, markerindex2) -> mar1 = scantwo_data.labels[markerindex1] mar2 = scantwo_data.labels[markerindex2] g1 = pheno_and_geno.geno[mar1] g2 = pheno_and_geno.geno[mar2] chr1 = pheno_and_geno.chr[mar1] chr2 = pheno_and_geno.chr[mar2] gnames1 = pheno_and_geno.genonames[chr1] gnames2 = pheno_and_geno.genonames[chr2] ng1 = gnames1.length ng2 = gnames2.length g = (g1[i] + (g2[i]-1)*ng1 for i of g1) gn1 = [] gn2 = [] cicolors_expanded = [] for i in [0...ng1] for j in [0...ng2] gn1.push(gnames1[i]) gn2.push(gnames2[j]) cicolors_expanded.push(cicolors[i]) for i in [0..1] g_eff[i].remove() if g_eff[i]? pxg_data = g:g y:pheno_and_geno.pheno indID:pheno_and_geno.indID mydotchart = dotchart().height(hright) .width(wright) .margin(margin) .axispos(axispos) .rectcolor(lightrect) .pointsize(3) .pointstroke(pointstroke) .xcategories([1..gn1.length]) .xcatlabels(gn1) .xlab("") .ylab("Phenotype") .xvar("g") .yvar("y") .dataByInd(false) .title("#{mar1} : #{mar2}") g_eff[1] = svg.append("g") .attr("id", "eff_1") .attr("transform", "translate(#{eff_hpos[1]}, #{eff_vpos[1]})") .datum(pxg_data) .call(mydotchart) # revise point colors mydotchart.pointsSelect() .attr("fill", (d,i) -> cicolors_expanded[g[i]-1]) cis = ci_by_group(g, pheno_and_geno.pheno, 2) ci_data = means: (cis[x]?.mean ? null for x in [1..gn1.length]) low: (cis[x]?.low ? null for x in [1..gn1.length]) high: (cis[x]?.high ? null for x in [1..gn1.length]) categories: [1..gn1.length] # adjust segment widths in ci chart xs = mydotchart.xscale() dif = xs(2) - xs(1) segwidth = if gn1.length > 9 then dif*0.5 else dif*0.25 mycichart = cichart().height(hright) .width(wright) .margin(margin) .axispos(axispos) .rectcolor(lightrect) .segcolor(cicolors_expanded) .segwidth(segwidth) .vertsegcolor(cicolors_expanded) .segstrokewidth(linewidth) .xlab("") .ylab("Phenotype") .xcatlabels(gn1) .title("#{mar1} : #{mar2}") g_eff[0] = svg.append("g") .attr("id", "eff_0") .attr("transform", "translate(#{eff_hpos[0]}, #{eff_vpos[0]})") .datum(ci_data) .call(mycichart) # add second row of labels for p in [0..1] g_eff[p].select("svg") .append("g").attr("class", "x axis") .selectAll("empty") .data(gn2) .enter() .append("text") .attr("x", (d,i) -> mydotchart.xscale()(i+1)) .attr("y", margin.top+hright+margin.bottom/2+axispos.xlabel) .text((d) -> d) g_eff[p].select("svg") .append("g").attr("class", "x axis") .selectAll("empty") .data([mar1, mar2]) .enter() .append("text") .attr("x", (margin.left + mydotchart.xscale()(1))/2.0) .attr("y", (d,i) -> margin.top+hright+margin.bottom/2*i+axispos.xlabel) .style("text-anchor", "end") .text((d) -> d + ":") # add full,add,int,av1,fv1 lod scores to scantwo_data add_symmetric_lod = (scantwo_data) -> scantwo_data.full = scantwo_data.lod.map (d) -> d.map (dd) -> dd scantwo_data.add = scantwo_data.lod.map (d) -> d.map (dd) -> dd scantwo_data.fv1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd scantwo_data.av1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd scantwo_data.int = scantwo_data.lod.map (d) -> d.map (dd) -> dd for i in [0...(scantwo_data.lod.length-1)] for j in [(i+1)...scantwo_data.lod[i].length] scantwo_data.full[i][j] = scantwo_data.lod[j][i] scantwo_data.add[j][i] = scantwo_data.lod[i][j] scantwo_data.fv1[i][j] = scantwo_data.lodv1[j][i] scantwo_data.av1[j][i] = scantwo_data.lodv1[i][j] scantwo_data.one = [] for i in [0...scantwo_data.lod.length] scantwo_data.full[i][i] = 0 scantwo_data.add[i][i] = 0 scantwo_data.fv1[i][i] = 0 scantwo_data.av1[i][i] = 0 scantwo_data.one.push(scantwo_data.lod[i]) for j in [0...scantwo_data.lod.length] scantwo_data.int[i][j] = scantwo_data.full[i][j] - scantwo_data.add[i][j] # delete the non-symmetric versions scantwo_data.lod = null scantwo_data.lodv1 = null scantwo_data.max = {} for i in ["full", "add", "fv1", "av1", "int"] scantwo_data.max[i] = matrixMax(scantwo_data[i]) scantwo_data lod_for_heatmap = (scantwo_data, left, right) -> # make copy of lod z = scantwo_data.full.map (d) -> d.map (dd) -> dd for i in [0...z.length] for j in [0...z.length] thelod = if j < i then right else left z[i][j] = scantwo_data[thelod][i][j]/scantwo_data.max[thelod]*scantwo_data.max["full"] z # return the matrix we created
35298
# iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan) # <NAME> iplotScantwo = (scantwo_data, pheno_and_geno, chartOpts) -> # chartOpts start pixelPerCell = chartOpts?.pixelPerCell ? null # pixels per cell in heat map chrGap = chartOpts?.chrGap ? 2 # gaps between chr in heat map wright = chartOpts?.wright ? 500 # width (in pixels) of right panels hbot = chartOpts?.hbot ? 150 # height (in pixels) of each of the lower panels margin = chartOpts?.margin ? {left:60, top:30, right:10, bottom: 40, inner: 5} # margins in each panel axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # axis positions in heatmap lightrect = chartOpts?.lightrect ? "#e6e6e6" # color for light rect in lower panels and backgrd in right panels darkrect = chartOpts?.darkrect ? "#c8c8c8" # dark rectangle in lower panels nullcolor = chartOpts?.nullcolor ? "#e6e6e6" # color of null pixels in heat map bordercolor = chartOpts?.bordercolor ? "black" # border color in heat map linecolor = chartOpts?.linecolor ? "slateblue" # line color in lower panels linewidth = chartOpts?.linewidth ? 2 # line width in lower panels pointsize = chartOpts?.pointsize ? 3 # point size in right panels pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle in right panels cicolors = chartOpts?.cicolors ? null # colors for CIs in QTL effect plot; also used for points in phe x gen plot color = chartOpts?.color ? "slateblue" # color for heat map oneAtTop = chartOpts?.oneAtTop ? false # whether to put chr 1 at top of heatmap zthresh = chartOpts?.zthresh ? 0 # LOD values below this threshold aren't shown (on LOD_full scale) # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' # size of heatmap region totmar = sumArray(scantwo_data.nmar) pixelPerCell = d3.max([2, Math.floor(600/totmar)]) unless pixelPerCell? w = chrGap*scantwo_data.chrnames.length + pixelPerCell*totmar heatmap_width = w + margin.left + margin.right heatmap_height = w + margin.top + margin.bottom hright = heatmap_height/2 - margin.top - margin.bottom totalw = heatmap_width + wright + margin.left + margin.right totalh = heatmap_height + (hbot + margin.top + margin.bottom)*2 # width of lower panels wbot = (totalw/2 - margin.left - margin.right) # selected LODs on left and right leftvalue = "int" rightvalue = "fv1" # cicolors: check they're the write length or estimate them if pheno_and_geno? gn = pheno_and_geno.genonames ncat = d3.max(gn[x].length for x of gn) if cicolors? # cicolors provided; expand to ncat cicolors = expand2vector(cicolors, ncat) n = cicolors.length if n < ncat # not enough, display error displayError("length(cicolors) (#{n}) < maximum no. genotypes (#{ncat})") cicolors = (cicolors[i % n] for i in [0...ncat]) else # not provided; select them cicolors = selectGroupColors(ncat, "dark") # drop-down menus options = ["full", "fv1", "int", "add", "av1"] div = d3.select("div##{chartdivid}") form = d3.select("body") .insert("div", "div##{chartdivid}") .attr("id", "form") left = form.append("div") .text(if oneAtTop then "bottom-left: " else "top-left: ") .style("float", "left") .style("margin-left", "150px") leftsel = left.append("select") .attr("id", "leftselect") .attr("name", "left") leftsel.selectAll("empty") .data(options) .enter() .append("option") .attr("value", (d) -> d) .text((d) -> d) .attr("selected", (d) -> return "selected" if d==leftvalue null) right = form.append("div") .text(if oneAtTop then "top-right: " else "bottom-right: ") .style("float", "left") .style("margin-left", "50px") rightsel = right.append("select") .attr("id", "rightselect") .attr("name", "right") rightsel.selectAll("empty") .data(options) .enter() .append("option") .attr("value", (d) -> d) .text((d) -> d) .attr("selected", (d) -> return "selected" if d==rightvalue null) submit = form.append("div") .style("float", "left") .style("margin-left", "50px") .append("button") .attr("name", "refresh") .text("Refresh") .on "click", () -> leftsel = document.getElementById('leftselect') leftvalue = leftsel.options[leftsel.selectedIndex].value rightsel = document.getElementById('rightselect') rightvalue = rightsel.options[rightsel.selectedIndex].value scantwo_data.z = lod_for_heatmap(scantwo_data, leftvalue, rightvalue) d3.select("g#chrheatmap svg").remove() d3.select("g#chrheatmap").datum(scantwo_data).call(mychrheatmap) add_cell_tooltips() d3.select("body") .insert("p", "div##{chartdivid}") # create SVG svg = d3.select("div##{chartdivid}") .append("svg") .attr("height", totalh) .attr("width", totalw) # add the full,add,int,fv1,av1 lod matrices to scantwo_data # (and remove the non-symmetric ones) scantwo_data = add_symmetric_lod(scantwo_data) scantwo_data.z = lod_for_heatmap(scantwo_data, leftvalue, rightvalue) mychrheatmap = chrheatmap().pixelPerCell(pixelPerCell) .chrGap(chrGap) .axispos(axispos) .rectcolor("white") .nullcolor(nullcolor) .bordercolor(bordercolor) .colors(["white",color]) .zlim([0, scantwo_data.max.full]) .zthresh(zthresh) .oneAtTop(oneAtTop) .hover(false) g_heatmap = svg.append("g") .attr("id", "chrheatmap") .datum(scantwo_data) .call(mychrheatmap) # function to add tool tips and handle clicking add_cell_tooltips = () -> d3.selectAll(".d3-tip").remove() celltip = d3.tip() .attr('class', 'd3-tip') .html((d) -> mari = scantwo_data.labels[d.i] marj = scantwo_data.labels[d.j] if +d.i > +d.j # +'s ensure number not string leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.i][d.j]) rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.j][d.i]) return "(#{marj} #{mari}) #{rightvalue} = #{rightlod}, #{leftvalue} = #{leftlod}" else if +d.j > +d.i leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.j][d.i]) rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.i][d.j]) return "(#{marj} #{mari}) #{leftvalue} = #{leftlod}, #{rightvalue} = #{rightlod}" else return mari ) .direction('e') .offset([0,10]) svg.call(celltip) cells = mychrheatmap.cellSelect() cells.on("mouseover", (d) -> celltip.show(d)) .on("mouseout", () -> celltip.hide()) .on "click", (d) -> mari = scantwo_data.labels[d.i] marj = scantwo_data.labels[d.j] return null if d.i == d.j # skip the diagonal case # plot the cross-sections as genome scans, below plot_scan(d.i, 0, 0, leftvalue) plot_scan(d.i, 1, 0, rightvalue) plot_scan(d.j, 0, 1, leftvalue) plot_scan(d.j, 1, 1, rightvalue) # plot the effect plot and phe x gen plot to right if pheno_and_geno? plot_effects(d.i, d.j) add_cell_tooltips() # to hold groups and positions of scan and effect plots g_scans = [[null,null], [null,null]] scans_hpos = [0, wbot+margin.left+margin.right] scans_vpos = [heatmap_height, heatmap_height+hbot+margin.top+margin.bottom] g_eff = [null, null] eff_hpos = [heatmap_width, heatmap_width] eff_vpos = [0, heatmap_height/2] plot_scan = (markerindex, panelrow, panelcol, lod) -> data = chrnames: scantwo_data.chrnames lodnames: ["lod"] chr: scantwo_data.chr pos: scantwo_data.pos lod: (x for x in scantwo_data[lod][markerindex]) markernames: scantwo_data.labels g_scans[panelrow][panelcol].remove() if g_scans[panelrow][panelcol]? mylodchart = lodchart().height(hbot) .width(wbot) .margin(margin) .axispos(axispos) .ylim([0.0, scantwo_data.max[lod]]) .lightrect(lightrect) .darkrect(darkrect) .linewidth(linewidth) .linecolor(linecolor) .pointsize(0) .pointcolor("") .pointstroke("") .lodvarname("lod") .xlab("") .title("#{data.markernames[markerindex]} : #{lod}") g_scans[panelrow][panelcol] = svg.append("g") .attr("id", "scan_#{panelrow+1}_#{panelcol+1}") .attr("transform", "translate(#{scans_hpos[panelcol]}, #{scans_vpos[panelrow]})") .datum(data) .call(mylodchart) plot_effects = (markerindex1, markerindex2) -> mar1 = scantwo_data.labels[markerindex1] mar2 = scantwo_data.labels[markerindex2] g1 = pheno_and_geno.geno[mar1] g2 = pheno_and_geno.geno[mar2] chr1 = pheno_and_geno.chr[mar1] chr2 = pheno_and_geno.chr[mar2] gnames1 = pheno_and_geno.genonames[chr1] gnames2 = pheno_and_geno.genonames[chr2] ng1 = gnames1.length ng2 = gnames2.length g = (g1[i] + (g2[i]-1)*ng1 for i of g1) gn1 = [] gn2 = [] cicolors_expanded = [] for i in [0...ng1] for j in [0...ng2] gn1.push(gnames1[i]) gn2.push(gnames2[j]) cicolors_expanded.push(cicolors[i]) for i in [0..1] g_eff[i].remove() if g_eff[i]? pxg_data = g:g y:pheno_and_geno.pheno indID:pheno_and_geno.indID mydotchart = dotchart().height(hright) .width(wright) .margin(margin) .axispos(axispos) .rectcolor(lightrect) .pointsize(3) .pointstroke(pointstroke) .xcategories([1..gn1.length]) .xcatlabels(gn1) .xlab("") .ylab("Phenotype") .xvar("g") .yvar("y") .dataByInd(false) .title("#{mar1} : #{mar2}") g_eff[1] = svg.append("g") .attr("id", "eff_1") .attr("transform", "translate(#{eff_hpos[1]}, #{eff_vpos[1]})") .datum(pxg_data) .call(mydotchart) # revise point colors mydotchart.pointsSelect() .attr("fill", (d,i) -> cicolors_expanded[g[i]-1]) cis = ci_by_group(g, pheno_and_geno.pheno, 2) ci_data = means: (cis[x]?.mean ? null for x in [1..gn1.length]) low: (cis[x]?.low ? null for x in [1..gn1.length]) high: (cis[x]?.high ? null for x in [1..gn1.length]) categories: [1..gn1.length] # adjust segment widths in ci chart xs = mydotchart.xscale() dif = xs(2) - xs(1) segwidth = if gn1.length > 9 then dif*0.5 else dif*0.25 mycichart = cichart().height(hright) .width(wright) .margin(margin) .axispos(axispos) .rectcolor(lightrect) .segcolor(cicolors_expanded) .segwidth(segwidth) .vertsegcolor(cicolors_expanded) .segstrokewidth(linewidth) .xlab("") .ylab("Phenotype") .xcatlabels(gn1) .title("#{mar1} : #{mar2}") g_eff[0] = svg.append("g") .attr("id", "eff_0") .attr("transform", "translate(#{eff_hpos[0]}, #{eff_vpos[0]})") .datum(ci_data) .call(mycichart) # add second row of labels for p in [0..1] g_eff[p].select("svg") .append("g").attr("class", "x axis") .selectAll("empty") .data(gn2) .enter() .append("text") .attr("x", (d,i) -> mydotchart.xscale()(i+1)) .attr("y", margin.top+hright+margin.bottom/2+axispos.xlabel) .text((d) -> d) g_eff[p].select("svg") .append("g").attr("class", "x axis") .selectAll("empty") .data([mar1, mar2]) .enter() .append("text") .attr("x", (margin.left + mydotchart.xscale()(1))/2.0) .attr("y", (d,i) -> margin.top+hright+margin.bottom/2*i+axispos.xlabel) .style("text-anchor", "end") .text((d) -> d + ":") # add full,add,int,av1,fv1 lod scores to scantwo_data add_symmetric_lod = (scantwo_data) -> scantwo_data.full = scantwo_data.lod.map (d) -> d.map (dd) -> dd scantwo_data.add = scantwo_data.lod.map (d) -> d.map (dd) -> dd scantwo_data.fv1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd scantwo_data.av1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd scantwo_data.int = scantwo_data.lod.map (d) -> d.map (dd) -> dd for i in [0...(scantwo_data.lod.length-1)] for j in [(i+1)...scantwo_data.lod[i].length] scantwo_data.full[i][j] = scantwo_data.lod[j][i] scantwo_data.add[j][i] = scantwo_data.lod[i][j] scantwo_data.fv1[i][j] = scantwo_data.lodv1[j][i] scantwo_data.av1[j][i] = scantwo_data.lodv1[i][j] scantwo_data.one = [] for i in [0...scantwo_data.lod.length] scantwo_data.full[i][i] = 0 scantwo_data.add[i][i] = 0 scantwo_data.fv1[i][i] = 0 scantwo_data.av1[i][i] = 0 scantwo_data.one.push(scantwo_data.lod[i]) for j in [0...scantwo_data.lod.length] scantwo_data.int[i][j] = scantwo_data.full[i][j] - scantwo_data.add[i][j] # delete the non-symmetric versions scantwo_data.lod = null scantwo_data.lodv1 = null scantwo_data.max = {} for i in ["full", "add", "fv1", "av1", "int"] scantwo_data.max[i] = matrixMax(scantwo_data[i]) scantwo_data lod_for_heatmap = (scantwo_data, left, right) -> # make copy of lod z = scantwo_data.full.map (d) -> d.map (dd) -> dd for i in [0...z.length] for j in [0...z.length] thelod = if j < i then right else left z[i][j] = scantwo_data[thelod][i][j]/scantwo_data.max[thelod]*scantwo_data.max["full"] z # return the matrix we created
true
# iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan) # PI:NAME:<NAME>END_PI iplotScantwo = (scantwo_data, pheno_and_geno, chartOpts) -> # chartOpts start pixelPerCell = chartOpts?.pixelPerCell ? null # pixels per cell in heat map chrGap = chartOpts?.chrGap ? 2 # gaps between chr in heat map wright = chartOpts?.wright ? 500 # width (in pixels) of right panels hbot = chartOpts?.hbot ? 150 # height (in pixels) of each of the lower panels margin = chartOpts?.margin ? {left:60, top:30, right:10, bottom: 40, inner: 5} # margins in each panel axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # axis positions in heatmap lightrect = chartOpts?.lightrect ? "#e6e6e6" # color for light rect in lower panels and backgrd in right panels darkrect = chartOpts?.darkrect ? "#c8c8c8" # dark rectangle in lower panels nullcolor = chartOpts?.nullcolor ? "#e6e6e6" # color of null pixels in heat map bordercolor = chartOpts?.bordercolor ? "black" # border color in heat map linecolor = chartOpts?.linecolor ? "slateblue" # line color in lower panels linewidth = chartOpts?.linewidth ? 2 # line width in lower panels pointsize = chartOpts?.pointsize ? 3 # point size in right panels pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle in right panels cicolors = chartOpts?.cicolors ? null # colors for CIs in QTL effect plot; also used for points in phe x gen plot color = chartOpts?.color ? "slateblue" # color for heat map oneAtTop = chartOpts?.oneAtTop ? false # whether to put chr 1 at top of heatmap zthresh = chartOpts?.zthresh ? 0 # LOD values below this threshold aren't shown (on LOD_full scale) # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' # size of heatmap region totmar = sumArray(scantwo_data.nmar) pixelPerCell = d3.max([2, Math.floor(600/totmar)]) unless pixelPerCell? w = chrGap*scantwo_data.chrnames.length + pixelPerCell*totmar heatmap_width = w + margin.left + margin.right heatmap_height = w + margin.top + margin.bottom hright = heatmap_height/2 - margin.top - margin.bottom totalw = heatmap_width + wright + margin.left + margin.right totalh = heatmap_height + (hbot + margin.top + margin.bottom)*2 # width of lower panels wbot = (totalw/2 - margin.left - margin.right) # selected LODs on left and right leftvalue = "int" rightvalue = "fv1" # cicolors: check they're the write length or estimate them if pheno_and_geno? gn = pheno_and_geno.genonames ncat = d3.max(gn[x].length for x of gn) if cicolors? # cicolors provided; expand to ncat cicolors = expand2vector(cicolors, ncat) n = cicolors.length if n < ncat # not enough, display error displayError("length(cicolors) (#{n}) < maximum no. genotypes (#{ncat})") cicolors = (cicolors[i % n] for i in [0...ncat]) else # not provided; select them cicolors = selectGroupColors(ncat, "dark") # drop-down menus options = ["full", "fv1", "int", "add", "av1"] div = d3.select("div##{chartdivid}") form = d3.select("body") .insert("div", "div##{chartdivid}") .attr("id", "form") left = form.append("div") .text(if oneAtTop then "bottom-left: " else "top-left: ") .style("float", "left") .style("margin-left", "150px") leftsel = left.append("select") .attr("id", "leftselect") .attr("name", "left") leftsel.selectAll("empty") .data(options) .enter() .append("option") .attr("value", (d) -> d) .text((d) -> d) .attr("selected", (d) -> return "selected" if d==leftvalue null) right = form.append("div") .text(if oneAtTop then "top-right: " else "bottom-right: ") .style("float", "left") .style("margin-left", "50px") rightsel = right.append("select") .attr("id", "rightselect") .attr("name", "right") rightsel.selectAll("empty") .data(options) .enter() .append("option") .attr("value", (d) -> d) .text((d) -> d) .attr("selected", (d) -> return "selected" if d==rightvalue null) submit = form.append("div") .style("float", "left") .style("margin-left", "50px") .append("button") .attr("name", "refresh") .text("Refresh") .on "click", () -> leftsel = document.getElementById('leftselect') leftvalue = leftsel.options[leftsel.selectedIndex].value rightsel = document.getElementById('rightselect') rightvalue = rightsel.options[rightsel.selectedIndex].value scantwo_data.z = lod_for_heatmap(scantwo_data, leftvalue, rightvalue) d3.select("g#chrheatmap svg").remove() d3.select("g#chrheatmap").datum(scantwo_data).call(mychrheatmap) add_cell_tooltips() d3.select("body") .insert("p", "div##{chartdivid}") # create SVG svg = d3.select("div##{chartdivid}") .append("svg") .attr("height", totalh) .attr("width", totalw) # add the full,add,int,fv1,av1 lod matrices to scantwo_data # (and remove the non-symmetric ones) scantwo_data = add_symmetric_lod(scantwo_data) scantwo_data.z = lod_for_heatmap(scantwo_data, leftvalue, rightvalue) mychrheatmap = chrheatmap().pixelPerCell(pixelPerCell) .chrGap(chrGap) .axispos(axispos) .rectcolor("white") .nullcolor(nullcolor) .bordercolor(bordercolor) .colors(["white",color]) .zlim([0, scantwo_data.max.full]) .zthresh(zthresh) .oneAtTop(oneAtTop) .hover(false) g_heatmap = svg.append("g") .attr("id", "chrheatmap") .datum(scantwo_data) .call(mychrheatmap) # function to add tool tips and handle clicking add_cell_tooltips = () -> d3.selectAll(".d3-tip").remove() celltip = d3.tip() .attr('class', 'd3-tip') .html((d) -> mari = scantwo_data.labels[d.i] marj = scantwo_data.labels[d.j] if +d.i > +d.j # +'s ensure number not string leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.i][d.j]) rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.j][d.i]) return "(#{marj} #{mari}) #{rightvalue} = #{rightlod}, #{leftvalue} = #{leftlod}" else if +d.j > +d.i leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.j][d.i]) rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.i][d.j]) return "(#{marj} #{mari}) #{leftvalue} = #{leftlod}, #{rightvalue} = #{rightlod}" else return mari ) .direction('e') .offset([0,10]) svg.call(celltip) cells = mychrheatmap.cellSelect() cells.on("mouseover", (d) -> celltip.show(d)) .on("mouseout", () -> celltip.hide()) .on "click", (d) -> mari = scantwo_data.labels[d.i] marj = scantwo_data.labels[d.j] return null if d.i == d.j # skip the diagonal case # plot the cross-sections as genome scans, below plot_scan(d.i, 0, 0, leftvalue) plot_scan(d.i, 1, 0, rightvalue) plot_scan(d.j, 0, 1, leftvalue) plot_scan(d.j, 1, 1, rightvalue) # plot the effect plot and phe x gen plot to right if pheno_and_geno? plot_effects(d.i, d.j) add_cell_tooltips() # to hold groups and positions of scan and effect plots g_scans = [[null,null], [null,null]] scans_hpos = [0, wbot+margin.left+margin.right] scans_vpos = [heatmap_height, heatmap_height+hbot+margin.top+margin.bottom] g_eff = [null, null] eff_hpos = [heatmap_width, heatmap_width] eff_vpos = [0, heatmap_height/2] plot_scan = (markerindex, panelrow, panelcol, lod) -> data = chrnames: scantwo_data.chrnames lodnames: ["lod"] chr: scantwo_data.chr pos: scantwo_data.pos lod: (x for x in scantwo_data[lod][markerindex]) markernames: scantwo_data.labels g_scans[panelrow][panelcol].remove() if g_scans[panelrow][panelcol]? mylodchart = lodchart().height(hbot) .width(wbot) .margin(margin) .axispos(axispos) .ylim([0.0, scantwo_data.max[lod]]) .lightrect(lightrect) .darkrect(darkrect) .linewidth(linewidth) .linecolor(linecolor) .pointsize(0) .pointcolor("") .pointstroke("") .lodvarname("lod") .xlab("") .title("#{data.markernames[markerindex]} : #{lod}") g_scans[panelrow][panelcol] = svg.append("g") .attr("id", "scan_#{panelrow+1}_#{panelcol+1}") .attr("transform", "translate(#{scans_hpos[panelcol]}, #{scans_vpos[panelrow]})") .datum(data) .call(mylodchart) plot_effects = (markerindex1, markerindex2) -> mar1 = scantwo_data.labels[markerindex1] mar2 = scantwo_data.labels[markerindex2] g1 = pheno_and_geno.geno[mar1] g2 = pheno_and_geno.geno[mar2] chr1 = pheno_and_geno.chr[mar1] chr2 = pheno_and_geno.chr[mar2] gnames1 = pheno_and_geno.genonames[chr1] gnames2 = pheno_and_geno.genonames[chr2] ng1 = gnames1.length ng2 = gnames2.length g = (g1[i] + (g2[i]-1)*ng1 for i of g1) gn1 = [] gn2 = [] cicolors_expanded = [] for i in [0...ng1] for j in [0...ng2] gn1.push(gnames1[i]) gn2.push(gnames2[j]) cicolors_expanded.push(cicolors[i]) for i in [0..1] g_eff[i].remove() if g_eff[i]? pxg_data = g:g y:pheno_and_geno.pheno indID:pheno_and_geno.indID mydotchart = dotchart().height(hright) .width(wright) .margin(margin) .axispos(axispos) .rectcolor(lightrect) .pointsize(3) .pointstroke(pointstroke) .xcategories([1..gn1.length]) .xcatlabels(gn1) .xlab("") .ylab("Phenotype") .xvar("g") .yvar("y") .dataByInd(false) .title("#{mar1} : #{mar2}") g_eff[1] = svg.append("g") .attr("id", "eff_1") .attr("transform", "translate(#{eff_hpos[1]}, #{eff_vpos[1]})") .datum(pxg_data) .call(mydotchart) # revise point colors mydotchart.pointsSelect() .attr("fill", (d,i) -> cicolors_expanded[g[i]-1]) cis = ci_by_group(g, pheno_and_geno.pheno, 2) ci_data = means: (cis[x]?.mean ? null for x in [1..gn1.length]) low: (cis[x]?.low ? null for x in [1..gn1.length]) high: (cis[x]?.high ? null for x in [1..gn1.length]) categories: [1..gn1.length] # adjust segment widths in ci chart xs = mydotchart.xscale() dif = xs(2) - xs(1) segwidth = if gn1.length > 9 then dif*0.5 else dif*0.25 mycichart = cichart().height(hright) .width(wright) .margin(margin) .axispos(axispos) .rectcolor(lightrect) .segcolor(cicolors_expanded) .segwidth(segwidth) .vertsegcolor(cicolors_expanded) .segstrokewidth(linewidth) .xlab("") .ylab("Phenotype") .xcatlabels(gn1) .title("#{mar1} : #{mar2}") g_eff[0] = svg.append("g") .attr("id", "eff_0") .attr("transform", "translate(#{eff_hpos[0]}, #{eff_vpos[0]})") .datum(ci_data) .call(mycichart) # add second row of labels for p in [0..1] g_eff[p].select("svg") .append("g").attr("class", "x axis") .selectAll("empty") .data(gn2) .enter() .append("text") .attr("x", (d,i) -> mydotchart.xscale()(i+1)) .attr("y", margin.top+hright+margin.bottom/2+axispos.xlabel) .text((d) -> d) g_eff[p].select("svg") .append("g").attr("class", "x axis") .selectAll("empty") .data([mar1, mar2]) .enter() .append("text") .attr("x", (margin.left + mydotchart.xscale()(1))/2.0) .attr("y", (d,i) -> margin.top+hright+margin.bottom/2*i+axispos.xlabel) .style("text-anchor", "end") .text((d) -> d + ":") # add full,add,int,av1,fv1 lod scores to scantwo_data add_symmetric_lod = (scantwo_data) -> scantwo_data.full = scantwo_data.lod.map (d) -> d.map (dd) -> dd scantwo_data.add = scantwo_data.lod.map (d) -> d.map (dd) -> dd scantwo_data.fv1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd scantwo_data.av1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd scantwo_data.int = scantwo_data.lod.map (d) -> d.map (dd) -> dd for i in [0...(scantwo_data.lod.length-1)] for j in [(i+1)...scantwo_data.lod[i].length] scantwo_data.full[i][j] = scantwo_data.lod[j][i] scantwo_data.add[j][i] = scantwo_data.lod[i][j] scantwo_data.fv1[i][j] = scantwo_data.lodv1[j][i] scantwo_data.av1[j][i] = scantwo_data.lodv1[i][j] scantwo_data.one = [] for i in [0...scantwo_data.lod.length] scantwo_data.full[i][i] = 0 scantwo_data.add[i][i] = 0 scantwo_data.fv1[i][i] = 0 scantwo_data.av1[i][i] = 0 scantwo_data.one.push(scantwo_data.lod[i]) for j in [0...scantwo_data.lod.length] scantwo_data.int[i][j] = scantwo_data.full[i][j] - scantwo_data.add[i][j] # delete the non-symmetric versions scantwo_data.lod = null scantwo_data.lodv1 = null scantwo_data.max = {} for i in ["full", "add", "fv1", "av1", "int"] scantwo_data.max[i] = matrixMax(scantwo_data[i]) scantwo_data lod_for_heatmap = (scantwo_data, left, right) -> # make copy of lod z = scantwo_data.full.map (d) -> d.map (dd) -> dd for i in [0...z.length] for j in [0...z.length] thelod = if j < i then right else left z[i][j] = scantwo_data[thelod][i][j]/scantwo_data.max[thelod]*scantwo_data.max["full"] z # return the matrix we created
[ { "context": "l_id: 'cell_chembl_id'\n bucket_key: 'BUCKET.key'\n extra_buckets: 'EXTRA_BUCKETS.key'", "end": 6906, "score": 0.849937915802002, "start": 6896, "tag": "KEY", "value": "BUCKET.key" }, { "context": "l_id: 'cell_chembl_id'\n bucket_k...
src/glados/static/coffee/cellLineReportCardApp.coffee
BNext-IQT/glados-frontend-chembl-main-interface
33
class CellLineReportCardApp extends glados.ReportCardApp # ------------------------------------------------------------- # Initialisation # ------------------------------------------------------------- @init = -> super cellLine = CellLineReportCardApp.getCurrentCellLine() breadcrumbLinks = [ { label: cellLine.get('id') link: CellLine.get_report_card_url(cellLine.get('id')) } ] glados.apps.BreadcrumbApp.setBreadCrumb(breadcrumbLinks) CellLineReportCardApp.initBasicInformation() CellLineReportCardApp.initAssaySummary() CellLineReportCardApp.initActivitySummary() CellLineReportCardApp.initAssociatedCompounds() cellLine.fetch() # ------------------------------------------------------------- # Singleton # ------------------------------------------------------------- @getCurrentCellLine = -> if not @currentCellLine? chemblID = glados.Utils.URLS.getCurrentModelChemblID() @currentCellLine = new CellLine cell_chembl_id: chemblID return @currentCellLine else return @currentCellLine # ------------------------------------------------------------- # Specific section initialization # this is functions only initialize a section of the report card # ------------------------------------------------------------- @initBasicInformation = -> cellLine = CellLineReportCardApp.getCurrentCellLine() new CellLineBasicInformationView model: cellLine el: $('#CBasicInformation') section_id: 'BasicInformation' section_label: 'Basic Information' entity_name: CellLine.prototype.entityName report_card_app: @ if GlobalVariables['EMBEDED'] cellLine.fetch() @initAssaySummary = -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() associatedAssays = CellLineReportCardApp.getAssociatedAssaysAgg(chemblID) associatedAssaysProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Cell', 'RELATED_ASSAYS') pieConfig = x_axis_prop_name: 'types' title: "ChEMBL Assay Types for Assay " + chemblID title_link_url: Assay.getAssaysListURL('cell_chembl_id:' + chemblID) max_categories: glados.Settings.PIECHARTS.MAX_CATEGORIES properties: types: associatedAssaysProp viewConfig = pie_config: pieConfig resource_type: CellLine.prototype.entityName link_to_all: link_text: 'See all assays for cell line ' + chemblID + ' used in this visualisation.' url: Assay.getAssaysListURL('cell_chembl_id:' + chemblID) embed_section_name: 'related_assays' embed_identifier: chemblID new glados.views.ReportCards.PieInCardView model: associatedAssays el: $('#CAssociatedAssaysCard') config: viewConfig section_id: 'ActivityCharts' section_label: 'Activity Charts' entity_name: CellLine.prototype.entityName report_card_app: @ associatedAssays.fetch() @initActivitySummary = -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() bioactivities = CellLineReportCardApp.getAssociatedBioactivitiesAgg(chemblID) bioactivitiesProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Cell', 'RELATED_ACTIVITIES') pieConfig = x_axis_prop_name: 'types' title: "ChEMBL Activity Types for Cell Line " + chemblID title_link_url: Activity.getActivitiesListURL('_metadata.assay_data.cell_chembl_id:' + chemblID) max_categories: glados.Settings.PIECHARTS.MAX_CATEGORIES properties: types: bioactivitiesProp viewConfig = pie_config: pieConfig resource_type: CellLine.prototype.entityName embed_section_name: 'bioactivities' embed_identifier: chemblID link_to_all: link_text: 'See all bioactivities for cell line ' + chemblID + ' used in this visualisation.' url: Activity.getActivitiesListURL('_metadata.assay_data.cell_chembl_id:' + chemblID) new glados.views.ReportCards.PieInCardView model: bioactivities el: $('#CLAssociatedActivitiesCard') config: viewConfig section_id: 'ActivityCharts' section_label: 'Activity Charts' entity_name: CellLine.prototype.entityName report_card_app: @ bioactivities.fetch() @initAssociatedCompounds = (chemblID) -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() associatedCompounds = CellLineReportCardApp.getAssociatedCompoundsAgg(chemblID) histogramConfig = big_size: true paint_axes_selectors: true properties: mwt: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FULL_MWT') alogp: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'ALogP') psa: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'PSA') initial_property_x: 'mwt' x_axis_options: ['mwt', 'alogp', 'psa'] x_axis_min_columns: 1 x_axis_max_columns: 20 x_axis_initial_num_columns: 10 x_axis_prop_name: 'x_axis_agg' title: 'Associated Compounds for Cell Line ' + chemblID title_link_url: Compound.getCompoundsListURL('_metadata.related_cell_lines.all_chembl_ids:' + chemblID) external_title: true range_categories: true config = histogram_config: histogramConfig resource_type: CellLine.prototype.entityName embed_section_name: 'related_compounds' embed_identifier: chemblID new glados.views.ReportCards.HistogramInCardView el: $('#CLAssociatedCompoundProperties') model: associatedCompounds target_chembl_id: chemblID config: config section_id: 'CompoundSummaries' section_label: 'Compound Summaries' entity_name: CellLine.prototype.entityName report_card_app: @ associatedCompounds.fetch() # ------------------------------------------------------------- # Aggregations # ------------------------------------------------------------- @getAssociatedAssaysAgg = (chemblID) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING query_string_template: 'cell_chembl_id:{{cell_chembl_id}}' template_data: cell_chembl_id: 'cell_chembl_id' aggsConfig = aggs: types: type: glados.models.Aggregations.Aggregation.AggTypes.TERMS field: '_metadata.assay_generated.type_label' size: 20 bucket_links: bucket_filter_template: 'cell_chembl_id:{{cell_chembl_id}} ' + 'AND _metadata.assay_generated.type_label:("{{bucket_key}}"' + '{{#each extra_buckets}} OR "{{this}}"{{/each}})' template_data: cell_chembl_id: 'cell_chembl_id' bucket_key: 'BUCKET.key' extra_buckets: 'EXTRA_BUCKETS.key' link_generator: Assay.getAssaysListURL associatedAssays = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.ASSAY_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return associatedAssays @getAssociatedBioactivitiesAgg = (chemblID) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING query_string_template: '_metadata.assay_data.cell_chembl_id:{{cell_chembl_id}}' template_data: cell_chembl_id: 'cell_chembl_id' aggsConfig = aggs: types: type: glados.models.Aggregations.Aggregation.AggTypes.TERMS field: 'standard_type' size: 20 bucket_links: bucket_filter_template: '_metadata.assay_data.cell_chembl_id:{{cell_chembl_id}} ' + 'AND standard_type:("{{bucket_key}}"' + '{{#each extra_buckets}} OR "{{this}}"{{/each}})' template_data: cell_chembl_id: 'cell_chembl_id' bucket_key: 'BUCKET.key' extra_buckets: 'EXTRA_BUCKETS.key' link_generator: Activity.getActivitiesListURL bioactivities = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.ACTIVITY_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return bioactivities @getAssociatedCompoundsAgg = (chemblID, minCols=1, maxCols=20, defaultCols=10) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.MULTIMATCH queryValueField: 'cell_chembl_id' fields: ['_metadata.related_cell_lines.all_chembl_ids'] aggsConfig = aggs: x_axis_agg: field: 'molecule_properties.full_mwt' type: glados.models.Aggregations.Aggregation.AggTypes.RANGE min_columns: minCols max_columns: maxCols num_columns: defaultCols bucket_links: bucket_filter_template: '_metadata.related_cell_lines.all_chembl_ids:{{cell_chembl_id}} ' + 'AND molecule_properties.full_mwt:(>={{min_val}} AND <={{max_val}})' template_data: cell_chembl_id: 'cell_chembl_id' min_val: 'BUCKET.from' max_val: 'BUCKETS.to' link_generator: Compound.getCompoundsListURL associatedCompounds = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return associatedCompounds # -------------------------------------------------------------------------------------------------------------------- # Mini histograms # -------------------------------------------------------------------------------------------------------------------- @initMiniActivitiesHistogram = ($containerElem, chemblID) -> bioactivities = CellLineReportCardApp.getAssociatedBioactivitiesAgg(chemblID) stdTypeProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Activity', 'STANDARD_TYPE', withColourScale=true) barsColourScale = stdTypeProp.colourScale config = max_categories: 8 bars_colour_scale: barsColourScale fixed_bar_width: true hide_title: false x_axis_prop_name: 'types' properties: std_type: stdTypeProp initial_property_x: 'std_type' new glados.views.Visualisation.HistogramView model: bioactivities el: $containerElem config: config bioactivities.fetch() @initMiniCompoundsHistogram = ($containerElem, chemblID) -> associatedCompounds = CellLineReportCardApp.getAssociatedCompoundsAgg(chemblID, minCols=8, maxCols=8, defaultCols=8) config = max_categories: 8 fixed_bar_width: true hide_title: false x_axis_prop_name: 'x_axis_agg' properties: mwt: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FULL_MWT') initial_property_x: 'mwt' new glados.views.Visualisation.HistogramView model: associatedCompounds el: $containerElem config: config associatedCompounds.fetch() @initMiniHistogramFromFunctionLink = -> $clickedLink = $(@) [paramsList, constantParamsList, $containerElem] = \ glados.views.PaginatedViews.PaginatedTable.prepareAndGetParamsFromFunctionLinkCell($clickedLink) histogramType = constantParamsList[0] chemblID = paramsList[0] if histogramType == 'activities' CellLineReportCardApp.initMiniActivitiesHistogram($containerElem, chemblID) else if histogramType == 'compounds' CellLineReportCardApp.initMiniCompoundsHistogram($containerElem, chemblID)
91911
class CellLineReportCardApp extends glados.ReportCardApp # ------------------------------------------------------------- # Initialisation # ------------------------------------------------------------- @init = -> super cellLine = CellLineReportCardApp.getCurrentCellLine() breadcrumbLinks = [ { label: cellLine.get('id') link: CellLine.get_report_card_url(cellLine.get('id')) } ] glados.apps.BreadcrumbApp.setBreadCrumb(breadcrumbLinks) CellLineReportCardApp.initBasicInformation() CellLineReportCardApp.initAssaySummary() CellLineReportCardApp.initActivitySummary() CellLineReportCardApp.initAssociatedCompounds() cellLine.fetch() # ------------------------------------------------------------- # Singleton # ------------------------------------------------------------- @getCurrentCellLine = -> if not @currentCellLine? chemblID = glados.Utils.URLS.getCurrentModelChemblID() @currentCellLine = new CellLine cell_chembl_id: chemblID return @currentCellLine else return @currentCellLine # ------------------------------------------------------------- # Specific section initialization # this is functions only initialize a section of the report card # ------------------------------------------------------------- @initBasicInformation = -> cellLine = CellLineReportCardApp.getCurrentCellLine() new CellLineBasicInformationView model: cellLine el: $('#CBasicInformation') section_id: 'BasicInformation' section_label: 'Basic Information' entity_name: CellLine.prototype.entityName report_card_app: @ if GlobalVariables['EMBEDED'] cellLine.fetch() @initAssaySummary = -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() associatedAssays = CellLineReportCardApp.getAssociatedAssaysAgg(chemblID) associatedAssaysProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Cell', 'RELATED_ASSAYS') pieConfig = x_axis_prop_name: 'types' title: "ChEMBL Assay Types for Assay " + chemblID title_link_url: Assay.getAssaysListURL('cell_chembl_id:' + chemblID) max_categories: glados.Settings.PIECHARTS.MAX_CATEGORIES properties: types: associatedAssaysProp viewConfig = pie_config: pieConfig resource_type: CellLine.prototype.entityName link_to_all: link_text: 'See all assays for cell line ' + chemblID + ' used in this visualisation.' url: Assay.getAssaysListURL('cell_chembl_id:' + chemblID) embed_section_name: 'related_assays' embed_identifier: chemblID new glados.views.ReportCards.PieInCardView model: associatedAssays el: $('#CAssociatedAssaysCard') config: viewConfig section_id: 'ActivityCharts' section_label: 'Activity Charts' entity_name: CellLine.prototype.entityName report_card_app: @ associatedAssays.fetch() @initActivitySummary = -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() bioactivities = CellLineReportCardApp.getAssociatedBioactivitiesAgg(chemblID) bioactivitiesProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Cell', 'RELATED_ACTIVITIES') pieConfig = x_axis_prop_name: 'types' title: "ChEMBL Activity Types for Cell Line " + chemblID title_link_url: Activity.getActivitiesListURL('_metadata.assay_data.cell_chembl_id:' + chemblID) max_categories: glados.Settings.PIECHARTS.MAX_CATEGORIES properties: types: bioactivitiesProp viewConfig = pie_config: pieConfig resource_type: CellLine.prototype.entityName embed_section_name: 'bioactivities' embed_identifier: chemblID link_to_all: link_text: 'See all bioactivities for cell line ' + chemblID + ' used in this visualisation.' url: Activity.getActivitiesListURL('_metadata.assay_data.cell_chembl_id:' + chemblID) new glados.views.ReportCards.PieInCardView model: bioactivities el: $('#CLAssociatedActivitiesCard') config: viewConfig section_id: 'ActivityCharts' section_label: 'Activity Charts' entity_name: CellLine.prototype.entityName report_card_app: @ bioactivities.fetch() @initAssociatedCompounds = (chemblID) -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() associatedCompounds = CellLineReportCardApp.getAssociatedCompoundsAgg(chemblID) histogramConfig = big_size: true paint_axes_selectors: true properties: mwt: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FULL_MWT') alogp: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'ALogP') psa: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'PSA') initial_property_x: 'mwt' x_axis_options: ['mwt', 'alogp', 'psa'] x_axis_min_columns: 1 x_axis_max_columns: 20 x_axis_initial_num_columns: 10 x_axis_prop_name: 'x_axis_agg' title: 'Associated Compounds for Cell Line ' + chemblID title_link_url: Compound.getCompoundsListURL('_metadata.related_cell_lines.all_chembl_ids:' + chemblID) external_title: true range_categories: true config = histogram_config: histogramConfig resource_type: CellLine.prototype.entityName embed_section_name: 'related_compounds' embed_identifier: chemblID new glados.views.ReportCards.HistogramInCardView el: $('#CLAssociatedCompoundProperties') model: associatedCompounds target_chembl_id: chemblID config: config section_id: 'CompoundSummaries' section_label: 'Compound Summaries' entity_name: CellLine.prototype.entityName report_card_app: @ associatedCompounds.fetch() # ------------------------------------------------------------- # Aggregations # ------------------------------------------------------------- @getAssociatedAssaysAgg = (chemblID) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING query_string_template: 'cell_chembl_id:{{cell_chembl_id}}' template_data: cell_chembl_id: 'cell_chembl_id' aggsConfig = aggs: types: type: glados.models.Aggregations.Aggregation.AggTypes.TERMS field: '_metadata.assay_generated.type_label' size: 20 bucket_links: bucket_filter_template: 'cell_chembl_id:{{cell_chembl_id}} ' + 'AND _metadata.assay_generated.type_label:("{{bucket_key}}"' + '{{#each extra_buckets}} OR "{{this}}"{{/each}})' template_data: cell_chembl_id: 'cell_chembl_id' bucket_key: '<KEY>' extra_buckets: 'EXTRA_BUCKETS.key' link_generator: Assay.getAssaysListURL associatedAssays = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.ASSAY_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return associatedAssays @getAssociatedBioactivitiesAgg = (chemblID) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING query_string_template: '_metadata.assay_data.cell_chembl_id:{{cell_chembl_id}}' template_data: cell_chembl_id: 'cell_chembl_id' aggsConfig = aggs: types: type: glados.models.Aggregations.Aggregation.AggTypes.TERMS field: 'standard_type' size: 20 bucket_links: bucket_filter_template: '_metadata.assay_data.cell_chembl_id:{{cell_chembl_id}} ' + 'AND standard_type:("{{bucket_key}}"' + '{{#each extra_buckets}} OR "{{this}}"{{/each}})' template_data: cell_chembl_id: 'cell_chembl_id' bucket_key: '<KEY>.key' extra_buckets: 'EXTRA_BUCKETS.key' link_generator: Activity.getActivitiesListURL bioactivities = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.ACTIVITY_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return bioactivities @getAssociatedCompoundsAgg = (chemblID, minCols=1, maxCols=20, defaultCols=10) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.MULTIMATCH queryValueField: 'cell_chembl_id' fields: ['_metadata.related_cell_lines.all_chembl_ids'] aggsConfig = aggs: x_axis_agg: field: 'molecule_properties.full_mwt' type: glados.models.Aggregations.Aggregation.AggTypes.RANGE min_columns: minCols max_columns: maxCols num_columns: defaultCols bucket_links: bucket_filter_template: '_metadata.related_cell_lines.all_chembl_ids:{{cell_chembl_id}} ' + 'AND molecule_properties.full_mwt:(>={{min_val}} AND <={{max_val}})' template_data: cell_chembl_id: 'cell_chembl_id' min_val: 'BUCKET.from' max_val: 'BUCKETS.to' link_generator: Compound.getCompoundsListURL associatedCompounds = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return associatedCompounds # -------------------------------------------------------------------------------------------------------------------- # Mini histograms # -------------------------------------------------------------------------------------------------------------------- @initMiniActivitiesHistogram = ($containerElem, chemblID) -> bioactivities = CellLineReportCardApp.getAssociatedBioactivitiesAgg(chemblID) stdTypeProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Activity', 'STANDARD_TYPE', withColourScale=true) barsColourScale = stdTypeProp.colourScale config = max_categories: 8 bars_colour_scale: barsColourScale fixed_bar_width: true hide_title: false x_axis_prop_name: 'types' properties: std_type: stdTypeProp initial_property_x: 'std_type' new glados.views.Visualisation.HistogramView model: bioactivities el: $containerElem config: config bioactivities.fetch() @initMiniCompoundsHistogram = ($containerElem, chemblID) -> associatedCompounds = CellLineReportCardApp.getAssociatedCompoundsAgg(chemblID, minCols=8, maxCols=8, defaultCols=8) config = max_categories: 8 fixed_bar_width: true hide_title: false x_axis_prop_name: 'x_axis_agg' properties: mwt: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FULL_MWT') initial_property_x: 'mwt' new glados.views.Visualisation.HistogramView model: associatedCompounds el: $containerElem config: config associatedCompounds.fetch() @initMiniHistogramFromFunctionLink = -> $clickedLink = $(@) [paramsList, constantParamsList, $containerElem] = \ glados.views.PaginatedViews.PaginatedTable.prepareAndGetParamsFromFunctionLinkCell($clickedLink) histogramType = constantParamsList[0] chemblID = paramsList[0] if histogramType == 'activities' CellLineReportCardApp.initMiniActivitiesHistogram($containerElem, chemblID) else if histogramType == 'compounds' CellLineReportCardApp.initMiniCompoundsHistogram($containerElem, chemblID)
true
class CellLineReportCardApp extends glados.ReportCardApp # ------------------------------------------------------------- # Initialisation # ------------------------------------------------------------- @init = -> super cellLine = CellLineReportCardApp.getCurrentCellLine() breadcrumbLinks = [ { label: cellLine.get('id') link: CellLine.get_report_card_url(cellLine.get('id')) } ] glados.apps.BreadcrumbApp.setBreadCrumb(breadcrumbLinks) CellLineReportCardApp.initBasicInformation() CellLineReportCardApp.initAssaySummary() CellLineReportCardApp.initActivitySummary() CellLineReportCardApp.initAssociatedCompounds() cellLine.fetch() # ------------------------------------------------------------- # Singleton # ------------------------------------------------------------- @getCurrentCellLine = -> if not @currentCellLine? chemblID = glados.Utils.URLS.getCurrentModelChemblID() @currentCellLine = new CellLine cell_chembl_id: chemblID return @currentCellLine else return @currentCellLine # ------------------------------------------------------------- # Specific section initialization # this is functions only initialize a section of the report card # ------------------------------------------------------------- @initBasicInformation = -> cellLine = CellLineReportCardApp.getCurrentCellLine() new CellLineBasicInformationView model: cellLine el: $('#CBasicInformation') section_id: 'BasicInformation' section_label: 'Basic Information' entity_name: CellLine.prototype.entityName report_card_app: @ if GlobalVariables['EMBEDED'] cellLine.fetch() @initAssaySummary = -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() associatedAssays = CellLineReportCardApp.getAssociatedAssaysAgg(chemblID) associatedAssaysProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Cell', 'RELATED_ASSAYS') pieConfig = x_axis_prop_name: 'types' title: "ChEMBL Assay Types for Assay " + chemblID title_link_url: Assay.getAssaysListURL('cell_chembl_id:' + chemblID) max_categories: glados.Settings.PIECHARTS.MAX_CATEGORIES properties: types: associatedAssaysProp viewConfig = pie_config: pieConfig resource_type: CellLine.prototype.entityName link_to_all: link_text: 'See all assays for cell line ' + chemblID + ' used in this visualisation.' url: Assay.getAssaysListURL('cell_chembl_id:' + chemblID) embed_section_name: 'related_assays' embed_identifier: chemblID new glados.views.ReportCards.PieInCardView model: associatedAssays el: $('#CAssociatedAssaysCard') config: viewConfig section_id: 'ActivityCharts' section_label: 'Activity Charts' entity_name: CellLine.prototype.entityName report_card_app: @ associatedAssays.fetch() @initActivitySummary = -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() bioactivities = CellLineReportCardApp.getAssociatedBioactivitiesAgg(chemblID) bioactivitiesProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Cell', 'RELATED_ACTIVITIES') pieConfig = x_axis_prop_name: 'types' title: "ChEMBL Activity Types for Cell Line " + chemblID title_link_url: Activity.getActivitiesListURL('_metadata.assay_data.cell_chembl_id:' + chemblID) max_categories: glados.Settings.PIECHARTS.MAX_CATEGORIES properties: types: bioactivitiesProp viewConfig = pie_config: pieConfig resource_type: CellLine.prototype.entityName embed_section_name: 'bioactivities' embed_identifier: chemblID link_to_all: link_text: 'See all bioactivities for cell line ' + chemblID + ' used in this visualisation.' url: Activity.getActivitiesListURL('_metadata.assay_data.cell_chembl_id:' + chemblID) new glados.views.ReportCards.PieInCardView model: bioactivities el: $('#CLAssociatedActivitiesCard') config: viewConfig section_id: 'ActivityCharts' section_label: 'Activity Charts' entity_name: CellLine.prototype.entityName report_card_app: @ bioactivities.fetch() @initAssociatedCompounds = (chemblID) -> chemblID = glados.Utils.URLS.getCurrentModelChemblID() associatedCompounds = CellLineReportCardApp.getAssociatedCompoundsAgg(chemblID) histogramConfig = big_size: true paint_axes_selectors: true properties: mwt: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FULL_MWT') alogp: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'ALogP') psa: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'PSA') initial_property_x: 'mwt' x_axis_options: ['mwt', 'alogp', 'psa'] x_axis_min_columns: 1 x_axis_max_columns: 20 x_axis_initial_num_columns: 10 x_axis_prop_name: 'x_axis_agg' title: 'Associated Compounds for Cell Line ' + chemblID title_link_url: Compound.getCompoundsListURL('_metadata.related_cell_lines.all_chembl_ids:' + chemblID) external_title: true range_categories: true config = histogram_config: histogramConfig resource_type: CellLine.prototype.entityName embed_section_name: 'related_compounds' embed_identifier: chemblID new glados.views.ReportCards.HistogramInCardView el: $('#CLAssociatedCompoundProperties') model: associatedCompounds target_chembl_id: chemblID config: config section_id: 'CompoundSummaries' section_label: 'Compound Summaries' entity_name: CellLine.prototype.entityName report_card_app: @ associatedCompounds.fetch() # ------------------------------------------------------------- # Aggregations # ------------------------------------------------------------- @getAssociatedAssaysAgg = (chemblID) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING query_string_template: 'cell_chembl_id:{{cell_chembl_id}}' template_data: cell_chembl_id: 'cell_chembl_id' aggsConfig = aggs: types: type: glados.models.Aggregations.Aggregation.AggTypes.TERMS field: '_metadata.assay_generated.type_label' size: 20 bucket_links: bucket_filter_template: 'cell_chembl_id:{{cell_chembl_id}} ' + 'AND _metadata.assay_generated.type_label:("{{bucket_key}}"' + '{{#each extra_buckets}} OR "{{this}}"{{/each}})' template_data: cell_chembl_id: 'cell_chembl_id' bucket_key: 'PI:KEY:<KEY>END_PI' extra_buckets: 'EXTRA_BUCKETS.key' link_generator: Assay.getAssaysListURL associatedAssays = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.ASSAY_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return associatedAssays @getAssociatedBioactivitiesAgg = (chemblID) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.QUERY_STRING query_string_template: '_metadata.assay_data.cell_chembl_id:{{cell_chembl_id}}' template_data: cell_chembl_id: 'cell_chembl_id' aggsConfig = aggs: types: type: glados.models.Aggregations.Aggregation.AggTypes.TERMS field: 'standard_type' size: 20 bucket_links: bucket_filter_template: '_metadata.assay_data.cell_chembl_id:{{cell_chembl_id}} ' + 'AND standard_type:("{{bucket_key}}"' + '{{#each extra_buckets}} OR "{{this}}"{{/each}})' template_data: cell_chembl_id: 'cell_chembl_id' bucket_key: 'PI:KEY:<KEY>END_PI.key' extra_buckets: 'EXTRA_BUCKETS.key' link_generator: Activity.getActivitiesListURL bioactivities = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.ACTIVITY_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return bioactivities @getAssociatedCompoundsAgg = (chemblID, minCols=1, maxCols=20, defaultCols=10) -> queryConfig = type: glados.models.Aggregations.Aggregation.QueryTypes.MULTIMATCH queryValueField: 'cell_chembl_id' fields: ['_metadata.related_cell_lines.all_chembl_ids'] aggsConfig = aggs: x_axis_agg: field: 'molecule_properties.full_mwt' type: glados.models.Aggregations.Aggregation.AggTypes.RANGE min_columns: minCols max_columns: maxCols num_columns: defaultCols bucket_links: bucket_filter_template: '_metadata.related_cell_lines.all_chembl_ids:{{cell_chembl_id}} ' + 'AND molecule_properties.full_mwt:(>={{min_val}} AND <={{max_val}})' template_data: cell_chembl_id: 'cell_chembl_id' min_val: 'BUCKET.from' max_val: 'BUCKETS.to' link_generator: Compound.getCompoundsListURL associatedCompounds = new glados.models.Aggregations.Aggregation index_url: glados.models.Aggregations.Aggregation.COMPOUND_INDEX_URL query_config: queryConfig cell_chembl_id: chemblID aggs_config: aggsConfig return associatedCompounds # -------------------------------------------------------------------------------------------------------------------- # Mini histograms # -------------------------------------------------------------------------------------------------------------------- @initMiniActivitiesHistogram = ($containerElem, chemblID) -> bioactivities = CellLineReportCardApp.getAssociatedBioactivitiesAgg(chemblID) stdTypeProp = glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Activity', 'STANDARD_TYPE', withColourScale=true) barsColourScale = stdTypeProp.colourScale config = max_categories: 8 bars_colour_scale: barsColourScale fixed_bar_width: true hide_title: false x_axis_prop_name: 'types' properties: std_type: stdTypeProp initial_property_x: 'std_type' new glados.views.Visualisation.HistogramView model: bioactivities el: $containerElem config: config bioactivities.fetch() @initMiniCompoundsHistogram = ($containerElem, chemblID) -> associatedCompounds = CellLineReportCardApp.getAssociatedCompoundsAgg(chemblID, minCols=8, maxCols=8, defaultCols=8) config = max_categories: 8 fixed_bar_width: true hide_title: false x_axis_prop_name: 'x_axis_agg' properties: mwt: glados.models.visualisation.PropertiesFactory.getPropertyConfigFor('Compound', 'FULL_MWT') initial_property_x: 'mwt' new glados.views.Visualisation.HistogramView model: associatedCompounds el: $containerElem config: config associatedCompounds.fetch() @initMiniHistogramFromFunctionLink = -> $clickedLink = $(@) [paramsList, constantParamsList, $containerElem] = \ glados.views.PaginatedViews.PaginatedTable.prepareAndGetParamsFromFunctionLinkCell($clickedLink) histogramType = constantParamsList[0] chemblID = paramsList[0] if histogramType == 'activities' CellLineReportCardApp.initMiniActivitiesHistogram($containerElem, chemblID) else if histogramType == 'compounds' CellLineReportCardApp.initMiniCompoundsHistogram($containerElem, chemblID)
[ { "context": "file': 'enableLoad'\n 'keyup input:password': 'enableLoadVsac'\n 'change input:password': 'enableLoadVsac'\n ", "end": 1860, "score": 0.9985111951828003, "start": 1846, "tag": "PASSWORD", "value": "enableLoadVsac" }, { "context": "': 'enableLoadVsac'\n 'chang...
app/assets/javascripts/views/import_measure_view.js.coffee
projectcypress/bonnie
33
class Thorax.Views.ImportMeasure extends Thorax.Views.BonnieView template: JST['import/import_measure'] initialize: -> @programReleaseNamesCache = {} context: -> hqmfSetId = @model.get('cqmMeasure').hqmf_set_id if @model? calculationTypeLabel = if @model? if (@model.get('cqmMeasure').calculation_method == 'EPISODE_OF_CARE') is false and @model.get('cqmMeasure').measure_scoring is 'PROPORTION' then 'Patient Based' else if (@model.get('cqmMeasure').calculation_method == 'EPISODE_OF_CARE') is true then 'Episode of Care' else if @model.get('cqmMeasure').measure_scoring is 'CONTINUOUS_VARIABLE' then 'Continuous Variable' calcSDEs = @model.get('cqmMeasure').calculate_sdes if @model? currentRoute = Backbone.history.fragment _(super).extend titleSize: 3 dataSize: 9 token: $("meta[name='csrf-token']").attr('content') dialogTitle: if @model? then @model.get('cqmMeasure').title else "New Measure" isUpdate: @model? showLoadInformation: !@model? && @firstMeasure calculationTypeLabel: calculationTypeLabel calcSDEs: calcSDEs hqmfSetId: hqmfSetId redirectRoute: currentRoute defaultProgram: Thorax.Views.ImportMeasure.defaultProgram events: rendered: -> @$("option[value=\"#{eoc}\"]").attr('selected','selected') for eoc in @model.get('episode_ids') if @model? && @model.get('episode_of_care') && @model.get('episode_ids')? @$el.on 'hidden.bs.modal', -> @remove() unless $('#pleaseWaitDialog').is(':visible') @$("input[type=radio]:checked").next().css("color","white") # start load of profile names @loadProfileNames() # enable tooltips @$('a[data-toggle="popover"]').popover({ html: true }) 'ready': 'setup' 'change input:file': 'enableLoad' 'keyup input:password': 'enableLoadVsac' 'change input:password': 'enableLoadVsac' 'change input[type=radio]': -> @$('input[type=radio]').each (index, element) => if @$(element).prop("checked") @$(element).next().css("color","white") else @$(element).next().css("color","") 'change input[name="vsac_query_type"]': 'changeQueryType' 'change select[name="vsac_query_program"]': 'changeProgram' 'click #clearVSACCreds': 'clearCachedVSACTicket' 'vsac:param-load-error': 'showVSACError' enableLoadVsac: -> vsacApiKey = @$('#vsacApiKey') if (vsacApiKey.val().length > 0) vsacApiKey.closest('.form-group').removeClass('has-error') hasUser = true @$('#loadButton').prop('disabled', !hasUser) clearCachedVSACTicket: -> @$('#vsacSignIn').removeClass('hidden') @$('#vsac-query-settings').removeClass('hidden') @$('#vsacCachedMsg').addClass('hidden') @$('#loadButton').prop('disabled', true) $.post '/vsac_util/auth_expire' toggleVSAC: -> $.ajax url: '/vsac_util/auth_valid' success: (data, textStatus, jqXHR) -> if data? && data.valid $('#vsacSignIn').addClass('hidden') $('#vsac-query-settings').removeClass('hidden') $('#vsacCachedMsg').removeClass('hidden') $('#loadButton').prop('disabled', false) # If the measure import window is open long enough for the VSAC # credentials to expire, we need to reshow the vsacApiKey dialog. setTimeout -> @clearCachedVSACTicket() , new Date(data.expires) - new Date() else $('#vsacSignIn').removeClass('hidden') $('#vsac-query-settings').removeClass('hidden') $('#vsacCachedMsg').addClass('hidden') enableLoad: -> @toggleVSAC() ###* # Loads the program list and release names for the default program and populates the program # and release select boxes. This is called when the user switches to releases. ### loadProgramsAndDefaultProgramReleases: -> # only do this is if we dont have the programNames list if !@programNames? programSelect = @$('#vsac-query-program').prop('disabled', true) releaseSelect = @$('#vsac-query-release').prop('disabled', true) @populateSelectBox programSelect, ['Loading...'] @populateSelectBox releaseSelect, ['Loading...'] $.getJSON('/vsac_util/program_names') .done (data) => @programNames = data.programNames @populateSelectBox programSelect, @programNames, Thorax.Views.ImportMeasure.defaultProgram # Load the default program if it is found if @programNames.indexOf(Thorax.Views.ImportMeasure.defaultProgram) >= 0 @loadProgramReleaseNames Thorax.Views.ImportMeasure.defaultProgram, => @trigger 'vsac:default-program-loaded' # Otherwise load the first in the list else @loadProgramReleaseNames @programNames[0], => @trigger 'vsac:default-program-loaded' .fail => @trigger 'vsac:param-load-error' ###* # Event handler for program change. This kicks off the change of the release names select box. ### changeProgram: -> @loadProgramReleaseNames(@$('#vsac-query-program').val()) ###* # Loads the VSAC release names for a given profile and populates the select box. # This will use the cached release names if we had already loaded them for the given program. # # @param {String} program - The VSAC program to load. # @param {Function} callback - Optional callback for when this is complete. ### loadProgramReleaseNames: (program, callback) -> releaseSelect = @$('#vsac-query-release') programSelect = @$('#vsac-query-program') if @programReleaseNamesCache[program]? @populateSelectBox releaseSelect, @programReleaseNamesCache[program] @trigger 'vsac:release-list-updated' else # Disable both dropdowns and put "Loading..."" in place. programSelect.prop('disabled', true) releaseSelect.prop('disabled', true) @populateSelectBox releaseSelect, ['Loading...'] # begin request $.getJSON("/vsac_util/program_release_names/#{program}") .done (data) => @programReleaseNamesCache[program] = data.releaseNames @populateSelectBox releaseSelect, @programReleaseNamesCache[program], Thorax.Views.ImportMeasure.defaultRelease releaseSelect.prop('disabled', false) programSelect.prop('disabled', false) @trigger 'vsac:release-list-updated' callback() if callback .fail => @trigger 'vsac:param-load-error' ###* # Loads the VSAC profile names from the back end and populates the select box. ### loadProfileNames: -> profileSelect = @$('#vsac-query-profile').prop('disabled', true) @populateSelectBox profileSelect, ['Loading...'] $.getJSON("/vsac_util/profile_names") .done (data) => @profileNames = data.profileNames @latestProfile = data.latestProfile # Map for changing option text for the latest profile to put the profile in double angle brackets and # prefix the option with 'Latest eCQM'. optionTextMap = {} optionTextMap[@latestProfile] = "Latest eCQM&#x300a;#{@latestProfile}&#x300b;" @populateSelectBox profileSelect, @profileNames, @latestProfile, optionTextMap @trigger 'vsac:profiles-loaded' profileSelect.prop('disabled', false) .fail => @trigger 'vsac:param-load-error' ###* # Shows a bonnie error for VSAC parameter loading errors. ### showVSACError: -> bonnie.showError( title: "VSAC Error" summary: 'There was an error retrieving VSAC options.' body: 'Please reload Bonnie and try again.') ###* # Repopulates a select box with options. Optionally setting a default option or alternate text. # # @param {jQuery Element} selectBox - The jQuery element for the select box to refill. # @param {Array} options - List of options. # @param {String} defaultOption - Optional. Default option to select if found. # @param {Object} optionTextMap - Optional. For any options that require text to be different than value, this # parameter can be used to define different option text. ex: # { "eCQM Update 2018-05-04": "Latest eCQM - eCQM Update 2018-05-04"} ### populateSelectBox: (selectBox, options, defaultOption, optionTextMap) -> selectBox.empty() for option in options optionText = if optionTextMap?[option]? then optionTextMap[option] else option if option == defaultOption selectBox.append("<option value=\"#{option}\" selected=\"selected\">#{optionText}</option>") else selectBox.append("<option value=\"#{option}\">#{optionText}</option>") ###* # Event handler for query type selector change. This changes out the query parameters # that the user sees. ### changeQueryType: -> queryType = @$('input[name=vsac_query_type]:checked').val(); switch queryType when 'release' @$('#vsac-query-release-params').removeClass('hidden') @$('#vsac-query-profile-params').addClass('hidden') @loadProgramsAndDefaultProgramReleases() when 'profile' @$('#vsac-query-release-params').addClass('hidden') @$('#vsac-query-profile-params').removeClass('hidden') setup: -> @importDialog = @$("#importMeasureDialog") @importWait = @$("#pleaseWaitDialog") @finalizeDialog = @$("#finalizeMeasureDialog") display: -> @importDialog.modal( "backdrop" : "static", "keyboard" : true, "show" : true) @$('.nice_input').bootstrapFileInput() submit: -> @importWait.modal( "backdrop" : "static", "keyboard" : false, "show" : true) @importDialog.modal('hide') @$('form').trigger('submit') # FIXME: Is anything additional required for cleaning up this view on close? close: -> ''
158354
class Thorax.Views.ImportMeasure extends Thorax.Views.BonnieView template: JST['import/import_measure'] initialize: -> @programReleaseNamesCache = {} context: -> hqmfSetId = @model.get('cqmMeasure').hqmf_set_id if @model? calculationTypeLabel = if @model? if (@model.get('cqmMeasure').calculation_method == 'EPISODE_OF_CARE') is false and @model.get('cqmMeasure').measure_scoring is 'PROPORTION' then 'Patient Based' else if (@model.get('cqmMeasure').calculation_method == 'EPISODE_OF_CARE') is true then 'Episode of Care' else if @model.get('cqmMeasure').measure_scoring is 'CONTINUOUS_VARIABLE' then 'Continuous Variable' calcSDEs = @model.get('cqmMeasure').calculate_sdes if @model? currentRoute = Backbone.history.fragment _(super).extend titleSize: 3 dataSize: 9 token: $("meta[name='csrf-token']").attr('content') dialogTitle: if @model? then @model.get('cqmMeasure').title else "New Measure" isUpdate: @model? showLoadInformation: !@model? && @firstMeasure calculationTypeLabel: calculationTypeLabel calcSDEs: calcSDEs hqmfSetId: hqmfSetId redirectRoute: currentRoute defaultProgram: Thorax.Views.ImportMeasure.defaultProgram events: rendered: -> @$("option[value=\"#{eoc}\"]").attr('selected','selected') for eoc in @model.get('episode_ids') if @model? && @model.get('episode_of_care') && @model.get('episode_ids')? @$el.on 'hidden.bs.modal', -> @remove() unless $('#pleaseWaitDialog').is(':visible') @$("input[type=radio]:checked").next().css("color","white") # start load of profile names @loadProfileNames() # enable tooltips @$('a[data-toggle="popover"]').popover({ html: true }) 'ready': 'setup' 'change input:file': 'enableLoad' 'keyup input:password': '<PASSWORD>' 'change input:password': '<PASSWORD>' 'change input[type=radio]': -> @$('input[type=radio]').each (index, element) => if @$(element).prop("checked") @$(element).next().css("color","white") else @$(element).next().css("color","") 'change input[name="vsac_query_type"]': 'changeQueryType' 'change select[name="vsac_query_program"]': 'changeProgram' 'click #clearVSACCreds': 'clearCachedVSACTicket' 'vsac:param-load-error': 'showVSACError' enableLoadVsac: -> vsacApiKey = @$('#vsacApiKey') if (vsacApiKey.val().length > 0) vsacApiKey.closest('.form-group').removeClass('has-error') hasUser = true @$('#loadButton').prop('disabled', !hasUser) clearCachedVSACTicket: -> @$('#vsacSignIn').removeClass('hidden') @$('#vsac-query-settings').removeClass('hidden') @$('#vsacCachedMsg').addClass('hidden') @$('#loadButton').prop('disabled', true) $.post '/vsac_util/auth_expire' toggleVSAC: -> $.ajax url: '/vsac_util/auth_valid' success: (data, textStatus, jqXHR) -> if data? && data.valid $('#vsacSignIn').addClass('hidden') $('#vsac-query-settings').removeClass('hidden') $('#vsacCachedMsg').removeClass('hidden') $('#loadButton').prop('disabled', false) # If the measure import window is open long enough for the VSAC # credentials to expire, we need to reshow the vsacApiKey dialog. setTimeout -> @clearCachedVSACTicket() , new Date(data.expires) - new Date() else $('#vsacSignIn').removeClass('hidden') $('#vsac-query-settings').removeClass('hidden') $('#vsacCachedMsg').addClass('hidden') enableLoad: -> @toggleVSAC() ###* # Loads the program list and release names for the default program and populates the program # and release select boxes. This is called when the user switches to releases. ### loadProgramsAndDefaultProgramReleases: -> # only do this is if we dont have the programNames list if !@programNames? programSelect = @$('#vsac-query-program').prop('disabled', true) releaseSelect = @$('#vsac-query-release').prop('disabled', true) @populateSelectBox programSelect, ['Loading...'] @populateSelectBox releaseSelect, ['Loading...'] $.getJSON('/vsac_util/program_names') .done (data) => @programNames = data.programNames @populateSelectBox programSelect, @programNames, Thorax.Views.ImportMeasure.defaultProgram # Load the default program if it is found if @programNames.indexOf(Thorax.Views.ImportMeasure.defaultProgram) >= 0 @loadProgramReleaseNames Thorax.Views.ImportMeasure.defaultProgram, => @trigger 'vsac:default-program-loaded' # Otherwise load the first in the list else @loadProgramReleaseNames @programNames[0], => @trigger 'vsac:default-program-loaded' .fail => @trigger 'vsac:param-load-error' ###* # Event handler for program change. This kicks off the change of the release names select box. ### changeProgram: -> @loadProgramReleaseNames(@$('#vsac-query-program').val()) ###* # Loads the VSAC release names for a given profile and populates the select box. # This will use the cached release names if we had already loaded them for the given program. # # @param {String} program - The VSAC program to load. # @param {Function} callback - Optional callback for when this is complete. ### loadProgramReleaseNames: (program, callback) -> releaseSelect = @$('#vsac-query-release') programSelect = @$('#vsac-query-program') if @programReleaseNamesCache[program]? @populateSelectBox releaseSelect, @programReleaseNamesCache[program] @trigger 'vsac:release-list-updated' else # Disable both dropdowns and put "Loading..."" in place. programSelect.prop('disabled', true) releaseSelect.prop('disabled', true) @populateSelectBox releaseSelect, ['Loading...'] # begin request $.getJSON("/vsac_util/program_release_names/#{program}") .done (data) => @programReleaseNamesCache[program] = data.releaseNames @populateSelectBox releaseSelect, @programReleaseNamesCache[program], Thorax.Views.ImportMeasure.defaultRelease releaseSelect.prop('disabled', false) programSelect.prop('disabled', false) @trigger 'vsac:release-list-updated' callback() if callback .fail => @trigger 'vsac:param-load-error' ###* # Loads the VSAC profile names from the back end and populates the select box. ### loadProfileNames: -> profileSelect = @$('#vsac-query-profile').prop('disabled', true) @populateSelectBox profileSelect, ['Loading...'] $.getJSON("/vsac_util/profile_names") .done (data) => @profileNames = data.profileNames @latestProfile = data.latestProfile # Map for changing option text for the latest profile to put the profile in double angle brackets and # prefix the option with 'Latest eCQM'. optionTextMap = {} optionTextMap[@latestProfile] = "Latest eCQM&#x300a;#{@latestProfile}&#x300b;" @populateSelectBox profileSelect, @profileNames, @latestProfile, optionTextMap @trigger 'vsac:profiles-loaded' profileSelect.prop('disabled', false) .fail => @trigger 'vsac:param-load-error' ###* # Shows a bonnie error for VSAC parameter loading errors. ### showVSACError: -> bonnie.showError( title: "VSAC Error" summary: 'There was an error retrieving VSAC options.' body: 'Please reload Bonnie and try again.') ###* # Repopulates a select box with options. Optionally setting a default option or alternate text. # # @param {jQuery Element} selectBox - The jQuery element for the select box to refill. # @param {Array} options - List of options. # @param {String} defaultOption - Optional. Default option to select if found. # @param {Object} optionTextMap - Optional. For any options that require text to be different than value, this # parameter can be used to define different option text. ex: # { "eCQM Update 2018-05-04": "Latest eCQM - eCQM Update 2018-05-04"} ### populateSelectBox: (selectBox, options, defaultOption, optionTextMap) -> selectBox.empty() for option in options optionText = if optionTextMap?[option]? then optionTextMap[option] else option if option == defaultOption selectBox.append("<option value=\"#{option}\" selected=\"selected\">#{optionText}</option>") else selectBox.append("<option value=\"#{option}\">#{optionText}</option>") ###* # Event handler for query type selector change. This changes out the query parameters # that the user sees. ### changeQueryType: -> queryType = @$('input[name=vsac_query_type]:checked').val(); switch queryType when 'release' @$('#vsac-query-release-params').removeClass('hidden') @$('#vsac-query-profile-params').addClass('hidden') @loadProgramsAndDefaultProgramReleases() when 'profile' @$('#vsac-query-release-params').addClass('hidden') @$('#vsac-query-profile-params').removeClass('hidden') setup: -> @importDialog = @$("#importMeasureDialog") @importWait = @$("#pleaseWaitDialog") @finalizeDialog = @$("#finalizeMeasureDialog") display: -> @importDialog.modal( "backdrop" : "static", "keyboard" : true, "show" : true) @$('.nice_input').bootstrapFileInput() submit: -> @importWait.modal( "backdrop" : "static", "keyboard" : false, "show" : true) @importDialog.modal('hide') @$('form').trigger('submit') # FIXME: Is anything additional required for cleaning up this view on close? close: -> ''
true
class Thorax.Views.ImportMeasure extends Thorax.Views.BonnieView template: JST['import/import_measure'] initialize: -> @programReleaseNamesCache = {} context: -> hqmfSetId = @model.get('cqmMeasure').hqmf_set_id if @model? calculationTypeLabel = if @model? if (@model.get('cqmMeasure').calculation_method == 'EPISODE_OF_CARE') is false and @model.get('cqmMeasure').measure_scoring is 'PROPORTION' then 'Patient Based' else if (@model.get('cqmMeasure').calculation_method == 'EPISODE_OF_CARE') is true then 'Episode of Care' else if @model.get('cqmMeasure').measure_scoring is 'CONTINUOUS_VARIABLE' then 'Continuous Variable' calcSDEs = @model.get('cqmMeasure').calculate_sdes if @model? currentRoute = Backbone.history.fragment _(super).extend titleSize: 3 dataSize: 9 token: $("meta[name='csrf-token']").attr('content') dialogTitle: if @model? then @model.get('cqmMeasure').title else "New Measure" isUpdate: @model? showLoadInformation: !@model? && @firstMeasure calculationTypeLabel: calculationTypeLabel calcSDEs: calcSDEs hqmfSetId: hqmfSetId redirectRoute: currentRoute defaultProgram: Thorax.Views.ImportMeasure.defaultProgram events: rendered: -> @$("option[value=\"#{eoc}\"]").attr('selected','selected') for eoc in @model.get('episode_ids') if @model? && @model.get('episode_of_care') && @model.get('episode_ids')? @$el.on 'hidden.bs.modal', -> @remove() unless $('#pleaseWaitDialog').is(':visible') @$("input[type=radio]:checked").next().css("color","white") # start load of profile names @loadProfileNames() # enable tooltips @$('a[data-toggle="popover"]').popover({ html: true }) 'ready': 'setup' 'change input:file': 'enableLoad' 'keyup input:password': 'PI:PASSWORD:<PASSWORD>END_PI' 'change input:password': 'PI:PASSWORD:<PASSWORD>END_PI' 'change input[type=radio]': -> @$('input[type=radio]').each (index, element) => if @$(element).prop("checked") @$(element).next().css("color","white") else @$(element).next().css("color","") 'change input[name="vsac_query_type"]': 'changeQueryType' 'change select[name="vsac_query_program"]': 'changeProgram' 'click #clearVSACCreds': 'clearCachedVSACTicket' 'vsac:param-load-error': 'showVSACError' enableLoadVsac: -> vsacApiKey = @$('#vsacApiKey') if (vsacApiKey.val().length > 0) vsacApiKey.closest('.form-group').removeClass('has-error') hasUser = true @$('#loadButton').prop('disabled', !hasUser) clearCachedVSACTicket: -> @$('#vsacSignIn').removeClass('hidden') @$('#vsac-query-settings').removeClass('hidden') @$('#vsacCachedMsg').addClass('hidden') @$('#loadButton').prop('disabled', true) $.post '/vsac_util/auth_expire' toggleVSAC: -> $.ajax url: '/vsac_util/auth_valid' success: (data, textStatus, jqXHR) -> if data? && data.valid $('#vsacSignIn').addClass('hidden') $('#vsac-query-settings').removeClass('hidden') $('#vsacCachedMsg').removeClass('hidden') $('#loadButton').prop('disabled', false) # If the measure import window is open long enough for the VSAC # credentials to expire, we need to reshow the vsacApiKey dialog. setTimeout -> @clearCachedVSACTicket() , new Date(data.expires) - new Date() else $('#vsacSignIn').removeClass('hidden') $('#vsac-query-settings').removeClass('hidden') $('#vsacCachedMsg').addClass('hidden') enableLoad: -> @toggleVSAC() ###* # Loads the program list and release names for the default program and populates the program # and release select boxes. This is called when the user switches to releases. ### loadProgramsAndDefaultProgramReleases: -> # only do this is if we dont have the programNames list if !@programNames? programSelect = @$('#vsac-query-program').prop('disabled', true) releaseSelect = @$('#vsac-query-release').prop('disabled', true) @populateSelectBox programSelect, ['Loading...'] @populateSelectBox releaseSelect, ['Loading...'] $.getJSON('/vsac_util/program_names') .done (data) => @programNames = data.programNames @populateSelectBox programSelect, @programNames, Thorax.Views.ImportMeasure.defaultProgram # Load the default program if it is found if @programNames.indexOf(Thorax.Views.ImportMeasure.defaultProgram) >= 0 @loadProgramReleaseNames Thorax.Views.ImportMeasure.defaultProgram, => @trigger 'vsac:default-program-loaded' # Otherwise load the first in the list else @loadProgramReleaseNames @programNames[0], => @trigger 'vsac:default-program-loaded' .fail => @trigger 'vsac:param-load-error' ###* # Event handler for program change. This kicks off the change of the release names select box. ### changeProgram: -> @loadProgramReleaseNames(@$('#vsac-query-program').val()) ###* # Loads the VSAC release names for a given profile and populates the select box. # This will use the cached release names if we had already loaded them for the given program. # # @param {String} program - The VSAC program to load. # @param {Function} callback - Optional callback for when this is complete. ### loadProgramReleaseNames: (program, callback) -> releaseSelect = @$('#vsac-query-release') programSelect = @$('#vsac-query-program') if @programReleaseNamesCache[program]? @populateSelectBox releaseSelect, @programReleaseNamesCache[program] @trigger 'vsac:release-list-updated' else # Disable both dropdowns and put "Loading..."" in place. programSelect.prop('disabled', true) releaseSelect.prop('disabled', true) @populateSelectBox releaseSelect, ['Loading...'] # begin request $.getJSON("/vsac_util/program_release_names/#{program}") .done (data) => @programReleaseNamesCache[program] = data.releaseNames @populateSelectBox releaseSelect, @programReleaseNamesCache[program], Thorax.Views.ImportMeasure.defaultRelease releaseSelect.prop('disabled', false) programSelect.prop('disabled', false) @trigger 'vsac:release-list-updated' callback() if callback .fail => @trigger 'vsac:param-load-error' ###* # Loads the VSAC profile names from the back end and populates the select box. ### loadProfileNames: -> profileSelect = @$('#vsac-query-profile').prop('disabled', true) @populateSelectBox profileSelect, ['Loading...'] $.getJSON("/vsac_util/profile_names") .done (data) => @profileNames = data.profileNames @latestProfile = data.latestProfile # Map for changing option text for the latest profile to put the profile in double angle brackets and # prefix the option with 'Latest eCQM'. optionTextMap = {} optionTextMap[@latestProfile] = "Latest eCQM&#x300a;#{@latestProfile}&#x300b;" @populateSelectBox profileSelect, @profileNames, @latestProfile, optionTextMap @trigger 'vsac:profiles-loaded' profileSelect.prop('disabled', false) .fail => @trigger 'vsac:param-load-error' ###* # Shows a bonnie error for VSAC parameter loading errors. ### showVSACError: -> bonnie.showError( title: "VSAC Error" summary: 'There was an error retrieving VSAC options.' body: 'Please reload Bonnie and try again.') ###* # Repopulates a select box with options. Optionally setting a default option or alternate text. # # @param {jQuery Element} selectBox - The jQuery element for the select box to refill. # @param {Array} options - List of options. # @param {String} defaultOption - Optional. Default option to select if found. # @param {Object} optionTextMap - Optional. For any options that require text to be different than value, this # parameter can be used to define different option text. ex: # { "eCQM Update 2018-05-04": "Latest eCQM - eCQM Update 2018-05-04"} ### populateSelectBox: (selectBox, options, defaultOption, optionTextMap) -> selectBox.empty() for option in options optionText = if optionTextMap?[option]? then optionTextMap[option] else option if option == defaultOption selectBox.append("<option value=\"#{option}\" selected=\"selected\">#{optionText}</option>") else selectBox.append("<option value=\"#{option}\">#{optionText}</option>") ###* # Event handler for query type selector change. This changes out the query parameters # that the user sees. ### changeQueryType: -> queryType = @$('input[name=vsac_query_type]:checked').val(); switch queryType when 'release' @$('#vsac-query-release-params').removeClass('hidden') @$('#vsac-query-profile-params').addClass('hidden') @loadProgramsAndDefaultProgramReleases() when 'profile' @$('#vsac-query-release-params').addClass('hidden') @$('#vsac-query-profile-params').removeClass('hidden') setup: -> @importDialog = @$("#importMeasureDialog") @importWait = @$("#pleaseWaitDialog") @finalizeDialog = @$("#finalizeMeasureDialog") display: -> @importDialog.modal( "backdrop" : "static", "keyboard" : true, "show" : true) @$('.nice_input').bootstrapFileInput() submit: -> @importWait.modal( "backdrop" : "static", "keyboard" : false, "show" : true) @importDialog.modal('hide') @$('form').trigger('submit') # FIXME: Is anything additional required for cleaning up this view on close? close: -> ''
[ { "context": ", (next) ->\n Users.create [\n { username: 'username_1', email: '1@email.com', password: 'my_password' }", "end": 842, "score": 0.999579668045044, "start": 832, "tag": "USERNAME", "value": "username_1" }, { "context": ".create [\n { username: 'username_1', ...
test/list.coffee
wdavidw/node-ron
14
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get name: 'users' properties: user_id: identifier: true username: unique: true email: index: true name: index: true next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'list', -> it 'should be empty if there are no record', (next) -> Users.list { }, (err, users) -> should.not.exist err users.length.should.eql 0 Users.clear next it 'should sort record according to one property', (next) -> Users.create [ { username: 'username_1', email: '1@email.com', password: 'my_password' } { username: 'username_2', email: '2@email.com', password: 'my_password' } ], (err, users) -> Users.list { sort: 'username', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 users[0].username.should.eql 'username_2' users[1].username.should.eql 'username_1' Users.clear next it 'Test list # where', (next) -> Users.create [ { username: 'username_1', email: '1@email.com', password: 'my_password' } { username: 'username_2', email: '2@email.com', password: 'my_password' } { username: 'username_3', email: '1@email.com', password: 'my_password' } ], (err, users) -> Users.list { email: '1@email.com', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 users[0].username.should.eql 'username_3' users[1].username.should.eql 'username_1' Users.clear next it 'Test list # where union, same property', (next) -> Users.create [ { username: 'username_1', email: '1@email.com', password: 'my_password' } { username: 'username_2', email: '2@email.com', password: 'my_password' } { username: 'username_3', email: '1@email.com', password: 'my_password' } { username: 'username_4', email: '4@email.com', password: 'my_password' } ], (err, users) -> Users.list { email: ['1@email.com', '4@email.com'], operation: 'union', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 3 users[0].username.should.eql 'username_4' users[1].username.should.eql 'username_3' users[2].username.should.eql 'username_1' Users.clear next it 'should honor inter operation with a property having the same values', (next) -> Users.create [ { username: 'username_1', email: '1@email.com', password: 'my_password', name: 'name_1' } { username: 'username_2', email: '2@email.com', password: 'my_password', name: 'name_2' } { username: 'username_3', email: '1@email.com', password: 'my_password', name: 'name_3' } { username: 'username_4', email: '4@email.com', password: 'my_password', name: 'name_4' } ], (err, users) -> Users.list { email: '1@email.com', name: 'name_3', operation: 'inter', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 1 users[0].username.should.eql 'username_3' Users.clear next it 'should return only selected properties', (next) -> Users.create [ { username: 'username_1', email: '1@email.com', password: 'my_password', name: 'name_1' } { username: 'username_2', email: '2@email.com', password: 'my_password', name: 'name_2' } ], (err, users) -> Users.list { properties: ['username'], sort: 'username', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 for user in users then Object.keys(user).should.eql ['username'] users[0].username.should.eql 'username_2' users[1].username.should.eql 'username_1' Users.clear next it 'should return an array of identifiers', (next) -> Users.create [ { username: 'username_1', email: '1@email.com', password: 'my_password' } { username: 'username_2', email: '2@email.com', password: 'my_password' } ], (err, users) -> Users.list { identifiers: true }, (err, ids) -> should.not.exist err ids.length.should.eql 2 for id in ids then id.should.be.a.Number() Users.clear next
110855
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get name: 'users' properties: user_id: identifier: true username: unique: true email: index: true name: index: true next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'list', -> it 'should be empty if there are no record', (next) -> Users.list { }, (err, users) -> should.not.exist err users.length.should.eql 0 Users.clear next it 'should sort record according to one property', (next) -> Users.create [ { username: 'username_1', email: '<EMAIL>', password: '<PASSWORD>' } { username: 'username_2', email: '<EMAIL>', password: '<PASSWORD>' } ], (err, users) -> Users.list { sort: 'username', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 users[0].username.should.eql 'username_2' users[1].username.should.eql 'username_1' Users.clear next it 'Test list # where', (next) -> Users.create [ { username: 'username_1', email: '<EMAIL>', password: '<PASSWORD>' } { username: 'username_2', email: '<EMAIL>', password: '<PASSWORD>' } { username: 'username_3', email: '<EMAIL>', password: '<PASSWORD>' } ], (err, users) -> Users.list { email: '<EMAIL>', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 users[0].username.should.eql 'username_3' users[1].username.should.eql 'username_1' Users.clear next it 'Test list # where union, same property', (next) -> Users.create [ { username: 'username_1', email: '<EMAIL>', password: '<PASSWORD>' } { username: 'username_2', email: '<EMAIL>', password: '<PASSWORD>' } { username: 'username_3', email: '<EMAIL>', password: '<PASSWORD>' } { username: 'username_4', email: '<EMAIL>', password: '<PASSWORD>' } ], (err, users) -> Users.list { email: ['<EMAIL>', '<EMAIL>'], operation: 'union', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 3 users[0].username.should.eql 'username_4' users[1].username.should.eql 'username_3' users[2].username.should.eql 'username_1' Users.clear next it 'should honor inter operation with a property having the same values', (next) -> Users.create [ { username: 'username_1', email: '<EMAIL>', password: '<PASSWORD>', name: 'name_1' } { username: 'username_2', email: '<EMAIL>', password: '<PASSWORD>', name: 'name_2' } { username: 'username_3', email: '<EMAIL>', password: '<PASSWORD>', name: 'name_3' } { username: 'username_4', email: '<EMAIL>', password: '<PASSWORD>', name: 'name_4' } ], (err, users) -> Users.list { email: '<EMAIL>', name: 'name_3', operation: 'inter', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 1 users[0].username.should.eql 'username_3' Users.clear next it 'should return only selected properties', (next) -> Users.create [ { username: 'username_1', email: '<EMAIL>', password: '<PASSWORD>', name: 'name_1' } { username: 'username_2', email: '<EMAIL>', password: '<PASSWORD>', name: 'name_2' } ], (err, users) -> Users.list { properties: ['username'], sort: 'username', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 for user in users then Object.keys(user).should.eql ['username'] users[0].username.should.eql 'username_2' users[1].username.should.eql 'username_1' Users.clear next it 'should return an array of identifiers', (next) -> Users.create [ { username: 'username_1', email: '<EMAIL>', password: '<PASSWORD>' } { username: 'username_2', email: '<EMAIL>', password: '<PASSWORD>' } ], (err, users) -> Users.list { identifiers: true }, (err, ids) -> should.not.exist err ids.length.should.eql 2 for id in ids then id.should.be.a.Number() Users.clear next
true
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config Users = client.get name: 'users' properties: user_id: identifier: true username: unique: true email: index: true name: index: true next() beforeEach (next) -> Users.clear next afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'list', -> it 'should be empty if there are no record', (next) -> Users.list { }, (err, users) -> should.not.exist err users.length.should.eql 0 Users.clear next it 'should sort record according to one property', (next) -> Users.create [ { username: 'username_1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } { username: 'username_2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } ], (err, users) -> Users.list { sort: 'username', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 users[0].username.should.eql 'username_2' users[1].username.should.eql 'username_1' Users.clear next it 'Test list # where', (next) -> Users.create [ { username: 'username_1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } { username: 'username_2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } { username: 'username_3', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } ], (err, users) -> Users.list { email: 'PI:EMAIL:<EMAIL>END_PI', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 users[0].username.should.eql 'username_3' users[1].username.should.eql 'username_1' Users.clear next it 'Test list # where union, same property', (next) -> Users.create [ { username: 'username_1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } { username: 'username_2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } { username: 'username_3', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } { username: 'username_4', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } ], (err, users) -> Users.list { email: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI'], operation: 'union', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 3 users[0].username.should.eql 'username_4' users[1].username.should.eql 'username_3' users[2].username.should.eql 'username_1' Users.clear next it 'should honor inter operation with a property having the same values', (next) -> Users.create [ { username: 'username_1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'name_1' } { username: 'username_2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'name_2' } { username: 'username_3', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'name_3' } { username: 'username_4', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'name_4' } ], (err, users) -> Users.list { email: 'PI:EMAIL:<EMAIL>END_PI', name: 'name_3', operation: 'inter', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 1 users[0].username.should.eql 'username_3' Users.clear next it 'should return only selected properties', (next) -> Users.create [ { username: 'username_1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'name_1' } { username: 'username_2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'name_2' } ], (err, users) -> Users.list { properties: ['username'], sort: 'username', direction: 'desc' }, (err, users) -> should.not.exist err users.length.should.eql 2 for user in users then Object.keys(user).should.eql ['username'] users[0].username.should.eql 'username_2' users[1].username.should.eql 'username_1' Users.clear next it 'should return an array of identifiers', (next) -> Users.create [ { username: 'username_1', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } { username: 'username_2', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' } ], (err, users) -> Users.list { identifiers: true }, (err, ids) -> should.not.exist err ids.length.should.eql 2 for id in ids then id.should.be.a.Number() Users.clear next
[ { "context": " - stop and remove a scheduler \n#\n# Author:\n# Leon van Kammen\n#\n\nmodule.exports = (robot) ->\n util = requ", "end": 903, "score": 0.9998334050178528, "start": 888, "tag": "NAME", "value": "Leon van Kammen" } ]
test/scripts/recurry.coffee
coderofsalvation/hubot-recurry
0
# Description: # interface to recurry # # Dependencies: easy-table # # Commands: # hubot recurry - get overview of scheduled jobs (being pushed to core) # hubot recurry setscheduler - set scheduler frequency # hubot recurry setpayload <id> <jsonstr> - set json payload for scheduled call # hubot recurry view <id> - view details and payload of scheduled call # hubot recurry trigger <id> - manually trigger scheduler, regardless of shedulertime # hubot recurry add - how to add a recurring scheduled call # hubot recurry scheduler <action> <id> - control a scheduler, actions: start, stop, resume, pause # hubot recurry reset <id> - reset 'triggered' field to zero # hubot recurry remove <id> - stop and remove a scheduler # # Author: # Leon van Kammen # module.exports = (robot) -> util = require('util') ascii = require('easy-table') recurry = url: ( if process.env.RECURRY_URL then process.env.RECURRY_URL else "http://localhost:3333") usage: setscheduler: "Usage: recurry setscheduler <id> <phrase>\n\n Example: recurry setscheduler foo every 5 mins\n\nphrases: \n \t314 milliseconds\n \t5 minutes 15 seconds\n \tan hour and a minute\n \t1 Hour, 5 Minutes And 15 Seconds\n \t2h 15m 15s\n \t3 weeks, 5 days, 6 hours\n \t3 weeks, 5d 6h" add: "Usage: recurry add <method> <url> <name>\n\n Example: recurry add get http://fooo.com get_foo_com\n recurry setpayload get_foo_com {\"foo\":\"bar\"}\n" format = (data,format) -> return "empty reply from server..is recurry online?" if not data if format is "ascii" a = new ascii for row in data for key,value of row value = '{}' if typeof value is 'object' a.cell( key, value ) a.newRow() return a.toString() robot.respond /recurry$/i, (msg) -> robot.http( recurry.url+"/scheduler" ).get() (err,res,body) -> data = JSON.parse(body) msg.send format(data,'ascii') robot.respond /recurry reset (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send("Usage: recurry reset <id>") if args.length != 1 robot.http( recurry.url+"/scheduler/reset/"+args[0] ).get() (err,res,body) -> data = JSON.parse(body) msg.send format(data,'ascii') robot.respond /recurry add$/i, (msg) -> msg.send( recurry.usage.add ) robot.respond /recurry add (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send( recurry.usage.add ) if args.length != 3 data = {} data.id = args.pop().trim() data.url = args.pop().trim() data.method = args.pop().trim() data.scheduler = "?" console.dir data robot.http( recurry.url+"/scheduler" ) .header('Content-Type', 'application/json') .post( JSON.stringify(data) ) (err,res,body) -> console.dir body data = JSON.parse(body) msg.send "OK" if typeof JSON.stringify(data) is 'object' robot.respond /recurry setscheduler$/i, (msg) -> msg.send( recurry.usage.setscheduler ) robot.respond /recurry remove (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send(recurry.usage.setscheduler) if args.length < 1 id = args.shift() robot.http( recurry.url+"/scheduler/remove/"+id ) .header('Content-Type', 'application/json') .get() (err,res,body) -> msg.send body robot.respond /recurry setscheduler (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send(recurry.usage.setscheduler) if args.length < 2 id = args.shift() data = { scheduler: args.join(" ") } robot.http( recurry.url+"/scheduler/rule/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body robot.respond /recurry view (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = { payload: args.join(" ") } robot.http( recurry.url+"/scheduler/"+id ) .header('Content-Type', 'application/json') .get() (err,res,body) -> msg.send JSON.stringify( JSON.parse(body ),null, 2 ) robot.respond /recurry trigger (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = {} robot.http( recurry.url+"/scheduler/trigger/"+id ) .header('Content-Type', 'application/json') .put() (err,res,body) -> msg.send JSON.stringify( JSON.parse(body ),null, 2 ) robot.respond /recurry setpayload (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = { payload: args.join(" ") } robot.http( recurry.url+"/scheduler/payload/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body robot.respond /recurry scheduler (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send("incorrect arguments received, please check help") if args.length < 2 id = args[1] action = args[0] data = { action: action } console.dir data robot.http( recurry.url+"/scheduler/action/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body return this
151562
# Description: # interface to recurry # # Dependencies: easy-table # # Commands: # hubot recurry - get overview of scheduled jobs (being pushed to core) # hubot recurry setscheduler - set scheduler frequency # hubot recurry setpayload <id> <jsonstr> - set json payload for scheduled call # hubot recurry view <id> - view details and payload of scheduled call # hubot recurry trigger <id> - manually trigger scheduler, regardless of shedulertime # hubot recurry add - how to add a recurring scheduled call # hubot recurry scheduler <action> <id> - control a scheduler, actions: start, stop, resume, pause # hubot recurry reset <id> - reset 'triggered' field to zero # hubot recurry remove <id> - stop and remove a scheduler # # Author: # <NAME> # module.exports = (robot) -> util = require('util') ascii = require('easy-table') recurry = url: ( if process.env.RECURRY_URL then process.env.RECURRY_URL else "http://localhost:3333") usage: setscheduler: "Usage: recurry setscheduler <id> <phrase>\n\n Example: recurry setscheduler foo every 5 mins\n\nphrases: \n \t314 milliseconds\n \t5 minutes 15 seconds\n \tan hour and a minute\n \t1 Hour, 5 Minutes And 15 Seconds\n \t2h 15m 15s\n \t3 weeks, 5 days, 6 hours\n \t3 weeks, 5d 6h" add: "Usage: recurry add <method> <url> <name>\n\n Example: recurry add get http://fooo.com get_foo_com\n recurry setpayload get_foo_com {\"foo\":\"bar\"}\n" format = (data,format) -> return "empty reply from server..is recurry online?" if not data if format is "ascii" a = new ascii for row in data for key,value of row value = '{}' if typeof value is 'object' a.cell( key, value ) a.newRow() return a.toString() robot.respond /recurry$/i, (msg) -> robot.http( recurry.url+"/scheduler" ).get() (err,res,body) -> data = JSON.parse(body) msg.send format(data,'ascii') robot.respond /recurry reset (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send("Usage: recurry reset <id>") if args.length != 1 robot.http( recurry.url+"/scheduler/reset/"+args[0] ).get() (err,res,body) -> data = JSON.parse(body) msg.send format(data,'ascii') robot.respond /recurry add$/i, (msg) -> msg.send( recurry.usage.add ) robot.respond /recurry add (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send( recurry.usage.add ) if args.length != 3 data = {} data.id = args.pop().trim() data.url = args.pop().trim() data.method = args.pop().trim() data.scheduler = "?" console.dir data robot.http( recurry.url+"/scheduler" ) .header('Content-Type', 'application/json') .post( JSON.stringify(data) ) (err,res,body) -> console.dir body data = JSON.parse(body) msg.send "OK" if typeof JSON.stringify(data) is 'object' robot.respond /recurry setscheduler$/i, (msg) -> msg.send( recurry.usage.setscheduler ) robot.respond /recurry remove (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send(recurry.usage.setscheduler) if args.length < 1 id = args.shift() robot.http( recurry.url+"/scheduler/remove/"+id ) .header('Content-Type', 'application/json') .get() (err,res,body) -> msg.send body robot.respond /recurry setscheduler (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send(recurry.usage.setscheduler) if args.length < 2 id = args.shift() data = { scheduler: args.join(" ") } robot.http( recurry.url+"/scheduler/rule/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body robot.respond /recurry view (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = { payload: args.join(" ") } robot.http( recurry.url+"/scheduler/"+id ) .header('Content-Type', 'application/json') .get() (err,res,body) -> msg.send JSON.stringify( JSON.parse(body ),null, 2 ) robot.respond /recurry trigger (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = {} robot.http( recurry.url+"/scheduler/trigger/"+id ) .header('Content-Type', 'application/json') .put() (err,res,body) -> msg.send JSON.stringify( JSON.parse(body ),null, 2 ) robot.respond /recurry setpayload (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = { payload: args.join(" ") } robot.http( recurry.url+"/scheduler/payload/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body robot.respond /recurry scheduler (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send("incorrect arguments received, please check help") if args.length < 2 id = args[1] action = args[0] data = { action: action } console.dir data robot.http( recurry.url+"/scheduler/action/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body return this
true
# Description: # interface to recurry # # Dependencies: easy-table # # Commands: # hubot recurry - get overview of scheduled jobs (being pushed to core) # hubot recurry setscheduler - set scheduler frequency # hubot recurry setpayload <id> <jsonstr> - set json payload for scheduled call # hubot recurry view <id> - view details and payload of scheduled call # hubot recurry trigger <id> - manually trigger scheduler, regardless of shedulertime # hubot recurry add - how to add a recurring scheduled call # hubot recurry scheduler <action> <id> - control a scheduler, actions: start, stop, resume, pause # hubot recurry reset <id> - reset 'triggered' field to zero # hubot recurry remove <id> - stop and remove a scheduler # # Author: # PI:NAME:<NAME>END_PI # module.exports = (robot) -> util = require('util') ascii = require('easy-table') recurry = url: ( if process.env.RECURRY_URL then process.env.RECURRY_URL else "http://localhost:3333") usage: setscheduler: "Usage: recurry setscheduler <id> <phrase>\n\n Example: recurry setscheduler foo every 5 mins\n\nphrases: \n \t314 milliseconds\n \t5 minutes 15 seconds\n \tan hour and a minute\n \t1 Hour, 5 Minutes And 15 Seconds\n \t2h 15m 15s\n \t3 weeks, 5 days, 6 hours\n \t3 weeks, 5d 6h" add: "Usage: recurry add <method> <url> <name>\n\n Example: recurry add get http://fooo.com get_foo_com\n recurry setpayload get_foo_com {\"foo\":\"bar\"}\n" format = (data,format) -> return "empty reply from server..is recurry online?" if not data if format is "ascii" a = new ascii for row in data for key,value of row value = '{}' if typeof value is 'object' a.cell( key, value ) a.newRow() return a.toString() robot.respond /recurry$/i, (msg) -> robot.http( recurry.url+"/scheduler" ).get() (err,res,body) -> data = JSON.parse(body) msg.send format(data,'ascii') robot.respond /recurry reset (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send("Usage: recurry reset <id>") if args.length != 1 robot.http( recurry.url+"/scheduler/reset/"+args[0] ).get() (err,res,body) -> data = JSON.parse(body) msg.send format(data,'ascii') robot.respond /recurry add$/i, (msg) -> msg.send( recurry.usage.add ) robot.respond /recurry add (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send( recurry.usage.add ) if args.length != 3 data = {} data.id = args.pop().trim() data.url = args.pop().trim() data.method = args.pop().trim() data.scheduler = "?" console.dir data robot.http( recurry.url+"/scheduler" ) .header('Content-Type', 'application/json') .post( JSON.stringify(data) ) (err,res,body) -> console.dir body data = JSON.parse(body) msg.send "OK" if typeof JSON.stringify(data) is 'object' robot.respond /recurry setscheduler$/i, (msg) -> msg.send( recurry.usage.setscheduler ) robot.respond /recurry remove (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send(recurry.usage.setscheduler) if args.length < 1 id = args.shift() robot.http( recurry.url+"/scheduler/remove/"+id ) .header('Content-Type', 'application/json') .get() (err,res,body) -> msg.send body robot.respond /recurry setscheduler (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send(recurry.usage.setscheduler) if args.length < 2 id = args.shift() data = { scheduler: args.join(" ") } robot.http( recurry.url+"/scheduler/rule/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body robot.respond /recurry view (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = { payload: args.join(" ") } robot.http( recurry.url+"/scheduler/"+id ) .header('Content-Type', 'application/json') .get() (err,res,body) -> msg.send JSON.stringify( JSON.parse(body ),null, 2 ) robot.respond /recurry trigger (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = {} robot.http( recurry.url+"/scheduler/trigger/"+id ) .header('Content-Type', 'application/json') .put() (err,res,body) -> msg.send JSON.stringify( JSON.parse(body ),null, 2 ) robot.respond /recurry setpayload (.*)/i, (msg) -> args = msg.match[1].split(" ") id = args.shift() data = { payload: args.join(" ") } robot.http( recurry.url+"/scheduler/payload/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body robot.respond /recurry scheduler (.*)/i, (msg) -> args = msg.match[1].split(" ") return msg.send("incorrect arguments received, please check help") if args.length < 2 id = args[1] action = args[0] data = { action: action } console.dir data robot.http( recurry.url+"/scheduler/action/"+id ) .header('Content-Type', 'application/json') .put( JSON.stringify(data) ) (err,res,body) -> data = JSON.parse(body) msg.send body return this
[ { "context": " forks, pushed commits, and wikis\n#\n# Authors:\n# pnsk, mgriffin\n\nmodule.exports = (robot) ->\n url = pr", "end": 1148, "score": 0.9996919631958008, "start": 1144, "tag": "USERNAME", "value": "pnsk" }, { "context": ", pushed commits, and wikis\n#\n# Authors:\n# ...
src/ghe.coffee
hubot-scripts/hubot-ghe
4
# Description: # Access your GitHub Enterprise instance through Hubot # # Dependencies: # None # # Configuration: # HUBOT_GHE_URL # HUBOT_GHE_TOKEN # # Commands: # hubot ghe license - returns license information # hubot ghe stats issues - returns the number of open and closed issues # hubot ghe stats hooks - returns the number of active and inactive hooks # hubot ghe stats milestones - returns the number of open and closed milestones # hubot ghe stats orgs - returns the number of organizations, teams, team members, and disabled organizations # hubot ghe stats comments - returns the number of comments on issues, pull requests, commits, and gists # hubot ghe stats pages - returns the number of GitHub Pages sites # hubot ghe stats users - returns the number of suspended and admin users # hubot ghe stats gists - returns the number of private and public gists # hubot ghe stats pulls - returns the number of merged, mergeable, and unmergeable pull requests # hubot ghe stats repos - returns the number of organization-owned repositories, root repositories, forks, pushed commits, and wikis # # Authors: # pnsk, mgriffin module.exports = (robot) -> url = process.env.HUBOT_GHE_URL + '/api/v3' token = process.env.HUBOT_GHE_TOKEN # If you're using a self signed certificate, uncomment the next line # process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" unless token robot.logger.error "GitHub Enterprise token isn't set." robot.respond /ghe license$/i, (msg) -> ghe_license msg,token,url robot.respond /ghe stats (.*)$/i, (msg) -> ghe_stats msg,token,url ghe_license = (msg, token, url) -> msg.http("#{url}/enterprise/settings/license") .header("Authorization", "token #{token}") .get() (err, res, body) -> if err msg.send "error" else if res.statusCode is 200 results = JSON.parse body msg.send "GHE has #{results.seats} seats, and #{results.seats_used} are used. License expires at #{results.expire_at}." else msg.send "statusCode: #{res.statusCode}" ghe_stats = (msg, token, url) -> type = msg.match[1] msg.http("#{url}/enterprise/stats/#{type}") .header("Authorization", "token #{token}") .get() (err, res, body) -> if err msg.send "error" else if res.statusCode is 200 results = JSON.parse body switch type when "issues" then msg.send "#{results.total_issues} issues; #{results.open_issues} open and #{results.closed_issues} closed." when "hooks" then msg.send "#{results.total_hooks} hooks; #{results.active_hooks} active and #{results.inactive_hooks} inactive." when "milestones" then msg.send "#{results.total_milestones} milestones; #{results.open_milestones} open and #{results.closed_milestones} closed." when "orgs" then msg.send "#{results.total_orgs} organizations; #{results.disabled_orgs} disabled.\n#{results.total_teams} teams with #{results.total_team_members} members." when "comments" then msg.send "#{results.total_commit_comments} commit comments.\n#{results.total_gist_comments} gist comments.\n#{results.total_issue_comments} issue comments.\n#{results.total_pull_request_comments} pull request comments.\n" when "pages" then msg.send "#{results.total_pages} pages." when "users" then msg.send "#{results.total_users} users; #{results.admin_users} admins and #{results.suspended_users} suspended." when "gists" then msg.send "#{results.total_gists} gists; #{results.private_gists} private and #{results.public_gists} public." when "pulls" then msg.send "#{results.total_pulls} pulls; #{results.merged_pulls} merged, #{results.mergable_pulls} mergable and #{results.unmergable_pulls} unmergable." when "repos" then msg.send "#{results.total_repos} repositories, #{results.root_repos} root and #{results.fork_repos} forks.\n#{results.org_repos} in organizations.\n#{results.total_pushes} pushes in total.\n#{results.total_wikis} wikis." else msg.send "statusCode: #{res.statusCode} -- #{body} -- type: #{type} -- #{msg.match[1]}"
32393
# Description: # Access your GitHub Enterprise instance through Hubot # # Dependencies: # None # # Configuration: # HUBOT_GHE_URL # HUBOT_GHE_TOKEN # # Commands: # hubot ghe license - returns license information # hubot ghe stats issues - returns the number of open and closed issues # hubot ghe stats hooks - returns the number of active and inactive hooks # hubot ghe stats milestones - returns the number of open and closed milestones # hubot ghe stats orgs - returns the number of organizations, teams, team members, and disabled organizations # hubot ghe stats comments - returns the number of comments on issues, pull requests, commits, and gists # hubot ghe stats pages - returns the number of GitHub Pages sites # hubot ghe stats users - returns the number of suspended and admin users # hubot ghe stats gists - returns the number of private and public gists # hubot ghe stats pulls - returns the number of merged, mergeable, and unmergeable pull requests # hubot ghe stats repos - returns the number of organization-owned repositories, root repositories, forks, pushed commits, and wikis # # Authors: # pnsk, <NAME>iff<NAME> module.exports = (robot) -> url = process.env.HUBOT_GHE_URL + '/api/v3' token = process.env.HUBOT_GHE_TOKEN # If you're using a self signed certificate, uncomment the next line # process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" unless token robot.logger.error "GitHub Enterprise token isn't set." robot.respond /ghe license$/i, (msg) -> ghe_license msg,token,url robot.respond /ghe stats (.*)$/i, (msg) -> ghe_stats msg,token,url ghe_license = (msg, token, url) -> msg.http("#{url}/enterprise/settings/license") .header("Authorization", "token #{token}") .get() (err, res, body) -> if err msg.send "error" else if res.statusCode is 200 results = JSON.parse body msg.send "GHE has #{results.seats} seats, and #{results.seats_used} are used. License expires at #{results.expire_at}." else msg.send "statusCode: #{res.statusCode}" ghe_stats = (msg, token, url) -> type = msg.match[1] msg.http("#{url}/enterprise/stats/#{type}") .header("Authorization", "token #{token}") .get() (err, res, body) -> if err msg.send "error" else if res.statusCode is 200 results = JSON.parse body switch type when "issues" then msg.send "#{results.total_issues} issues; #{results.open_issues} open and #{results.closed_issues} closed." when "hooks" then msg.send "#{results.total_hooks} hooks; #{results.active_hooks} active and #{results.inactive_hooks} inactive." when "milestones" then msg.send "#{results.total_milestones} milestones; #{results.open_milestones} open and #{results.closed_milestones} closed." when "orgs" then msg.send "#{results.total_orgs} organizations; #{results.disabled_orgs} disabled.\n#{results.total_teams} teams with #{results.total_team_members} members." when "comments" then msg.send "#{results.total_commit_comments} commit comments.\n#{results.total_gist_comments} gist comments.\n#{results.total_issue_comments} issue comments.\n#{results.total_pull_request_comments} pull request comments.\n" when "pages" then msg.send "#{results.total_pages} pages." when "users" then msg.send "#{results.total_users} users; #{results.admin_users} admins and #{results.suspended_users} suspended." when "gists" then msg.send "#{results.total_gists} gists; #{results.private_gists} private and #{results.public_gists} public." when "pulls" then msg.send "#{results.total_pulls} pulls; #{results.merged_pulls} merged, #{results.mergable_pulls} mergable and #{results.unmergable_pulls} unmergable." when "repos" then msg.send "#{results.total_repos} repositories, #{results.root_repos} root and #{results.fork_repos} forks.\n#{results.org_repos} in organizations.\n#{results.total_pushes} pushes in total.\n#{results.total_wikis} wikis." else msg.send "statusCode: #{res.statusCode} -- #{body} -- type: #{type} -- #{msg.match[1]}"
true
# Description: # Access your GitHub Enterprise instance through Hubot # # Dependencies: # None # # Configuration: # HUBOT_GHE_URL # HUBOT_GHE_TOKEN # # Commands: # hubot ghe license - returns license information # hubot ghe stats issues - returns the number of open and closed issues # hubot ghe stats hooks - returns the number of active and inactive hooks # hubot ghe stats milestones - returns the number of open and closed milestones # hubot ghe stats orgs - returns the number of organizations, teams, team members, and disabled organizations # hubot ghe stats comments - returns the number of comments on issues, pull requests, commits, and gists # hubot ghe stats pages - returns the number of GitHub Pages sites # hubot ghe stats users - returns the number of suspended and admin users # hubot ghe stats gists - returns the number of private and public gists # hubot ghe stats pulls - returns the number of merged, mergeable, and unmergeable pull requests # hubot ghe stats repos - returns the number of organization-owned repositories, root repositories, forks, pushed commits, and wikis # # Authors: # pnsk, PI:NAME:<NAME>END_PIiffPI:NAME:<NAME>END_PI module.exports = (robot) -> url = process.env.HUBOT_GHE_URL + '/api/v3' token = process.env.HUBOT_GHE_TOKEN # If you're using a self signed certificate, uncomment the next line # process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" unless token robot.logger.error "GitHub Enterprise token isn't set." robot.respond /ghe license$/i, (msg) -> ghe_license msg,token,url robot.respond /ghe stats (.*)$/i, (msg) -> ghe_stats msg,token,url ghe_license = (msg, token, url) -> msg.http("#{url}/enterprise/settings/license") .header("Authorization", "token #{token}") .get() (err, res, body) -> if err msg.send "error" else if res.statusCode is 200 results = JSON.parse body msg.send "GHE has #{results.seats} seats, and #{results.seats_used} are used. License expires at #{results.expire_at}." else msg.send "statusCode: #{res.statusCode}" ghe_stats = (msg, token, url) -> type = msg.match[1] msg.http("#{url}/enterprise/stats/#{type}") .header("Authorization", "token #{token}") .get() (err, res, body) -> if err msg.send "error" else if res.statusCode is 200 results = JSON.parse body switch type when "issues" then msg.send "#{results.total_issues} issues; #{results.open_issues} open and #{results.closed_issues} closed." when "hooks" then msg.send "#{results.total_hooks} hooks; #{results.active_hooks} active and #{results.inactive_hooks} inactive." when "milestones" then msg.send "#{results.total_milestones} milestones; #{results.open_milestones} open and #{results.closed_milestones} closed." when "orgs" then msg.send "#{results.total_orgs} organizations; #{results.disabled_orgs} disabled.\n#{results.total_teams} teams with #{results.total_team_members} members." when "comments" then msg.send "#{results.total_commit_comments} commit comments.\n#{results.total_gist_comments} gist comments.\n#{results.total_issue_comments} issue comments.\n#{results.total_pull_request_comments} pull request comments.\n" when "pages" then msg.send "#{results.total_pages} pages." when "users" then msg.send "#{results.total_users} users; #{results.admin_users} admins and #{results.suspended_users} suspended." when "gists" then msg.send "#{results.total_gists} gists; #{results.private_gists} private and #{results.public_gists} public." when "pulls" then msg.send "#{results.total_pulls} pulls; #{results.merged_pulls} merged, #{results.mergable_pulls} mergable and #{results.unmergable_pulls} unmergable." when "repos" then msg.send "#{results.total_repos} repositories, #{results.root_repos} root and #{results.fork_repos} forks.\n#{results.org_repos} in organizations.\n#{results.total_pushes} pushes in total.\n#{results.total_wikis} wikis." else msg.send "statusCode: #{res.statusCode} -- #{body} -- type: #{type} -- #{msg.match[1]}"
[ { "context": "valuate(\"query\")).toEqual {query:\"WZM2hwPXWx4+7SbaJpUPrh6KZl7c4lqZ/67En5tJy8DGTjW+mxDV0g8t2UtDklW4f1Ec/mr", "end": 469, "score": 0.5457465052604675, "start": 464, "tag": "KEY", "value": "JpUPr" }, { "context": "(\"query\")).toEqual {query:\"WZM2hwPXWx4+7SbaJpUPrh6KZl...
public/test/e2e/protractor/fullquery.coffee
vetstoria-testing/angularjs-crypto
77
"use strict" describe "fullquery example", -> beforeEach -> browser.get "#/fullquery" expect(browser.getCurrentUrl()).toBe "http://localhost:9000/#/fullquery" it "check plain fullquery", -> expect(element(By.binding("plainQueryParam")).evaluate("plainQueryParam")).toEqual {name:"COMMERZBANK AG", value:12345, id:12345 } it "check encrypted query", -> expect(element(By.binding("query")).evaluate("query")).toEqual {query:"WZM2hwPXWx4+7SbaJpUPrh6KZl7c4lqZ/67En5tJy8DGTjW+mxDV0g8t2UtDklW4f1Ec/mr6hPf2K6V+oE/21A=="}
119138
"use strict" describe "fullquery example", -> beforeEach -> browser.get "#/fullquery" expect(browser.getCurrentUrl()).toBe "http://localhost:9000/#/fullquery" it "check plain fullquery", -> expect(element(By.binding("plainQueryParam")).evaluate("plainQueryParam")).toEqual {name:"COMMERZBANK AG", value:12345, id:12345 } it "check encrypted query", -> expect(element(By.binding("query")).evaluate("query")).toEqual {query:"WZM2hwPXWx4+7Sba<KEY>h6<KEY>4<KEY>/<KEY>Jy<KEY>D<KEY>j<KEY>=="}
true
"use strict" describe "fullquery example", -> beforeEach -> browser.get "#/fullquery" expect(browser.getCurrentUrl()).toBe "http://localhost:9000/#/fullquery" it "check plain fullquery", -> expect(element(By.binding("plainQueryParam")).evaluate("plainQueryParam")).toEqual {name:"COMMERZBANK AG", value:12345, id:12345 } it "check encrypted query", -> expect(element(By.binding("query")).evaluate("query")).toEqual {query:"WZM2hwPXWx4+7SbaPI:KEY:<KEY>END_PIh6PI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PIJyPI:KEY:<KEY>END_PIDPI:KEY:<KEY>END_PIjPI:KEY:<KEY>END_PI=="}
[ { "context": "lly on a port that probably isn't taken\ndomain = \"127.0.0.1\"\nport = 6080\n\nrequestURL = \"https://trello.com/1/", "end": 144, "score": 0.9997342228889465, "start": 135, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ace these with your application key/s...
app/scripts/code/oauth.coffee
SeanKilleen/api-docs
0
http = require('http') OAuth = require('oauth').OAuth url = require('url') #run locally on a port that probably isn't taken domain = "127.0.0.1" port = 6080 requestURL = "https://trello.com/1/OAuthGetRequestToken" accessURL = "https://trello.com/1/OAuthGetAccessToken" authorizeURL = "https://trello.com/1/OAuthAuthorizeToken" appName = "Trello OAuth Example" #replace these with your application key/secret key = "YOURKEY" secret = "YOURSECRET" #Trello redirects the user here after authentication loginCallback = "http://#{domain}:#{port}/cb" #need to store token: tokenSecret pairs; in a real application, this should be more permanent (redis would be a good choice) oauth_secrets = {} oauth = new OAuth(requestURL, accessURL, key, secret, "1.0", loginCallback, "HMAC-SHA1") login = (req, res) -> oauth.getOAuthRequestToken (error, token, tokenSecret, results) => oauth_secrets[token] = tokenSecret res.writeHead(302, { 'Location': "#{authorizeURL}?oauth_token=#{token}&name=#{appName}" }) res.end() cb = (req, res) -> query = url.parse(req.url, true).query token = query.oauth_token tokenSecret = oauth_secrets[token] verifier = query.oauth_verifier oauth.getOAuthAccessToken token, tokenSecret, verifier, (error, accessToken, accessTokenSecret, results) -> #in a real app, the accessToken and accessTokenSecret should be stored oauth.getProtectedResource("https://api.trello.com/1/members/me", "GET", accessToken, accessTokenSecret, (error, data, response) -> #respond with data to show that we now have access to your data res.end(data) ) http.createServer( (req, res) -> if /^\/login/.test(req.url) login(req, res) else if /^\/cb/.test(req.url) cb(req, res) else res.end("Don't know about that") ).listen(port, domain) console.log "Server running at #{domain}:#{port}; hit #{domain}:#{port}/login"
200050
http = require('http') OAuth = require('oauth').OAuth url = require('url') #run locally on a port that probably isn't taken domain = "127.0.0.1" port = 6080 requestURL = "https://trello.com/1/OAuthGetRequestToken" accessURL = "https://trello.com/1/OAuthGetAccessToken" authorizeURL = "https://trello.com/1/OAuthAuthorizeToken" appName = "Trello OAuth Example" #replace these with your application key/secret key = "<KEY>" secret = "<KEY>" #Trello redirects the user here after authentication loginCallback = "http://#{domain}:#{port}/cb" #need to store token: tokenSecret pairs; in a real application, this should be more permanent (redis would be a good choice) oauth_secrets = {} oauth = new OAuth(requestURL, accessURL, key, secret, "1.0", loginCallback, "HMAC-SHA1") login = (req, res) -> oauth.getOAuthRequestToken (error, token, tokenSecret, results) => oauth_secrets[token] = tokenSecret res.writeHead(302, { 'Location': "#{authorizeURL}?oauth_token=#{token}&name=#{appName}" }) res.end() cb = (req, res) -> query = url.parse(req.url, true).query token = query.oauth_token tokenSecret = oauth_secrets[token] verifier = query.oauth_verifier oauth.getOAuthAccessToken token, tokenSecret, verifier, (error, accessToken, accessTokenSecret, results) -> #in a real app, the accessToken and accessTokenSecret should be stored oauth.getProtectedResource("https://api.trello.com/1/members/me", "GET", accessToken, accessTokenSecret, (error, data, response) -> #respond with data to show that we now have access to your data res.end(data) ) http.createServer( (req, res) -> if /^\/login/.test(req.url) login(req, res) else if /^\/cb/.test(req.url) cb(req, res) else res.end("Don't know about that") ).listen(port, domain) console.log "Server running at #{domain}:#{port}; hit #{domain}:#{port}/login"
true
http = require('http') OAuth = require('oauth').OAuth url = require('url') #run locally on a port that probably isn't taken domain = "127.0.0.1" port = 6080 requestURL = "https://trello.com/1/OAuthGetRequestToken" accessURL = "https://trello.com/1/OAuthGetAccessToken" authorizeURL = "https://trello.com/1/OAuthAuthorizeToken" appName = "Trello OAuth Example" #replace these with your application key/secret key = "PI:KEY:<KEY>END_PI" secret = "PI:KEY:<KEY>END_PI" #Trello redirects the user here after authentication loginCallback = "http://#{domain}:#{port}/cb" #need to store token: tokenSecret pairs; in a real application, this should be more permanent (redis would be a good choice) oauth_secrets = {} oauth = new OAuth(requestURL, accessURL, key, secret, "1.0", loginCallback, "HMAC-SHA1") login = (req, res) -> oauth.getOAuthRequestToken (error, token, tokenSecret, results) => oauth_secrets[token] = tokenSecret res.writeHead(302, { 'Location': "#{authorizeURL}?oauth_token=#{token}&name=#{appName}" }) res.end() cb = (req, res) -> query = url.parse(req.url, true).query token = query.oauth_token tokenSecret = oauth_secrets[token] verifier = query.oauth_verifier oauth.getOAuthAccessToken token, tokenSecret, verifier, (error, accessToken, accessTokenSecret, results) -> #in a real app, the accessToken and accessTokenSecret should be stored oauth.getProtectedResource("https://api.trello.com/1/members/me", "GET", accessToken, accessTokenSecret, (error, data, response) -> #respond with data to show that we now have access to your data res.end(data) ) http.createServer( (req, res) -> if /^\/login/.test(req.url) login(req, res) else if /^\/cb/.test(req.url) cb(req, res) else res.end("Don't know about that") ).listen(port, domain) console.log "Server running at #{domain}:#{port}; hit #{domain}:#{port}/login"
[ { "context": "ost', ->\n div class: 'field', ->\n label for: 'username', -> 'Username: '\n input id: 'username', name:", "end": 169, "score": 0.999419093132019, "start": 161, "tag": "USERNAME", "value": "username" }, { "context": "l for: 'username', -> 'Username: '\n input ...
node_modules/coffeekup/examples/express/views/login.coffee
brad-langshaw/project2
157
@title = 'Log In' h1 @title p "A local var: #{ping}" p "A context var: #{@foo}" form action: '/', method: 'post', -> div class: 'field', -> label for: 'username', -> 'Username: ' input id: 'username', name: 'username' div class: 'field', -> label for: 'password', -> 'Password: ' input id: 'password', name: 'password'
209423
@title = 'Log In' h1 @title p "A local var: #{ping}" p "A context var: #{@foo}" form action: '/', method: 'post', -> div class: 'field', -> label for: 'username', -> 'Username: ' input id: 'username', name: 'username' div class: 'field', -> label for: 'password', -> 'Password: ' input id: '<PASSWORD>', name: 'password'
true
@title = 'Log In' h1 @title p "A local var: #{ping}" p "A context var: #{@foo}" form action: '/', method: 'post', -> div class: 'field', -> label for: 'username', -> 'Username: ' input id: 'username', name: 'username' div class: 'field', -> label for: 'password', -> 'Password: ' input id: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'password'
[ { "context": " { separator: \"---------------\" },\n { name: \"Картинка\"\n key: \"P\"\n replaceWith: \"![[![Альте", "end": 1367, "score": 0.5141812562942505, "start": 1366, "tag": "NAME", "value": "К" }, { "context": " separator: \"---------------\" },\n { name: \"Карт...
app/assets/javascripts/markitup-setup.js.coffee
akolosov/houston
0
window.markdownSettings = { nameSpace: "markdown" # Useful to prevent multi-instances CSS conflict onShiftEnter: keepDefault: false openWith: "\n\n" markupSet: [ { name: "Заголовок 1-го уровня" key: "1" placeHolder: "Название здесь..." closeWith: (markItUp) -> miu.markdownTitle markItUp, "=" }, { name: "Заголовок 2-го уровня" key: "2" placeHolder: "Название здесь..." closeWith: (markItUp) -> miu.markdownTitle markItUp, "-" }, { name: "Заголовок 3-го уровня" key: "3" openWith: "### " placeHolder: "Название здесь..." }, { name: "Заголовок 4-го уровня" key: "4" openWith: "#### " placeHolder: "Название здесь..." }, { name: "Заголовок 5-го уровня" key: "5" openWith: "##### " placeHolder: "Название здесь..." }, { name: "Заголовок 6-го уровня" key: "6" openWith: "###### " placeHolder: "Название здесь..." }, { separator: "---------------" }, { name: "Полужирный" key: "B" openWith: "**" closeWith: "**" }, { name: "Наклонный" key: "I" openWith: "_" closeWith: "_" }, { separator: "---------------" }, { name: "Список" openWith: "- " }, { name: "Нумерованный список" openWith: (markItUp) -> markItUp.line + ". " }, { separator: "---------------" }, { name: "Картинка" key: "P" replaceWith: "![[![Альтернативный текст]!]]([![Ссылка:!:http://]!] \"[![Название]!]\")" }, { name: "Ссылка" key: "L" openWith: "[" closeWith: "]([![Ссылка:!:http://]!] \"[![Название]!]\")" placeHolder: "Текст для ссылки..." }, { separator: "---------------" }, { name: "Цитата" openWith: "> " }, { name: "Блок кода" openWith: "(!(\t|!|`)!)" closeWith: "(!(`)!)" } ] } # mIu nameSpace to avoid conflict. window.miu = markdownTitle: (markItUp, char) -> heading = "" n = $.trim(markItUp.selection or markItUp.placeHolder).length i = 0 while i < n heading += char i++ "\n" + heading + "\n"
223172
window.markdownSettings = { nameSpace: "markdown" # Useful to prevent multi-instances CSS conflict onShiftEnter: keepDefault: false openWith: "\n\n" markupSet: [ { name: "Заголовок 1-го уровня" key: "1" placeHolder: "Название здесь..." closeWith: (markItUp) -> miu.markdownTitle markItUp, "=" }, { name: "Заголовок 2-го уровня" key: "2" placeHolder: "Название здесь..." closeWith: (markItUp) -> miu.markdownTitle markItUp, "-" }, { name: "Заголовок 3-го уровня" key: "3" openWith: "### " placeHolder: "Название здесь..." }, { name: "Заголовок 4-го уровня" key: "4" openWith: "#### " placeHolder: "Название здесь..." }, { name: "Заголовок 5-го уровня" key: "5" openWith: "##### " placeHolder: "Название здесь..." }, { name: "Заголовок 6-го уровня" key: "6" openWith: "###### " placeHolder: "Название здесь..." }, { separator: "---------------" }, { name: "Полужирный" key: "B" openWith: "**" closeWith: "**" }, { name: "Наклонный" key: "I" openWith: "_" closeWith: "_" }, { separator: "---------------" }, { name: "Список" openWith: "- " }, { name: "Нумерованный список" openWith: (markItUp) -> markItUp.line + ". " }, { separator: "---------------" }, { name: "<NAME>арт<NAME>ка" key: "P" replaceWith: "![[![Альтернативный текст]!]]([![Ссылка:!:http://]!] \"[![Название]!]\")" }, { name: "<NAME>" key: "L" openWith: "[" closeWith: "]([![Ссылка:!:http://]!] \"[![Название]!]\")" placeHolder: "Текст для ссылки..." }, { separator: "---------------" }, { name: "<NAME>" openWith: "> " }, { name: "<NAME> кода" openWith: "(!(\t|!|`)!)" closeWith: "(!(`)!)" } ] } # mIu nameSpace to avoid conflict. window.miu = markdownTitle: (markItUp, char) -> heading = "" n = $.trim(markItUp.selection or markItUp.placeHolder).length i = 0 while i < n heading += char i++ "\n" + heading + "\n"
true
window.markdownSettings = { nameSpace: "markdown" # Useful to prevent multi-instances CSS conflict onShiftEnter: keepDefault: false openWith: "\n\n" markupSet: [ { name: "Заголовок 1-го уровня" key: "1" placeHolder: "Название здесь..." closeWith: (markItUp) -> miu.markdownTitle markItUp, "=" }, { name: "Заголовок 2-го уровня" key: "2" placeHolder: "Название здесь..." closeWith: (markItUp) -> miu.markdownTitle markItUp, "-" }, { name: "Заголовок 3-го уровня" key: "3" openWith: "### " placeHolder: "Название здесь..." }, { name: "Заголовок 4-го уровня" key: "4" openWith: "#### " placeHolder: "Название здесь..." }, { name: "Заголовок 5-го уровня" key: "5" openWith: "##### " placeHolder: "Название здесь..." }, { name: "Заголовок 6-го уровня" key: "6" openWith: "###### " placeHolder: "Название здесь..." }, { separator: "---------------" }, { name: "Полужирный" key: "B" openWith: "**" closeWith: "**" }, { name: "Наклонный" key: "I" openWith: "_" closeWith: "_" }, { separator: "---------------" }, { name: "Список" openWith: "- " }, { name: "Нумерованный список" openWith: (markItUp) -> markItUp.line + ". " }, { separator: "---------------" }, { name: "PI:NAME:<NAME>END_PIартPI:NAME:<NAME>END_PIка" key: "P" replaceWith: "![[![Альтернативный текст]!]]([![Ссылка:!:http://]!] \"[![Название]!]\")" }, { name: "PI:NAME:<NAME>END_PI" key: "L" openWith: "[" closeWith: "]([![Ссылка:!:http://]!] \"[![Название]!]\")" placeHolder: "Текст для ссылки..." }, { separator: "---------------" }, { name: "PI:NAME:<NAME>END_PI" openWith: "> " }, { name: "PI:NAME:<NAME>END_PI кода" openWith: "(!(\t|!|`)!)" closeWith: "(!(`)!)" } ] } # mIu nameSpace to avoid conflict. window.miu = markdownTitle: (markItUp, char) -> heading = "" n = $.trim(markItUp.selection or markItUp.placeHolder).length i = 0 while i < n heading += char i++ "\n" + heading + "\n"
[ { "context": "pi\n# A NodeJS interface for the Public Bitly API\n# Nathaniel Kirby <nate@projectspong.com\n# https://github.com/nkirb", "end": 132, "score": 0.9998853802680969, "start": 117, "tag": "NAME", "value": "Nathaniel Kirby" }, { "context": "rface for the Public Bitly API\n# ...
src/BitlyUser.coffee
nkirby/node-bitlyapi
30
#################################################### # node-bitlyapi # A NodeJS interface for the Public Bitly API # Nathaniel Kirby <nate@projectspong.com # https://github.com/nkirby/node-bitlyapi #################################################### class BitlyUser constructor: (@login, @bitly) -> #################################################### # User Info / History getInfo: (callback) -> if @login @bitly.getInfoForUser {login:@login}, callback else @bitly.getInfoForUser null, callback getLinkHistory: (params, callback) -> if @login params.user = @login @bitly.getUserLinkHistory params, callback getNetworkHistory: (params, callback) -> @bitly.getUserNetworkHistory params, callback getTrackingDomains: (params, callback) -> @bitly.getUserTrackingDomains params, callback #################################################### # User Metrics getClicks: (params, callback) -> @bitly.getUserClicks params, callback getCountries: (params, callback) -> @bitly.getUserCountries params, callback getPopularEarnedByClicks: (params, callback) -> @bitly.getUserPopularEarnedByClicks params, callback getPopularEarnedByShortens: (params, callback) -> @bitly.getUserPopularEarnedByShortens params, callback getPopularLinks: (params, callback) -> @bitly.getUserPopularLinks params, callback getPopularOwnedByClicks: (params, callback) -> @bitly.getUserPopularOwnedByClicks params, callback getPopularOwnedByShortens: (params, callback) -> @bitly.getUserPopularOwnedByShortens params, callback getReferrers: (params, callback) -> @bitly.getUserReferrers params, callback getReferringDomains: (params, callback) -> @bitly.getUserReferringDomains params, callback getShareCounts: (params, callback) -> @bitly.getUserShareCounts params, callback getShareCountsByShareType: (params, callback) -> @bitly.getUserShareCountsByShareType params, callback getShortenCounts: (params, callback) -> @bitly.getUserShortenCounts params, callback #################################################### # Bundles getBundles: (params, callback) -> if @login params.user = @login @bitly.bundlesByUser params, callback else @bitly.getUserBundleHistory params, callback
175341
#################################################### # node-bitlyapi # A NodeJS interface for the Public Bitly API # <NAME> <<EMAIL> # https://github.com/nkirby/node-bitlyapi #################################################### class BitlyUser constructor: (@login, @bitly) -> #################################################### # User Info / History getInfo: (callback) -> if @login @bitly.getInfoForUser {login:@login}, callback else @bitly.getInfoForUser null, callback getLinkHistory: (params, callback) -> if @login params.user = @login @bitly.getUserLinkHistory params, callback getNetworkHistory: (params, callback) -> @bitly.getUserNetworkHistory params, callback getTrackingDomains: (params, callback) -> @bitly.getUserTrackingDomains params, callback #################################################### # User Metrics getClicks: (params, callback) -> @bitly.getUserClicks params, callback getCountries: (params, callback) -> @bitly.getUserCountries params, callback getPopularEarnedByClicks: (params, callback) -> @bitly.getUserPopularEarnedByClicks params, callback getPopularEarnedByShortens: (params, callback) -> @bitly.getUserPopularEarnedByShortens params, callback getPopularLinks: (params, callback) -> @bitly.getUserPopularLinks params, callback getPopularOwnedByClicks: (params, callback) -> @bitly.getUserPopularOwnedByClicks params, callback getPopularOwnedByShortens: (params, callback) -> @bitly.getUserPopularOwnedByShortens params, callback getReferrers: (params, callback) -> @bitly.getUserReferrers params, callback getReferringDomains: (params, callback) -> @bitly.getUserReferringDomains params, callback getShareCounts: (params, callback) -> @bitly.getUserShareCounts params, callback getShareCountsByShareType: (params, callback) -> @bitly.getUserShareCountsByShareType params, callback getShortenCounts: (params, callback) -> @bitly.getUserShortenCounts params, callback #################################################### # Bundles getBundles: (params, callback) -> if @login params.user = @login @bitly.bundlesByUser params, callback else @bitly.getUserBundleHistory params, callback
true
#################################################### # node-bitlyapi # A NodeJS interface for the Public Bitly API # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI # https://github.com/nkirby/node-bitlyapi #################################################### class BitlyUser constructor: (@login, @bitly) -> #################################################### # User Info / History getInfo: (callback) -> if @login @bitly.getInfoForUser {login:@login}, callback else @bitly.getInfoForUser null, callback getLinkHistory: (params, callback) -> if @login params.user = @login @bitly.getUserLinkHistory params, callback getNetworkHistory: (params, callback) -> @bitly.getUserNetworkHistory params, callback getTrackingDomains: (params, callback) -> @bitly.getUserTrackingDomains params, callback #################################################### # User Metrics getClicks: (params, callback) -> @bitly.getUserClicks params, callback getCountries: (params, callback) -> @bitly.getUserCountries params, callback getPopularEarnedByClicks: (params, callback) -> @bitly.getUserPopularEarnedByClicks params, callback getPopularEarnedByShortens: (params, callback) -> @bitly.getUserPopularEarnedByShortens params, callback getPopularLinks: (params, callback) -> @bitly.getUserPopularLinks params, callback getPopularOwnedByClicks: (params, callback) -> @bitly.getUserPopularOwnedByClicks params, callback getPopularOwnedByShortens: (params, callback) -> @bitly.getUserPopularOwnedByShortens params, callback getReferrers: (params, callback) -> @bitly.getUserReferrers params, callback getReferringDomains: (params, callback) -> @bitly.getUserReferringDomains params, callback getShareCounts: (params, callback) -> @bitly.getUserShareCounts params, callback getShareCountsByShareType: (params, callback) -> @bitly.getUserShareCountsByShareType params, callback getShortenCounts: (params, callback) -> @bitly.getUserShortenCounts params, callback #################################################### # Bundles getBundles: (params, callback) -> if @login params.user = @login @bitly.bundlesByUser params, callback else @bitly.getUserBundleHistory params, callback
[ { "context": " \"start_year\":\"2009\"\n },\n {\n \"grant_title\":\"Stimulus Tracker\",\n \"id\":\"33\",\n \"organization\":\"Education Wr", "end": 10198, "score": 0.9720997214317322, "start": 10182, "tag": "NAME", "value": "Stimulus Tracker" }, { "context": "tion Network...
app/data/bubble/default.coffee
Tuhaj/ember-charts
1
App.data.bubble_default = [ { "grant_title":"New Mexico Business Roundtable", "id":"1", "organization":"New Mexico Business Roundtable for Educational Excellence", "total_amount":"5000", "group":"low", "Grant start date":"2/4/2010", "start_month":"2", "start_day":"4", "start_year":"2010" }, { "grant_title":"LA NSC Match", "id":"2", "organization":"Trustees of Dartmouth College", "total_amount":"27727", "group":"low", "Grant start date":"8/3/2009", "start_month":"8", "start_day":"3", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"3", "organization":"Denver School of Science and Technology Inc.", "total_amount":"36018", "group":"low", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"Convening of Stakeholder Planning Committee for the Institute for Local Innovation in Teaching and Learning", "id":"4", "organization":"The NEA Foundation for the Improvement of Education", "total_amount":"38420", "group":"low", "Grant start date":"3/11/2010", "start_month":"3", "start_day":"11", "start_year":"2010" }, { "grant_title":"Conference Support", "id":"5", "organization":"New Schools for New Orleans", "total_amount":"50000", "group":"low", "Grant start date":"10/12/2009", "start_month":"10", "start_day":"12", "start_year":"2009" }, { "grant_title":"Conference Support Grant on differentiated compensation symposium", "id":"6", "organization":"Battelle For Kids", "total_amount":"50000", "group":"low", "Grant start date":"6/30/2009", "start_month":"6", "start_day":"30", "start_year":"2009" }, { "grant_title":"Conference Support On School Turnaround Issues", "id":"7", "organization":"FSG Social Impact Advisors", "total_amount":"50000", "group":"low", "Grant start date":"9/24/2009", "start_month":"9", "start_day":"24", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - Aspire Public Schools", "id":"8", "organization":"Aspire Public Schools", "total_amount":"51500", "group":"low", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"Formative Assessment Task Development and Validation (Supplemental to OPP53449)", "id":"9", "organization":"Educational Policy Improvement Center", "total_amount":"55752", "group":"low", "Grant start date":"11/16/2009", "start_month":"11", "start_day":"16", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - E3 Alliance", "id":"10", "organization":"E3 Alliance", "total_amount":"56245", "group":"low", "Grant start date":"10/28/2009", "start_month":"10", "start_day":"28", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (Hillsborough)", "id":"11", "organization":"Hillsborough Education Foundation, Inc.", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (LA CMOs)", "id":"12", "organization":"The College-Ready Promise", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (Memphis)", "id":"13", "organization":"Memphis City Schools Foundation", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partners (Pittsburgh)", "id":"14", "organization":"Pittsburgh Public Schools", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - GHCF", "id":"15", "organization":"Greater Houston Community Foundation", "total_amount":"68500", "group":"low", "Grant start date":"10/28/2009", "start_month":"10", "start_day":"28", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - New Visions for Public Schools", "id":"16", "organization":"New Visions for Public Schools, Inc", "total_amount":"70116", "group":"low", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - Philadelphia Public Schools", "id":"17", "organization":"School District of Philadelphia", "total_amount":"74219", "group":"low", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"18", "organization":"Hamilton County Department of Education", "total_amount":"74800", "group":"low", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund – Internationals Network (with NCLR)", "id":"19", "organization":"Internationals Network For Public Schools Inc", "total_amount":"74900", "group":"low", "Grant start date":"3/24/2010", "start_month":"3", "start_day":"24", "start_year":"2010" }, { "grant_title":"City Based Proposal for What Works Fund - Minneapolis Public Schools", "id":"20", "organization":"Achieve Minneapolis", "total_amount":"74963", "group":"low", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - PTE", "id":"21", "organization":"The College-Ready Promise", "total_amount":"75000", "group":"low", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"TPERF Statewide Education Summit and Legislative Briefing", "id":"22", "organization":"Texas Public Education Reform Foundation", "total_amount":"75000", "group":"low", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"City Based Proposal for What Works Fund - NYC Charter Center", "id":"23", "organization":"New York City Center for Charter School Excellence", "total_amount":"75300", "group":"low", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"Supporting the development of a cross-sector plan that represent new levels of collaboration between one or more districts and the SEED School, a leading CMO in Washington, DC and Baltimore", "id":"24", "organization":"SEED Foundation, Inc.", "total_amount":"75970", "group":"low", "Grant start date":"1/28/2010", "start_month":"1", "start_day":"28", "start_year":"2010" }, { "grant_title":"City based proposal for What Works Fund - City of New Haven", "id":"25", "organization":"City of New Haven", "total_amount":"82500", "group":"low", "Grant start date":"11/17/2009", "start_month":"11", "start_day":"17", "start_year":"2009" }, { "grant_title":"Achievement Gap Institute: Annual Research-to-Practice Conference, How Teachers Improve", "id":"26", "organization":"President and Fellows of Harvard College", "total_amount":"91300", "group":"low", "Grant start date":"5/13/2009", "start_month":"5", "start_day":"13", "start_year":"2009" }, { "grant_title":"National Education Forum", "id":"27", "organization":"The Library of Congress", "total_amount":"91350", "group":"low", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Community Engagement Supporting College and Career Readiness", "id":"28", "organization":"Austin Voices for Education and Youth", "total_amount":"93000", "group":"low", "Grant start date":"10/1/2009", "start_month":"10", "start_day":"1", "start_year":"2009" }, { "grant_title":"Building & Sustaining Support for Good Schools: A Public Information Campaign", "id":"29", "organization":"Prichard Committee for Academic Excellence", "total_amount":"100000", "group":"medium", "Grant start date":"4/30/2010", "start_month":"4", "start_day":"30", "start_year":"2010" }, { "grant_title":"City Based Proposal for What Works Fund – Council of Great City Schools", "id":"30", "organization":"Council Of The Great City Schools", "total_amount":"100000", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"City based proposal for What Works Fund - New Schools for New Orleans", "id":"31", "organization":"New Schools for New Orleans", "total_amount":"100000", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"EEP Equality Day Rally Support", "id":"32", "organization":"Education Equality Project", "total_amount":"100000", "group":"medium", "Grant start date":"6/19/2009", "start_month":"6", "start_day":"19", "start_year":"2009" }, { "grant_title":"Stimulus Tracker", "id":"33", "organization":"Education Writers Association", "total_amount":"100000", "group":"medium", "Grant start date":"7/22/2009", "start_month":"7", "start_day":"22", "start_year":"2009" }, { "grant_title":"Repurpose of Alliance for Education Funds to a Variety of Essential Organizational Functions and Programs", "id":"34", "organization":"Alliance for Education", "total_amount":"110610", "group":"medium", "Grant start date":"2/26/2010", "start_month":"2", "start_day":"26", "start_year":"2010" }, { "grant_title":"Secondary STEM Data and Standards Analysis", "id":"35", "organization":"Texas Public Education Reform Foundation", "total_amount":"140000", "group":"medium", "Grant start date":"7/28/2009", "start_month":"7", "start_day":"28", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"36", "organization":"Charlotte-Mecklenburg Schools", "total_amount":"143973", "group":"medium", "Grant start date":"11/9/2009", "start_month":"11", "start_day":"9", "start_year":"2009" }, { "grant_title":"Ethnic Commission Education Reform Project", "id":"37", "organization":"Washington State Commission on African American Affairs", "total_amount":"146025", "group":"medium", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"38", "organization":"Cristo Rey Network", "total_amount":"149733", "group":"medium", "Grant start date":"11/6/2009", "start_month":"11", "start_day":"6", "start_year":"2009" }, { "grant_title":"California Collaborative on District Reform Phase 2", "id":"39", "organization":"American Institutes for Research", "total_amount":"150000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Professional Educator Standards Board", "id":"40", "organization":"Professional Educator Standards Board", "total_amount":"150000", "group":"medium", "Grant start date":"10/9/2009", "start_month":"10", "start_day":"9", "start_year":"2009" }, { "grant_title":"Evaluate the Leaky College Pipeline in New York City", "id":"41", "organization":"Fund for Public Schools Inc.", "total_amount":"170023", "group":"medium", "Grant start date":"10/27/2009", "start_month":"10", "start_day":"27", "start_year":"2009" }, { "grant_title":"Advocacy for Sustained School Reform in the Nation's Capital", "id":"42", "organization":"DC VOICE", "total_amount":"200000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"DC Expansion and CA STEM partnership", "id":"43", "organization":"Tiger Woods Foundation Inc.", "total_amount":"200000", "group":"medium", "Grant start date":"8/29/2009", "start_month":"8", "start_day":"29", "start_year":"2009" }, { "grant_title":"Retaining Teacher Talent: What Matters for Gen-Y Teachers", "id":"44", "organization":"Public Agenda Foundation, Inc.", "total_amount":"215000", "group":"medium", "Grant start date":"3/2/2009", "start_month":"3", "start_day":"2", "start_year":"2009" }, { "grant_title":"Supplemental Support for the New York STEM Progressive Dialogues (original grant on OPP52284)", "id":"45", "organization":"Rensselaer Polytechnic Institute", "total_amount":"220654", "group":"medium", "Grant start date":"9/29/2009", "start_month":"9", "start_day":"29", "start_year":"2009" }, { "grant_title":"Teacher Demographics and Pension Policies", "id":"46", "organization":"National Commission on Teachings & America's Future", "total_amount":"221755", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Charter School Initiative", "id":"47", "organization":"President and Fellows of Harvard College", "total_amount":"224030", "group":"medium", "Grant start date":"2/25/2010", "start_month":"2", "start_day":"25", "start_year":"2010" }, { "grant_title":"High School Standards Review project", "id":"48", "organization":"Illinois State Board of Education", "total_amount":"225000", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Progressive Dialogues (Supplemental grant on OPP1008819)", "id":"49", "organization":"Rensselaer Polytechnic Institute", "total_amount":"231382", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Support access to ARRA funds for strong CMOs", "id":"50", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"246070", "group":"medium", "Grant start date":"9/10/2009", "start_month":"9", "start_day":"10", "start_year":"2009" }, { "grant_title":"Aspen-NewSchools Fellows", "id":"51", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"250000", "group":"medium", "Grant start date":"3/26/2009", "start_month":"3", "start_day":"26", "start_year":"2009" }, { "grant_title":"Texas Charter Schools Association", "id":"52", "organization":"Texas Charter Schools Association", "total_amount":"250000", "group":"medium", "Grant start date":"5/18/2009", "start_month":"5", "start_day":"18", "start_year":"2009" }, { "grant_title":"to support the work of a teacher evaluation task force", "id":"53", "organization":"American Federation Of Teachers Educational Foundation", "total_amount":"250000", "group":"medium", "Grant start date":"6/23/2009", "start_month":"6", "start_day":"23", "start_year":"2009" }, { "grant_title":"Ensuring a Valid and Useable Teacher Student Link", "id":"54", "organization":"National Center For Educational Achievement", "total_amount":"260760", "group":"medium", "Grant start date":"11/21/2009", "start_month":"11", "start_day":"21", "start_year":"2009" }, { "grant_title":"Consistent College-Ready Standards", "id":"55", "organization":"Military Child Education Coalition", "total_amount":"269998", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"DCPS Measures of Teacher Effectiveness Study", "id":"56", "organization":"DC Public Education Fund", "total_amount":"299985", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Creating a Stronger Philanthropic Sector in Education", "id":"57", "organization":"Grantmakers for Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/6/2009", "start_month":"11", "start_day":"6", "start_year":"2009" }, { "grant_title":"Envision Schools Post-Secondary Tracking", "id":"58", "organization":"Envision Schools", "total_amount":"300000", "group":"medium", "Grant start date":"6/1/2008", "start_month":"6", "start_day":"1", "start_year":"2008" }, { "grant_title":"Global Education Leaders' Program (GELP)", "id":"59", "organization":"Silicon Valley Community Foundation", "total_amount":"300000", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Investigation of the Relationship between Teacher Quality and Student Learning Outcomes", "id":"60", "organization":"ACT, Inc.", "total_amount":"300000", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher-Student Data Link Project - Arkansas", "id":"61", "organization":"Arkansas Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Florida", "id":"62", "organization":"Florida Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Georgia", "id":"63", "organization":"Georgia Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Louisiana", "id":"64", "organization":"Louisiana Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Ohio", "id":"65", "organization":"Ohio Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"The California STEM Innovation Network", "id":"66", "organization":"California Polytechnic State University Foundation", "total_amount":"300000", "group":"medium", "Grant start date":"1/8/2009", "start_month":"1", "start_day":"8", "start_year":"2009" }, { "grant_title":"TN SCORE state advocacy coalition", "id":"67", "organization":"Tennessee State Collaborative on Reforming Education", "total_amount":"300250", "group":"medium", "Grant start date":"2/19/2010", "start_month":"2", "start_day":"19", "start_year":"2010" }, { "grant_title":"Bring Your 'A' Game", "id":"68", "organization":"Twenty First Century Foundation", "total_amount":"302425", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Instructional Support at Cleveland and Rainier Beach", "id":"69", "organization":"Alliance for Education", "total_amount":"309554", "group":"medium", "Grant start date":"9/17/2008", "start_month":"9", "start_day":"17", "start_year":"2008" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"70", "organization":"National Council of La Raza", "total_amount":"322103", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"NYC Public Schools: A Retrospective 2002-2009", "id":"71", "organization":"American Institutes for Research", "total_amount":"325000", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"NSC Student Data for High Schools Pilot: Georgia", "id":"72", "organization":"University System of Georgia Foundation, Inc.", "total_amount":"331678", "group":"medium", "Grant start date":"11/11/2009", "start_month":"11", "start_day":"11", "start_year":"2009" }, { "grant_title":"Common Core Companion Curriculum Project", "id":"73", "organization":"Common Core Inc.", "total_amount":"331890", "group":"medium", "Grant start date":"12/17/2009", "start_month":"12", "start_day":"17", "start_year":"2009" }, { "grant_title":"Civic Mission of Schools", "id":"74", "organization":"National Council for the Social Studies", "total_amount":"351704", "group":"medium", "Grant start date":"6/1/2008", "start_month":"6", "start_day":"1", "start_year":"2008" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"75", "organization":"Pittsburgh Public Schools", "total_amount":"353977", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"Institute for Local Innovation in Teaching and Learning", "id":"76", "organization":"The NEA Foundation for the Improvement of Education", "total_amount":"358915", "group":"medium", "Grant start date":"10/22/2009", "start_month":"10", "start_day":"22", "start_year":"2009" }, { "grant_title":"Campaign for High School Equity", "id":"77", "organization":"L.U.L.A.C. Institute, Inc.", "total_amount":"370005", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Preparing Secondary English Learners for Graduation and College", "id":"78", "organization":"University of California, Los Angeles", "total_amount":"375000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"79", "organization":"Leadership Conference on Civil Rights Education Fund, Inc.", "total_amount":"375030", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"NSC Student Data for High Schools Pilot: Florida", "id":"80", "organization":"Florida Department of Education", "total_amount":"383465", "group":"medium", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"The Policy Innovation in Education Network", "id":"81", "organization":"Thomas B. Fordham Institute", "total_amount":"398534", "group":"medium", "Grant start date":"6/15/2009", "start_month":"6", "start_day":"15", "start_year":"2009" }, { "grant_title":"Common Core Strategies for State Policymakers", "id":"82", "organization":"Council of State Governments", "total_amount":"399953", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"83", "organization":"Mexican American Legal Defense and Educational Fund", "total_amount":"400000", "group":"medium", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Education Equity Agenda: LULAC Parent Involvement Initiative for Campaign for High School Equity", "id":"84", "organization":"L.U.L.A.C. Institute, Inc.", "total_amount":"400017", "group":"medium", "Grant start date":"9/21/2009", "start_month":"9", "start_day":"21", "start_year":"2009" }, { "grant_title":"8th to 9th Grade Transition and Acceleration Project", "id":"85", "organization":"National Summer Learning Association", "total_amount":"400366", "group":"medium", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"Support of professional development and an education workshop for education beat reporters", "id":"86", "organization":"Teachers College, Columbia University", "total_amount":"402493", "group":"medium", "Grant start date":"9/29/2009", "start_month":"9", "start_day":"29", "start_year":"2009" }, { "grant_title":"NSC Student Data for High Schools Pilot: Texas", "id":"87", "organization":"Communities Foundation of Texas", "total_amount":"406610", "group":"medium", "Grant start date":"10/15/2009", "start_month":"10", "start_day":"15", "start_year":"2009" }, { "grant_title":"Supplemental Support Review and Build-out of the Raytheon STEM Model", "id":"88", "organization":"Business Higher Education Forum", "total_amount":"417517", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"The State of Professional Learning: A National Study", "id":"89", "organization":"National Staff Development Council", "total_amount":"421603", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Southeast Asian American Action and Visibility in Education (SAVE) Project", "id":"90", "organization":"Southeast Asia Resource Action Center", "total_amount":"425000", "group":"medium", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Roads to Success Curriculum Completion and Distribution", "id":"91", "organization":"Roads to Success Inc.", "total_amount":"430000", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"STEM Community Collaborative Phase 2", "id":"92", "organization":"MCNC", "total_amount":"432898", "group":"medium", "Grant start date":"3/6/2009", "start_month":"3", "start_day":"6", "start_year":"2009" }, { "grant_title":"California ADP Support", "id":"93", "organization":"Regents of the University of California at Berkeley", "total_amount":"437807", "group":"medium", "Grant start date":"10/22/2008", "start_month":"10", "start_day":"22", "start_year":"2008" }, { "grant_title":"Regional convenings for policymakers and leaders to develop commitment to standards and assessments", "id":"94", "organization":"National Association of State Boards of Education", "total_amount":"450675", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"Business Planning to Create Hybrid Learning Environments in Existing and New Schools", "id":"95", "organization":"Pollinate Ventures", "total_amount":"451125", "group":"medium", "Grant start date":"11/8/2009", "start_month":"11", "start_day":"8", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"96", "organization":"Fund for Public Schools Inc.", "total_amount":"455394", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"KIPPShare National Data Platform", "id":"97", "organization":"KIPP Foundation", "total_amount":"468500", "group":"medium", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"The Equity Project (TEP) Charter School Evaluation", "id":"98", "organization":"Mathematica Policy Research", "total_amount":"470507", "group":"medium", "Grant start date":"7/16/2009", "start_month":"7", "start_day":"16", "start_year":"2009" }, { "grant_title":"North Carolina STEM Development", "id":"99", "organization":"MCNC", "total_amount":"475000", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Using web-based videos to teach math to high school students", "id":"100", "organization":"Guaranteach", "total_amount":"475077", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"CPS Community Ownership Proposal", "id":"101", "organization":"Strive: Cincinnati/Northern Kentucky, LLC", "total_amount":"490021", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher Working Conditions Survey", "id":"102", "organization":"New Teacher Center", "total_amount":"494933", "group":"medium", "Grant start date":"10/13/2009", "start_month":"10", "start_day":"13", "start_year":"2009" }, { "grant_title":"North Carolina New Technology High School Network Sustainability", "id":"103", "organization":"New Technology Foundation", "total_amount":"496776", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Planning Grant for Evaluation of Green Dot's Locke Transformation Project", "id":"104", "organization":"University of California, Los Angeles", "total_amount":"498724", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Preparing All Students for College, Work and Citizenship", "id":"105", "organization":"National Conference of State Legislatures", "total_amount":"499225", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Gateway to College Capacity-Building", "id":"106", "organization":"Gateway to College National Network", "total_amount":"499398", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Doubling the Numbers in STEM", "id":"107", "organization":"Ohio Business Alliance for Higher Education and the Economy", "total_amount":"500000", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"IMPLEMENTATION: StartL: A Digital Media and Learning Accelerator", "id":"108", "organization":"Social Science Research Council", "total_amount":"500000", "group":"medium", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"NAPCS General Operating Support", "id":"109", "organization":"National Alliance For Public Charter Schools", "total_amount":"500000", "group":"medium", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"New England Consortium", "id":"110", "organization":"Nellie Mae Education Foundation", "total_amount":"500000", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"WGHA Ambassadors", "id":"111", "organization":"Seattle Biomedical Research Institute", "total_amount":"500000", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Stay for America (retaining effective Teach for America teachers beyond year 2)", "id":"112", "organization":"Teach for America, Inc.", "total_amount":"500422", "group":"medium", "Grant start date":"10/1/2009", "start_month":"10", "start_day":"1", "start_year":"2009" }, { "grant_title":"Grassroots Media Project", "id":"113", "organization":"Fund for the City of New York, Inc.", "total_amount":"513219", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Improving Native Student Graduation Rates: Policy Recommendations on High School Reform", "id":"114", "organization":"National Indian Education Association", "total_amount":"520446", "group":"medium", "Grant start date":"8/31/2009", "start_month":"8", "start_day":"31", "start_year":"2009" }, { "grant_title":"The State Role In Improving Low-performing Schools", "id":"115", "organization":"Center on Education Policy", "total_amount":"544700", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Engaging Communities for College Readiness (ENCORE)", "id":"116", "organization":"Texas Valley Communities Foundation", "total_amount":"546865", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"New Degree Program for Education Leaders", "id":"117", "organization":"President and Fellows of Harvard College", "total_amount":"550000", "group":"medium", "Grant start date":"8/1/2008", "start_month":"8", "start_day":"1", "start_year":"2008" }, { "grant_title":"National Advocacy Support for the Common Core Initiative", "id":"118", "organization":"Alliance for Excellent Education, Inc.", "total_amount":"551336", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"Conceptual and Organizing Platform for Secondary Mathematics Formative Assessments", "id":"119", "organization":"Regents University Of California Los Angeles", "total_amount":"576191", "group":"medium", "Grant start date":"5/11/2009", "start_month":"5", "start_day":"11", "start_year":"2009" }, { "grant_title":"Education Practice Launch", "id":"120", "organization":"Innosight Institute Inc", "total_amount":"588559", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Building Business Leadership for New Approaches to Teacher Compensation", "id":"121", "organization":"Committee for Economic Development", "total_amount":"597077", "group":"medium", "Grant start date":"5/5/2009", "start_month":"5", "start_day":"5", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"122", "organization":"Prichard Committee for Academic Excellence", "total_amount":"599016", "group":"medium", "Grant start date":"11/16/2009", "start_month":"11", "start_day":"16", "start_year":"2009" }, { "grant_title":"THE HIGH SCHOOL REDESIGN INITIATIVE -- PHASE TWO", "id":"123", "organization":"National Association of State Boards of Education", "total_amount":"599725", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Aligning P-12 and Postsecondary Data Systems", "id":"124", "organization":"National Center For Educational Achievement", "total_amount":"600000", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"The Next Generation of NCLR Schools", "id":"125", "organization":"National Council of La Raza", "total_amount":"600000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Washington STEM Innovation Initiative", "id":"126", "organization":"Partnership for Learning", "total_amount":"643881", "group":"medium", "Grant start date":"3/11/2009", "start_month":"3", "start_day":"11", "start_year":"2009" }, { "grant_title":"Teacher Effectiveness work", "id":"127", "organization":"Hope Street Group", "total_amount":"650108", "group":"medium", "Grant start date":"11/7/2009", "start_month":"11", "start_day":"7", "start_year":"2009" }, { "grant_title":"Stimulus related work and CSA support", "id":"128", "organization":"Institute for a Competitive Workforce", "total_amount":"653077", "group":"medium", "Grant start date":"11/11/2009", "start_month":"11", "start_day":"11", "start_year":"2009" }, { "grant_title":"Validating a Common Core of Fewer, Clearer, Higher Standards", "id":"129", "organization":"Educational Policy Improvement Center", "total_amount":"721687", "group":"medium", "Grant start date":"5/5/2009", "start_month":"5", "start_day":"5", "start_year":"2009" }, { "grant_title":"Preparing parents and students to be advocates for quality school reform in Illinois", "id":"130", "organization":"Target Area Development Corporation", "total_amount":"725000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Building Capacity for College Success: Implementing Data Collection Systems and Best Practices", "id":"131", "organization":"National Association of Street Schools", "total_amount":"742223", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Support for National Lab Day", "id":"132", "organization":"Tides Center", "total_amount":"750000", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Winning Strategies Black Male Donor Collaborative", "id":"133", "organization":"The Schott Foundation For Public Education", "total_amount":"750000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"The Role of School Board Governance in Preaparing Students for College and Workplace Readiness", "id":"134", "organization":"National School Boards Foundation", "total_amount":"755603", "group":"medium", "Grant start date":"4/25/2009", "start_month":"4", "start_day":"25", "start_year":"2009" }, { "grant_title":"Tracking Students from Secondary to Post Secondary Institutions", "id":"135", "organization":"National Student Clearinghouse", "total_amount":"792216", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"136", "organization":"National Urban League Inc.", "total_amount":"800000", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"WA State Board of Education Phase II: A Meaningful High School Diploma and A State Accountability Education System", "id":"137", "organization":"The Washington State Board of Education", "total_amount":"850000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Measures of Effective Teaching Research Site", "id":"138", "organization":"Denver Public Schools", "total_amount":"878493", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"STEM Capacity Building", "id":"139", "organization":"Business Higher Education Forum", "total_amount":"910000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"140", "organization":"National Council of La Raza", "total_amount":"930223", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"DC Achiever Restructuring Partner", "id":"141", "organization":"Friendship Public Charter School", "total_amount":"937088", "group":"medium", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"PRI Guaranty To Unlock Facilities Financing for High Quality Charter Schools", "id":"142", "organization":"Local Initiatives Support Corporation", "total_amount":"950000", "group":"medium", "Grant start date":"8/27/2009", "start_month":"8", "start_day":"27", "start_year":"2009" }, { "grant_title":"Common Standards Review and Task Development", "id":"143", "organization":"Thomas B. Fordham Institute", "total_amount":"959116", "group":"medium", "Grant start date":"10/10/2009", "start_month":"10", "start_day":"10", "start_year":"2009" }, { "grant_title":"Intermediary management of PRI/Credit Enhancement Program - Los Angeles (Aspire)", "id":"144", "organization":"NCB Capital Impact", "total_amount":"959373", "group":"medium", "Grant start date":"4/8/2010", "start_month":"4", "start_day":"8", "start_year":"2010" }, { "grant_title":"Sustainability for Recovery School District", "id":"145", "organization":"Baton Rouge Area Foundation", "total_amount":"993219", "group":"medium", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"Research Design for Project-Based Advanced Placement Courses", "id":"146", "organization":"University of Washington", "total_amount":"996185", "group":"medium", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Accelerate and Enhance Teacher Effectiveness Methods In Districts/Networks", "id":"147", "organization":"Achievement First Inc.", "total_amount":"998221", "group":"medium", "Grant start date":"10/9/2009", "start_month":"10", "start_day":"9", "start_year":"2009" }, { "grant_title":"AFT Innovation Fund", "id":"148", "organization":"American Federation Of Teachers Educational Foundation", "total_amount":"1000000", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Applying an R&D model to education to unearth root causes of performance gaps, to effectively vet options for reform.", "id":"149", "organization":"President and Fellows of Harvard College", "total_amount":"1000000", "group":"medium", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"For the Future", "id":"150", "organization":"Team Pennsylvania Foundation", "total_amount":"1000000", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"General Support Supplemental", "id":"151", "organization":"The Education Trust", "total_amount":"1000000", "group":"medium", "Grant start date":"1/21/2010", "start_month":"1", "start_day":"21", "start_year":"2010" }, { "grant_title":"Ohio College and Career Ready Consortium", "id":"152", "organization":"Ohio Grantmakers Forum", "total_amount":"1000000", "group":"medium", "Grant start date":"7/18/2009", "start_month":"7", "start_day":"18", "start_year":"2009" }, { "grant_title":"Strategic Management of Human Capital in Public Ed", "id":"153", "organization":"University of Wisconsin", "total_amount":"1000000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"to support Teach for America (TFA) with the goal of bringing low income and minority students in TFA classrooms to proficiency", "id":"154", "organization":"Teach for America, Inc.", "total_amount":"1000000", "group":"medium", "Grant start date":"6/26/2009", "start_month":"6", "start_day":"26", "start_year":"2009" }, { "grant_title":"Los Angeles Collaborative to Improve College and Career Readiness in LAUSD Schools", "id":"155", "organization":"United Way Inc.", "total_amount":"1000330", "group":"high", "Grant start date":"1/15/2009", "start_month":"1", "start_day":"15", "start_year":"2009" }, { "grant_title":"PEN business planning", "id":"156", "organization":"Public Education Network", "total_amount":"1001363", "group":"high", "Grant start date":"7/10/2009", "start_month":"7", "start_day":"10", "start_year":"2009" }, { "grant_title":"Accelerate and Enhance Teacher Effectiveness Methods In Districts/Networks", "id":"157", "organization":"Recovery School District", "total_amount":"1004719", "group":"high", "Grant start date":"10/22/2009", "start_month":"10", "start_day":"22", "start_year":"2009" }, { "grant_title":"CEP standards and assessment work", "id":"158", "organization":"Center on Education Policy", "total_amount":"1047928", "group":"high", "Grant start date":"9/8/2009", "start_month":"9", "start_day":"8", "start_year":"2009" }, { "grant_title":"College Bound", "id":"159", "organization":"College Success Foundation", "total_amount":"1053150", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Accelerator Enhance Teacher Effectiveness Methods - RE: ASPIRE Model in HISD", "id":"160", "organization":"Houston Independent School District", "total_amount":"1100000", "group":"high", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"Ohio Follow-Through on Achieve Policy Study Recommendations", "id":"161", "organization":"Ohio Department of Education", "total_amount":"1175000", "group":"high", "Grant start date":"1/1/2008", "start_month":"1", "start_day":"1", "start_year":"2008" }, { "grant_title":"Philanthropic Partnership for Public Education", "id":"162", "organization":"Seattle Foundation", "total_amount":"1181375", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"A Progressive Agenda for Human Capital Policy Reform", "id":"163", "organization":"Center for American Progress", "total_amount":"1198248", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Gates-EdVisions Moving Forward", "id":"164", "organization":"EdVisions Inc", "total_amount":"1200552", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Texas Education Research Support", "id":"165", "organization":"College for All Texans Foundation: Closing the Gaps", "total_amount":"1221800", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Portable Word Play - Discovering What Handheld Games Can Do for Adolescent Reading Comprehension", "id":"166", "organization":"Education Development Center, Inc.", "total_amount":"1224953", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Baltimore Sustainability Plan", "id":"167", "organization":"Fund for Educational Excellence", "total_amount":"1229730", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Academic Youth Development", "id":"168", "organization":"University of Texas at Austin", "total_amount":"1235787", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Campaign for High School Equity", "id":"169", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"1279229", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"support the K-12 backmapping of the standards", "id":"170", "organization":"Council of Chief State School Officers", "total_amount":"1291738", "group":"high", "Grant start date":"10/12/2009", "start_month":"10", "start_day":"12", "start_year":"2009" }, { "grant_title":"Building College-Ready Culture in Our High Schools", "id":"171", "organization":"College Summit Inc.", "total_amount":"1300000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Measures of Effective Teaching Research Site", "id":"172", "organization":"Dallas Independent School District", "total_amount":"1332279", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Technical Assistance for Standards/Assessment Partners", "id":"173", "organization":"National Center for the Improvement of Educational Assessment Inc.", "total_amount":"1362773", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Making NSC Data Actionable for School Leaders", "id":"174", "organization":"College Summit Inc", "total_amount":"1383137", "group":"high", "Grant start date":"5/22/2009", "start_month":"5", "start_day":"22", "start_year":"2009" }, { "grant_title":"Charlotte-Mecklenburg Measures of Teacher Effectiveness Research", "id":"175", "organization":"Charlotte-Mecklenburg Schools", "total_amount":"1431534", "group":"high", "Grant start date":"9/3/2009", "start_month":"9", "start_day":"3", "start_year":"2009" }, { "grant_title":"College Ready Course Sequence Implementation", "id":"176", "organization":"ACT, Inc.", "total_amount":"1445269", "group":"high", "Grant start date":"9/14/2009", "start_month":"9", "start_day":"14", "start_year":"2009" }, { "grant_title":"Partnership for Learning Statewide Advocacy + Stimulus RTT TA", "id":"177", "organization":"Partnership for Learning", "total_amount":"1493522", "group":"high", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"178", "organization":"Tulsa Public Schools", "total_amount":"1500000", "group":"high", "Grant start date":"2/4/2010", "start_month":"2", "start_day":"4", "start_year":"2010" }, { "grant_title":"LEV Statewide Advocacy Expansion", "id":"179", "organization":"League of Education Voters Foundation", "total_amount":"1500000", "group":"high", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"NCEE state partnerships", "id":"180", "organization":"National Center on Education & the Economy", "total_amount":"1500000", "group":"high", "Grant start date":"10/19/2009", "start_month":"10", "start_day":"19", "start_year":"2009" }, { "grant_title":"Development of frameworks for the assessment of teacher knowledge", "id":"181", "organization":"Educational Testing Service", "total_amount":"1521971", "group":"high", "Grant start date":"11/14/2009", "start_month":"11", "start_day":"14", "start_year":"2009" }, { "grant_title":"Organizing for High School Reform", "id":"182", "organization":"Pacific Institute For Community Organizations", "total_amount":"1600000", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Expansion of Urban Teacher Residency (UTRU)", "id":"183", "organization":"The Urban Teacher Residency Institute", "total_amount":"1635665", "group":"high", "Grant start date":"9/1/2009", "start_month":"9", "start_day":"1", "start_year":"2009" }, { "grant_title":"Advance Illinois organization build", "id":"184", "organization":"Advance Illinois", "total_amount":"1800000", "group":"high", "Grant start date":"5/15/2008", "start_month":"5", "start_day":"15", "start_year":"2008" }, { "grant_title":"Validation of the Teaching as Leadership Rubric", "id":"185", "organization":"Teach for America, Inc.", "total_amount":"1840548", "group":"high", "Grant start date":"10/5/2009", "start_month":"10", "start_day":"5", "start_year":"2009" }, { "grant_title":"CMO Research Study Project Management", "id":"186", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"1891265", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"6to16", "id":"187", "organization":"University of Chicago - Urban Education Institute", "total_amount":"1894228", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Support for Campaign for High School Equity coordination of national civil rights organization national policy advocacy of College Ready and Postsecondary Strategies", "id":"188", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"1915298", "group":"high", "Grant start date":"10/19/2009", "start_month":"10", "start_day":"19", "start_year":"2009" }, { "grant_title":"Strengthening State College Readiness Initiatives", "id":"189", "organization":"Board Of Control For Southern Regional Education", "total_amount":"1987015", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"190", "organization":"Memphis City Schools", "total_amount":"1988654", "group":"high", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"New-Media Capacity Building at EPE", "id":"191", "organization":"Editorial Projects in Education", "total_amount":"1997280", "group":"high", "Grant start date":"5/1/2009", "start_month":"5", "start_day":"1", "start_year":"2009" }, { "grant_title":"Implementation: National PTA support for college-readiness", "id":"192", "organization":"National Congress of Parents and Teachers", "total_amount":"2000000", "group":"high", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"The Public Education Reform and Community Development Link: A Sustainable Solution", "id":"193", "organization":"Deutsche Bank Americas Foundation", "total_amount":"2000000", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Project GRAD USA's National College Readiness Initiative", "id":"194", "organization":"Project GRAD", "total_amount":"2025892", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Literacy by Design", "id":"195", "organization":"The Trust For Early Education Inc", "total_amount":"2039526", "group":"high", "Grant start date":"9/17/2009", "start_month":"9", "start_day":"17", "start_year":"2009" }, { "grant_title":"THSP Alliance Business Planning", "id":"196", "organization":"Communities Foundation of Texas", "total_amount":"2046674", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher-Student Data Link Project", "id":"197", "organization":"CELT Corporation", "total_amount":"2200000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Dropout Prevention", "id":"198", "organization":"Americas Promise-The Alliance For Youth", "total_amount":"2211517", "group":"high", "Grant start date":"3/19/2008", "start_month":"3", "start_day":"19", "start_year":"2008" }, { "grant_title":"Hunt Institute Common State Education Standards Project", "id":"199", "organization":"The James B. Hunt, Jr. Institute for Educational Leadership and Policy", "total_amount":"2213470", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Business Planning for Education grantees", "id":"200", "organization":"The Bridgespan Group", "total_amount":"2237530", "group":"high", "Grant start date":"4/20/2009", "start_month":"4", "start_day":"20", "start_year":"2009" }, { "grant_title":"Develop Tools for Teachers/Districts to Monitor Student Progress", "id":"201", "organization":"Math Solutions", "total_amount":"2274957", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"IB Middle Years Summative Assessment", "id":"202", "organization":"IB Fund US Inc.", "total_amount":"2423679", "group":"high", "Grant start date":"8/22/2009", "start_month":"8", "start_day":"22", "start_year":"2009" }, { "grant_title":"To Help Governors Improve College and Career Ready Rates", "id":"203", "organization":"National Governors Association Center For Best Practices", "total_amount":"2496814", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Next Generation PD System", "id":"204", "organization":"DC Public Education Fund", "total_amount":"2500000", "group":"high", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"205", "organization":"Prince George's County Public Schools", "total_amount":"2500169", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"206", "organization":"Hillsborough County Public Schools", "total_amount":"2502146", "group":"high", "Grant start date":"10/20/2009", "start_month":"10", "start_day":"20", "start_year":"2009" }, { "grant_title":"Scaling NCTQ state and district work", "id":"207", "organization":"National Council on Teacher Quality", "total_amount":"2565641", "group":"high", "Grant start date":"10/21/2009", "start_month":"10", "start_day":"21", "start_year":"2009" }, { "grant_title":"NAPCS Industry Development", "id":"208", "organization":"National Alliance For Public Charter Schools", "total_amount":"2605527", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Increasing Business Engagement", "id":"209", "organization":"Institute for a Competitive Workforce", "total_amount":"2625837", "group":"high", "Grant start date":"10/8/2008", "start_month":"10", "start_day":"8", "start_year":"2008" }, { "grant_title":"Building Support for Federal High School Policy Reform", "id":"210", "organization":"Alliance for Excellent Education, Inc.", "total_amount":"2644892", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"NYC DOE Measures of Teacher Effectiveness Research", "id":"211", "organization":"Fund for Public Schools Inc.", "total_amount":"2646876", "group":"high", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Aspire Public Schools' Early College High School Capacity Project", "id":"212", "organization":"Aspire Public Schools", "total_amount":"2899727", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Big 8 Superintendents Data Assessment", "id":"213", "organization":"Communities Foundation of Texas", "total_amount":"2901632", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"National Impact Initiative", "id":"214", "organization":"National Association Of Charter School Authorizers", "total_amount":"2979186", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Development and Adaptation of Science and Literacy Formative Assessment Tasks", "id":"215", "organization":"Regents Of The University Of California At Berkeley", "total_amount":"2999730", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Research Alliance for New York City Schools", "id":"216", "organization":"New York University", "total_amount":"2999960", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"CCSR General Operating Support", "id":"217", "organization":"University of Chicago (Parent Org)", "total_amount":"3000000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Deepening and Expanding the Impact of Diploma Plus", "id":"218", "organization":"Third Sector New England, Inc.", "total_amount":"3179363", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"To provide support to states on RTTT applications", "id":"219", "organization":"New Venture Fund", "total_amount":"3240000", "group":"high", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"Alternative High School Initiative", "id":"220", "organization":"The Big Picture Company", "total_amount":"3315216", "group":"high", "Grant start date":"7/15/2009", "start_month":"7", "start_day":"15", "start_year":"2009" }, { "grant_title":"Support for Teaching First to ensure that there is public support for district efforts to improve teacher effectiveness", "id":"221", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"3487270", "group":"high", "Grant start date":"9/25/2009", "start_month":"9", "start_day":"25", "start_year":"2009" }, { "grant_title":"IDEA Public Schools Expansion", "id":"222", "organization":"Idea Academy Inc", "total_amount":"3498875", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Title", "id":"223", "organization":"College Summit Inc", "total_amount":"3500000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"College Ready Mathematics Formative Assessments", "id":"224", "organization":"Regents Of The University Of California At Berkeley", "total_amount":"3661294", "group":"high", "Grant start date":"9/25/2009", "start_month":"9", "start_day":"25", "start_year":"2009" }, { "grant_title":"Using Standards and Data to Improve Urban School Systems", "id":"225", "organization":"Council Of The Great City Schools", "total_amount":"3735866", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"College Readiness Data Initiative", "id":"226", "organization":"Dallas Independent School District", "total_amount":"3774912", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Project support for expanding Aspen network", "id":"227", "organization":"The Aspen Institute", "total_amount":"3878680", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Aligned Instructional Systems", "id":"228", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"3999127", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"DC Schools Fund", "id":"229", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"4000000", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Newark School Fund", "id":"230", "organization":"Newark Charter School Fund, Inc.", "total_amount":"4000000", "group":"high", "Grant start date":"2/15/2008", "start_month":"2", "start_day":"15", "start_year":"2008" }, { "grant_title":"SeaChange Capacity and Catalyst Funding", "id":"231", "organization":"SeaChange Capital Partners, Inc.", "total_amount":"4000000", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"College and Career Ready Graduation Initiative", "id":"232", "organization":"United Way of America", "total_amount":"4001263", "group":"high", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Elevating An Alternative Teacher Voice", "id":"233", "organization":"Teach Plus, Incorporated", "total_amount":"4010611", "group":"high", "Grant start date":"9/30/2009", "start_month":"9", "start_day":"30", "start_year":"2009" }, { "grant_title":"Big Picture School Initiative", "id":"234", "organization":"The Big Picture Company", "total_amount":"4079157", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Matching Grant for Classroom Projects in Public High Schools", "id":"235", "organization":"DonorsChoose.org", "total_amount":"4114700", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Formative Assessment Data Collection, Task Analysis and Implementation (UCLA/CRESST)", "id":"236", "organization":"Regents University Of California Los Angeles", "total_amount":"4342988", "group":"high", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"State and National Common Core Standards Adoption/Implementation Advocacy Support", "id":"237", "organization":"James B. Hunt, Jr. Institute for Educational Leadership and Policy Foundation, Inc.", "total_amount":"4368176", "group":"high", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"Ohio High School Value-Added Project", "id":"238", "organization":"Battelle For Kids", "total_amount":"4989262", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Creating a National Movement for Improved K-12 Education", "id":"239", "organization":"GreatSchools, Inc.", "total_amount":"6000000", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Smart Scholars: Early College High Schools in New York State", "id":"240", "organization":"The University of the State of New York", "total_amount":"6000000", "group":"high", "Grant start date":"7/29/2009", "start_month":"7", "start_day":"29", "start_year":"2009" }, { "grant_title":"Phase II - to support the expansion of second generation student tracker for high schools", "id":"241", "organization":"National Student Clearinghouse Research Center", "total_amount":"6094497", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Support for Seattle Public Schools' Strategic Plan", "id":"242", "organization":"Alliance for Education", "total_amount":"6929430", "group":"high", "Grant start date":"11/10/2008", "start_month":"11", "start_day":"10", "start_year":"2008" }, { "grant_title":"Reforming the Widget Effect: Increasing teacher effectiveness in America's schools", "id":"243", "organization":"The New Teacher Project, Inc.", "total_amount":"7000000", "group":"high", "Grant start date":"7/10/2009", "start_month":"7", "start_day":"10", "start_year":"2009" }, { "grant_title":"Understanding Teacher Quality", "id":"244", "organization":"Educational Testing Service", "total_amount":"7348925", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Equity and Excellence in a Global Era: Expanding the International Studies Schools Network", "id":"245", "organization":"Asia Society", "total_amount":"7750417", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Increase the leadership capacity of chiefs", "id":"246", "organization":"Council of Chief State School Officers", "total_amount":"7770104", "group":"high", "Grant start date":"7/1/2009", "start_month":"7", "start_day":"1", "start_year":"2009" }, { "grant_title":"Strong American Schools", "id":"247", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"9958245", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"248", "organization":"Denver Public Schools", "total_amount":"10000000", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"249", "organization":"Atlanta Public Schools", "total_amount":"10000000", "group":"high", "Grant start date":"1/13/2010", "start_month":"1", "start_day":"13", "start_year":"2010" }, { "grant_title":"American Diploma Project Network", "id":"250", "organization":"Achieve Inc.", "total_amount":"12614352", "group":"high", "Grant start date":"2/1/2008", "start_month":"2", "start_day":"1", "start_year":"2008" }, { "grant_title":"Strategic Data Project", "id":"251", "organization":"President and Fellows of Harvard College", "total_amount":"14994686", "group":"high", "Grant start date":"6/17/2009", "start_month":"6", "start_day":"17", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"252", "organization":"Pittsburgh Public Schools", "total_amount":"40000000", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers (LA-CMO's)", "id":"253", "organization":"The College-Ready Promise", "total_amount":"60000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"254", "organization":"Memphis City Schools", "total_amount":"90000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"255", "organization":"Hillsborough County Public Schools", "total_amount":"100000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" } ]
225928
App.data.bubble_default = [ { "grant_title":"New Mexico Business Roundtable", "id":"1", "organization":"New Mexico Business Roundtable for Educational Excellence", "total_amount":"5000", "group":"low", "Grant start date":"2/4/2010", "start_month":"2", "start_day":"4", "start_year":"2010" }, { "grant_title":"LA NSC Match", "id":"2", "organization":"Trustees of Dartmouth College", "total_amount":"27727", "group":"low", "Grant start date":"8/3/2009", "start_month":"8", "start_day":"3", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"3", "organization":"Denver School of Science and Technology Inc.", "total_amount":"36018", "group":"low", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"Convening of Stakeholder Planning Committee for the Institute for Local Innovation in Teaching and Learning", "id":"4", "organization":"The NEA Foundation for the Improvement of Education", "total_amount":"38420", "group":"low", "Grant start date":"3/11/2010", "start_month":"3", "start_day":"11", "start_year":"2010" }, { "grant_title":"Conference Support", "id":"5", "organization":"New Schools for New Orleans", "total_amount":"50000", "group":"low", "Grant start date":"10/12/2009", "start_month":"10", "start_day":"12", "start_year":"2009" }, { "grant_title":"Conference Support Grant on differentiated compensation symposium", "id":"6", "organization":"Battelle For Kids", "total_amount":"50000", "group":"low", "Grant start date":"6/30/2009", "start_month":"6", "start_day":"30", "start_year":"2009" }, { "grant_title":"Conference Support On School Turnaround Issues", "id":"7", "organization":"FSG Social Impact Advisors", "total_amount":"50000", "group":"low", "Grant start date":"9/24/2009", "start_month":"9", "start_day":"24", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - Aspire Public Schools", "id":"8", "organization":"Aspire Public Schools", "total_amount":"51500", "group":"low", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"Formative Assessment Task Development and Validation (Supplemental to OPP53449)", "id":"9", "organization":"Educational Policy Improvement Center", "total_amount":"55752", "group":"low", "Grant start date":"11/16/2009", "start_month":"11", "start_day":"16", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - E3 Alliance", "id":"10", "organization":"E3 Alliance", "total_amount":"56245", "group":"low", "Grant start date":"10/28/2009", "start_month":"10", "start_day":"28", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (Hillsborough)", "id":"11", "organization":"Hillsborough Education Foundation, Inc.", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (LA CMOs)", "id":"12", "organization":"The College-Ready Promise", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (Memphis)", "id":"13", "organization":"Memphis City Schools Foundation", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partners (Pittsburgh)", "id":"14", "organization":"Pittsburgh Public Schools", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - GHCF", "id":"15", "organization":"Greater Houston Community Foundation", "total_amount":"68500", "group":"low", "Grant start date":"10/28/2009", "start_month":"10", "start_day":"28", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - New Visions for Public Schools", "id":"16", "organization":"New Visions for Public Schools, Inc", "total_amount":"70116", "group":"low", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - Philadelphia Public Schools", "id":"17", "organization":"School District of Philadelphia", "total_amount":"74219", "group":"low", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"18", "organization":"Hamilton County Department of Education", "total_amount":"74800", "group":"low", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund – Internationals Network (with NCLR)", "id":"19", "organization":"Internationals Network For Public Schools Inc", "total_amount":"74900", "group":"low", "Grant start date":"3/24/2010", "start_month":"3", "start_day":"24", "start_year":"2010" }, { "grant_title":"City Based Proposal for What Works Fund - Minneapolis Public Schools", "id":"20", "organization":"Achieve Minneapolis", "total_amount":"74963", "group":"low", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - PTE", "id":"21", "organization":"The College-Ready Promise", "total_amount":"75000", "group":"low", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"TPERF Statewide Education Summit and Legislative Briefing", "id":"22", "organization":"Texas Public Education Reform Foundation", "total_amount":"75000", "group":"low", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"City Based Proposal for What Works Fund - NYC Charter Center", "id":"23", "organization":"New York City Center for Charter School Excellence", "total_amount":"75300", "group":"low", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"Supporting the development of a cross-sector plan that represent new levels of collaboration between one or more districts and the SEED School, a leading CMO in Washington, DC and Baltimore", "id":"24", "organization":"SEED Foundation, Inc.", "total_amount":"75970", "group":"low", "Grant start date":"1/28/2010", "start_month":"1", "start_day":"28", "start_year":"2010" }, { "grant_title":"City based proposal for What Works Fund - City of New Haven", "id":"25", "organization":"City of New Haven", "total_amount":"82500", "group":"low", "Grant start date":"11/17/2009", "start_month":"11", "start_day":"17", "start_year":"2009" }, { "grant_title":"Achievement Gap Institute: Annual Research-to-Practice Conference, How Teachers Improve", "id":"26", "organization":"President and Fellows of Harvard College", "total_amount":"91300", "group":"low", "Grant start date":"5/13/2009", "start_month":"5", "start_day":"13", "start_year":"2009" }, { "grant_title":"National Education Forum", "id":"27", "organization":"The Library of Congress", "total_amount":"91350", "group":"low", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Community Engagement Supporting College and Career Readiness", "id":"28", "organization":"Austin Voices for Education and Youth", "total_amount":"93000", "group":"low", "Grant start date":"10/1/2009", "start_month":"10", "start_day":"1", "start_year":"2009" }, { "grant_title":"Building & Sustaining Support for Good Schools: A Public Information Campaign", "id":"29", "organization":"Prichard Committee for Academic Excellence", "total_amount":"100000", "group":"medium", "Grant start date":"4/30/2010", "start_month":"4", "start_day":"30", "start_year":"2010" }, { "grant_title":"City Based Proposal for What Works Fund – Council of Great City Schools", "id":"30", "organization":"Council Of The Great City Schools", "total_amount":"100000", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"City based proposal for What Works Fund - New Schools for New Orleans", "id":"31", "organization":"New Schools for New Orleans", "total_amount":"100000", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"EEP Equality Day Rally Support", "id":"32", "organization":"Education Equality Project", "total_amount":"100000", "group":"medium", "Grant start date":"6/19/2009", "start_month":"6", "start_day":"19", "start_year":"2009" }, { "grant_title":"<NAME>", "id":"33", "organization":"Education Writers Association", "total_amount":"100000", "group":"medium", "Grant start date":"7/22/2009", "start_month":"7", "start_day":"22", "start_year":"2009" }, { "grant_title":"Repurpose of Alliance for Education Funds to a Variety of Essential Organizational Functions and Programs", "id":"34", "organization":"Alliance for Education", "total_amount":"110610", "group":"medium", "Grant start date":"2/26/2010", "start_month":"2", "start_day":"26", "start_year":"2010" }, { "grant_title":"Secondary STEM Data and Standards Analysis", "id":"35", "organization":"Texas Public Education Reform Foundation", "total_amount":"140000", "group":"medium", "Grant start date":"7/28/2009", "start_month":"7", "start_day":"28", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"36", "organization":"Charlotte-Mecklenburg Schools", "total_amount":"143973", "group":"medium", "Grant start date":"11/9/2009", "start_month":"11", "start_day":"9", "start_year":"2009" }, { "grant_title":"Ethnic Commission Education Reform Project", "id":"37", "organization":"Washington State Commission on African American Affairs", "total_amount":"146025", "group":"medium", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"38", "organization":"Cristo Rey Network", "total_amount":"149733", "group":"medium", "Grant start date":"11/6/2009", "start_month":"11", "start_day":"6", "start_year":"2009" }, { "grant_title":"California Collaborative on District Reform Phase 2", "id":"39", "organization":"American Institutes for Research", "total_amount":"150000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Professional Educator Standards Board", "id":"40", "organization":"Professional Educator Standards Board", "total_amount":"150000", "group":"medium", "Grant start date":"10/9/2009", "start_month":"10", "start_day":"9", "start_year":"2009" }, { "grant_title":"Evaluate the Leaky College Pipeline in New York City", "id":"41", "organization":"Fund for Public Schools Inc.", "total_amount":"170023", "group":"medium", "Grant start date":"10/27/2009", "start_month":"10", "start_day":"27", "start_year":"2009" }, { "grant_title":"Advocacy for Sustained School Reform in the Nation's Capital", "id":"42", "organization":"DC VOICE", "total_amount":"200000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"DC Expansion and CA STEM partnership", "id":"43", "organization":"Tiger Woods Foundation Inc.", "total_amount":"200000", "group":"medium", "Grant start date":"8/29/2009", "start_month":"8", "start_day":"29", "start_year":"2009" }, { "grant_title":"Retaining Teacher Talent: What Matters for Gen-Y Teachers", "id":"44", "organization":"Public Agenda Foundation, Inc.", "total_amount":"215000", "group":"medium", "Grant start date":"3/2/2009", "start_month":"3", "start_day":"2", "start_year":"2009" }, { "grant_title":"Supplemental Support for the New York STEM Progressive Dialogues (original grant on OPP52284)", "id":"45", "organization":"Rensselaer Polytechnic Institute", "total_amount":"220654", "group":"medium", "Grant start date":"9/29/2009", "start_month":"9", "start_day":"29", "start_year":"2009" }, { "grant_title":"Teacher Demographics and Pension Policies", "id":"46", "organization":"National Commission on Teachings & America's Future", "total_amount":"221755", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Charter School Initiative", "id":"47", "organization":"President and Fellows of Harvard College", "total_amount":"224030", "group":"medium", "Grant start date":"2/25/2010", "start_month":"2", "start_day":"25", "start_year":"2010" }, { "grant_title":"High School Standards Review project", "id":"48", "organization":"Illinois State Board of Education", "total_amount":"225000", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Progressive Dialogues (Supplemental grant on OPP1008819)", "id":"49", "organization":"Rensselaer Polytechnic Institute", "total_amount":"231382", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Support access to ARRA funds for strong CMOs", "id":"50", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"246070", "group":"medium", "Grant start date":"9/10/2009", "start_month":"9", "start_day":"10", "start_year":"2009" }, { "grant_title":"Aspen-NewSchools Fellows", "id":"51", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"250000", "group":"medium", "Grant start date":"3/26/2009", "start_month":"3", "start_day":"26", "start_year":"2009" }, { "grant_title":"Texas Charter Schools Association", "id":"52", "organization":"Texas Charter Schools Association", "total_amount":"250000", "group":"medium", "Grant start date":"5/18/2009", "start_month":"5", "start_day":"18", "start_year":"2009" }, { "grant_title":"to support the work of a teacher evaluation task force", "id":"53", "organization":"American Federation Of Teachers Educational Foundation", "total_amount":"250000", "group":"medium", "Grant start date":"6/23/2009", "start_month":"6", "start_day":"23", "start_year":"2009" }, { "grant_title":"Ensuring a Valid and Useable Teacher Student Link", "id":"54", "organization":"National Center For Educational Achievement", "total_amount":"260760", "group":"medium", "Grant start date":"11/21/2009", "start_month":"11", "start_day":"21", "start_year":"2009" }, { "grant_title":"Consistent College-Ready Standards", "id":"55", "organization":"Military Child Education Coalition", "total_amount":"269998", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"DCPS Measures of Teacher Effectiveness Study", "id":"56", "organization":"DC Public Education Fund", "total_amount":"299985", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Creating a Stronger Philanthropic Sector in Education", "id":"57", "organization":"Grantmakers for Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/6/2009", "start_month":"11", "start_day":"6", "start_year":"2009" }, { "grant_title":"Envision Schools Post-Secondary Tracking", "id":"58", "organization":"Envision Schools", "total_amount":"300000", "group":"medium", "Grant start date":"6/1/2008", "start_month":"6", "start_day":"1", "start_year":"2008" }, { "grant_title":"Global Education Leaders' Program (GELP)", "id":"59", "organization":"Silicon Valley Community Foundation", "total_amount":"300000", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Investigation of the Relationship between Teacher Quality and Student Learning Outcomes", "id":"60", "organization":"ACT, Inc.", "total_amount":"300000", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher-Student Data Link Project - Arkansas", "id":"61", "organization":"Arkansas Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Florida", "id":"62", "organization":"Florida Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Georgia", "id":"63", "organization":"Georgia Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Louisiana", "id":"64", "organization":"Louisiana Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Ohio", "id":"65", "organization":"Ohio Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"The California STEM Innovation Network", "id":"66", "organization":"California Polytechnic State University Foundation", "total_amount":"300000", "group":"medium", "Grant start date":"1/8/2009", "start_month":"1", "start_day":"8", "start_year":"2009" }, { "grant_title":"TN SCORE state advocacy coalition", "id":"67", "organization":"Tennessee State Collaborative on Reforming Education", "total_amount":"300250", "group":"medium", "Grant start date":"2/19/2010", "start_month":"2", "start_day":"19", "start_year":"2010" }, { "grant_title":"Bring Your 'A' Game", "id":"68", "organization":"Twenty First Century Foundation", "total_amount":"302425", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Instructional Support at Cleveland and Rainier Beach", "id":"69", "organization":"Alliance for Education", "total_amount":"309554", "group":"medium", "Grant start date":"9/17/2008", "start_month":"9", "start_day":"17", "start_year":"2008" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"70", "organization":"National Council of La Raza", "total_amount":"322103", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"NYC Public Schools: A Retrospective 2002-2009", "id":"71", "organization":"American Institutes for Research", "total_amount":"325000", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"NSC Student Data for High Schools Pilot: Georgia", "id":"72", "organization":"University System of Georgia Foundation, Inc.", "total_amount":"331678", "group":"medium", "Grant start date":"11/11/2009", "start_month":"11", "start_day":"11", "start_year":"2009" }, { "grant_title":"Common Core Companion Curriculum Project", "id":"73", "organization":"Common Core Inc.", "total_amount":"331890", "group":"medium", "Grant start date":"12/17/2009", "start_month":"12", "start_day":"17", "start_year":"2009" }, { "grant_title":"Civic Mission of Schools", "id":"74", "organization":"National Council for the Social Studies", "total_amount":"351704", "group":"medium", "Grant start date":"6/1/2008", "start_month":"6", "start_day":"1", "start_year":"2008" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"75", "organization":"Pittsburgh Public Schools", "total_amount":"353977", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"Institute for Local Innovation in Teaching and Learning", "id":"76", "organization":"The NEA Foundation for the Improvement of Education", "total_amount":"358915", "group":"medium", "Grant start date":"10/22/2009", "start_month":"10", "start_day":"22", "start_year":"2009" }, { "grant_title":"Campaign for High School Equity", "id":"77", "organization":"L.U.L.A.C. Institute, Inc.", "total_amount":"370005", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Preparing Secondary English Learners for Graduation and College", "id":"78", "organization":"University of California, Los Angeles", "total_amount":"375000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"79", "organization":"Leadership Conference on Civil Rights Education Fund, Inc.", "total_amount":"375030", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"NSC Student Data for High Schools Pilot: Florida", "id":"80", "organization":"Florida Department of Education", "total_amount":"383465", "group":"medium", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"The Policy Innovation in Education Network", "id":"81", "organization":"<NAME>", "total_amount":"398534", "group":"medium", "Grant start date":"6/15/2009", "start_month":"6", "start_day":"15", "start_year":"2009" }, { "grant_title":"Common Core Strategies for State Policymakers", "id":"82", "organization":"Council of State Governments", "total_amount":"399953", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"83", "organization":"Mexican American Legal Defense and Educational Fund", "total_amount":"400000", "group":"medium", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Education Equity Agenda: LULAC Parent Involvement Initiative for Campaign for High School Equity", "id":"84", "organization":"L.U.L.A.C. Institute, Inc.", "total_amount":"400017", "group":"medium", "Grant start date":"9/21/2009", "start_month":"9", "start_day":"21", "start_year":"2009" }, { "grant_title":"8th to 9th Grade Transition and Acceleration Project", "id":"85", "organization":"National Summer Learning Association", "total_amount":"400366", "group":"medium", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"Support of professional development and an education workshop for education beat reporters", "id":"86", "organization":"Teachers College, Columbia University", "total_amount":"402493", "group":"medium", "Grant start date":"9/29/2009", "start_month":"9", "start_day":"29", "start_year":"2009" }, { "grant_title":"NSC Student Data for High Schools Pilot: Texas", "id":"87", "organization":"Communities Foundation of Texas", "total_amount":"406610", "group":"medium", "Grant start date":"10/15/2009", "start_month":"10", "start_day":"15", "start_year":"2009" }, { "grant_title":"Supplemental Support Review and Build-out of the Raytheon STEM Model", "id":"88", "organization":"Business Higher Education Forum", "total_amount":"417517", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"The State of Professional Learning: A National Study", "id":"89", "organization":"National Staff Development Council", "total_amount":"421603", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Southeast Asian American Action and Visibility in Education (SAVE) Project", "id":"90", "organization":"Southeast Asia Resource Action Center", "total_amount":"425000", "group":"medium", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Roads to Success Curriculum Completion and Distribution", "id":"91", "organization":"Roads to Success Inc.", "total_amount":"430000", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"STEM Community Collaborative Phase 2", "id":"92", "organization":"MCNC", "total_amount":"432898", "group":"medium", "Grant start date":"3/6/2009", "start_month":"3", "start_day":"6", "start_year":"2009" }, { "grant_title":"California ADP Support", "id":"93", "organization":"Regents of the University of California at Berkeley", "total_amount":"437807", "group":"medium", "Grant start date":"10/22/2008", "start_month":"10", "start_day":"22", "start_year":"2008" }, { "grant_title":"Regional convenings for policymakers and leaders to develop commitment to standards and assessments", "id":"94", "organization":"National Association of State Boards of Education", "total_amount":"450675", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"Business Planning to Create Hybrid Learning Environments in Existing and New Schools", "id":"95", "organization":"Pollinate Ventures", "total_amount":"451125", "group":"medium", "Grant start date":"11/8/2009", "start_month":"11", "start_day":"8", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"96", "organization":"Fund for Public Schools Inc.", "total_amount":"455394", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"KIPPShare National Data Platform", "id":"97", "organization":"KIPP Foundation", "total_amount":"468500", "group":"medium", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"The Equity Project (TEP) Charter School Evaluation", "id":"98", "organization":"Mathematica Policy Research", "total_amount":"470507", "group":"medium", "Grant start date":"7/16/2009", "start_month":"7", "start_day":"16", "start_year":"2009" }, { "grant_title":"North Carolina STEM Development", "id":"99", "organization":"MCNC", "total_amount":"475000", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Using web-based videos to teach math to high school students", "id":"100", "organization":"Guaranteach", "total_amount":"475077", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"CPS Community Ownership Proposal", "id":"101", "organization":"Strive: Cincinnati/Northern Kentucky, LLC", "total_amount":"490021", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher Working Conditions Survey", "id":"102", "organization":"New Teacher Center", "total_amount":"494933", "group":"medium", "Grant start date":"10/13/2009", "start_month":"10", "start_day":"13", "start_year":"2009" }, { "grant_title":"North Carolina New Technology High School Network Sustainability", "id":"103", "organization":"New Technology Foundation", "total_amount":"496776", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Planning Grant for Evaluation of Green Dot's Locke Transformation Project", "id":"104", "organization":"University of California, Los Angeles", "total_amount":"498724", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Preparing All Students for College, Work and Citizenship", "id":"105", "organization":"National Conference of State Legislatures", "total_amount":"499225", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Gateway to College Capacity-Building", "id":"106", "organization":"Gateway to College National Network", "total_amount":"499398", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Doubling the Numbers in STEM", "id":"107", "organization":"Ohio Business Alliance for Higher Education and the Economy", "total_amount":"500000", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"IMPLEMENTATION: StartL: A Digital Media and Learning Accelerator", "id":"108", "organization":"Social Science Research Council", "total_amount":"500000", "group":"medium", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"NAPCS General Operating Support", "id":"109", "organization":"National Alliance For Public Charter Schools", "total_amount":"500000", "group":"medium", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"New England Consortium", "id":"110", "organization":"Nellie Mae Education Foundation", "total_amount":"500000", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"WGHA Amb<NAME>", "id":"111", "organization":"Seattle Biomedical Research Institute", "total_amount":"500000", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Stay for America (retaining effective Teach for America teachers beyond year 2)", "id":"112", "organization":"Teach for America, Inc.", "total_amount":"500422", "group":"medium", "Grant start date":"10/1/2009", "start_month":"10", "start_day":"1", "start_year":"2009" }, { "grant_title":"Grassroots Media Project", "id":"113", "organization":"Fund for the City of New York, Inc.", "total_amount":"513219", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Improving Native Student Graduation Rates: Policy Recommendations on High School Reform", "id":"114", "organization":"National Indian Education Association", "total_amount":"520446", "group":"medium", "Grant start date":"8/31/2009", "start_month":"8", "start_day":"31", "start_year":"2009" }, { "grant_title":"The State Role In Improving Low-performing Schools", "id":"115", "organization":"Center on Education Policy", "total_amount":"544700", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Engaging Communities for College Readiness (ENCORE)", "id":"116", "organization":"Texas Valley Communities Foundation", "total_amount":"546865", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"New Degree Program for Education Leaders", "id":"117", "organization":"President and Fellows of Harvard College", "total_amount":"550000", "group":"medium", "Grant start date":"8/1/2008", "start_month":"8", "start_day":"1", "start_year":"2008" }, { "grant_title":"National Advocacy Support for the Common Core Initiative", "id":"118", "organization":"Alliance for Excellent Education, Inc.", "total_amount":"551336", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"Conceptual and Organizing Platform for Secondary Mathematics Formative Assessments", "id":"119", "organization":"Regents University Of California Los Angeles", "total_amount":"576191", "group":"medium", "Grant start date":"5/11/2009", "start_month":"5", "start_day":"11", "start_year":"2009" }, { "grant_title":"Education Practice Launch", "id":"120", "organization":"Innosight Institute Inc", "total_amount":"588559", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Building Business Leadership for New Approaches to Teacher Compensation", "id":"121", "organization":"Committee for Economic Development", "total_amount":"597077", "group":"medium", "Grant start date":"5/5/2009", "start_month":"5", "start_day":"5", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"122", "organization":"Prichard Committee for Academic Excellence", "total_amount":"599016", "group":"medium", "Grant start date":"11/16/2009", "start_month":"11", "start_day":"16", "start_year":"2009" }, { "grant_title":"THE HIGH SCHOOL REDESIGN INITIATIVE -- PHASE TWO", "id":"123", "organization":"National Association of State Boards of Education", "total_amount":"599725", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Aligning P-12 and Postsecondary Data Systems", "id":"124", "organization":"National Center For Educational Achievement", "total_amount":"600000", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"The Next Generation of NCLR Schools", "id":"125", "organization":"National Council of La Raza", "total_amount":"600000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Washington STEM Innovation Initiative", "id":"126", "organization":"Partnership for Learning", "total_amount":"643881", "group":"medium", "Grant start date":"3/11/2009", "start_month":"3", "start_day":"11", "start_year":"2009" }, { "grant_title":"Teacher Effectiveness work", "id":"127", "organization":"Hope Street Group", "total_amount":"650108", "group":"medium", "Grant start date":"11/7/2009", "start_month":"11", "start_day":"7", "start_year":"2009" }, { "grant_title":"Stimulus related work and CSA support", "id":"128", "organization":"Institute for a Competitive Workforce", "total_amount":"653077", "group":"medium", "Grant start date":"11/11/2009", "start_month":"11", "start_day":"11", "start_year":"2009" }, { "grant_title":"Validating a Common Core of Fewer, Clearer, Higher Standards", "id":"129", "organization":"Educational Policy Improvement Center", "total_amount":"721687", "group":"medium", "Grant start date":"5/5/2009", "start_month":"5", "start_day":"5", "start_year":"2009" }, { "grant_title":"Preparing parents and students to be advocates for quality school reform in Illinois", "id":"130", "organization":"Target Area Development Corporation", "total_amount":"725000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Building Capacity for College Success: Implementing Data Collection Systems and Best Practices", "id":"131", "organization":"National Association of Street Schools", "total_amount":"742223", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Support for National Lab Day", "id":"132", "organization":"Tides Center", "total_amount":"750000", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Winning Strategies Black Male Donor Collaborative", "id":"133", "organization":"The Schott Foundation For Public Education", "total_amount":"750000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"The Role of School Board Governance in Preaparing Students for College and Workplace Readiness", "id":"134", "organization":"National School Boards Foundation", "total_amount":"755603", "group":"medium", "Grant start date":"4/25/2009", "start_month":"4", "start_day":"25", "start_year":"2009" }, { "grant_title":"Tracking Students from Secondary to Post Secondary Institutions", "id":"135", "organization":"National Student Clearinghouse", "total_amount":"792216", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"136", "organization":"National Urban League Inc.", "total_amount":"800000", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"WA State Board of Education Phase II: A Meaningful High School Diploma and A State Accountability Education System", "id":"137", "organization":"The Washington State Board of Education", "total_amount":"850000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Measures of Effective Teaching Research Site", "id":"138", "organization":"Denver Public Schools", "total_amount":"878493", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"STEM Capacity Building", "id":"139", "organization":"Business Higher Education Forum", "total_amount":"910000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"140", "organization":"National Council of La Raza", "total_amount":"930223", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"DC Achiever Restructuring Partner", "id":"141", "organization":"Friendship Public Charter School", "total_amount":"937088", "group":"medium", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"PRI Guaranty To Unlock Facilities Financing for High Quality Charter Schools", "id":"142", "organization":"Local Initiatives Support Corporation", "total_amount":"950000", "group":"medium", "Grant start date":"8/27/2009", "start_month":"8", "start_day":"27", "start_year":"2009" }, { "grant_title":"Common Standards Review and Task Development", "id":"143", "organization":"<NAME> Institute", "total_amount":"959116", "group":"medium", "Grant start date":"10/10/2009", "start_month":"10", "start_day":"10", "start_year":"2009" }, { "grant_title":"Intermediary management of PRI/Credit Enhancement Program - Los Angeles (Aspire)", "id":"144", "organization":"NCB Capital Impact", "total_amount":"959373", "group":"medium", "Grant start date":"4/8/2010", "start_month":"4", "start_day":"8", "start_year":"2010" }, { "grant_title":"Sustainability for Recovery School District", "id":"145", "organization":"Baton Rouge Area Foundation", "total_amount":"993219", "group":"medium", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"Research Design for Project-Based Advanced Placement Courses", "id":"146", "organization":"University of Washington", "total_amount":"996185", "group":"medium", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Accelerate and Enhance Teacher Effectiveness Methods In Districts/Networks", "id":"147", "organization":"Achievement First Inc.", "total_amount":"998221", "group":"medium", "Grant start date":"10/9/2009", "start_month":"10", "start_day":"9", "start_year":"2009" }, { "grant_title":"AFT Innovation Fund", "id":"148", "organization":"American Federation Of Teachers Educational Foundation", "total_amount":"1000000", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Applying an R&D model to education to unearth root causes of performance gaps, to effectively vet options for reform.", "id":"149", "organization":"President and Fellows of Harvard College", "total_amount":"1000000", "group":"medium", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"For the Future", "id":"150", "organization":"Team Pennsylvania Foundation", "total_amount":"1000000", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"General Support Supplemental", "id":"151", "organization":"The Education Trust", "total_amount":"1000000", "group":"medium", "Grant start date":"1/21/2010", "start_month":"1", "start_day":"21", "start_year":"2010" }, { "grant_title":"Ohio College and Career Ready Consortium", "id":"152", "organization":"Ohio Grantmakers Forum", "total_amount":"1000000", "group":"medium", "Grant start date":"7/18/2009", "start_month":"7", "start_day":"18", "start_year":"2009" }, { "grant_title":"Strategic Management of Human Capital in Public Ed", "id":"153", "organization":"University of Wisconsin", "total_amount":"1000000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"to support Teach for America (TFA) with the goal of bringing low income and minority students in TFA classrooms to proficiency", "id":"154", "organization":"Teach for America, Inc.", "total_amount":"1000000", "group":"medium", "Grant start date":"6/26/2009", "start_month":"6", "start_day":"26", "start_year":"2009" }, { "grant_title":"Los Angeles Collaborative to Improve College and Career Readiness in LAUSD Schools", "id":"155", "organization":"United Way Inc.", "total_amount":"1000330", "group":"high", "Grant start date":"1/15/2009", "start_month":"1", "start_day":"15", "start_year":"2009" }, { "grant_title":"PEN business planning", "id":"156", "organization":"Public Education Network", "total_amount":"1001363", "group":"high", "Grant start date":"7/10/2009", "start_month":"7", "start_day":"10", "start_year":"2009" }, { "grant_title":"Accelerate and Enhance Teacher Effectiveness Methods In Districts/Networks", "id":"157", "organization":"Recovery School District", "total_amount":"1004719", "group":"high", "Grant start date":"10/22/2009", "start_month":"10", "start_day":"22", "start_year":"2009" }, { "grant_title":"CEP standards and assessment work", "id":"158", "organization":"Center on Education Policy", "total_amount":"1047928", "group":"high", "Grant start date":"9/8/2009", "start_month":"9", "start_day":"8", "start_year":"2009" }, { "grant_title":"College Bound", "id":"159", "organization":"College Success Foundation", "total_amount":"1053150", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Accelerator Enhance Teacher Effectiveness Methods - RE: ASPIRE Model in HISD", "id":"160", "organization":"Houston Independent School District", "total_amount":"1100000", "group":"high", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"Ohio Follow-Through on Achieve Policy Study Recommendations", "id":"161", "organization":"Ohio Department of Education", "total_amount":"1175000", "group":"high", "Grant start date":"1/1/2008", "start_month":"1", "start_day":"1", "start_year":"2008" }, { "grant_title":"Philanthropic Partnership for Public Education", "id":"162", "organization":"Seattle Foundation", "total_amount":"1181375", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"A Progressive Agenda for Human Capital Policy Reform", "id":"163", "organization":"Center for American Progress", "total_amount":"1198248", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Gates-EdVisions Moving Forward", "id":"164", "organization":"EdVisions Inc", "total_amount":"1200552", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Texas Education Research Support", "id":"165", "organization":"College for All Texans Foundation: Closing the Gaps", "total_amount":"1221800", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Portable Word Play - Discovering What Handheld Games Can Do for Adolescent Reading Comprehension", "id":"166", "organization":"Education Development Center, Inc.", "total_amount":"1224953", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Baltimore Sustainability Plan", "id":"167", "organization":"Fund for Educational Excellence", "total_amount":"1229730", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Academic Youth Development", "id":"168", "organization":"University of Texas at Austin", "total_amount":"1235787", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Campaign for High School Equity", "id":"169", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"1279229", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"support the K-12 backmapping of the standards", "id":"170", "organization":"Council of Chief State School Officers", "total_amount":"1291738", "group":"high", "Grant start date":"10/12/2009", "start_month":"10", "start_day":"12", "start_year":"2009" }, { "grant_title":"Building College-Ready Culture in Our High Schools", "id":"171", "organization":"College Summit Inc.", "total_amount":"1300000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Measures of Effective Teaching Research Site", "id":"172", "organization":"Dallas Independent School District", "total_amount":"1332279", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Technical Assistance for Standards/Assessment Partners", "id":"173", "organization":"National Center for the Improvement of Educational Assessment Inc.", "total_amount":"1362773", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Making NSC Data Actionable for School Leaders", "id":"174", "organization":"College Summit Inc", "total_amount":"1383137", "group":"high", "Grant start date":"5/22/2009", "start_month":"5", "start_day":"22", "start_year":"2009" }, { "grant_title":"Charlotte-Mecklenburg Measures of Teacher Effectiveness Research", "id":"175", "organization":"Charlotte-Mecklenburg Schools", "total_amount":"1431534", "group":"high", "Grant start date":"9/3/2009", "start_month":"9", "start_day":"3", "start_year":"2009" }, { "grant_title":"College Ready Course Sequence Implementation", "id":"176", "organization":"ACT, Inc.", "total_amount":"1445269", "group":"high", "Grant start date":"9/14/2009", "start_month":"9", "start_day":"14", "start_year":"2009" }, { "grant_title":"Partnership for Learning Statewide Advocacy + Stimulus RTT TA", "id":"177", "organization":"Partnership for Learning", "total_amount":"1493522", "group":"high", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"178", "organization":"Tulsa Public Schools", "total_amount":"1500000", "group":"high", "Grant start date":"2/4/2010", "start_month":"2", "start_day":"4", "start_year":"2010" }, { "grant_title":"LEV Statewide Advocacy Expansion", "id":"179", "organization":"League of Education Voters Foundation", "total_amount":"1500000", "group":"high", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"NCEE state partnerships", "id":"180", "organization":"National Center on Education & the Economy", "total_amount":"1500000", "group":"high", "Grant start date":"10/19/2009", "start_month":"10", "start_day":"19", "start_year":"2009" }, { "grant_title":"Development of frameworks for the assessment of teacher knowledge", "id":"181", "organization":"Educational Testing Service", "total_amount":"1521971", "group":"high", "Grant start date":"11/14/2009", "start_month":"11", "start_day":"14", "start_year":"2009" }, { "grant_title":"Organizing for High School Reform", "id":"182", "organization":"Pacific Institute For Community Organizations", "total_amount":"1600000", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Expansion of Urban Teacher Residency (UTRU)", "id":"183", "organization":"The Urban Teacher Residency Institute", "total_amount":"1635665", "group":"high", "Grant start date":"9/1/2009", "start_month":"9", "start_day":"1", "start_year":"2009" }, { "grant_title":"Advance Illinois organization build", "id":"184", "organization":"Advance Illinois", "total_amount":"1800000", "group":"high", "Grant start date":"5/15/2008", "start_month":"5", "start_day":"15", "start_year":"2008" }, { "grant_title":"Validation of the Teaching as Leadership Rubric", "id":"185", "organization":"Teach for America, Inc.", "total_amount":"1840548", "group":"high", "Grant start date":"10/5/2009", "start_month":"10", "start_day":"5", "start_year":"2009" }, { "grant_title":"CMO Research Study Project Management", "id":"186", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"1891265", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"6to16", "id":"187", "organization":"University of Chicago - Urban Education Institute", "total_amount":"1894228", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Support for Campaign for High School Equity coordination of national civil rights organization national policy advocacy of College Ready and Postsecondary Strategies", "id":"188", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"1915298", "group":"high", "Grant start date":"10/19/2009", "start_month":"10", "start_day":"19", "start_year":"2009" }, { "grant_title":"Strengthening State College Readiness Initiatives", "id":"189", "organization":"Board Of Control For Southern Regional Education", "total_amount":"1987015", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"190", "organization":"Memphis City Schools", "total_amount":"1988654", "group":"high", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"New-Media Capacity Building at EPE", "id":"191", "organization":"Editorial Projects in Education", "total_amount":"1997280", "group":"high", "Grant start date":"5/1/2009", "start_month":"5", "start_day":"1", "start_year":"2009" }, { "grant_title":"Implementation: National PTA support for college-readiness", "id":"192", "organization":"National Congress of Parents and Teachers", "total_amount":"2000000", "group":"high", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"The Public Education Reform and Community Development Link: A Sustainable Solution", "id":"193", "organization":"Deutsche Bank Americas Foundation", "total_amount":"2000000", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Project GRAD USA's National College Readiness Initiative", "id":"194", "organization":"Project GRAD", "total_amount":"2025892", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Literacy by Design", "id":"195", "organization":"The Trust For Early Education Inc", "total_amount":"2039526", "group":"high", "Grant start date":"9/17/2009", "start_month":"9", "start_day":"17", "start_year":"2009" }, { "grant_title":"THSP Alliance Business Planning", "id":"196", "organization":"Communities Foundation of Texas", "total_amount":"2046674", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher-Student Data Link Project", "id":"197", "organization":"CELT Corporation", "total_amount":"2200000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Dropout Prevention", "id":"198", "organization":"Americas Promise-The Alliance For Youth", "total_amount":"2211517", "group":"high", "Grant start date":"3/19/2008", "start_month":"3", "start_day":"19", "start_year":"2008" }, { "grant_title":"Hunt Institute Common State Education Standards Project", "id":"199", "organization":"The <NAME>, Jr. Institute for Educational Leadership and Policy", "total_amount":"2213470", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Business Planning for Education grantees", "id":"200", "organization":"The Bridgespan Group", "total_amount":"2237530", "group":"high", "Grant start date":"4/20/2009", "start_month":"4", "start_day":"20", "start_year":"2009" }, { "grant_title":"Develop Tools for Teachers/Districts to Monitor Student Progress", "id":"201", "organization":"Math Solutions", "total_amount":"2274957", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"IB Middle Years Summative Assessment", "id":"202", "organization":"IB Fund US Inc.", "total_amount":"2423679", "group":"high", "Grant start date":"8/22/2009", "start_month":"8", "start_day":"22", "start_year":"2009" }, { "grant_title":"To Help Governors Improve College and Career Ready Rates", "id":"203", "organization":"National Governors Association Center For Best Practices", "total_amount":"2496814", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Next Generation PD System", "id":"204", "organization":"DC Public Education Fund", "total_amount":"2500000", "group":"high", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"205", "organization":"Prince George's County Public Schools", "total_amount":"2500169", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"206", "organization":"Hillsborough County Public Schools", "total_amount":"2502146", "group":"high", "Grant start date":"10/20/2009", "start_month":"10", "start_day":"20", "start_year":"2009" }, { "grant_title":"Scaling NCTQ state and district work", "id":"207", "organization":"National Council on Teacher Quality", "total_amount":"2565641", "group":"high", "Grant start date":"10/21/2009", "start_month":"10", "start_day":"21", "start_year":"2009" }, { "grant_title":"NAPCS Industry Development", "id":"208", "organization":"National Alliance For Public Charter Schools", "total_amount":"2605527", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Increasing Business Engagement", "id":"209", "organization":"Institute for a Competitive Workforce", "total_amount":"2625837", "group":"high", "Grant start date":"10/8/2008", "start_month":"10", "start_day":"8", "start_year":"2008" }, { "grant_title":"Building Support for Federal High School Policy Reform", "id":"210", "organization":"Alliance for Excellent Education, Inc.", "total_amount":"2644892", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"NYC DOE Measures of Teacher Effectiveness Research", "id":"211", "organization":"Fund for Public Schools Inc.", "total_amount":"2646876", "group":"high", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Aspire Public Schools' Early College High School Capacity Project", "id":"212", "organization":"Aspire Public Schools", "total_amount":"2899727", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Big 8 Superintendents Data Assessment", "id":"213", "organization":"Communities Foundation of Texas", "total_amount":"2901632", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"National Impact Initiative", "id":"214", "organization":"National Association Of Charter School Authorizers", "total_amount":"2979186", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Development and Adaptation of Science and Literacy Formative Assessment Tasks", "id":"215", "organization":"Regents Of The University Of California At Berkeley", "total_amount":"2999730", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Research Alliance for New York City Schools", "id":"216", "organization":"New York University", "total_amount":"2999960", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"CCSR General Operating Support", "id":"217", "organization":"University of Chicago (Parent Org)", "total_amount":"3000000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Deepening and Expanding the Impact of Diploma Plus", "id":"218", "organization":"Third Sector New England, Inc.", "total_amount":"3179363", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"To provide support to states on RTTT applications", "id":"219", "organization":"New Venture Fund", "total_amount":"3240000", "group":"high", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"Alternative High School Initiative", "id":"220", "organization":"The Big Picture Company", "total_amount":"3315216", "group":"high", "Grant start date":"7/15/2009", "start_month":"7", "start_day":"15", "start_year":"2009" }, { "grant_title":"Support for Teaching First to ensure that there is public support for district efforts to improve teacher effectiveness", "id":"221", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"3487270", "group":"high", "Grant start date":"9/25/2009", "start_month":"9", "start_day":"25", "start_year":"2009" }, { "grant_title":"IDEA Public Schools Expansion", "id":"222", "organization":"Idea Academy Inc", "total_amount":"3498875", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Title", "id":"223", "organization":"College Summit Inc", "total_amount":"3500000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"College Ready Mathematics Formative Assessments", "id":"224", "organization":"Regents Of The University Of California At Berkeley", "total_amount":"3661294", "group":"high", "Grant start date":"9/25/2009", "start_month":"9", "start_day":"25", "start_year":"2009" }, { "grant_title":"Using Standards and Data to Improve Urban School Systems", "id":"225", "organization":"Council Of The Great City Schools", "total_amount":"3735866", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"College Readiness Data Initiative", "id":"226", "organization":"Dallas Independent School District", "total_amount":"3774912", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Project support for expanding Aspen network", "id":"227", "organization":"The Aspen Institute", "total_amount":"3878680", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Aligned Instructional Systems", "id":"228", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"3999127", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"DC Schools Fund", "id":"229", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"4000000", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Newark School Fund", "id":"230", "organization":"Newark Charter School Fund, Inc.", "total_amount":"4000000", "group":"high", "Grant start date":"2/15/2008", "start_month":"2", "start_day":"15", "start_year":"2008" }, { "grant_title":"SeaChange Capacity and Catalyst Funding", "id":"231", "organization":"SeaChange Capital Partners, Inc.", "total_amount":"4000000", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"College and Career Ready Graduation Initiative", "id":"232", "organization":"United Way of America", "total_amount":"4001263", "group":"high", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Elevating An Alternative Teacher Voice", "id":"233", "organization":"Teach Plus, Incorporated", "total_amount":"4010611", "group":"high", "Grant start date":"9/30/2009", "start_month":"9", "start_day":"30", "start_year":"2009" }, { "grant_title":"Big Picture School Initiative", "id":"234", "organization":"The Big Picture Company", "total_amount":"4079157", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Matching Grant for Classroom Projects in Public High Schools", "id":"235", "organization":"DonorsChoose.org", "total_amount":"4114700", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Formative Assessment Data Collection, Task Analysis and Implementation (UCLA/CRESST)", "id":"236", "organization":"Regents University Of California Los Angeles", "total_amount":"4342988", "group":"high", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"State and National Common Core Standards Adoption/Implementation Advocacy Support", "id":"237", "organization":"<NAME>, Jr. Institute for Educational Leadership and Policy Foundation, Inc.", "total_amount":"4368176", "group":"high", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"Ohio High School Value-Added Project", "id":"238", "organization":"Battelle For Kids", "total_amount":"4989262", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Creating a National Movement for Improved K-12 Education", "id":"239", "organization":"GreatSchools, Inc.", "total_amount":"6000000", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Smart Scholars: Early College High Schools in New York State", "id":"240", "organization":"The University of the State of New York", "total_amount":"6000000", "group":"high", "Grant start date":"7/29/2009", "start_month":"7", "start_day":"29", "start_year":"2009" }, { "grant_title":"Phase II - to support the expansion of second generation student tracker for high schools", "id":"241", "organization":"National Student Clearinghouse Research Center", "total_amount":"6094497", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Support for Seattle Public Schools' Strategic Plan", "id":"242", "organization":"Alliance for Education", "total_amount":"6929430", "group":"high", "Grant start date":"11/10/2008", "start_month":"11", "start_day":"10", "start_year":"2008" }, { "grant_title":"Reforming the Widget Effect: Increasing teacher effectiveness in America's schools", "id":"243", "organization":"The New Teacher Project, Inc.", "total_amount":"7000000", "group":"high", "Grant start date":"7/10/2009", "start_month":"7", "start_day":"10", "start_year":"2009" }, { "grant_title":"Understanding Teacher Quality", "id":"244", "organization":"Educational Testing Service", "total_amount":"7348925", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Equity and Excellence in a Global Era: Expanding the International Studies Schools Network", "id":"245", "organization":"Asia Society", "total_amount":"7750417", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Increase the leadership capacity of chiefs", "id":"246", "organization":"Council of Chief State School Officers", "total_amount":"7770104", "group":"high", "Grant start date":"7/1/2009", "start_month":"7", "start_day":"1", "start_year":"2009" }, { "grant_title":"Strong American Schools", "id":"247", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"9958245", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"248", "organization":"Denver Public Schools", "total_amount":"10000000", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"249", "organization":"Atlanta Public Schools", "total_amount":"10000000", "group":"high", "Grant start date":"1/13/2010", "start_month":"1", "start_day":"13", "start_year":"2010" }, { "grant_title":"American Diploma Project Network", "id":"250", "organization":"Achieve Inc.", "total_amount":"12614352", "group":"high", "Grant start date":"2/1/2008", "start_month":"2", "start_day":"1", "start_year":"2008" }, { "grant_title":"Strategic Data Project", "id":"251", "organization":"President and Fellows of Harvard College", "total_amount":"14994686", "group":"high", "Grant start date":"6/17/2009", "start_month":"6", "start_day":"17", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"252", "organization":"Pittsburgh Public Schools", "total_amount":"40000000", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers (LA-CMO's)", "id":"253", "organization":"The College-Ready Promise", "total_amount":"60000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"254", "organization":"Memphis City Schools", "total_amount":"90000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"255", "organization":"Hillsborough County Public Schools", "total_amount":"100000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" } ]
true
App.data.bubble_default = [ { "grant_title":"New Mexico Business Roundtable", "id":"1", "organization":"New Mexico Business Roundtable for Educational Excellence", "total_amount":"5000", "group":"low", "Grant start date":"2/4/2010", "start_month":"2", "start_day":"4", "start_year":"2010" }, { "grant_title":"LA NSC Match", "id":"2", "organization":"Trustees of Dartmouth College", "total_amount":"27727", "group":"low", "Grant start date":"8/3/2009", "start_month":"8", "start_day":"3", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"3", "organization":"Denver School of Science and Technology Inc.", "total_amount":"36018", "group":"low", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"Convening of Stakeholder Planning Committee for the Institute for Local Innovation in Teaching and Learning", "id":"4", "organization":"The NEA Foundation for the Improvement of Education", "total_amount":"38420", "group":"low", "Grant start date":"3/11/2010", "start_month":"3", "start_day":"11", "start_year":"2010" }, { "grant_title":"Conference Support", "id":"5", "organization":"New Schools for New Orleans", "total_amount":"50000", "group":"low", "Grant start date":"10/12/2009", "start_month":"10", "start_day":"12", "start_year":"2009" }, { "grant_title":"Conference Support Grant on differentiated compensation symposium", "id":"6", "organization":"Battelle For Kids", "total_amount":"50000", "group":"low", "Grant start date":"6/30/2009", "start_month":"6", "start_day":"30", "start_year":"2009" }, { "grant_title":"Conference Support On School Turnaround Issues", "id":"7", "organization":"FSG Social Impact Advisors", "total_amount":"50000", "group":"low", "Grant start date":"9/24/2009", "start_month":"9", "start_day":"24", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - Aspire Public Schools", "id":"8", "organization":"Aspire Public Schools", "total_amount":"51500", "group":"low", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"Formative Assessment Task Development and Validation (Supplemental to OPP53449)", "id":"9", "organization":"Educational Policy Improvement Center", "total_amount":"55752", "group":"low", "Grant start date":"11/16/2009", "start_month":"11", "start_day":"16", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - E3 Alliance", "id":"10", "organization":"E3 Alliance", "total_amount":"56245", "group":"low", "Grant start date":"10/28/2009", "start_month":"10", "start_day":"28", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (Hillsborough)", "id":"11", "organization":"Hillsborough Education Foundation, Inc.", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (LA CMOs)", "id":"12", "organization":"The College-Ready Promise", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partner (Memphis)", "id":"13", "organization":"Memphis City Schools Foundation", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"Light touch communications grant for EET district partners (Pittsburgh)", "id":"14", "organization":"Pittsburgh Public Schools", "total_amount":"60000", "group":"low", "Grant start date":"11/2/2009", "start_month":"11", "start_day":"2", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - GHCF", "id":"15", "organization":"Greater Houston Community Foundation", "total_amount":"68500", "group":"low", "Grant start date":"10/28/2009", "start_month":"10", "start_day":"28", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - New Visions for Public Schools", "id":"16", "organization":"New Visions for Public Schools, Inc", "total_amount":"70116", "group":"low", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - Philadelphia Public Schools", "id":"17", "organization":"School District of Philadelphia", "total_amount":"74219", "group":"low", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"18", "organization":"Hamilton County Department of Education", "total_amount":"74800", "group":"low", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund – Internationals Network (with NCLR)", "id":"19", "organization":"Internationals Network For Public Schools Inc", "total_amount":"74900", "group":"low", "Grant start date":"3/24/2010", "start_month":"3", "start_day":"24", "start_year":"2010" }, { "grant_title":"City Based Proposal for What Works Fund - Minneapolis Public Schools", "id":"20", "organization":"Achieve Minneapolis", "total_amount":"74963", "group":"low", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"City Based Proposal for What Works Fund - PTE", "id":"21", "organization":"The College-Ready Promise", "total_amount":"75000", "group":"low", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"TPERF Statewide Education Summit and Legislative Briefing", "id":"22", "organization":"Texas Public Education Reform Foundation", "total_amount":"75000", "group":"low", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"City Based Proposal for What Works Fund - NYC Charter Center", "id":"23", "organization":"New York City Center for Charter School Excellence", "total_amount":"75300", "group":"low", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"Supporting the development of a cross-sector plan that represent new levels of collaboration between one or more districts and the SEED School, a leading CMO in Washington, DC and Baltimore", "id":"24", "organization":"SEED Foundation, Inc.", "total_amount":"75970", "group":"low", "Grant start date":"1/28/2010", "start_month":"1", "start_day":"28", "start_year":"2010" }, { "grant_title":"City based proposal for What Works Fund - City of New Haven", "id":"25", "organization":"City of New Haven", "total_amount":"82500", "group":"low", "Grant start date":"11/17/2009", "start_month":"11", "start_day":"17", "start_year":"2009" }, { "grant_title":"Achievement Gap Institute: Annual Research-to-Practice Conference, How Teachers Improve", "id":"26", "organization":"President and Fellows of Harvard College", "total_amount":"91300", "group":"low", "Grant start date":"5/13/2009", "start_month":"5", "start_day":"13", "start_year":"2009" }, { "grant_title":"National Education Forum", "id":"27", "organization":"The Library of Congress", "total_amount":"91350", "group":"low", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Community Engagement Supporting College and Career Readiness", "id":"28", "organization":"Austin Voices for Education and Youth", "total_amount":"93000", "group":"low", "Grant start date":"10/1/2009", "start_month":"10", "start_day":"1", "start_year":"2009" }, { "grant_title":"Building & Sustaining Support for Good Schools: A Public Information Campaign", "id":"29", "organization":"Prichard Committee for Academic Excellence", "total_amount":"100000", "group":"medium", "Grant start date":"4/30/2010", "start_month":"4", "start_day":"30", "start_year":"2010" }, { "grant_title":"City Based Proposal for What Works Fund – Council of Great City Schools", "id":"30", "organization":"Council Of The Great City Schools", "total_amount":"100000", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"City based proposal for What Works Fund - New Schools for New Orleans", "id":"31", "organization":"New Schools for New Orleans", "total_amount":"100000", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"EEP Equality Day Rally Support", "id":"32", "organization":"Education Equality Project", "total_amount":"100000", "group":"medium", "Grant start date":"6/19/2009", "start_month":"6", "start_day":"19", "start_year":"2009" }, { "grant_title":"PI:NAME:<NAME>END_PI", "id":"33", "organization":"Education Writers Association", "total_amount":"100000", "group":"medium", "Grant start date":"7/22/2009", "start_month":"7", "start_day":"22", "start_year":"2009" }, { "grant_title":"Repurpose of Alliance for Education Funds to a Variety of Essential Organizational Functions and Programs", "id":"34", "organization":"Alliance for Education", "total_amount":"110610", "group":"medium", "Grant start date":"2/26/2010", "start_month":"2", "start_day":"26", "start_year":"2010" }, { "grant_title":"Secondary STEM Data and Standards Analysis", "id":"35", "organization":"Texas Public Education Reform Foundation", "total_amount":"140000", "group":"medium", "Grant start date":"7/28/2009", "start_month":"7", "start_day":"28", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"36", "organization":"Charlotte-Mecklenburg Schools", "total_amount":"143973", "group":"medium", "Grant start date":"11/9/2009", "start_month":"11", "start_day":"9", "start_year":"2009" }, { "grant_title":"Ethnic Commission Education Reform Project", "id":"37", "organization":"Washington State Commission on African American Affairs", "total_amount":"146025", "group":"medium", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"38", "organization":"Cristo Rey Network", "total_amount":"149733", "group":"medium", "Grant start date":"11/6/2009", "start_month":"11", "start_day":"6", "start_year":"2009" }, { "grant_title":"California Collaborative on District Reform Phase 2", "id":"39", "organization":"American Institutes for Research", "total_amount":"150000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Professional Educator Standards Board", "id":"40", "organization":"Professional Educator Standards Board", "total_amount":"150000", "group":"medium", "Grant start date":"10/9/2009", "start_month":"10", "start_day":"9", "start_year":"2009" }, { "grant_title":"Evaluate the Leaky College Pipeline in New York City", "id":"41", "organization":"Fund for Public Schools Inc.", "total_amount":"170023", "group":"medium", "Grant start date":"10/27/2009", "start_month":"10", "start_day":"27", "start_year":"2009" }, { "grant_title":"Advocacy for Sustained School Reform in the Nation's Capital", "id":"42", "organization":"DC VOICE", "total_amount":"200000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"DC Expansion and CA STEM partnership", "id":"43", "organization":"Tiger Woods Foundation Inc.", "total_amount":"200000", "group":"medium", "Grant start date":"8/29/2009", "start_month":"8", "start_day":"29", "start_year":"2009" }, { "grant_title":"Retaining Teacher Talent: What Matters for Gen-Y Teachers", "id":"44", "organization":"Public Agenda Foundation, Inc.", "total_amount":"215000", "group":"medium", "Grant start date":"3/2/2009", "start_month":"3", "start_day":"2", "start_year":"2009" }, { "grant_title":"Supplemental Support for the New York STEM Progressive Dialogues (original grant on OPP52284)", "id":"45", "organization":"Rensselaer Polytechnic Institute", "total_amount":"220654", "group":"medium", "Grant start date":"9/29/2009", "start_month":"9", "start_day":"29", "start_year":"2009" }, { "grant_title":"Teacher Demographics and Pension Policies", "id":"46", "organization":"National Commission on Teachings & America's Future", "total_amount":"221755", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Charter School Initiative", "id":"47", "organization":"President and Fellows of Harvard College", "total_amount":"224030", "group":"medium", "Grant start date":"2/25/2010", "start_month":"2", "start_day":"25", "start_year":"2010" }, { "grant_title":"High School Standards Review project", "id":"48", "organization":"Illinois State Board of Education", "total_amount":"225000", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Progressive Dialogues (Supplemental grant on OPP1008819)", "id":"49", "organization":"Rensselaer Polytechnic Institute", "total_amount":"231382", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Support access to ARRA funds for strong CMOs", "id":"50", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"246070", "group":"medium", "Grant start date":"9/10/2009", "start_month":"9", "start_day":"10", "start_year":"2009" }, { "grant_title":"Aspen-NewSchools Fellows", "id":"51", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"250000", "group":"medium", "Grant start date":"3/26/2009", "start_month":"3", "start_day":"26", "start_year":"2009" }, { "grant_title":"Texas Charter Schools Association", "id":"52", "organization":"Texas Charter Schools Association", "total_amount":"250000", "group":"medium", "Grant start date":"5/18/2009", "start_month":"5", "start_day":"18", "start_year":"2009" }, { "grant_title":"to support the work of a teacher evaluation task force", "id":"53", "organization":"American Federation Of Teachers Educational Foundation", "total_amount":"250000", "group":"medium", "Grant start date":"6/23/2009", "start_month":"6", "start_day":"23", "start_year":"2009" }, { "grant_title":"Ensuring a Valid and Useable Teacher Student Link", "id":"54", "organization":"National Center For Educational Achievement", "total_amount":"260760", "group":"medium", "Grant start date":"11/21/2009", "start_month":"11", "start_day":"21", "start_year":"2009" }, { "grant_title":"Consistent College-Ready Standards", "id":"55", "organization":"Military Child Education Coalition", "total_amount":"269998", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"DCPS Measures of Teacher Effectiveness Study", "id":"56", "organization":"DC Public Education Fund", "total_amount":"299985", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Creating a Stronger Philanthropic Sector in Education", "id":"57", "organization":"Grantmakers for Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/6/2009", "start_month":"11", "start_day":"6", "start_year":"2009" }, { "grant_title":"Envision Schools Post-Secondary Tracking", "id":"58", "organization":"Envision Schools", "total_amount":"300000", "group":"medium", "Grant start date":"6/1/2008", "start_month":"6", "start_day":"1", "start_year":"2008" }, { "grant_title":"Global Education Leaders' Program (GELP)", "id":"59", "organization":"Silicon Valley Community Foundation", "total_amount":"300000", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Investigation of the Relationship between Teacher Quality and Student Learning Outcomes", "id":"60", "organization":"ACT, Inc.", "total_amount":"300000", "group":"medium", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher-Student Data Link Project - Arkansas", "id":"61", "organization":"Arkansas Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Florida", "id":"62", "organization":"Florida Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Georgia", "id":"63", "organization":"Georgia Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Louisiana", "id":"64", "organization":"Louisiana Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Teacher-Student Data Link Project - Ohio", "id":"65", "organization":"Ohio Department of Education", "total_amount":"300000", "group":"medium", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"The California STEM Innovation Network", "id":"66", "organization":"California Polytechnic State University Foundation", "total_amount":"300000", "group":"medium", "Grant start date":"1/8/2009", "start_month":"1", "start_day":"8", "start_year":"2009" }, { "grant_title":"TN SCORE state advocacy coalition", "id":"67", "organization":"Tennessee State Collaborative on Reforming Education", "total_amount":"300250", "group":"medium", "Grant start date":"2/19/2010", "start_month":"2", "start_day":"19", "start_year":"2010" }, { "grant_title":"Bring Your 'A' Game", "id":"68", "organization":"Twenty First Century Foundation", "total_amount":"302425", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Instructional Support at Cleveland and Rainier Beach", "id":"69", "organization":"Alliance for Education", "total_amount":"309554", "group":"medium", "Grant start date":"9/17/2008", "start_month":"9", "start_day":"17", "start_year":"2008" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"70", "organization":"National Council of La Raza", "total_amount":"322103", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"NYC Public Schools: A Retrospective 2002-2009", "id":"71", "organization":"American Institutes for Research", "total_amount":"325000", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"NSC Student Data for High Schools Pilot: Georgia", "id":"72", "organization":"University System of Georgia Foundation, Inc.", "total_amount":"331678", "group":"medium", "Grant start date":"11/11/2009", "start_month":"11", "start_day":"11", "start_year":"2009" }, { "grant_title":"Common Core Companion Curriculum Project", "id":"73", "organization":"Common Core Inc.", "total_amount":"331890", "group":"medium", "Grant start date":"12/17/2009", "start_month":"12", "start_day":"17", "start_year":"2009" }, { "grant_title":"Civic Mission of Schools", "id":"74", "organization":"National Council for the Social Studies", "total_amount":"351704", "group":"medium", "Grant start date":"6/1/2008", "start_month":"6", "start_day":"1", "start_year":"2008" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"75", "organization":"Pittsburgh Public Schools", "total_amount":"353977", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"Institute for Local Innovation in Teaching and Learning", "id":"76", "organization":"The NEA Foundation for the Improvement of Education", "total_amount":"358915", "group":"medium", "Grant start date":"10/22/2009", "start_month":"10", "start_day":"22", "start_year":"2009" }, { "grant_title":"Campaign for High School Equity", "id":"77", "organization":"L.U.L.A.C. Institute, Inc.", "total_amount":"370005", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Preparing Secondary English Learners for Graduation and College", "id":"78", "organization":"University of California, Los Angeles", "total_amount":"375000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"79", "organization":"Leadership Conference on Civil Rights Education Fund, Inc.", "total_amount":"375030", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"NSC Student Data for High Schools Pilot: Florida", "id":"80", "organization":"Florida Department of Education", "total_amount":"383465", "group":"medium", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"The Policy Innovation in Education Network", "id":"81", "organization":"PI:NAME:<NAME>END_PI", "total_amount":"398534", "group":"medium", "Grant start date":"6/15/2009", "start_month":"6", "start_day":"15", "start_year":"2009" }, { "grant_title":"Common Core Strategies for State Policymakers", "id":"82", "organization":"Council of State Governments", "total_amount":"399953", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"83", "organization":"Mexican American Legal Defense and Educational Fund", "total_amount":"400000", "group":"medium", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Education Equity Agenda: LULAC Parent Involvement Initiative for Campaign for High School Equity", "id":"84", "organization":"L.U.L.A.C. Institute, Inc.", "total_amount":"400017", "group":"medium", "Grant start date":"9/21/2009", "start_month":"9", "start_day":"21", "start_year":"2009" }, { "grant_title":"8th to 9th Grade Transition and Acceleration Project", "id":"85", "organization":"National Summer Learning Association", "total_amount":"400366", "group":"medium", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"Support of professional development and an education workshop for education beat reporters", "id":"86", "organization":"Teachers College, Columbia University", "total_amount":"402493", "group":"medium", "Grant start date":"9/29/2009", "start_month":"9", "start_day":"29", "start_year":"2009" }, { "grant_title":"NSC Student Data for High Schools Pilot: Texas", "id":"87", "organization":"Communities Foundation of Texas", "total_amount":"406610", "group":"medium", "Grant start date":"10/15/2009", "start_month":"10", "start_day":"15", "start_year":"2009" }, { "grant_title":"Supplemental Support Review and Build-out of the Raytheon STEM Model", "id":"88", "organization":"Business Higher Education Forum", "total_amount":"417517", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"The State of Professional Learning: A National Study", "id":"89", "organization":"National Staff Development Council", "total_amount":"421603", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Southeast Asian American Action and Visibility in Education (SAVE) Project", "id":"90", "organization":"Southeast Asia Resource Action Center", "total_amount":"425000", "group":"medium", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Roads to Success Curriculum Completion and Distribution", "id":"91", "organization":"Roads to Success Inc.", "total_amount":"430000", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"STEM Community Collaborative Phase 2", "id":"92", "organization":"MCNC", "total_amount":"432898", "group":"medium", "Grant start date":"3/6/2009", "start_month":"3", "start_day":"6", "start_year":"2009" }, { "grant_title":"California ADP Support", "id":"93", "organization":"Regents of the University of California at Berkeley", "total_amount":"437807", "group":"medium", "Grant start date":"10/22/2008", "start_month":"10", "start_day":"22", "start_year":"2008" }, { "grant_title":"Regional convenings for policymakers and leaders to develop commitment to standards and assessments", "id":"94", "organization":"National Association of State Boards of Education", "total_amount":"450675", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"Business Planning to Create Hybrid Learning Environments in Existing and New Schools", "id":"95", "organization":"Pollinate Ventures", "total_amount":"451125", "group":"medium", "Grant start date":"11/8/2009", "start_month":"11", "start_day":"8", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"96", "organization":"Fund for Public Schools Inc.", "total_amount":"455394", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"KIPPShare National Data Platform", "id":"97", "organization":"KIPP Foundation", "total_amount":"468500", "group":"medium", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"The Equity Project (TEP) Charter School Evaluation", "id":"98", "organization":"Mathematica Policy Research", "total_amount":"470507", "group":"medium", "Grant start date":"7/16/2009", "start_month":"7", "start_day":"16", "start_year":"2009" }, { "grant_title":"North Carolina STEM Development", "id":"99", "organization":"MCNC", "total_amount":"475000", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Using web-based videos to teach math to high school students", "id":"100", "organization":"Guaranteach", "total_amount":"475077", "group":"medium", "Grant start date":"3/18/2010", "start_month":"3", "start_day":"18", "start_year":"2010" }, { "grant_title":"CPS Community Ownership Proposal", "id":"101", "organization":"Strive: Cincinnati/Northern Kentucky, LLC", "total_amount":"490021", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher Working Conditions Survey", "id":"102", "organization":"New Teacher Center", "total_amount":"494933", "group":"medium", "Grant start date":"10/13/2009", "start_month":"10", "start_day":"13", "start_year":"2009" }, { "grant_title":"North Carolina New Technology High School Network Sustainability", "id":"103", "organization":"New Technology Foundation", "total_amount":"496776", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Planning Grant for Evaluation of Green Dot's Locke Transformation Project", "id":"104", "organization":"University of California, Los Angeles", "total_amount":"498724", "group":"medium", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Preparing All Students for College, Work and Citizenship", "id":"105", "organization":"National Conference of State Legislatures", "total_amount":"499225", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Gateway to College Capacity-Building", "id":"106", "organization":"Gateway to College National Network", "total_amount":"499398", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Doubling the Numbers in STEM", "id":"107", "organization":"Ohio Business Alliance for Higher Education and the Economy", "total_amount":"500000", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"IMPLEMENTATION: StartL: A Digital Media and Learning Accelerator", "id":"108", "organization":"Social Science Research Council", "total_amount":"500000", "group":"medium", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"NAPCS General Operating Support", "id":"109", "organization":"National Alliance For Public Charter Schools", "total_amount":"500000", "group":"medium", "Grant start date":"10/30/2009", "start_month":"10", "start_day":"30", "start_year":"2009" }, { "grant_title":"New England Consortium", "id":"110", "organization":"Nellie Mae Education Foundation", "total_amount":"500000", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"WGHA AmbPI:NAME:<NAME>END_PI", "id":"111", "organization":"Seattle Biomedical Research Institute", "total_amount":"500000", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Stay for America (retaining effective Teach for America teachers beyond year 2)", "id":"112", "organization":"Teach for America, Inc.", "total_amount":"500422", "group":"medium", "Grant start date":"10/1/2009", "start_month":"10", "start_day":"1", "start_year":"2009" }, { "grant_title":"Grassroots Media Project", "id":"113", "organization":"Fund for the City of New York, Inc.", "total_amount":"513219", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Improving Native Student Graduation Rates: Policy Recommendations on High School Reform", "id":"114", "organization":"National Indian Education Association", "total_amount":"520446", "group":"medium", "Grant start date":"8/31/2009", "start_month":"8", "start_day":"31", "start_year":"2009" }, { "grant_title":"The State Role In Improving Low-performing Schools", "id":"115", "organization":"Center on Education Policy", "total_amount":"544700", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Engaging Communities for College Readiness (ENCORE)", "id":"116", "organization":"Texas Valley Communities Foundation", "total_amount":"546865", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"New Degree Program for Education Leaders", "id":"117", "organization":"President and Fellows of Harvard College", "total_amount":"550000", "group":"medium", "Grant start date":"8/1/2008", "start_month":"8", "start_day":"1", "start_year":"2008" }, { "grant_title":"National Advocacy Support for the Common Core Initiative", "id":"118", "organization":"Alliance for Excellent Education, Inc.", "total_amount":"551336", "group":"medium", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"Conceptual and Organizing Platform for Secondary Mathematics Formative Assessments", "id":"119", "organization":"Regents University Of California Los Angeles", "total_amount":"576191", "group":"medium", "Grant start date":"5/11/2009", "start_month":"5", "start_day":"11", "start_year":"2009" }, { "grant_title":"Education Practice Launch", "id":"120", "organization":"Innosight Institute Inc", "total_amount":"588559", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Building Business Leadership for New Approaches to Teacher Compensation", "id":"121", "organization":"Committee for Economic Development", "total_amount":"597077", "group":"medium", "Grant start date":"5/5/2009", "start_month":"5", "start_day":"5", "start_year":"2009" }, { "grant_title":"Mathematics Assessment for Learning Phase One RFP", "id":"122", "organization":"Prichard Committee for Academic Excellence", "total_amount":"599016", "group":"medium", "Grant start date":"11/16/2009", "start_month":"11", "start_day":"16", "start_year":"2009" }, { "grant_title":"THE HIGH SCHOOL REDESIGN INITIATIVE -- PHASE TWO", "id":"123", "organization":"National Association of State Boards of Education", "total_amount":"599725", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Aligning P-12 and Postsecondary Data Systems", "id":"124", "organization":"National Center For Educational Achievement", "total_amount":"600000", "group":"medium", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"The Next Generation of NCLR Schools", "id":"125", "organization":"National Council of La Raza", "total_amount":"600000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Washington STEM Innovation Initiative", "id":"126", "organization":"Partnership for Learning", "total_amount":"643881", "group":"medium", "Grant start date":"3/11/2009", "start_month":"3", "start_day":"11", "start_year":"2009" }, { "grant_title":"Teacher Effectiveness work", "id":"127", "organization":"Hope Street Group", "total_amount":"650108", "group":"medium", "Grant start date":"11/7/2009", "start_month":"11", "start_day":"7", "start_year":"2009" }, { "grant_title":"Stimulus related work and CSA support", "id":"128", "organization":"Institute for a Competitive Workforce", "total_amount":"653077", "group":"medium", "Grant start date":"11/11/2009", "start_month":"11", "start_day":"11", "start_year":"2009" }, { "grant_title":"Validating a Common Core of Fewer, Clearer, Higher Standards", "id":"129", "organization":"Educational Policy Improvement Center", "total_amount":"721687", "group":"medium", "Grant start date":"5/5/2009", "start_month":"5", "start_day":"5", "start_year":"2009" }, { "grant_title":"Preparing parents and students to be advocates for quality school reform in Illinois", "id":"130", "organization":"Target Area Development Corporation", "total_amount":"725000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Building Capacity for College Success: Implementing Data Collection Systems and Best Practices", "id":"131", "organization":"National Association of Street Schools", "total_amount":"742223", "group":"medium", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Support for National Lab Day", "id":"132", "organization":"Tides Center", "total_amount":"750000", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"Winning Strategies Black Male Donor Collaborative", "id":"133", "organization":"The Schott Foundation For Public Education", "total_amount":"750000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"The Role of School Board Governance in Preaparing Students for College and Workplace Readiness", "id":"134", "organization":"National School Boards Foundation", "total_amount":"755603", "group":"medium", "Grant start date":"4/25/2009", "start_month":"4", "start_day":"25", "start_year":"2009" }, { "grant_title":"Tracking Students from Secondary to Post Secondary Institutions", "id":"135", "organization":"National Student Clearinghouse", "total_amount":"792216", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"136", "organization":"National Urban League Inc.", "total_amount":"800000", "group":"medium", "Grant start date":"10/26/2009", "start_month":"10", "start_day":"26", "start_year":"2009" }, { "grant_title":"WA State Board of Education Phase II: A Meaningful High School Diploma and A State Accountability Education System", "id":"137", "organization":"The Washington State Board of Education", "total_amount":"850000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Measures of Effective Teaching Research Site", "id":"138", "organization":"Denver Public Schools", "total_amount":"878493", "group":"medium", "Grant start date":"11/13/2009", "start_month":"11", "start_day":"13", "start_year":"2009" }, { "grant_title":"STEM Capacity Building", "id":"139", "organization":"Business Higher Education Forum", "total_amount":"910000", "group":"medium", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Federal and Regional Advocacy Policy Support for College Ready Work, Transparent Education Data System Alignment, Effective & Empowered Teachers and Innovation.", "id":"140", "organization":"National Council of La Raza", "total_amount":"930223", "group":"medium", "Grant start date":"11/10/2009", "start_month":"11", "start_day":"10", "start_year":"2009" }, { "grant_title":"DC Achiever Restructuring Partner", "id":"141", "organization":"Friendship Public Charter School", "total_amount":"937088", "group":"medium", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"PRI Guaranty To Unlock Facilities Financing for High Quality Charter Schools", "id":"142", "organization":"Local Initiatives Support Corporation", "total_amount":"950000", "group":"medium", "Grant start date":"8/27/2009", "start_month":"8", "start_day":"27", "start_year":"2009" }, { "grant_title":"Common Standards Review and Task Development", "id":"143", "organization":"PI:NAME:<NAME>END_PI Institute", "total_amount":"959116", "group":"medium", "Grant start date":"10/10/2009", "start_month":"10", "start_day":"10", "start_year":"2009" }, { "grant_title":"Intermediary management of PRI/Credit Enhancement Program - Los Angeles (Aspire)", "id":"144", "organization":"NCB Capital Impact", "total_amount":"959373", "group":"medium", "Grant start date":"4/8/2010", "start_month":"4", "start_day":"8", "start_year":"2010" }, { "grant_title":"Sustainability for Recovery School District", "id":"145", "organization":"Baton Rouge Area Foundation", "total_amount":"993219", "group":"medium", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"Research Design for Project-Based Advanced Placement Courses", "id":"146", "organization":"University of Washington", "total_amount":"996185", "group":"medium", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Accelerate and Enhance Teacher Effectiveness Methods In Districts/Networks", "id":"147", "organization":"Achievement First Inc.", "total_amount":"998221", "group":"medium", "Grant start date":"10/9/2009", "start_month":"10", "start_day":"9", "start_year":"2009" }, { "grant_title":"AFT Innovation Fund", "id":"148", "organization":"American Federation Of Teachers Educational Foundation", "total_amount":"1000000", "group":"medium", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Applying an R&D model to education to unearth root causes of performance gaps, to effectively vet options for reform.", "id":"149", "organization":"President and Fellows of Harvard College", "total_amount":"1000000", "group":"medium", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"For the Future", "id":"150", "organization":"Team Pennsylvania Foundation", "total_amount":"1000000", "group":"medium", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"General Support Supplemental", "id":"151", "organization":"The Education Trust", "total_amount":"1000000", "group":"medium", "Grant start date":"1/21/2010", "start_month":"1", "start_day":"21", "start_year":"2010" }, { "grant_title":"Ohio College and Career Ready Consortium", "id":"152", "organization":"Ohio Grantmakers Forum", "total_amount":"1000000", "group":"medium", "Grant start date":"7/18/2009", "start_month":"7", "start_day":"18", "start_year":"2009" }, { "grant_title":"Strategic Management of Human Capital in Public Ed", "id":"153", "organization":"University of Wisconsin", "total_amount":"1000000", "group":"medium", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"to support Teach for America (TFA) with the goal of bringing low income and minority students in TFA classrooms to proficiency", "id":"154", "organization":"Teach for America, Inc.", "total_amount":"1000000", "group":"medium", "Grant start date":"6/26/2009", "start_month":"6", "start_day":"26", "start_year":"2009" }, { "grant_title":"Los Angeles Collaborative to Improve College and Career Readiness in LAUSD Schools", "id":"155", "organization":"United Way Inc.", "total_amount":"1000330", "group":"high", "Grant start date":"1/15/2009", "start_month":"1", "start_day":"15", "start_year":"2009" }, { "grant_title":"PEN business planning", "id":"156", "organization":"Public Education Network", "total_amount":"1001363", "group":"high", "Grant start date":"7/10/2009", "start_month":"7", "start_day":"10", "start_year":"2009" }, { "grant_title":"Accelerate and Enhance Teacher Effectiveness Methods In Districts/Networks", "id":"157", "organization":"Recovery School District", "total_amount":"1004719", "group":"high", "Grant start date":"10/22/2009", "start_month":"10", "start_day":"22", "start_year":"2009" }, { "grant_title":"CEP standards and assessment work", "id":"158", "organization":"Center on Education Policy", "total_amount":"1047928", "group":"high", "Grant start date":"9/8/2009", "start_month":"9", "start_day":"8", "start_year":"2009" }, { "grant_title":"College Bound", "id":"159", "organization":"College Success Foundation", "total_amount":"1053150", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Accelerator Enhance Teacher Effectiveness Methods - RE: ASPIRE Model in HISD", "id":"160", "organization":"Houston Independent School District", "total_amount":"1100000", "group":"high", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"Ohio Follow-Through on Achieve Policy Study Recommendations", "id":"161", "organization":"Ohio Department of Education", "total_amount":"1175000", "group":"high", "Grant start date":"1/1/2008", "start_month":"1", "start_day":"1", "start_year":"2008" }, { "grant_title":"Philanthropic Partnership for Public Education", "id":"162", "organization":"Seattle Foundation", "total_amount":"1181375", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"A Progressive Agenda for Human Capital Policy Reform", "id":"163", "organization":"Center for American Progress", "total_amount":"1198248", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Gates-EdVisions Moving Forward", "id":"164", "organization":"EdVisions Inc", "total_amount":"1200552", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Texas Education Research Support", "id":"165", "organization":"College for All Texans Foundation: Closing the Gaps", "total_amount":"1221800", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Portable Word Play - Discovering What Handheld Games Can Do for Adolescent Reading Comprehension", "id":"166", "organization":"Education Development Center, Inc.", "total_amount":"1224953", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Baltimore Sustainability Plan", "id":"167", "organization":"Fund for Educational Excellence", "total_amount":"1229730", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Academic Youth Development", "id":"168", "organization":"University of Texas at Austin", "total_amount":"1235787", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Campaign for High School Equity", "id":"169", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"1279229", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"support the K-12 backmapping of the standards", "id":"170", "organization":"Council of Chief State School Officers", "total_amount":"1291738", "group":"high", "Grant start date":"10/12/2009", "start_month":"10", "start_day":"12", "start_year":"2009" }, { "grant_title":"Building College-Ready Culture in Our High Schools", "id":"171", "organization":"College Summit Inc.", "total_amount":"1300000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Measures of Effective Teaching Research Site", "id":"172", "organization":"Dallas Independent School District", "total_amount":"1332279", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Technical Assistance for Standards/Assessment Partners", "id":"173", "organization":"National Center for the Improvement of Educational Assessment Inc.", "total_amount":"1362773", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Making NSC Data Actionable for School Leaders", "id":"174", "organization":"College Summit Inc", "total_amount":"1383137", "group":"high", "Grant start date":"5/22/2009", "start_month":"5", "start_day":"22", "start_year":"2009" }, { "grant_title":"Charlotte-Mecklenburg Measures of Teacher Effectiveness Research", "id":"175", "organization":"Charlotte-Mecklenburg Schools", "total_amount":"1431534", "group":"high", "Grant start date":"9/3/2009", "start_month":"9", "start_day":"3", "start_year":"2009" }, { "grant_title":"College Ready Course Sequence Implementation", "id":"176", "organization":"ACT, Inc.", "total_amount":"1445269", "group":"high", "Grant start date":"9/14/2009", "start_month":"9", "start_day":"14", "start_year":"2009" }, { "grant_title":"Partnership for Learning Statewide Advocacy + Stimulus RTT TA", "id":"177", "organization":"Partnership for Learning", "total_amount":"1493522", "group":"high", "Grant start date":"11/1/2009", "start_month":"11", "start_day":"1", "start_year":"2009" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"178", "organization":"Tulsa Public Schools", "total_amount":"1500000", "group":"high", "Grant start date":"2/4/2010", "start_month":"2", "start_day":"4", "start_year":"2010" }, { "grant_title":"LEV Statewide Advocacy Expansion", "id":"179", "organization":"League of Education Voters Foundation", "total_amount":"1500000", "group":"high", "Grant start date":"10/29/2009", "start_month":"10", "start_day":"29", "start_year":"2009" }, { "grant_title":"NCEE state partnerships", "id":"180", "organization":"National Center on Education & the Economy", "total_amount":"1500000", "group":"high", "Grant start date":"10/19/2009", "start_month":"10", "start_day":"19", "start_year":"2009" }, { "grant_title":"Development of frameworks for the assessment of teacher knowledge", "id":"181", "organization":"Educational Testing Service", "total_amount":"1521971", "group":"high", "Grant start date":"11/14/2009", "start_month":"11", "start_day":"14", "start_year":"2009" }, { "grant_title":"Organizing for High School Reform", "id":"182", "organization":"Pacific Institute For Community Organizations", "total_amount":"1600000", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Expansion of Urban Teacher Residency (UTRU)", "id":"183", "organization":"The Urban Teacher Residency Institute", "total_amount":"1635665", "group":"high", "Grant start date":"9/1/2009", "start_month":"9", "start_day":"1", "start_year":"2009" }, { "grant_title":"Advance Illinois organization build", "id":"184", "organization":"Advance Illinois", "total_amount":"1800000", "group":"high", "Grant start date":"5/15/2008", "start_month":"5", "start_day":"15", "start_year":"2008" }, { "grant_title":"Validation of the Teaching as Leadership Rubric", "id":"185", "organization":"Teach for America, Inc.", "total_amount":"1840548", "group":"high", "Grant start date":"10/5/2009", "start_month":"10", "start_day":"5", "start_year":"2009" }, { "grant_title":"CMO Research Study Project Management", "id":"186", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"1891265", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"6to16", "id":"187", "organization":"University of Chicago - Urban Education Institute", "total_amount":"1894228", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Education Equity Agenda: Support for Campaign for High School Equity coordination of national civil rights organization national policy advocacy of College Ready and Postsecondary Strategies", "id":"188", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"1915298", "group":"high", "Grant start date":"10/19/2009", "start_month":"10", "start_day":"19", "start_year":"2009" }, { "grant_title":"Strengthening State College Readiness Initiatives", "id":"189", "organization":"Board Of Control For Southern Regional Education", "total_amount":"1987015", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"190", "organization":"Memphis City Schools", "total_amount":"1988654", "group":"high", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"New-Media Capacity Building at EPE", "id":"191", "organization":"Editorial Projects in Education", "total_amount":"1997280", "group":"high", "Grant start date":"5/1/2009", "start_month":"5", "start_day":"1", "start_year":"2009" }, { "grant_title":"Implementation: National PTA support for college-readiness", "id":"192", "organization":"National Congress of Parents and Teachers", "total_amount":"2000000", "group":"high", "Grant start date":"11/3/2009", "start_month":"11", "start_day":"3", "start_year":"2009" }, { "grant_title":"The Public Education Reform and Community Development Link: A Sustainable Solution", "id":"193", "organization":"Deutsche Bank Americas Foundation", "total_amount":"2000000", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Project GRAD USA's National College Readiness Initiative", "id":"194", "organization":"Project GRAD", "total_amount":"2025892", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Literacy by Design", "id":"195", "organization":"The Trust For Early Education Inc", "total_amount":"2039526", "group":"high", "Grant start date":"9/17/2009", "start_month":"9", "start_day":"17", "start_year":"2009" }, { "grant_title":"THSP Alliance Business Planning", "id":"196", "organization":"Communities Foundation of Texas", "total_amount":"2046674", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Teacher-Student Data Link Project", "id":"197", "organization":"CELT Corporation", "total_amount":"2200000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Dropout Prevention", "id":"198", "organization":"Americas Promise-The Alliance For Youth", "total_amount":"2211517", "group":"high", "Grant start date":"3/19/2008", "start_month":"3", "start_day":"19", "start_year":"2008" }, { "grant_title":"Hunt Institute Common State Education Standards Project", "id":"199", "organization":"The PI:NAME:<NAME>END_PI, Jr. Institute for Educational Leadership and Policy", "total_amount":"2213470", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Business Planning for Education grantees", "id":"200", "organization":"The Bridgespan Group", "total_amount":"2237530", "group":"high", "Grant start date":"4/20/2009", "start_month":"4", "start_day":"20", "start_year":"2009" }, { "grant_title":"Develop Tools for Teachers/Districts to Monitor Student Progress", "id":"201", "organization":"Math Solutions", "total_amount":"2274957", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"IB Middle Years Summative Assessment", "id":"202", "organization":"IB Fund US Inc.", "total_amount":"2423679", "group":"high", "Grant start date":"8/22/2009", "start_month":"8", "start_day":"22", "start_year":"2009" }, { "grant_title":"To Help Governors Improve College and Career Ready Rates", "id":"203", "organization":"National Governors Association Center For Best Practices", "total_amount":"2496814", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Next Generation PD System", "id":"204", "organization":"DC Public Education Fund", "total_amount":"2500000", "group":"high", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"205", "organization":"Prince George's County Public Schools", "total_amount":"2500169", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Intensive Partnership Site - Participation in MET Research Study", "id":"206", "organization":"Hillsborough County Public Schools", "total_amount":"2502146", "group":"high", "Grant start date":"10/20/2009", "start_month":"10", "start_day":"20", "start_year":"2009" }, { "grant_title":"Scaling NCTQ state and district work", "id":"207", "organization":"National Council on Teacher Quality", "total_amount":"2565641", "group":"high", "Grant start date":"10/21/2009", "start_month":"10", "start_day":"21", "start_year":"2009" }, { "grant_title":"NAPCS Industry Development", "id":"208", "organization":"National Alliance For Public Charter Schools", "total_amount":"2605527", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Increasing Business Engagement", "id":"209", "organization":"Institute for a Competitive Workforce", "total_amount":"2625837", "group":"high", "Grant start date":"10/8/2008", "start_month":"10", "start_day":"8", "start_year":"2008" }, { "grant_title":"Building Support for Federal High School Policy Reform", "id":"210", "organization":"Alliance for Excellent Education, Inc.", "total_amount":"2644892", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"NYC DOE Measures of Teacher Effectiveness Research", "id":"211", "organization":"Fund for Public Schools Inc.", "total_amount":"2646876", "group":"high", "Grant start date":"8/28/2009", "start_month":"8", "start_day":"28", "start_year":"2009" }, { "grant_title":"Aspire Public Schools' Early College High School Capacity Project", "id":"212", "organization":"Aspire Public Schools", "total_amount":"2899727", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"Big 8 Superintendents Data Assessment", "id":"213", "organization":"Communities Foundation of Texas", "total_amount":"2901632", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"National Impact Initiative", "id":"214", "organization":"National Association Of Charter School Authorizers", "total_amount":"2979186", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Development and Adaptation of Science and Literacy Formative Assessment Tasks", "id":"215", "organization":"Regents Of The University Of California At Berkeley", "total_amount":"2999730", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Research Alliance for New York City Schools", "id":"216", "organization":"New York University", "total_amount":"2999960", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"CCSR General Operating Support", "id":"217", "organization":"University of Chicago (Parent Org)", "total_amount":"3000000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"Deepening and Expanding the Impact of Diploma Plus", "id":"218", "organization":"Third Sector New England, Inc.", "total_amount":"3179363", "group":"high", "Grant start date":"9/1/2008", "start_month":"9", "start_day":"1", "start_year":"2008" }, { "grant_title":"To provide support to states on RTTT applications", "id":"219", "organization":"New Venture Fund", "total_amount":"3240000", "group":"high", "Grant start date":"11/4/2009", "start_month":"11", "start_day":"4", "start_year":"2009" }, { "grant_title":"Alternative High School Initiative", "id":"220", "organization":"The Big Picture Company", "total_amount":"3315216", "group":"high", "Grant start date":"7/15/2009", "start_month":"7", "start_day":"15", "start_year":"2009" }, { "grant_title":"Support for Teaching First to ensure that there is public support for district efforts to improve teacher effectiveness", "id":"221", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"3487270", "group":"high", "Grant start date":"9/25/2009", "start_month":"9", "start_day":"25", "start_year":"2009" }, { "grant_title":"IDEA Public Schools Expansion", "id":"222", "organization":"Idea Academy Inc", "total_amount":"3498875", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Title", "id":"223", "organization":"College Summit Inc", "total_amount":"3500000", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"College Ready Mathematics Formative Assessments", "id":"224", "organization":"Regents Of The University Of California At Berkeley", "total_amount":"3661294", "group":"high", "Grant start date":"9/25/2009", "start_month":"9", "start_day":"25", "start_year":"2009" }, { "grant_title":"Using Standards and Data to Improve Urban School Systems", "id":"225", "organization":"Council Of The Great City Schools", "total_amount":"3735866", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"College Readiness Data Initiative", "id":"226", "organization":"Dallas Independent School District", "total_amount":"3774912", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"Project support for expanding Aspen network", "id":"227", "organization":"The Aspen Institute", "total_amount":"3878680", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Aligned Instructional Systems", "id":"228", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"3999127", "group":"high", "Grant start date":"5/1/2008", "start_month":"5", "start_day":"1", "start_year":"2008" }, { "grant_title":"DC Schools Fund", "id":"229", "organization":"New Schools Fund dba NewSchools Venture Fund", "total_amount":"4000000", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Newark School Fund", "id":"230", "organization":"Newark Charter School Fund, Inc.", "total_amount":"4000000", "group":"high", "Grant start date":"2/15/2008", "start_month":"2", "start_day":"15", "start_year":"2008" }, { "grant_title":"SeaChange Capacity and Catalyst Funding", "id":"231", "organization":"SeaChange Capital Partners, Inc.", "total_amount":"4000000", "group":"high", "Grant start date":"12/1/2008", "start_month":"12", "start_day":"1", "start_year":"2008" }, { "grant_title":"College and Career Ready Graduation Initiative", "id":"232", "organization":"United Way of America", "total_amount":"4001263", "group":"high", "Grant start date":"1/1/2009", "start_month":"1", "start_day":"1", "start_year":"2009" }, { "grant_title":"Elevating An Alternative Teacher Voice", "id":"233", "organization":"Teach Plus, Incorporated", "total_amount":"4010611", "group":"high", "Grant start date":"9/30/2009", "start_month":"9", "start_day":"30", "start_year":"2009" }, { "grant_title":"Big Picture School Initiative", "id":"234", "organization":"The Big Picture Company", "total_amount":"4079157", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Matching Grant for Classroom Projects in Public High Schools", "id":"235", "organization":"DonorsChoose.org", "total_amount":"4114700", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Formative Assessment Data Collection, Task Analysis and Implementation (UCLA/CRESST)", "id":"236", "organization":"Regents University Of California Los Angeles", "total_amount":"4342988", "group":"high", "Grant start date":"11/12/2009", "start_month":"11", "start_day":"12", "start_year":"2009" }, { "grant_title":"State and National Common Core Standards Adoption/Implementation Advocacy Support", "id":"237", "organization":"PI:NAME:<NAME>END_PI, Jr. Institute for Educational Leadership and Policy Foundation, Inc.", "total_amount":"4368176", "group":"high", "Grant start date":"11/5/2009", "start_month":"11", "start_day":"5", "start_year":"2009" }, { "grant_title":"Ohio High School Value-Added Project", "id":"238", "organization":"Battelle For Kids", "total_amount":"4989262", "group":"high", "Grant start date":"10/1/2008", "start_month":"10", "start_day":"1", "start_year":"2008" }, { "grant_title":"Creating a National Movement for Improved K-12 Education", "id":"239", "organization":"GreatSchools, Inc.", "total_amount":"6000000", "group":"high", "Grant start date":"7/1/2008", "start_month":"7", "start_day":"1", "start_year":"2008" }, { "grant_title":"Smart Scholars: Early College High Schools in New York State", "id":"240", "organization":"The University of the State of New York", "total_amount":"6000000", "group":"high", "Grant start date":"7/29/2009", "start_month":"7", "start_day":"29", "start_year":"2009" }, { "grant_title":"Phase II - to support the expansion of second generation student tracker for high schools", "id":"241", "organization":"National Student Clearinghouse Research Center", "total_amount":"6094497", "group":"high", "Grant start date":"11/20/2009", "start_month":"11", "start_day":"20", "start_year":"2009" }, { "grant_title":"Support for Seattle Public Schools' Strategic Plan", "id":"242", "organization":"Alliance for Education", "total_amount":"6929430", "group":"high", "Grant start date":"11/10/2008", "start_month":"11", "start_day":"10", "start_year":"2008" }, { "grant_title":"Reforming the Widget Effect: Increasing teacher effectiveness in America's schools", "id":"243", "organization":"The New Teacher Project, Inc.", "total_amount":"7000000", "group":"high", "Grant start date":"7/10/2009", "start_month":"7", "start_day":"10", "start_year":"2009" }, { "grant_title":"Understanding Teacher Quality", "id":"244", "organization":"Educational Testing Service", "total_amount":"7348925", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Equity and Excellence in a Global Era: Expanding the International Studies Schools Network", "id":"245", "organization":"Asia Society", "total_amount":"7750417", "group":"high", "Grant start date":"11/1/2008", "start_month":"11", "start_day":"1", "start_year":"2008" }, { "grant_title":"Increase the leadership capacity of chiefs", "id":"246", "organization":"Council of Chief State School Officers", "total_amount":"7770104", "group":"high", "Grant start date":"7/1/2009", "start_month":"7", "start_day":"1", "start_year":"2009" }, { "grant_title":"Strong American Schools", "id":"247", "organization":"Rockefeller Philanthropy Advisors, Inc.", "total_amount":"9958245", "group":"high", "Grant start date":"3/1/2008", "start_month":"3", "start_day":"1", "start_year":"2008" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"248", "organization":"Denver Public Schools", "total_amount":"10000000", "group":"high", "Grant start date":"1/4/2010", "start_month":"1", "start_day":"4", "start_year":"2010" }, { "grant_title":"Accelerated Partnership to Empower Effective Teachers", "id":"249", "organization":"Atlanta Public Schools", "total_amount":"10000000", "group":"high", "Grant start date":"1/13/2010", "start_month":"1", "start_day":"13", "start_year":"2010" }, { "grant_title":"American Diploma Project Network", "id":"250", "organization":"Achieve Inc.", "total_amount":"12614352", "group":"high", "Grant start date":"2/1/2008", "start_month":"2", "start_day":"1", "start_year":"2008" }, { "grant_title":"Strategic Data Project", "id":"251", "organization":"President and Fellows of Harvard College", "total_amount":"14994686", "group":"high", "Grant start date":"6/17/2009", "start_month":"6", "start_day":"17", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"252", "organization":"Pittsburgh Public Schools", "total_amount":"40000000", "group":"high", "Grant start date":"11/18/2009", "start_month":"11", "start_day":"18", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers (LA-CMO's)", "id":"253", "organization":"The College-Ready Promise", "total_amount":"60000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"254", "organization":"Memphis City Schools", "total_amount":"90000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" }, { "grant_title":"Intensive Partnerships to Empower Effective Teachers", "id":"255", "organization":"Hillsborough County Public Schools", "total_amount":"100000000", "group":"high", "Grant start date":"11/19/2009", "start_month":"11", "start_day":"19", "start_year":"2009" } ]
[ { "context": "name: \"Pfunk\"\nscopeName: \"source.pf\"\nfoldingStartMarker: \"(", "end": 9, "score": 0.7155128121376038, "start": 7, "tag": "NAME", "value": "Pf" }, { "context": "name: \"Pfunk\"\nscopeName: \"source.pf\"\nfoldingStartMarker: \"(/\\\\", "end": 12, "score": 0....
grammars/pfunk.cson
Chronoes/language-pfunk
0
name: "Pfunk" scopeName: "source.pf" foldingStartMarker: "(/\\*|\\{|\\()" foldingEndMarker: "(\\*/|\\}|\\))" firstLineMatch: "^#!\\s*/.*\\b(node|js)$\\n?" fileTypes: [ "pf" ] patterns: [ { include: "#core" } ] repository: core: patterns: [ { include: "#ignore-long-lines" } { include: "#literal-labels" } { include: "#literal-keywords" } { include: "#literal-for" } { include: "#literal-switch" } { include: "#expression" } { include: "#literal-punctuation" } ] expression: patterns: [ { include: "#ignore-long-lines" } { include: "#jsx" } { include: "#support" } { include: "#literal-function" } { include: "#literal-arrow-function" } { include: "#literal-regexp" comment: "before operators to avoid abiguities" } { include: "#literal-number" } { include: "#literal-quasi" } { include: "#literal-string" } { include: "#literal-language-constant" } { include: "#literal-language-variable" } { include: "#literal-module" } { include: "#literal-class" } { include: "#literal-constructor" } { include: "#literal-method-call" } { include: "#literal-function-call" } { include: "#comments" } { include: "#brackets" } { include: "#literal-operators" } { include: "#literal-variable" } { include: "#literal-comma" } ] "ignore-long-lines": comment: "so set at arbitary 1000 chars to avoid parsing minified files" patterns: [ match: "^(?:).{1000,}" ] "literal-function-labels": patterns: [ { comment: "e.g. play: fn(arg1, arg2) { }" name: "meta.function.json.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(:)\\s*(\\bfn\\b)\\s*\\s*(?=\\()" end: "(?=\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "punctuation.separator.key-value.pf" "3": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. 'play': fn(arg1, arg2) { }" name: "meta.function.json.pf" begin: "\\s*((')(\\b[_a-zA-Z][\\w]*)(\\g2))\\s*(:)\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.begin.pf" "3": name: "entity.name.function.pf" "4": name: "punctuation.definition.string.end.pf" "5": name: "punctuation.separator.key-value.pf" "6": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-keywords": patterns: [ { name: "keyword.control.conditional.pf" match: "\\s*(?<!\\.)\\b(if|else)\\b" } { name: "keyword.control.loop.pf" match: "\\s*(?<!\\.)\\b(break|continue|do|while)\\b" } ] "literal-for": patterns: [ { name: "meta.for.pf" match: "\\s*(?<!\\.)\\b(for)\\b" captures: "1": name: "keyword.control.loop.pf" patterns: [ { begin: "\\s*\\(" end: "\\s*(?=\\))" beginCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#expression" } { include: "#literal-punctuation" } ] } ] } ] "literal-switch": patterns: [ { name: "meta.switch.pf" begin: "\\s*(?<!\\.)\\b(switch)\\b" end: "\\s*\\}" beginCaptures: "1": name: "keyword.control.switch.pf" endCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { include: "#round-brackets" } { begin: "\\s*\\{" end: "\\s*(?=})" beginCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { begin: "\\s*(?<!\\.)\\b(case|default)\\b" end: "\\s*(?=:)" beginCaptures: "1": name: "keyword.control.switch.pf" patterns: [ { include: "#expression" } ] } { include: "$self" } ] } ] } ] brackets: patterns: [ { include: "#round-brackets" } { include: "#square-brackets" } { include: "#curly-brackets" } ] "round-brackets": patterns: [ { comment: "try to avoid ternary operators which have a '? some chars :'" name: "meta.group.braces.round" begin: "(^|:|;|=|(?<=:|;|=))\\s*(\\((?=((\"|').*?(?<=[^\\\\])\\k<-1>|[^?:])*(:|\\?\\s*:)))" end: "\\s*\\)" beginCaptures: "2": name: "meta.brace.round.pf" endCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#flowtype-typecast" } { include: "#expression" } ] } { name: "meta.group.braces.round" begin: "\\s*\\(" end: "\\s*\\)" endCaptures: "0": name: "meta.brace.round.pf" beginCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#expression" } ] } ] "square-brackets": patterns: [ { name: "meta.group.braces.square" begin: "\\s*\\[" end: "\\s*\\]" endCaptures: "0": name: "meta.brace.square.pf" beginCaptures: "0": name: "meta.brace.square.pf" patterns: [ { include: "#expression" } ] } ] "curly-brackets": patterns: [ { name: "meta.group.braces.curly" begin: "\\s*\\{" end: "\\s*\\}" endCaptures: "0": name: "meta.brace.curly.pf" beginCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { include: "$self" } ] } ] jsdoc: patterns: [ { comment: "common doc @ keywords" match: "(?<!\\w)@(abstract|alias|author|class|constructor|deprecated|enum|event|example|extends|fires|ignore|inheritdoc|member|method|param|private|property|protected|readonly|requires|return|since|static|throws|type|var)\\b" name: "storage.type.class.doc" } { comment: "additional jsdoc keywords" match: "(?<!\\w)@(access|also|arg|arguments|augments|borrows|callback|classdesc|constant|const|constructs|copyright|default|defaultvalue|desc|description|emits|exception|exports|external|file|fileoverview|function|func|global|host|implements|inner|instance|interface|kind|lends|license|listens|memberof|mixes|mixin|module|name|namsepace|overview|prop|public|returns|see|summary|this|todo|tutorial|typedef|undocumented|variation|version|virtual)\\b" name: "storage.type.class.jsdoc" } { comment: "additional jsduck keywords" match: "(?<!\\w)@(accessor|alternateClassName|aside|cfg|chainable|docauthor|evented|experimental|ftype|hide|inheritable|localdoc|markdown|mixins|new|override|preventable|ptype|removed|scss mixin|singleton|template|uses|xtype)\\b" name: "storage.type.class.jsduck" } ] comments: patterns: [ { include: "#special-comments-conditional-compilation" } { name: "comment.block.documentation.pf" begin: "\\s*/\\*\\*(?!/)" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" patterns: [ { include: "#jsdoc" } ] } { name: "comment.block.pf" begin: "\\s*/\\*" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" } { name: "comment.block.html.pf" match: "\\s*(<!--|-->)" captures: "0": name: "punctuation.definition.comment.pf" } { name: "comment.line.double-slash.pf" begin: "\\s*(//)" end: "\\s*$" beginCaptures: "1": name: "punctuation.definition.comment.pf" } { name: "comment.line.shebang.pf" match: "^(#!).*$\\n?" captures: "1": name: "punctuation.definition.comment.pf" } ] "special-comments-conditional-compilation": patterns: [ { name: "comment.block.conditional.pf" begin: "\\s*/\\*(?=@)" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" endCaptures: "1": name: "keyword.control.conditional.pf" "2": name: "punctuation.definition.keyword.pf" patterns: [ { name: "punctuation.definition.comment.pf" match: "\\s*/\\*" } { include: "$self" } ] } { name: "keyword.control.conditional.pf" match: "\\s*(?!@)(@)(if|elif|else|end|ifdef|endif|cc_on|set)\\b" captures: "1": name: "punctuation.definition.keyword.pf" } { name: "variable.other.conditional.pf" match: "\\s*(?!@)(@)(_win32|_win16|_mac|_alpha|_x86|_mc680x0|_PowerPC|_jscript|_jscript_build|_jscript_version|_debug|_fast|[a-zA-Z]\\w+)" captures: "1": name: "punctuation.definition.variable.pf" } ] "literal-punctuation": patterns: [ { include: "#literal-semi-colon" } { include: "#literal-comma" } ] "literal-semi-colon": patterns: [ { name: "punctuation.terminator.statement.pf" match: "\\s*\\;" } ] "literal-comma": patterns: [ { name: "meta.delimiter.comma.pf" match: "\\s*," } ] "literal-function": patterns: [ { comment: "e.g. fn (arg1, arg2) { }" name: "meta.function.pf" begin: "\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\s*\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. play = fn(arg1, arg2) { }" name: "meta.function.pf" begin: "\\s*(\\b[_a-zA-Z][\\w]*)\\s*(=)\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\s*\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "keyword.operator.assignment.pf" "3": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-quasi": patterns: [ { name: "string.quasi.pf" begin: "\\s*([a-zA-Z$_][\\w$_]*)?(`)" end: "\\s*(?<!\\\\)`" beginCaptures: "1": name: "entity.quasi.tag.name.pf" "2": name: "punctuation.definition.quasi.begin.pf" endCaptures: "0": name: "punctuation.definition.quasi.end.pf" patterns: [ { name: "entity.quasi.element.pf" begin: "(?<!\\\\)\\${" end: "\\s*}" beginCaptures: "0": name: "punctuation.quasi.element.begin.pf" endCaptures: "0": name: "punctuation.quasi.element.end.pf" patterns: [ { include: "#expression" } ] } { include: "#string-content" } ] } ] "literal-operators": patterns: [ { name: "keyword.operator.pf" match: "\\s*(?<!\\.)\\b(delete|in|instanceof|new|of|typeof|void|with)\\b" } { name: "keyword.operator.logical.pf" match: "\\s*(!(?!=)|&&|\\|\\|)" } { name: "keyword.operator.assignment.pf" match: "\\s*(=(?!=))" } { name: "keyword.operator.assignment.augmented.pf" match: "\\s*(%=|&=|\\*=|\\+=|-=|/=|\\^=|\\|=|<<=|>>=|>>>=)" } { name: "keyword.operator.bitwise.pf" match: "\\s*(~|<<|>>>|>>|&|\\^|\\|)" } { name: "keyword.operator.relational.pf" match: "\\s*(<=|>=|<|>)" } { name: "keyword.operator.comparison.pf" match: "\\s*(==|!=)" } { name: "keyword.operator.arithmetic.pf" match: "\\s*(--|\\+\\+|/(?!/|\\*)|%|\\*(?<!/\\*)|\\+|-)" } { comment: "ternary operator" begin: "\\s*(\\?)" end: "\\s*(:)" beginCaptures: "1": name: "keyword.operator.ternary.pf" endCaptures: "1": name: "keyword.operator.ternary.pf" patterns: [ { include: "#expression" } ] } { name: "keyword.operator.spread.pf" match: "\\s*(?<!\\.)\\.\\.\\." } { name: "keyword.operator.accessor.pf" match: "\\." } ] "literal-function-call": comment: "maybe in array form e.g. foo[bar]()" patterns: [ { name: "meta.function-call.without-arguments.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(?=\\(\\s*\\))" end: "\\s*(?<=\\))" beginCaptures: "1": name: "entity.name.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.without-arguments.pf" begin: "\\s*(?=(\\[(?:(?>[^\\[\\]]+)|\\g<-1>)*\\])\\s*\\(\\s*\\))" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.with-arguments.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(?=\\()" end: "(?=.)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.without-arguments.pf" begin: "\\s*(?=(\\[(?:(?>[^\\[\\]]+)|\\g<-1>)*\\])\\s*\\()" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-language-constant": patterns: [ { name: "constant.language.boolean.true.pf" match: "\\s*(?<!\\.)\\btrue\\b" } { name: "constant.language.boolean.false.pf" match: "\\s*(?<!\\.)\\bfalse\\b" } { name: "constant.language.null.pf" match: "\\s*(?<!\\.)\\bnull\\b" } ] support: patterns: [ { name: "support.class.builtin.pf" match: "\\s*\\b(Array|ArrayBuffer|Boolean|DataView|Date|Float(32|64)Array|Int(8|16|32)Array|Function|GeneratorFunction|Map|Math|Number|Object|Promise|Proxy|RegExp|Set|String|Uint(8|16|32)Array|Uint8ClampedArray|WeakMap|WeakSet)\\b" } { name: "support.function.pf" match: "\\s*(?<!\\.)\\b(decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|eval|isFinite|isNaN|parseFloat|parseInt|unescape)\\b" } { name: "support.function.mutator.pf" match: "(?<=\\.)(shift|sort|splice|unshift|pop|push|reverse)\\b" } { name: "support.class.error.pf" match: "\\s*(?<!\\.)\\b((Eval|Range|Reference|Syntax|Type|URI)?Error)\\b" } { name: "keyword.other.pf" match: "\\s*(?<!\\.)\\b(debugger)\\b" } { name: "support.type.object.dom.pf" match: "\\s*(?<!\\.)\\b(document|window)\\b" } { name: "support.constant.dom.pf" match: "\\s*\\b(ELEMENT_NODE|ATTRIBUTE_NODE|TEXT_NODE|CDATA_SECTION_NODE|ENTITY_REFERENCE_NODE|ENTITY_NODE|PROCESSING_INSTRUCTION_NODE|COMMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE|DOCUMENT_FRAGMENT_NODE|NOTATION_NODE|INDEX_SIZE_ERR|DOMSTRING_SIZE_ERR|HIERARCHY_REQUEST_ERR|WRONG_DOCUMENT_ERR|INVALID_CHARACTER_ERR|NO_DATA_ALLOWED_ERR|NO_MODIFICATION_ALLOWED_ERR|NOT_FOUND_ERR|NOT_SUPPORTED_ERR|INUSE_ATTRIBUTE_ERR)\\b" } { match: "\\s*(?<!\\.)\\b(console)(?:(\\.)(warn|info|log|error|time|timeEnd|assert))?\\b" captures: "1": name: "support.type.object.console.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.function.console.pf" } { name: "support.module.node.pf" match: "\\s*(?<!\\.)\\b(natives|buffer|child_process|cluster|crypto|dgram|dns|fs|http|https|net|os|path|punycode|string|string_decoder|readline|repl|tls|tty|util|vm|zlib)\\b" } { match: "\\s*(?<!\\.)\\b(process)(?:(\\.)(stdout|stderr|stdin|argv|execPath|execArgv|env|exitCode|version|versions|config|pid|title|arch|platform|mainModule))?\\b" captures: "1": name: "support.type.object.process.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.type.object.process.pf" } { match: "\\s*(?<!\\.)\\b(process)(?:(\\.)(abort|chdir|cwd|exit|getgid|setgid|getuid|setuid|setgroups|getgroups|initgroups|kill|memoryUsage|nextTick|umask|uptime|hrtime))?\\b" captures: "1": name: "support.type.object.process.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.function.process.pf" } { match: "\\s*\\b(((?<!\\.)module\\.((?<!\\,)exports|id|require|parent|filename|loaded|children)|exports))\\b" captures: "1": name: "support.type.object.module.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.type.object.module.pf" } { name: "support.type.object.node.pf" match: "\\s*(?<!\\.)\\b(global|GLOBAL|root|__dirname|__filename)\\b" } { name: "support.class.node.pf" match: "\\s*\\b(Buffer|EventEmitter|Server|Pipe|Socket|REPLServer|ReadStream|WriteStream|Stream|Inflate|Deflate|InflateRaw|DeflateRaw|GZip|GUnzip|Unzip|Zip)\\b" } { name: "meta.tag.mustache.pf" begin: "\\s*{{" end: "\\s*}}" } ] "literal-class": patterns: [ { comment: "Classes" begin: "\\s*(?<!\\.)\\b(class)\\s+" end: "\\s*(})" beginCaptures: "0": name: "meta.class.pf" "1": name: "storage.type.class.pf" endCaptures: "1": name: "punctuation.section.class.end.pf" patterns: [ { match: "\\s*\\b(extends)\\b\\s*" captures: "0": name: "meta.class.extends.pf" "1": name: "storage.type.extends.pf" } { include: "#flowtype-class-name" } { include: "#flowtype-polymorphs" } { begin: "\\s*{" end: "\\s*(?=})" contentName: "meta.class.body.pf" beginCaptures: "0": name: "punctuation.section.class.begin.pf" patterns: [ { match: "\\s*\\b(?<!\\.)static\\b(?!\\.)" name: "storage.modifier.pf" } { include: "#literal-method" } { include: "#brackets" } { include: "#es7-decorators" } { include: "#comments" } { include: "#flowtype-variable" } { include: "#literal-semi-colon" } ] } { include: "#expression" } ] } ] "literal-method-call": patterns: [ { name: "meta.function-call.static.without-arguments.pf" comment: "e.g Abc.aaa()" match: "\\s*(?:(?<=\\.)|\\b)([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)\\s*(\\(\\s*\\))" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "entity.name.function.pf" "4": name: "meta.group.braces.round.function.arguments.pf" } { name: "meta.function-call.static.with-arguments.pf" match: "\\s*(?:(?<=\\.)|\\b)\\s*([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)\\s*(?=\\()" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "entity.name.function.pf" } { name: "meta.function-call.method.without-arguments.pf" match: "\\s*(?<=\\.)\\s*([_a-zA-Z][\\w]*)\\s*(\\(\\s*\\))" captures: "1": name: "entity.name.function.pf" "2": name: "meta.group.braces.round.function.arguments.pf" } { name: "meta.function-call.method.with-arguments.pf" match: "\\s*(?<=\\.)([_a-zA-Z][\\w]*)\\s*(?=\\()" captures: "1": name: "entity.name.function.pf" } ] "literal-language-variable": patterns: [ { name: "variable.language.arguments.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(arguments)\\b" } { name: "variable.language.super.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(super)\\b\\s*(?!\\()" } { name: "variable.language.this.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(this)\\b" } { name: "variable.language.self.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(self)\\b\\s*(?!\\()" } { name: "variable.language.proto.pf" match: "\\s*(?<=\\.)\\b(__proto__)\\b" } { name: "variable.language.constructor.pf" match: "\\s*(?<=\\.)\\b(constructor)\\b\\s*(?!\\()" } { name: "variable.language.prototype.pf" match: "\\s*(?<=\\.)\\b(prototype)\\b" } ] "string-content": patterns: [ { name: "constant.character.escape.newline.pf" match: "\\\\\\s*\\n" } { name: "constant.character.escape" match: "\\\\['|\"|\\\\|n|r|t|b|f|v|0]" } { name: "constant.character.escape" match: "\\\\u((\\{[0-9a-fA-F]+\\})|[0-9a-fA-F]{4})" } { name: "constant.character.escape" match: "\\\\x[0-9a-fA-F]{2}" } ] "literal-number": patterns: [ { match: "\\s*((?i)(?:\\B[-+]|\\b)0x[0-9a-f]*\\.(\\B|\\b[0-9]+))" captures: "1": name: "invalid.illegal.numeric.hex.pf" } { match: "\\s*((?:\\B[-+]|\\b)0[0-9]+\\.(\\B|\\b[0-9]+))" captures: "1": name: "invalid.illegal.numeric.octal.pf" } { match: "\\s*((?:\\B[-+])?(?:\\b0b[0-1]*|\\b0o[0-7]*|\\b0x[0-9a-f]*|(\\B\\.[0-9]+|\\b[0-9]+(\\.[0-9]*)?)(e[-+]?[0-9]+)?))" captures: "1": name: "constant.numeric.pf" } { match: "\\s*((?:\\B[-+]|\\b)(Infinity)\\b)" captures: "1": name: "constant.language.infinity.pf" } ] "literal-constructor": patterns: [ { disabled: 1 name: "meta.instance.constructor" begin: "\\s*(new)\\s+(?=[_$a-zA-Z][$\\w.]*)" end: "(?![_$a-zA-Z][$\\w.]*)" beginCaptures: "1": name: "keyword.operator.new.pf" patterns: [ { include: "#support" } { match: "([_$a-zA-Z][$\\w.]*\\.)?([_a-zA-Z][\\w]*)" captures: "2": name: "entity.name.type.new.pf" } ] } ] "literal-arrow-function": patterns: [ { comment: "e.g. (args) => { }" name: "meta.function.arrow.pf" begin: "\\s*(\\basync\\b)?\\s*(?=(<(?:(?>[^<>]+)|\\g<-1>)*>)?\\s*(\\((?:(?>[^()]+)|\\g<-1>)*\\))\\s*(?:\\s*(:|\\|)(\\s*[$_a-zA-Z0-9]+(<(?:(?>[^<>]+)|\\g<-1>)*>)?|\\s*(\\{(?:(?>[^{}]+)|\\g<-1>)*\\})|\\s*(((')((?:[^']|\\\\')*)('))|\\s*((\")((?:[^\"]|\\\\\")*)(\")))|\\s*[x0-9A-Fa-f]+))*\\s*=>)" end: "\\s*(=>)" applyEndPatternLast: 1 endCaptures: "1": name: "storage.type.function.arrow.pf" beginCaptures: "1": name: "storage.type.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. play = (args) => { }" name: "meta.function.arrow.pf" begin: "\\s*(\\b[_a-zA-Z][\\w]*)\\s*(=)\\s*(?=(<(?:(?>[^<>]+)|\\g<-1>)*>)?\\s*(\\((?:(?>[^()]+)|\\g<-1>)*\\))\\s*(?:\\s*(:|\\|)(\\s*[$_a-zA-Z0-9]+(<(?:(?>[^<>]+)|\\g<-1>)*>)?|\\s*(\\{(?:(?>[^{}]+)|\\g<-1>)*\\})|\\s*(((')((?:[^']|\\\\')*)('))|\\s*((\")((?:[^\"]|\\\\\")*)(\")))|\\s*[x0-9A-Fa-f]+))*\\s*=>)" end: "\\s*(=>)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "keyword.operator.assignment.pf" "3": name: "storage.type.pf" endCaptures: "1": name: "storage.type.function.arrow.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-regexp": patterns: [ { name: "string.regexp.pf" begin: "(?<=\\.|\\(|,|{|}|\\[|;|,|<|>|<=|>=|==|!=|===|!==|\\+|-|\\*|%|\\+\\+|--|<<|>>|>>>|&|\\||\\^|!|~|&&|\\|\\||\\?|:|=|\\+=|-=|\\*=|%=|<<=|>>=|>>>=|&=|\\|=|\\^=|/|/=|\\Wnew|\\Wdelete|\\Wvoid|\\Wtypeof|\\Winstanceof|\\Win|\\Wdo|\\Wreturn|\\Wcase|\\Wthrow|^new|^delete|^void|^typeof|^instanceof|^in|^do|^return|^case|^throw|^)\\s*(/)(?!/|\\*|$)" end: "(/)([gimy]*)" beginCaptures: "1": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "punctuation.definition.string.end.pf" "2": name: "keyword.other.pf" patterns: [ { include: "source.regexp.babel" } ] } ] "literal-string": patterns: [ { contentName: "string.quoted.single.pf" begin: "\\s*(('))" end: "(('))|(\\n)" beginCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.end.pf" "3": name: "invalid.illegal.newline.pf" patterns: [ { include: "#string-content" } ] } { contentName: "string.quoted.double.pf" begin: "\\s*((\"))" end: "((\"))|(\\n)" beginCaptures: "1": name: "string.quoted.double.pf" "2": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "string.quoted.double.pf" "2": name: "punctuation.definition.string.end.pf" "3": name: "invalid.illegal.newline.pf" patterns: [ { include: "#string-content" } ] } ] "literal-module": patterns: [ { name: "keyword.control.module.pf" match: "\\s*(?<!\\.)\\b(import|export|default)\\b" } { name: "keyword.control.module.reference.pf" match: "\\s*(?<!\\.)\\b(from|as)\\b" } ] "literal-variable": patterns: [ { comment: "e.g. CONSTANT" name: "variable.other.constant.pf" match: "\\s*[A-Z][_$\\dA-Z]*\\b" } { comment: "e.g. Class.property" name: "meta.property.class.pf" match: "\\s*\\b([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "variable.other.property.static.pf" } { comment: "e.g. obj.property" name: "variable.other.object.pf" match: "\\s*(?<!\\.)[_a-zA-Z][\\w]*\\s*(?=[\\[\\.])" captures: "1": name: "variable.other.object.pf" } { comment: "e.g. obj.property" name: "meta.property.object.pf" match: "\\s*(?<=\\.)\\s*[_a-zA-Z][\\w]*" captures: "0": name: "variable.other.property.pf" } { name: "variable.other.readwrite.pf" match: "\\s*[_a-zA-Z][\\w]*" } ] jsx: comment: "Avoid < operator expressions as best we can using Zertosh's regex" patterns: [ { begin: "(?<=\\(|\\{|\\[|,|&&|\\|\\||\\?|:|=|=>|\\Wreturn|^return|^)\\s*(?=<[_$a-zA-Z])" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#jsx-tag-element-name" } ] } ] "jsx-tag-element-name": patterns: [ { comment: "Tags that end > are trapped in #jsx-tag-termination" name: "meta.tag.pfx" begin: "\\s*(<)([$_\\p{L}](?:[$.:\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}-](?<!\\.\\.))*+)(?=[/>\\s])(?<![\\.:])" end: "\\s*(?<=</)(\\2)(>)|(/>)|((?<=</)[\\S ]*?)>" beginCaptures: "1": name: "punctuation.definition.tag.pfx" "2": name: "entity.name.tag.open.pfx" endCaptures: "1": name: "entity.name.tag.close.pfx" "2": name: "punctuation.definition.tag.pfx" "3": name: "punctuation.definition.tag.pfx" "4": name: "invalid.illegal.termination.pfx" patterns: [ { include: "#jsx-tag-termination" } { include: "#jsx-tag-attributes" } ] } ] "jsx-tag-termination": patterns: [ { comment: "uses non consuming search for </ in </tag>" begin: "(>)" end: "(</)" beginCaptures: "0": name: "punctuation.definition.tag.pfx" "1": name: "JSXStartTagEnd" endCaptures: "0": name: "punctuation.definition.tag.pfx" "1": name: "JSXEndTagStart" patterns: [ { include: "#jsx-evaluated-code" } { include: "#jsx-entities" } { include: "#jsx-tag-element-name" } ] } ] "jsx-tag-attributes": patterns: [ { include: "#jsx-attribute-name" } { include: "#jsx-assignment" } { include: "#jsx-string-double-quoted" } { include: "#jsx-string-single-quoted" } { include: "#jsx-evaluated-code" } { include: "#jsx-tag-element-name" } { include: "#comments" } ] "jsx-spread-attribute": patterns: [ { comment: "Spread attribute { ... AssignmentExpression }" match: "(?<!\\.)\\.\\.\\." name: "keyword.operator.spread.pfx" } ] "jsx-attribute-name": patterns: [ { comment: "look for attribute name" match: "(?<!\\S)([$_\\p{L}](?:[$.\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}-](?<!\\.\\.))*+)(?<!\\.)(?=//|/\\*|=|\\s|>|/>)" captures: "0": name: "entity.other.attribute-name.pfx" } ] "jsx-assignment": patterns: [ { comment: "look for attribute assignment" name: "keyword.operator.assignment.pfx" match: "=(?=\\s*(?:'|\"|{|/\\*|<|//|\\n))" } ] "jsx-string-double-quoted": name: "string.quoted.double.pf" begin: "\"" end: "\"(?<!\\\\\")" beginCaptures: "0": name: "punctuation.definition.string.begin.pfx" endCaptures: "0": name: "punctuation.definition.string.end.pfx" patterns: [ { include: "#jsx-entities" } ] "jsx-string-single-quoted": name: "string.quoted.single.pf" begin: "'" end: "'(?<!\\\\')" beginCaptures: "0": name: "punctuation.definition.string.begin.pfx" endCaptures: "0": name: "punctuation.definition.string.end.pfx" patterns: [ { include: "#jsx-entities" } ] "jsx-evaluated-code": name: "meta.embedded.expression.pf" begin: "{" end: "}" beginCaptures: "0": name: "punctuation.section.embedded.begin.pfx" endCaptures: "0": name: "punctuation.section.embedded.end.pfx" contentName: "source.pf.pfx" patterns: [ { include: "#jsx-string-double-quoted" } { include: "#jsx-string-single-quoted" } { include: "#jsx-spread-attribute" } { include: "#expression" } ] "jsx-entities": patterns: [ { comment: "Embeded HTML entities &blah" match: "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)" captures: "0": name: "constant.character.entity.pfx" "1": name: "punctuation.definition.entity.pfx" "2": name: "entity.name.tag.html.pfx" "3": name: "punctuation.definition.entity.pfx" } { comment: "Entity with & and invalid name" match: "&\\S*;" name: "invalid.illegal.bad-ampersand.pfx" } ] "flowtype-variable": patterns: [ { comment: "name of variable spread var with flowtype :" match: "\\s*((?<!\\.)\\.\\.\\.)?([$_\\p{L}](?:[$.\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}])*+)\\s*(\\??)\\s*(?=:|=>)" captures: "1": name: "keyword.operator.spread.pf" "2": name: "variable.other.readwrite.pf" "3": name: "keyword.operator.optional.parameter.flowtype" } { include: "#flowtype-vars-and-props" } ] "flowtype-vars-and-props": patterns: [ { comment: "flowtype optional arg/parameter e.g. protocol? : string" name: "punctuation.type.flowtype" match: "\\?(?=\\s*:)" } { comment: "typed entity :" begin: "\\s*(:)" end: "(?=.)" applyEndPatternLast: 1 beginCaptures: "1": name: "punctuation.type.flowtype" patterns: [ { include: "#flowtype-parse-types" } ] } { include: "#literal-comma" } { comment: "An Iterator prefix?" match: "\\s*@@" } { match: "\\s*(=>)" captures: "1": name: "storage.type.function.arrow.pf" } { include: "#flowtype-bracketed-parameters" } { include: "#flowtype-parse-array" } { include: "#expression" } ] "flowtype-bracketed-parameters": patterns: [ { comment: "Get parameters within a function/method call" begin: "\\s*(\\()" end: "\\s*(\\))" beginCaptures: "1": name: "punctuation.definition.parameters.begin.pf" endCaptures: "1": name: "punctuation.definition.parameters.end.pf" patterns: [ { include: "#flowtype-variable" } ] } ]
217441
name: "<NAME>unk" scopeName: "source.pf" foldingStartMarker: "(/\\*|\\{|\\()" foldingEndMarker: "(\\*/|\\}|\\))" firstLineMatch: "^#!\\s*/.*\\b(node|js)$\\n?" fileTypes: [ "pf" ] patterns: [ { include: "#core" } ] repository: core: patterns: [ { include: "#ignore-long-lines" } { include: "#literal-labels" } { include: "#literal-keywords" } { include: "#literal-for" } { include: "#literal-switch" } { include: "#expression" } { include: "#literal-punctuation" } ] expression: patterns: [ { include: "#ignore-long-lines" } { include: "#jsx" } { include: "#support" } { include: "#literal-function" } { include: "#literal-arrow-function" } { include: "#literal-regexp" comment: "before operators to avoid abiguities" } { include: "#literal-number" } { include: "#literal-quasi" } { include: "#literal-string" } { include: "#literal-language-constant" } { include: "#literal-language-variable" } { include: "#literal-module" } { include: "#literal-class" } { include: "#literal-constructor" } { include: "#literal-method-call" } { include: "#literal-function-call" } { include: "#comments" } { include: "#brackets" } { include: "#literal-operators" } { include: "#literal-variable" } { include: "#literal-comma" } ] "ignore-long-lines": comment: "so set at arbitary 1000 chars to avoid parsing minified files" patterns: [ match: "^(?:).{1000,}" ] "literal-function-labels": patterns: [ { comment: "e.g. play: fn(arg1, arg2) { }" name: "meta.function.json.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(:)\\s*(\\bfn\\b)\\s*\\s*(?=\\()" end: "(?=\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "punctuation.separator.key-value.pf" "3": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. 'play': fn(arg1, arg2) { }" name: "meta.function.json.pf" begin: "\\s*((')(\\b[_a-zA-Z][\\w]*)(\\g2))\\s*(:)\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.begin.pf" "3": name: "entity.name.function.pf" "4": name: "punctuation.definition.string.end.pf" "5": name: "punctuation.separator.key-value.pf" "6": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-keywords": patterns: [ { name: "keyword.control.conditional.pf" match: "\\s*(?<!\\.)\\b(if|else)\\b" } { name: "keyword.control.loop.pf" match: "\\s*(?<!\\.)\\b(break|continue|do|while)\\b" } ] "literal-for": patterns: [ { name: "meta.for.pf" match: "\\s*(?<!\\.)\\b(for)\\b" captures: "1": name: "keyword.control.loop.pf" patterns: [ { begin: "\\s*\\(" end: "\\s*(?=\\))" beginCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#expression" } { include: "#literal-punctuation" } ] } ] } ] "literal-switch": patterns: [ { name: "meta.switch.pf" begin: "\\s*(?<!\\.)\\b(switch)\\b" end: "\\s*\\}" beginCaptures: "1": name: "keyword.control.switch.pf" endCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { include: "#round-brackets" } { begin: "\\s*\\{" end: "\\s*(?=})" beginCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { begin: "\\s*(?<!\\.)\\b(case|default)\\b" end: "\\s*(?=:)" beginCaptures: "1": name: "keyword.control.switch.pf" patterns: [ { include: "#expression" } ] } { include: "$self" } ] } ] } ] brackets: patterns: [ { include: "#round-brackets" } { include: "#square-brackets" } { include: "#curly-brackets" } ] "round-brackets": patterns: [ { comment: "try to avoid ternary operators which have a '? some chars :'" name: "meta.group.braces.round" begin: "(^|:|;|=|(?<=:|;|=))\\s*(\\((?=((\"|').*?(?<=[^\\\\])\\k<-1>|[^?:])*(:|\\?\\s*:)))" end: "\\s*\\)" beginCaptures: "2": name: "meta.brace.round.pf" endCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#flowtype-typecast" } { include: "#expression" } ] } { name: "meta.group.braces.round" begin: "\\s*\\(" end: "\\s*\\)" endCaptures: "0": name: "meta.brace.round.pf" beginCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#expression" } ] } ] "square-brackets": patterns: [ { name: "meta.group.braces.square" begin: "\\s*\\[" end: "\\s*\\]" endCaptures: "0": name: "meta.brace.square.pf" beginCaptures: "0": name: "meta.brace.square.pf" patterns: [ { include: "#expression" } ] } ] "curly-brackets": patterns: [ { name: "meta.group.braces.curly" begin: "\\s*\\{" end: "\\s*\\}" endCaptures: "0": name: "meta.brace.curly.pf" beginCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { include: "$self" } ] } ] jsdoc: patterns: [ { comment: "common doc @ keywords" match: "(?<!\\w)@(abstract|alias|author|class|constructor|deprecated|enum|event|example|extends|fires|ignore|inheritdoc|member|method|param|private|property|protected|readonly|requires|return|since|static|throws|type|var)\\b" name: "storage.type.class.doc" } { comment: "additional jsdoc keywords" match: "(?<!\\w)@(access|also|arg|arguments|augments|borrows|callback|classdesc|constant|const|constructs|copyright|default|defaultvalue|desc|description|emits|exception|exports|external|file|fileoverview|function|func|global|host|implements|inner|instance|interface|kind|lends|license|listens|memberof|mixes|mixin|module|name|namsepace|overview|prop|public|returns|see|summary|this|todo|tutorial|typedef|undocumented|variation|version|virtual)\\b" name: "storage.type.class.jsdoc" } { comment: "additional jsduck keywords" match: "(?<!\\w)@(accessor|alternateClassName|aside|cfg|chainable|docauthor|evented|experimental|ftype|hide|inheritable|localdoc|markdown|mixins|new|override|preventable|ptype|removed|scss mixin|singleton|template|uses|xtype)\\b" name: "storage.type.class.jsduck" } ] comments: patterns: [ { include: "#special-comments-conditional-compilation" } { name: "comment.block.documentation.pf" begin: "\\s*/\\*\\*(?!/)" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" patterns: [ { include: "#jsdoc" } ] } { name: "comment.block.pf" begin: "\\s*/\\*" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" } { name: "comment.block.html.pf" match: "\\s*(<!--|-->)" captures: "0": name: "punctuation.definition.comment.pf" } { name: "comment.line.double-slash.pf" begin: "\\s*(//)" end: "\\s*$" beginCaptures: "1": name: "punctuation.definition.comment.pf" } { name: "comment.line.shebang.pf" match: "^(#!).*$\\n?" captures: "1": name: "punctuation.definition.comment.pf" } ] "special-comments-conditional-compilation": patterns: [ { name: "comment.block.conditional.pf" begin: "\\s*/\\*(?=@)" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" endCaptures: "1": name: "keyword.control.conditional.pf" "2": name: "punctuation.definition.keyword.pf" patterns: [ { name: "punctuation.definition.comment.pf" match: "\\s*/\\*" } { include: "$self" } ] } { name: "keyword.control.conditional.pf" match: "\\s*(?!@)(@)(if|elif|else|end|ifdef|endif|cc_on|set)\\b" captures: "1": name: "punctuation.definition.keyword.pf" } { name: "variable.other.conditional.pf" match: "\\s*(?!@)(@)(_win32|_win16|_mac|_alpha|_x86|_mc680x0|_PowerPC|_jscript|_jscript_build|_jscript_version|_debug|_fast|[a-zA-Z]\\w+)" captures: "1": name: "punctuation.definition.variable.pf" } ] "literal-punctuation": patterns: [ { include: "#literal-semi-colon" } { include: "#literal-comma" } ] "literal-semi-colon": patterns: [ { name: "punctuation.terminator.statement.pf" match: "\\s*\\;" } ] "literal-comma": patterns: [ { name: "meta.delimiter.comma.pf" match: "\\s*," } ] "literal-function": patterns: [ { comment: "e.g. fn (arg1, arg2) { }" name: "meta.function.pf" begin: "\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\s*\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. play = fn(arg1, arg2) { }" name: "meta.function.pf" begin: "\\s*(\\b[_a-zA-Z][\\w]*)\\s*(=)\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\s*\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "keyword.operator.assignment.pf" "3": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-quasi": patterns: [ { name: "string.quasi.pf" begin: "\\s*([a-zA-Z$_][\\w$_]*)?(`)" end: "\\s*(?<!\\\\)`" beginCaptures: "1": name: "entity.quasi.tag.name.pf" "2": name: "punctuation.definition.quasi.begin.pf" endCaptures: "0": name: "punctuation.definition.quasi.end.pf" patterns: [ { name: "entity.quasi.element.pf" begin: "(?<!\\\\)\\${" end: "\\s*}" beginCaptures: "0": name: "punctuation.quasi.element.begin.pf" endCaptures: "0": name: "punctuation.quasi.element.end.pf" patterns: [ { include: "#expression" } ] } { include: "#string-content" } ] } ] "literal-operators": patterns: [ { name: "keyword.operator.pf" match: "\\s*(?<!\\.)\\b(delete|in|instanceof|new|of|typeof|void|with)\\b" } { name: "keyword.operator.logical.pf" match: "\\s*(!(?!=)|&&|\\|\\|)" } { name: "keyword.operator.assignment.pf" match: "\\s*(=(?!=))" } { name: "keyword.operator.assignment.augmented.pf" match: "\\s*(%=|&=|\\*=|\\+=|-=|/=|\\^=|\\|=|<<=|>>=|>>>=)" } { name: "keyword.operator.bitwise.pf" match: "\\s*(~|<<|>>>|>>|&|\\^|\\|)" } { name: "keyword.operator.relational.pf" match: "\\s*(<=|>=|<|>)" } { name: "keyword.operator.comparison.pf" match: "\\s*(==|!=)" } { name: "keyword.operator.arithmetic.pf" match: "\\s*(--|\\+\\+|/(?!/|\\*)|%|\\*(?<!/\\*)|\\+|-)" } { comment: "ternary operator" begin: "\\s*(\\?)" end: "\\s*(:)" beginCaptures: "1": name: "keyword.operator.ternary.pf" endCaptures: "1": name: "keyword.operator.ternary.pf" patterns: [ { include: "#expression" } ] } { name: "keyword.operator.spread.pf" match: "\\s*(?<!\\.)\\.\\.\\." } { name: "keyword.operator.accessor.pf" match: "\\." } ] "literal-function-call": comment: "maybe in array form e.g. foo[bar]()" patterns: [ { name: "meta.function-call.without-arguments.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(?=\\(\\s*\\))" end: "\\s*(?<=\\))" beginCaptures: "1": name: "entity.name.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.without-arguments.pf" begin: "\\s*(?=(\\[(?:(?>[^\\[\\]]+)|\\g<-1>)*\\])\\s*\\(\\s*\\))" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.with-arguments.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(?=\\()" end: "(?=.)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.without-arguments.pf" begin: "\\s*(?=(\\[(?:(?>[^\\[\\]]+)|\\g<-1>)*\\])\\s*\\()" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-language-constant": patterns: [ { name: "constant.language.boolean.true.pf" match: "\\s*(?<!\\.)\\btrue\\b" } { name: "constant.language.boolean.false.pf" match: "\\s*(?<!\\.)\\bfalse\\b" } { name: "constant.language.null.pf" match: "\\s*(?<!\\.)\\bnull\\b" } ] support: patterns: [ { name: "support.class.builtin.pf" match: "\\s*\\b(Array|ArrayBuffer|Boolean|DataView|Date|Float(32|64)Array|Int(8|16|32)Array|Function|GeneratorFunction|Map|Math|Number|Object|Promise|Proxy|RegExp|Set|String|Uint(8|16|32)Array|Uint8ClampedArray|WeakMap|WeakSet)\\b" } { name: "support.function.pf" match: "\\s*(?<!\\.)\\b(decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|eval|isFinite|isNaN|parseFloat|parseInt|unescape)\\b" } { name: "support.function.mutator.pf" match: "(?<=\\.)(shift|sort|splice|unshift|pop|push|reverse)\\b" } { name: "support.class.error.pf" match: "\\s*(?<!\\.)\\b((Eval|Range|Reference|Syntax|Type|URI)?Error)\\b" } { name: "keyword.other.pf" match: "\\s*(?<!\\.)\\b(debugger)\\b" } { name: "support.type.object.dom.pf" match: "\\s*(?<!\\.)\\b(document|window)\\b" } { name: "support.constant.dom.pf" match: "\\s*\\b(ELEMENT_NODE|ATTRIBUTE_NODE|TEXT_NODE|CDATA_SECTION_NODE|ENTITY_REFERENCE_NODE|ENTITY_NODE|PROCESSING_INSTRUCTION_NODE|COMMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE|DOCUMENT_FRAGMENT_NODE|NOTATION_NODE|INDEX_SIZE_ERR|DOMSTRING_SIZE_ERR|HIERARCHY_REQUEST_ERR|WRONG_DOCUMENT_ERR|INVALID_CHARACTER_ERR|NO_DATA_ALLOWED_ERR|NO_MODIFICATION_ALLOWED_ERR|NOT_FOUND_ERR|NOT_SUPPORTED_ERR|INUSE_ATTRIBUTE_ERR)\\b" } { match: "\\s*(?<!\\.)\\b(console)(?:(\\.)(warn|info|log|error|time|timeEnd|assert))?\\b" captures: "1": name: "support.type.object.console.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.function.console.pf" } { name: "support.module.node.pf" match: "\\s*(?<!\\.)\\b(natives|buffer|child_process|cluster|crypto|dgram|dns|fs|http|https|net|os|path|punycode|string|string_decoder|readline|repl|tls|tty|util|vm|zlib)\\b" } { match: "\\s*(?<!\\.)\\b(process)(?:(\\.)(stdout|stderr|stdin|argv|execPath|execArgv|env|exitCode|version|versions|config|pid|title|arch|platform|mainModule))?\\b" captures: "1": name: "support.type.object.process.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.type.object.process.pf" } { match: "\\s*(?<!\\.)\\b(process)(?:(\\.)(abort|chdir|cwd|exit|getgid|setgid|getuid|setuid|setgroups|getgroups|initgroups|kill|memoryUsage|nextTick|umask|uptime|hrtime))?\\b" captures: "1": name: "support.type.object.process.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.function.process.pf" } { match: "\\s*\\b(((?<!\\.)module\\.((?<!\\,)exports|id|require|parent|filename|loaded|children)|exports))\\b" captures: "1": name: "support.type.object.module.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.type.object.module.pf" } { name: "support.type.object.node.pf" match: "\\s*(?<!\\.)\\b(global|GLOBAL|root|__dirname|__filename)\\b" } { name: "support.class.node.pf" match: "\\s*\\b(Buffer|EventEmitter|Server|Pipe|Socket|REPLServer|ReadStream|WriteStream|Stream|Inflate|Deflate|InflateRaw|DeflateRaw|GZip|GUnzip|Unzip|Zip)\\b" } { name: "meta.tag.mustache.pf" begin: "\\s*{{" end: "\\s*}}" } ] "literal-class": patterns: [ { comment: "Classes" begin: "\\s*(?<!\\.)\\b(class)\\s+" end: "\\s*(})" beginCaptures: "0": name: "meta.class.pf" "1": name: "storage.type.class.pf" endCaptures: "1": name: "punctuation.section.class.end.pf" patterns: [ { match: "\\s*\\b(extends)\\b\\s*" captures: "0": name: "meta.class.extends.pf" "1": name: "storage.type.extends.pf" } { include: "#flowtype-class-name" } { include: "#flowtype-polymorphs" } { begin: "\\s*{" end: "\\s*(?=})" contentName: "meta.class.body.pf" beginCaptures: "0": name: "punctuation.section.class.begin.pf" patterns: [ { match: "\\s*\\b(?<!\\.)static\\b(?!\\.)" name: "storage.modifier.pf" } { include: "#literal-method" } { include: "#brackets" } { include: "#es7-decorators" } { include: "#comments" } { include: "#flowtype-variable" } { include: "#literal-semi-colon" } ] } { include: "#expression" } ] } ] "literal-method-call": patterns: [ { name: "meta.function-call.static.without-arguments.pf" comment: "e.g Abc.aaa()" match: "\\s*(?:(?<=\\.)|\\b)([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)\\s*(\\(\\s*\\))" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "entity.name.function.pf" "4": name: "meta.group.braces.round.function.arguments.pf" } { name: "meta.function-call.static.with-arguments.pf" match: "\\s*(?:(?<=\\.)|\\b)\\s*([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)\\s*(?=\\()" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "entity.name.function.pf" } { name: "meta.function-call.method.without-arguments.pf" match: "\\s*(?<=\\.)\\s*([_a-zA-Z][\\w]*)\\s*(\\(\\s*\\))" captures: "1": name: "entity.name.function.pf" "2": name: "meta.group.braces.round.function.arguments.pf" } { name: "meta.function-call.method.with-arguments.pf" match: "\\s*(?<=\\.)([_a-zA-Z][\\w]*)\\s*(?=\\()" captures: "1": name: "entity.name.function.pf" } ] "literal-language-variable": patterns: [ { name: "variable.language.arguments.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(arguments)\\b" } { name: "variable.language.super.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(super)\\b\\s*(?!\\()" } { name: "variable.language.this.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(this)\\b" } { name: "variable.language.self.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(self)\\b\\s*(?!\\()" } { name: "variable.language.proto.pf" match: "\\s*(?<=\\.)\\b(__proto__)\\b" } { name: "variable.language.constructor.pf" match: "\\s*(?<=\\.)\\b(constructor)\\b\\s*(?!\\()" } { name: "variable.language.prototype.pf" match: "\\s*(?<=\\.)\\b(prototype)\\b" } ] "string-content": patterns: [ { name: "constant.character.escape.newline.pf" match: "\\\\\\s*\\n" } { name: "constant.character.escape" match: "\\\\['|\"|\\\\|n|r|t|b|f|v|0]" } { name: "constant.character.escape" match: "\\\\u((\\{[0-9a-fA-F]+\\})|[0-9a-fA-F]{4})" } { name: "constant.character.escape" match: "\\\\x[0-9a-fA-F]{2}" } ] "literal-number": patterns: [ { match: "\\s*((?i)(?:\\B[-+]|\\b)0x[0-9a-f]*\\.(\\B|\\b[0-9]+))" captures: "1": name: "invalid.illegal.numeric.hex.pf" } { match: "\\s*((?:\\B[-+]|\\b)0[0-9]+\\.(\\B|\\b[0-9]+))" captures: "1": name: "invalid.illegal.numeric.octal.pf" } { match: "\\s*((?:\\B[-+])?(?:\\b0b[0-1]*|\\b0o[0-7]*|\\b0x[0-9a-f]*|(\\B\\.[0-9]+|\\b[0-9]+(\\.[0-9]*)?)(e[-+]?[0-9]+)?))" captures: "1": name: "constant.numeric.pf" } { match: "\\s*((?:\\B[-+]|\\b)(Infinity)\\b)" captures: "1": name: "constant.language.infinity.pf" } ] "literal-constructor": patterns: [ { disabled: 1 name: "meta.instance.constructor" begin: "\\s*(new)\\s+(?=[_$a-zA-Z][$\\w.]*)" end: "(?![_$a-zA-Z][$\\w.]*)" beginCaptures: "1": name: "keyword.operator.new.pf" patterns: [ { include: "#support" } { match: "([_$a-zA-Z][$\\w.]*\\.)?([_a-zA-Z][\\w]*)" captures: "2": name: "entity.name.type.new.pf" } ] } ] "literal-arrow-function": patterns: [ { comment: "e.g. (args) => { }" name: "meta.function.arrow.pf" begin: "\\s*(\\basync\\b)?\\s*(?=(<(?:(?>[^<>]+)|\\g<-1>)*>)?\\s*(\\((?:(?>[^()]+)|\\g<-1>)*\\))\\s*(?:\\s*(:|\\|)(\\s*[$_a-zA-Z0-9]+(<(?:(?>[^<>]+)|\\g<-1>)*>)?|\\s*(\\{(?:(?>[^{}]+)|\\g<-1>)*\\})|\\s*(((')((?:[^']|\\\\')*)('))|\\s*((\")((?:[^\"]|\\\\\")*)(\")))|\\s*[x0-9A-Fa-f]+))*\\s*=>)" end: "\\s*(=>)" applyEndPatternLast: 1 endCaptures: "1": name: "storage.type.function.arrow.pf" beginCaptures: "1": name: "storage.type.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. play = (args) => { }" name: "meta.function.arrow.pf" begin: "\\s*(\\b[_a-zA-Z][\\w]*)\\s*(=)\\s*(?=(<(?:(?>[^<>]+)|\\g<-1>)*>)?\\s*(\\((?:(?>[^()]+)|\\g<-1>)*\\))\\s*(?:\\s*(:|\\|)(\\s*[$_a-zA-Z0-9]+(<(?:(?>[^<>]+)|\\g<-1>)*>)?|\\s*(\\{(?:(?>[^{}]+)|\\g<-1>)*\\})|\\s*(((')((?:[^']|\\\\')*)('))|\\s*((\")((?:[^\"]|\\\\\")*)(\")))|\\s*[x0-9A-Fa-f]+))*\\s*=>)" end: "\\s*(=>)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "keyword.operator.assignment.pf" "3": name: "storage.type.pf" endCaptures: "1": name: "storage.type.function.arrow.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-regexp": patterns: [ { name: "string.regexp.pf" begin: "(?<=\\.|\\(|,|{|}|\\[|;|,|<|>|<=|>=|==|!=|===|!==|\\+|-|\\*|%|\\+\\+|--|<<|>>|>>>|&|\\||\\^|!|~|&&|\\|\\||\\?|:|=|\\+=|-=|\\*=|%=|<<=|>>=|>>>=|&=|\\|=|\\^=|/|/=|\\Wnew|\\Wdelete|\\Wvoid|\\Wtypeof|\\Winstanceof|\\Win|\\Wdo|\\Wreturn|\\Wcase|\\Wthrow|^new|^delete|^void|^typeof|^instanceof|^in|^do|^return|^case|^throw|^)\\s*(/)(?!/|\\*|$)" end: "(/)([gimy]*)" beginCaptures: "1": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "punctuation.definition.string.end.pf" "2": name: "keyword.other.pf" patterns: [ { include: "source.regexp.babel" } ] } ] "literal-string": patterns: [ { contentName: "string.quoted.single.pf" begin: "\\s*(('))" end: "(('))|(\\n)" beginCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.end.pf" "3": name: "invalid.illegal.newline.pf" patterns: [ { include: "#string-content" } ] } { contentName: "string.quoted.double.pf" begin: "\\s*((\"))" end: "((\"))|(\\n)" beginCaptures: "1": name: "string.quoted.double.pf" "2": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "string.quoted.double.pf" "2": name: "punctuation.definition.string.end.pf" "3": name: "invalid.illegal.newline.pf" patterns: [ { include: "#string-content" } ] } ] "literal-module": patterns: [ { name: "keyword.control.module.pf" match: "\\s*(?<!\\.)\\b(import|export|default)\\b" } { name: "keyword.control.module.reference.pf" match: "\\s*(?<!\\.)\\b(from|as)\\b" } ] "literal-variable": patterns: [ { comment: "e.g. CONSTANT" name: "variable.other.constant.pf" match: "\\s*[A-Z][_$\\dA-Z]*\\b" } { comment: "e.g. Class.property" name: "meta.property.class.pf" match: "\\s*\\b([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "variable.other.property.static.pf" } { comment: "e.g. obj.property" name: "variable.other.object.pf" match: "\\s*(?<!\\.)[_a-zA-Z][\\w]*\\s*(?=[\\[\\.])" captures: "1": name: "variable.other.object.pf" } { comment: "e.g. obj.property" name: "meta.property.object.pf" match: "\\s*(?<=\\.)\\s*[_a-zA-Z][\\w]*" captures: "0": name: "variable.other.property.pf" } { name: "variable.other.readwrite.pf" match: "\\s*[_a-zA-Z][\\w]*" } ] jsx: comment: "Avoid < operator expressions as best we can using Zertosh's regex" patterns: [ { begin: "(?<=\\(|\\{|\\[|,|&&|\\|\\||\\?|:|=|=>|\\Wreturn|^return|^)\\s*(?=<[_$a-zA-Z])" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#jsx-tag-element-name" } ] } ] "jsx-tag-element-name": patterns: [ { comment: "Tags that end > are trapped in #jsx-tag-termination" name: "meta.tag.pfx" begin: "\\s*(<)([$_\\p{L}](?:[$.:\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}-](?<!\\.\\.))*+)(?=[/>\\s])(?<![\\.:])" end: "\\s*(?<=</)(\\2)(>)|(/>)|((?<=</)[\\S ]*?)>" beginCaptures: "1": name: "punctuation.definition.tag.pfx" "2": name: "entity.name.tag.open.pfx" endCaptures: "1": name: "entity.name.tag.close.pfx" "2": name: "punctuation.definition.tag.pfx" "3": name: "punctuation.definition.tag.pfx" "4": name: "invalid.illegal.termination.pfx" patterns: [ { include: "#jsx-tag-termination" } { include: "#jsx-tag-attributes" } ] } ] "jsx-tag-termination": patterns: [ { comment: "uses non consuming search for </ in </tag>" begin: "(>)" end: "(</)" beginCaptures: "0": name: "punctuation.definition.tag.pfx" "1": name: "JSXStartTagEnd" endCaptures: "0": name: "punctuation.definition.tag.pfx" "1": name: "JSXEndTagStart" patterns: [ { include: "#jsx-evaluated-code" } { include: "#jsx-entities" } { include: "#jsx-tag-element-name" } ] } ] "jsx-tag-attributes": patterns: [ { include: "#jsx-attribute-name" } { include: "#jsx-assignment" } { include: "#jsx-string-double-quoted" } { include: "#jsx-string-single-quoted" } { include: "#jsx-evaluated-code" } { include: "#jsx-tag-element-name" } { include: "#comments" } ] "jsx-spread-attribute": patterns: [ { comment: "Spread attribute { ... AssignmentExpression }" match: "(?<!\\.)\\.\\.\\." name: "keyword.operator.spread.pfx" } ] "jsx-attribute-name": patterns: [ { comment: "look for attribute name" match: "(?<!\\S)([$_\\p{L}](?:[$.\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}-](?<!\\.\\.))*+)(?<!\\.)(?=//|/\\*|=|\\s|>|/>)" captures: "0": name: "entity.other.attribute-name.pfx" } ] "jsx-assignment": patterns: [ { comment: "look for attribute assignment" name: "keyword.operator.assignment.pfx" match: "=(?=\\s*(?:'|\"|{|/\\*|<|//|\\n))" } ] "jsx-string-double-quoted": name: "string.quoted.double.pf" begin: "\"" end: "\"(?<!\\\\\")" beginCaptures: "0": name: "punctuation.definition.string.begin.pfx" endCaptures: "0": name: "punctuation.definition.string.end.pfx" patterns: [ { include: "#jsx-entities" } ] "jsx-string-single-quoted": name: "string.quoted.single.pf" begin: "'" end: "'(?<!\\\\')" beginCaptures: "0": name: "punctuation.definition.string.begin.pfx" endCaptures: "0": name: "punctuation.definition.string.end.pfx" patterns: [ { include: "#jsx-entities" } ] "jsx-evaluated-code": name: "meta.embedded.expression.pf" begin: "{" end: "}" beginCaptures: "0": name: "punctuation.section.embedded.begin.pfx" endCaptures: "0": name: "punctuation.section.embedded.end.pfx" contentName: "source.pf.pfx" patterns: [ { include: "#jsx-string-double-quoted" } { include: "#jsx-string-single-quoted" } { include: "#jsx-spread-attribute" } { include: "#expression" } ] "jsx-entities": patterns: [ { comment: "Embeded HTML entities &blah" match: "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)" captures: "0": name: "constant.character.entity.pfx" "1": name: "punctuation.definition.entity.pfx" "2": name: "entity.name.tag.html.pfx" "3": name: "punctuation.definition.entity.pfx" } { comment: "Entity with & and invalid name" match: "&\\S*;" name: "invalid.illegal.bad-ampersand.pfx" } ] "flowtype-variable": patterns: [ { comment: "name of variable spread var with flowtype :" match: "\\s*((?<!\\.)\\.\\.\\.)?([$_\\p{L}](?:[$.\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}])*+)\\s*(\\??)\\s*(?=:|=>)" captures: "1": name: "keyword.operator.spread.pf" "2": name: "variable.other.readwrite.pf" "3": name: "keyword.operator.optional.parameter.flowtype" } { include: "#flowtype-vars-and-props" } ] "flowtype-vars-and-props": patterns: [ { comment: "flowtype optional arg/parameter e.g. protocol? : string" name: "punctuation.type.flowtype" match: "\\?(?=\\s*:)" } { comment: "typed entity :" begin: "\\s*(:)" end: "(?=.)" applyEndPatternLast: 1 beginCaptures: "1": name: "punctuation.type.flowtype" patterns: [ { include: "#flowtype-parse-types" } ] } { include: "#literal-comma" } { comment: "An Iterator prefix?" match: "\\s*@@" } { match: "\\s*(=>)" captures: "1": name: "storage.type.function.arrow.pf" } { include: "#flowtype-bracketed-parameters" } { include: "#flowtype-parse-array" } { include: "#expression" } ] "flowtype-bracketed-parameters": patterns: [ { comment: "Get parameters within a function/method call" begin: "\\s*(\\()" end: "\\s*(\\))" beginCaptures: "1": name: "punctuation.definition.parameters.begin.pf" endCaptures: "1": name: "punctuation.definition.parameters.end.pf" patterns: [ { include: "#flowtype-variable" } ] } ]
true
name: "PI:NAME:<NAME>END_PIunk" scopeName: "source.pf" foldingStartMarker: "(/\\*|\\{|\\()" foldingEndMarker: "(\\*/|\\}|\\))" firstLineMatch: "^#!\\s*/.*\\b(node|js)$\\n?" fileTypes: [ "pf" ] patterns: [ { include: "#core" } ] repository: core: patterns: [ { include: "#ignore-long-lines" } { include: "#literal-labels" } { include: "#literal-keywords" } { include: "#literal-for" } { include: "#literal-switch" } { include: "#expression" } { include: "#literal-punctuation" } ] expression: patterns: [ { include: "#ignore-long-lines" } { include: "#jsx" } { include: "#support" } { include: "#literal-function" } { include: "#literal-arrow-function" } { include: "#literal-regexp" comment: "before operators to avoid abiguities" } { include: "#literal-number" } { include: "#literal-quasi" } { include: "#literal-string" } { include: "#literal-language-constant" } { include: "#literal-language-variable" } { include: "#literal-module" } { include: "#literal-class" } { include: "#literal-constructor" } { include: "#literal-method-call" } { include: "#literal-function-call" } { include: "#comments" } { include: "#brackets" } { include: "#literal-operators" } { include: "#literal-variable" } { include: "#literal-comma" } ] "ignore-long-lines": comment: "so set at arbitary 1000 chars to avoid parsing minified files" patterns: [ match: "^(?:).{1000,}" ] "literal-function-labels": patterns: [ { comment: "e.g. play: fn(arg1, arg2) { }" name: "meta.function.json.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(:)\\s*(\\bfn\\b)\\s*\\s*(?=\\()" end: "(?=\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "punctuation.separator.key-value.pf" "3": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. 'play': fn(arg1, arg2) { }" name: "meta.function.json.pf" begin: "\\s*((')(\\b[_a-zA-Z][\\w]*)(\\g2))\\s*(:)\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.begin.pf" "3": name: "entity.name.function.pf" "4": name: "punctuation.definition.string.end.pf" "5": name: "punctuation.separator.key-value.pf" "6": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-keywords": patterns: [ { name: "keyword.control.conditional.pf" match: "\\s*(?<!\\.)\\b(if|else)\\b" } { name: "keyword.control.loop.pf" match: "\\s*(?<!\\.)\\b(break|continue|do|while)\\b" } ] "literal-for": patterns: [ { name: "meta.for.pf" match: "\\s*(?<!\\.)\\b(for)\\b" captures: "1": name: "keyword.control.loop.pf" patterns: [ { begin: "\\s*\\(" end: "\\s*(?=\\))" beginCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#expression" } { include: "#literal-punctuation" } ] } ] } ] "literal-switch": patterns: [ { name: "meta.switch.pf" begin: "\\s*(?<!\\.)\\b(switch)\\b" end: "\\s*\\}" beginCaptures: "1": name: "keyword.control.switch.pf" endCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { include: "#round-brackets" } { begin: "\\s*\\{" end: "\\s*(?=})" beginCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { begin: "\\s*(?<!\\.)\\b(case|default)\\b" end: "\\s*(?=:)" beginCaptures: "1": name: "keyword.control.switch.pf" patterns: [ { include: "#expression" } ] } { include: "$self" } ] } ] } ] brackets: patterns: [ { include: "#round-brackets" } { include: "#square-brackets" } { include: "#curly-brackets" } ] "round-brackets": patterns: [ { comment: "try to avoid ternary operators which have a '? some chars :'" name: "meta.group.braces.round" begin: "(^|:|;|=|(?<=:|;|=))\\s*(\\((?=((\"|').*?(?<=[^\\\\])\\k<-1>|[^?:])*(:|\\?\\s*:)))" end: "\\s*\\)" beginCaptures: "2": name: "meta.brace.round.pf" endCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#flowtype-typecast" } { include: "#expression" } ] } { name: "meta.group.braces.round" begin: "\\s*\\(" end: "\\s*\\)" endCaptures: "0": name: "meta.brace.round.pf" beginCaptures: "0": name: "meta.brace.round.pf" patterns: [ { include: "#expression" } ] } ] "square-brackets": patterns: [ { name: "meta.group.braces.square" begin: "\\s*\\[" end: "\\s*\\]" endCaptures: "0": name: "meta.brace.square.pf" beginCaptures: "0": name: "meta.brace.square.pf" patterns: [ { include: "#expression" } ] } ] "curly-brackets": patterns: [ { name: "meta.group.braces.curly" begin: "\\s*\\{" end: "\\s*\\}" endCaptures: "0": name: "meta.brace.curly.pf" beginCaptures: "0": name: "meta.brace.curly.pf" patterns: [ { include: "$self" } ] } ] jsdoc: patterns: [ { comment: "common doc @ keywords" match: "(?<!\\w)@(abstract|alias|author|class|constructor|deprecated|enum|event|example|extends|fires|ignore|inheritdoc|member|method|param|private|property|protected|readonly|requires|return|since|static|throws|type|var)\\b" name: "storage.type.class.doc" } { comment: "additional jsdoc keywords" match: "(?<!\\w)@(access|also|arg|arguments|augments|borrows|callback|classdesc|constant|const|constructs|copyright|default|defaultvalue|desc|description|emits|exception|exports|external|file|fileoverview|function|func|global|host|implements|inner|instance|interface|kind|lends|license|listens|memberof|mixes|mixin|module|name|namsepace|overview|prop|public|returns|see|summary|this|todo|tutorial|typedef|undocumented|variation|version|virtual)\\b" name: "storage.type.class.jsdoc" } { comment: "additional jsduck keywords" match: "(?<!\\w)@(accessor|alternateClassName|aside|cfg|chainable|docauthor|evented|experimental|ftype|hide|inheritable|localdoc|markdown|mixins|new|override|preventable|ptype|removed|scss mixin|singleton|template|uses|xtype)\\b" name: "storage.type.class.jsduck" } ] comments: patterns: [ { include: "#special-comments-conditional-compilation" } { name: "comment.block.documentation.pf" begin: "\\s*/\\*\\*(?!/)" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" patterns: [ { include: "#jsdoc" } ] } { name: "comment.block.pf" begin: "\\s*/\\*" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" } { name: "comment.block.html.pf" match: "\\s*(<!--|-->)" captures: "0": name: "punctuation.definition.comment.pf" } { name: "comment.line.double-slash.pf" begin: "\\s*(//)" end: "\\s*$" beginCaptures: "1": name: "punctuation.definition.comment.pf" } { name: "comment.line.shebang.pf" match: "^(#!).*$\\n?" captures: "1": name: "punctuation.definition.comment.pf" } ] "special-comments-conditional-compilation": patterns: [ { name: "comment.block.conditional.pf" begin: "\\s*/\\*(?=@)" end: "\\s*\\*/" captures: "0": name: "punctuation.definition.comment.pf" endCaptures: "1": name: "keyword.control.conditional.pf" "2": name: "punctuation.definition.keyword.pf" patterns: [ { name: "punctuation.definition.comment.pf" match: "\\s*/\\*" } { include: "$self" } ] } { name: "keyword.control.conditional.pf" match: "\\s*(?!@)(@)(if|elif|else|end|ifdef|endif|cc_on|set)\\b" captures: "1": name: "punctuation.definition.keyword.pf" } { name: "variable.other.conditional.pf" match: "\\s*(?!@)(@)(_win32|_win16|_mac|_alpha|_x86|_mc680x0|_PowerPC|_jscript|_jscript_build|_jscript_version|_debug|_fast|[a-zA-Z]\\w+)" captures: "1": name: "punctuation.definition.variable.pf" } ] "literal-punctuation": patterns: [ { include: "#literal-semi-colon" } { include: "#literal-comma" } ] "literal-semi-colon": patterns: [ { name: "punctuation.terminator.statement.pf" match: "\\s*\\;" } ] "literal-comma": patterns: [ { name: "meta.delimiter.comma.pf" match: "\\s*," } ] "literal-function": patterns: [ { comment: "e.g. fn (arg1, arg2) { }" name: "meta.function.pf" begin: "\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\s*\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. play = fn(arg1, arg2) { }" name: "meta.function.pf" begin: "\\s*(\\b[_a-zA-Z][\\w]*)\\s*(=)\\s*(\\bfn\\b)\\s*(?=\\()" end: "(?=\\s*\\{)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "keyword.operator.assignment.pf" "3": name: "storage.type.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-quasi": patterns: [ { name: "string.quasi.pf" begin: "\\s*([a-zA-Z$_][\\w$_]*)?(`)" end: "\\s*(?<!\\\\)`" beginCaptures: "1": name: "entity.quasi.tag.name.pf" "2": name: "punctuation.definition.quasi.begin.pf" endCaptures: "0": name: "punctuation.definition.quasi.end.pf" patterns: [ { name: "entity.quasi.element.pf" begin: "(?<!\\\\)\\${" end: "\\s*}" beginCaptures: "0": name: "punctuation.quasi.element.begin.pf" endCaptures: "0": name: "punctuation.quasi.element.end.pf" patterns: [ { include: "#expression" } ] } { include: "#string-content" } ] } ] "literal-operators": patterns: [ { name: "keyword.operator.pf" match: "\\s*(?<!\\.)\\b(delete|in|instanceof|new|of|typeof|void|with)\\b" } { name: "keyword.operator.logical.pf" match: "\\s*(!(?!=)|&&|\\|\\|)" } { name: "keyword.operator.assignment.pf" match: "\\s*(=(?!=))" } { name: "keyword.operator.assignment.augmented.pf" match: "\\s*(%=|&=|\\*=|\\+=|-=|/=|\\^=|\\|=|<<=|>>=|>>>=)" } { name: "keyword.operator.bitwise.pf" match: "\\s*(~|<<|>>>|>>|&|\\^|\\|)" } { name: "keyword.operator.relational.pf" match: "\\s*(<=|>=|<|>)" } { name: "keyword.operator.comparison.pf" match: "\\s*(==|!=)" } { name: "keyword.operator.arithmetic.pf" match: "\\s*(--|\\+\\+|/(?!/|\\*)|%|\\*(?<!/\\*)|\\+|-)" } { comment: "ternary operator" begin: "\\s*(\\?)" end: "\\s*(:)" beginCaptures: "1": name: "keyword.operator.ternary.pf" endCaptures: "1": name: "keyword.operator.ternary.pf" patterns: [ { include: "#expression" } ] } { name: "keyword.operator.spread.pf" match: "\\s*(?<!\\.)\\.\\.\\." } { name: "keyword.operator.accessor.pf" match: "\\." } ] "literal-function-call": comment: "maybe in array form e.g. foo[bar]()" patterns: [ { name: "meta.function-call.without-arguments.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(?=\\(\\s*\\))" end: "\\s*(?<=\\))" beginCaptures: "1": name: "entity.name.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.without-arguments.pf" begin: "\\s*(?=(\\[(?:(?>[^\\[\\]]+)|\\g<-1>)*\\])\\s*\\(\\s*\\))" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.with-arguments.pf" begin: "\\s*([_a-zA-Z][\\w]*)\\s*(?=\\()" end: "(?=.)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { name: "meta.function-call.without-arguments.pf" begin: "\\s*(?=(\\[(?:(?>[^\\[\\]]+)|\\g<-1>)*\\])\\s*\\()" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-language-constant": patterns: [ { name: "constant.language.boolean.true.pf" match: "\\s*(?<!\\.)\\btrue\\b" } { name: "constant.language.boolean.false.pf" match: "\\s*(?<!\\.)\\bfalse\\b" } { name: "constant.language.null.pf" match: "\\s*(?<!\\.)\\bnull\\b" } ] support: patterns: [ { name: "support.class.builtin.pf" match: "\\s*\\b(Array|ArrayBuffer|Boolean|DataView|Date|Float(32|64)Array|Int(8|16|32)Array|Function|GeneratorFunction|Map|Math|Number|Object|Promise|Proxy|RegExp|Set|String|Uint(8|16|32)Array|Uint8ClampedArray|WeakMap|WeakSet)\\b" } { name: "support.function.pf" match: "\\s*(?<!\\.)\\b(decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|eval|isFinite|isNaN|parseFloat|parseInt|unescape)\\b" } { name: "support.function.mutator.pf" match: "(?<=\\.)(shift|sort|splice|unshift|pop|push|reverse)\\b" } { name: "support.class.error.pf" match: "\\s*(?<!\\.)\\b((Eval|Range|Reference|Syntax|Type|URI)?Error)\\b" } { name: "keyword.other.pf" match: "\\s*(?<!\\.)\\b(debugger)\\b" } { name: "support.type.object.dom.pf" match: "\\s*(?<!\\.)\\b(document|window)\\b" } { name: "support.constant.dom.pf" match: "\\s*\\b(ELEMENT_NODE|ATTRIBUTE_NODE|TEXT_NODE|CDATA_SECTION_NODE|ENTITY_REFERENCE_NODE|ENTITY_NODE|PROCESSING_INSTRUCTION_NODE|COMMENT_NODE|DOCUMENT_NODE|DOCUMENT_TYPE_NODE|DOCUMENT_FRAGMENT_NODE|NOTATION_NODE|INDEX_SIZE_ERR|DOMSTRING_SIZE_ERR|HIERARCHY_REQUEST_ERR|WRONG_DOCUMENT_ERR|INVALID_CHARACTER_ERR|NO_DATA_ALLOWED_ERR|NO_MODIFICATION_ALLOWED_ERR|NOT_FOUND_ERR|NOT_SUPPORTED_ERR|INUSE_ATTRIBUTE_ERR)\\b" } { match: "\\s*(?<!\\.)\\b(console)(?:(\\.)(warn|info|log|error|time|timeEnd|assert))?\\b" captures: "1": name: "support.type.object.console.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.function.console.pf" } { name: "support.module.node.pf" match: "\\s*(?<!\\.)\\b(natives|buffer|child_process|cluster|crypto|dgram|dns|fs|http|https|net|os|path|punycode|string|string_decoder|readline|repl|tls|tty|util|vm|zlib)\\b" } { match: "\\s*(?<!\\.)\\b(process)(?:(\\.)(stdout|stderr|stdin|argv|execPath|execArgv|env|exitCode|version|versions|config|pid|title|arch|platform|mainModule))?\\b" captures: "1": name: "support.type.object.process.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.type.object.process.pf" } { match: "\\s*(?<!\\.)\\b(process)(?:(\\.)(abort|chdir|cwd|exit|getgid|setgid|getuid|setuid|setgroups|getgroups|initgroups|kill|memoryUsage|nextTick|umask|uptime|hrtime))?\\b" captures: "1": name: "support.type.object.process.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.function.process.pf" } { match: "\\s*\\b(((?<!\\.)module\\.((?<!\\,)exports|id|require|parent|filename|loaded|children)|exports))\\b" captures: "1": name: "support.type.object.module.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "support.type.object.module.pf" } { name: "support.type.object.node.pf" match: "\\s*(?<!\\.)\\b(global|GLOBAL|root|__dirname|__filename)\\b" } { name: "support.class.node.pf" match: "\\s*\\b(Buffer|EventEmitter|Server|Pipe|Socket|REPLServer|ReadStream|WriteStream|Stream|Inflate|Deflate|InflateRaw|DeflateRaw|GZip|GUnzip|Unzip|Zip)\\b" } { name: "meta.tag.mustache.pf" begin: "\\s*{{" end: "\\s*}}" } ] "literal-class": patterns: [ { comment: "Classes" begin: "\\s*(?<!\\.)\\b(class)\\s+" end: "\\s*(})" beginCaptures: "0": name: "meta.class.pf" "1": name: "storage.type.class.pf" endCaptures: "1": name: "punctuation.section.class.end.pf" patterns: [ { match: "\\s*\\b(extends)\\b\\s*" captures: "0": name: "meta.class.extends.pf" "1": name: "storage.type.extends.pf" } { include: "#flowtype-class-name" } { include: "#flowtype-polymorphs" } { begin: "\\s*{" end: "\\s*(?=})" contentName: "meta.class.body.pf" beginCaptures: "0": name: "punctuation.section.class.begin.pf" patterns: [ { match: "\\s*\\b(?<!\\.)static\\b(?!\\.)" name: "storage.modifier.pf" } { include: "#literal-method" } { include: "#brackets" } { include: "#es7-decorators" } { include: "#comments" } { include: "#flowtype-variable" } { include: "#literal-semi-colon" } ] } { include: "#expression" } ] } ] "literal-method-call": patterns: [ { name: "meta.function-call.static.without-arguments.pf" comment: "e.g Abc.aaa()" match: "\\s*(?:(?<=\\.)|\\b)([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)\\s*(\\(\\s*\\))" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "entity.name.function.pf" "4": name: "meta.group.braces.round.function.arguments.pf" } { name: "meta.function-call.static.with-arguments.pf" match: "\\s*(?:(?<=\\.)|\\b)\\s*([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)\\s*(?=\\()" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "entity.name.function.pf" } { name: "meta.function-call.method.without-arguments.pf" match: "\\s*(?<=\\.)\\s*([_a-zA-Z][\\w]*)\\s*(\\(\\s*\\))" captures: "1": name: "entity.name.function.pf" "2": name: "meta.group.braces.round.function.arguments.pf" } { name: "meta.function-call.method.with-arguments.pf" match: "\\s*(?<=\\.)([_a-zA-Z][\\w]*)\\s*(?=\\()" captures: "1": name: "entity.name.function.pf" } ] "literal-language-variable": patterns: [ { name: "variable.language.arguments.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(arguments)\\b" } { name: "variable.language.super.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(super)\\b\\s*(?!\\()" } { name: "variable.language.this.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(this)\\b" } { name: "variable.language.self.pf" match: "\\s*(?<!(?<!\\.\\.)\\.)\\b(self)\\b\\s*(?!\\()" } { name: "variable.language.proto.pf" match: "\\s*(?<=\\.)\\b(__proto__)\\b" } { name: "variable.language.constructor.pf" match: "\\s*(?<=\\.)\\b(constructor)\\b\\s*(?!\\()" } { name: "variable.language.prototype.pf" match: "\\s*(?<=\\.)\\b(prototype)\\b" } ] "string-content": patterns: [ { name: "constant.character.escape.newline.pf" match: "\\\\\\s*\\n" } { name: "constant.character.escape" match: "\\\\['|\"|\\\\|n|r|t|b|f|v|0]" } { name: "constant.character.escape" match: "\\\\u((\\{[0-9a-fA-F]+\\})|[0-9a-fA-F]{4})" } { name: "constant.character.escape" match: "\\\\x[0-9a-fA-F]{2}" } ] "literal-number": patterns: [ { match: "\\s*((?i)(?:\\B[-+]|\\b)0x[0-9a-f]*\\.(\\B|\\b[0-9]+))" captures: "1": name: "invalid.illegal.numeric.hex.pf" } { match: "\\s*((?:\\B[-+]|\\b)0[0-9]+\\.(\\B|\\b[0-9]+))" captures: "1": name: "invalid.illegal.numeric.octal.pf" } { match: "\\s*((?:\\B[-+])?(?:\\b0b[0-1]*|\\b0o[0-7]*|\\b0x[0-9a-f]*|(\\B\\.[0-9]+|\\b[0-9]+(\\.[0-9]*)?)(e[-+]?[0-9]+)?))" captures: "1": name: "constant.numeric.pf" } { match: "\\s*((?:\\B[-+]|\\b)(Infinity)\\b)" captures: "1": name: "constant.language.infinity.pf" } ] "literal-constructor": patterns: [ { disabled: 1 name: "meta.instance.constructor" begin: "\\s*(new)\\s+(?=[_$a-zA-Z][$\\w.]*)" end: "(?![_$a-zA-Z][$\\w.]*)" beginCaptures: "1": name: "keyword.operator.new.pf" patterns: [ { include: "#support" } { match: "([_$a-zA-Z][$\\w.]*\\.)?([_a-zA-Z][\\w]*)" captures: "2": name: "entity.name.type.new.pf" } ] } ] "literal-arrow-function": patterns: [ { comment: "e.g. (args) => { }" name: "meta.function.arrow.pf" begin: "\\s*(\\basync\\b)?\\s*(?=(<(?:(?>[^<>]+)|\\g<-1>)*>)?\\s*(\\((?:(?>[^()]+)|\\g<-1>)*\\))\\s*(?:\\s*(:|\\|)(\\s*[$_a-zA-Z0-9]+(<(?:(?>[^<>]+)|\\g<-1>)*>)?|\\s*(\\{(?:(?>[^{}]+)|\\g<-1>)*\\})|\\s*(((')((?:[^']|\\\\')*)('))|\\s*((\")((?:[^\"]|\\\\\")*)(\")))|\\s*[x0-9A-Fa-f]+))*\\s*=>)" end: "\\s*(=>)" applyEndPatternLast: 1 endCaptures: "1": name: "storage.type.function.arrow.pf" beginCaptures: "1": name: "storage.type.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } { comment: "e.g. play = (args) => { }" name: "meta.function.arrow.pf" begin: "\\s*(\\b[_a-zA-Z][\\w]*)\\s*(=)\\s*(?=(<(?:(?>[^<>]+)|\\g<-1>)*>)?\\s*(\\((?:(?>[^()]+)|\\g<-1>)*\\))\\s*(?:\\s*(:|\\|)(\\s*[$_a-zA-Z0-9]+(<(?:(?>[^<>]+)|\\g<-1>)*>)?|\\s*(\\{(?:(?>[^{}]+)|\\g<-1>)*\\})|\\s*(((')((?:[^']|\\\\')*)('))|\\s*((\")((?:[^\"]|\\\\\")*)(\")))|\\s*[x0-9A-Fa-f]+))*\\s*=>)" end: "\\s*(=>)" applyEndPatternLast: 1 beginCaptures: "1": name: "entity.name.function.pf" "2": name: "keyword.operator.assignment.pf" "3": name: "storage.type.pf" endCaptures: "1": name: "storage.type.function.arrow.pf" patterns: [ { include: "#flowtype-bracketed-parameters" } ] } ] "literal-regexp": patterns: [ { name: "string.regexp.pf" begin: "(?<=\\.|\\(|,|{|}|\\[|;|,|<|>|<=|>=|==|!=|===|!==|\\+|-|\\*|%|\\+\\+|--|<<|>>|>>>|&|\\||\\^|!|~|&&|\\|\\||\\?|:|=|\\+=|-=|\\*=|%=|<<=|>>=|>>>=|&=|\\|=|\\^=|/|/=|\\Wnew|\\Wdelete|\\Wvoid|\\Wtypeof|\\Winstanceof|\\Win|\\Wdo|\\Wreturn|\\Wcase|\\Wthrow|^new|^delete|^void|^typeof|^instanceof|^in|^do|^return|^case|^throw|^)\\s*(/)(?!/|\\*|$)" end: "(/)([gimy]*)" beginCaptures: "1": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "punctuation.definition.string.end.pf" "2": name: "keyword.other.pf" patterns: [ { include: "source.regexp.babel" } ] } ] "literal-string": patterns: [ { contentName: "string.quoted.single.pf" begin: "\\s*(('))" end: "(('))|(\\n)" beginCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "string.quoted.single.pf" "2": name: "punctuation.definition.string.end.pf" "3": name: "invalid.illegal.newline.pf" patterns: [ { include: "#string-content" } ] } { contentName: "string.quoted.double.pf" begin: "\\s*((\"))" end: "((\"))|(\\n)" beginCaptures: "1": name: "string.quoted.double.pf" "2": name: "punctuation.definition.string.begin.pf" endCaptures: "1": name: "string.quoted.double.pf" "2": name: "punctuation.definition.string.end.pf" "3": name: "invalid.illegal.newline.pf" patterns: [ { include: "#string-content" } ] } ] "literal-module": patterns: [ { name: "keyword.control.module.pf" match: "\\s*(?<!\\.)\\b(import|export|default)\\b" } { name: "keyword.control.module.reference.pf" match: "\\s*(?<!\\.)\\b(from|as)\\b" } ] "literal-variable": patterns: [ { comment: "e.g. CONSTANT" name: "variable.other.constant.pf" match: "\\s*[A-Z][_$\\dA-Z]*\\b" } { comment: "e.g. Class.property" name: "meta.property.class.pf" match: "\\s*\\b([A-Z][$\\w]*)\\s*(\\.)([_a-zA-Z][\\w]*)" captures: "1": name: "variable.other.class.pf" "2": name: "keyword.operator.accessor.pf" "3": name: "variable.other.property.static.pf" } { comment: "e.g. obj.property" name: "variable.other.object.pf" match: "\\s*(?<!\\.)[_a-zA-Z][\\w]*\\s*(?=[\\[\\.])" captures: "1": name: "variable.other.object.pf" } { comment: "e.g. obj.property" name: "meta.property.object.pf" match: "\\s*(?<=\\.)\\s*[_a-zA-Z][\\w]*" captures: "0": name: "variable.other.property.pf" } { name: "variable.other.readwrite.pf" match: "\\s*[_a-zA-Z][\\w]*" } ] jsx: comment: "Avoid < operator expressions as best we can using Zertosh's regex" patterns: [ { begin: "(?<=\\(|\\{|\\[|,|&&|\\|\\||\\?|:|=|=>|\\Wreturn|^return|^)\\s*(?=<[_$a-zA-Z])" end: "(?=.)" applyEndPatternLast: 1 patterns: [ { include: "#jsx-tag-element-name" } ] } ] "jsx-tag-element-name": patterns: [ { comment: "Tags that end > are trapped in #jsx-tag-termination" name: "meta.tag.pfx" begin: "\\s*(<)([$_\\p{L}](?:[$.:\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}-](?<!\\.\\.))*+)(?=[/>\\s])(?<![\\.:])" end: "\\s*(?<=</)(\\2)(>)|(/>)|((?<=</)[\\S ]*?)>" beginCaptures: "1": name: "punctuation.definition.tag.pfx" "2": name: "entity.name.tag.open.pfx" endCaptures: "1": name: "entity.name.tag.close.pfx" "2": name: "punctuation.definition.tag.pfx" "3": name: "punctuation.definition.tag.pfx" "4": name: "invalid.illegal.termination.pfx" patterns: [ { include: "#jsx-tag-termination" } { include: "#jsx-tag-attributes" } ] } ] "jsx-tag-termination": patterns: [ { comment: "uses non consuming search for </ in </tag>" begin: "(>)" end: "(</)" beginCaptures: "0": name: "punctuation.definition.tag.pfx" "1": name: "JSXStartTagEnd" endCaptures: "0": name: "punctuation.definition.tag.pfx" "1": name: "JSXEndTagStart" patterns: [ { include: "#jsx-evaluated-code" } { include: "#jsx-entities" } { include: "#jsx-tag-element-name" } ] } ] "jsx-tag-attributes": patterns: [ { include: "#jsx-attribute-name" } { include: "#jsx-assignment" } { include: "#jsx-string-double-quoted" } { include: "#jsx-string-single-quoted" } { include: "#jsx-evaluated-code" } { include: "#jsx-tag-element-name" } { include: "#comments" } ] "jsx-spread-attribute": patterns: [ { comment: "Spread attribute { ... AssignmentExpression }" match: "(?<!\\.)\\.\\.\\." name: "keyword.operator.spread.pfx" } ] "jsx-attribute-name": patterns: [ { comment: "look for attribute name" match: "(?<!\\S)([$_\\p{L}](?:[$.\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}-](?<!\\.\\.))*+)(?<!\\.)(?=//|/\\*|=|\\s|>|/>)" captures: "0": name: "entity.other.attribute-name.pfx" } ] "jsx-assignment": patterns: [ { comment: "look for attribute assignment" name: "keyword.operator.assignment.pfx" match: "=(?=\\s*(?:'|\"|{|/\\*|<|//|\\n))" } ] "jsx-string-double-quoted": name: "string.quoted.double.pf" begin: "\"" end: "\"(?<!\\\\\")" beginCaptures: "0": name: "punctuation.definition.string.begin.pfx" endCaptures: "0": name: "punctuation.definition.string.end.pfx" patterns: [ { include: "#jsx-entities" } ] "jsx-string-single-quoted": name: "string.quoted.single.pf" begin: "'" end: "'(?<!\\\\')" beginCaptures: "0": name: "punctuation.definition.string.begin.pfx" endCaptures: "0": name: "punctuation.definition.string.end.pfx" patterns: [ { include: "#jsx-entities" } ] "jsx-evaluated-code": name: "meta.embedded.expression.pf" begin: "{" end: "}" beginCaptures: "0": name: "punctuation.section.embedded.begin.pfx" endCaptures: "0": name: "punctuation.section.embedded.end.pfx" contentName: "source.pf.pfx" patterns: [ { include: "#jsx-string-double-quoted" } { include: "#jsx-string-single-quoted" } { include: "#jsx-spread-attribute" } { include: "#expression" } ] "jsx-entities": patterns: [ { comment: "Embeded HTML entities &blah" match: "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)" captures: "0": name: "constant.character.entity.pfx" "1": name: "punctuation.definition.entity.pfx" "2": name: "entity.name.tag.html.pfx" "3": name: "punctuation.definition.entity.pfx" } { comment: "Entity with & and invalid name" match: "&\\S*;" name: "invalid.illegal.bad-ampersand.pfx" } ] "flowtype-variable": patterns: [ { comment: "name of variable spread var with flowtype :" match: "\\s*((?<!\\.)\\.\\.\\.)?([$_\\p{L}](?:[$.\\p{L}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Nl}\\p{Pc}])*+)\\s*(\\??)\\s*(?=:|=>)" captures: "1": name: "keyword.operator.spread.pf" "2": name: "variable.other.readwrite.pf" "3": name: "keyword.operator.optional.parameter.flowtype" } { include: "#flowtype-vars-and-props" } ] "flowtype-vars-and-props": patterns: [ { comment: "flowtype optional arg/parameter e.g. protocol? : string" name: "punctuation.type.flowtype" match: "\\?(?=\\s*:)" } { comment: "typed entity :" begin: "\\s*(:)" end: "(?=.)" applyEndPatternLast: 1 beginCaptures: "1": name: "punctuation.type.flowtype" patterns: [ { include: "#flowtype-parse-types" } ] } { include: "#literal-comma" } { comment: "An Iterator prefix?" match: "\\s*@@" } { match: "\\s*(=>)" captures: "1": name: "storage.type.function.arrow.pf" } { include: "#flowtype-bracketed-parameters" } { include: "#flowtype-parse-array" } { include: "#expression" } ] "flowtype-bracketed-parameters": patterns: [ { comment: "Get parameters within a function/method call" begin: "\\s*(\\()" end: "\\s*(\\))" beginCaptures: "1": name: "punctuation.definition.parameters.begin.pf" endCaptures: "1": name: "punctuation.definition.parameters.end.pf" patterns: [ { include: "#flowtype-variable" } ] } ]
[ { "context": " Ogre kills fighter\n\n# Lvl 7 Gladiator\n# Axe rends Steve in twain\n# CARL: \"Steve's dead man...\"\n# Carl doe", "end": 1621, "score": 0.7810045480728149, "start": 1616, "tag": "NAME", "value": "Steve" }, { "context": "l 7 Gladiator\n# Axe rends Steve in twain\n# CAR...
main.coffee
STRd6/ld33
2
# Canvas where we draw our duders # Text box where we display dialog # Options to choose from # Moving around # Triggered events # Die Hard Quotes http://www.imdb.com/title/tt0095016/quotes # Wall Sprites # Chair Sprites # TV Sprites # Goblin Sprites # Ogre Sprites # Hero Sprites # 3 Goblins sitting in a room in a dungeon # Chillin, watching Die Hard # Adevnturers come in and try to wreck up the place # Lvl 1 Cleric # Goblins kill the poor bastard # A two headed ogre want's to borrow some rock salt to add to Bud LightTM # Lime-A-Ritas # The ogre also wants to stay and watch die hard # YOU DECIDE # Lvl 4 Fighter # Talking to Steve # STEVE: "Remember that project I was really excited about... well BOSS says I # Shouldn't work on it any more... so forget it." # There is a chest in the room, if you try to open it steve says: Boss told us # not to mess into that. # Chest contians healing elixir and broken cassette tape # They don't keep the Hard-A in Lvl 1 loot tables # Wait, so do we work here, or is this the break room, because I've always # thought it was the break room... That Craig's List add wasn't very specific # - Steve # There is a rock trap if you try to leave the room # Steve will say: Boss says to stay in here # The rock trap will kill you # Achievements: # Die Hard: With a Vengance - Watch all of Die Hard # Hard Hat Warning - Died to a rock trap # A Winner is You - Survived all Encounters # OGRE: "This is our house!" # OGRE: "You're going DOWN scrote sac!" # YOU: "So is a scrote sac like a scrotum, or a sack of scrotums?" # Ogre kills fighter # Lvl 7 Gladiator # Axe rends Steve in twain # CARL: "Steve's dead man..." # Carl doesn't speak for the rest of the game, sits in the corner '...' # After the gladiator encounter the rock trap will be trigered and you can # go out and find another room with some swank loot (wand of death). # Lvl 10 Thief # Use wand of death to kill thief # Lvl 13 mage # Burns the place to shit # Hell Spawn then enters and kills Mage # Grab orb of Zot # Show orb to Ogre # Ogre drops it and it shatters # Messenger comes to tell Steve that his project is back on! # Steve's dead man... # G_G require "cornerstone" TouchCanvas = require "touch-canvas" {width, height} = require "./pixie" style = document.createElement "style" style.innerText = """ * { box-sizing: border-box; } html, body { background-color: black; margin: 0; padding: 0; overflow: hidden; } canvas { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } """ document.head.appendChild style canvas = TouchCanvas width: width height: height document.body.appendChild canvas.element() Dialog = require("./dialog") dialog = null dialogs = [] move = (p) -> if dialog dialog.move p else player.move p, map dieHardPlaying = false hasElixir = false emptyCrate = -> hasElixir = true map.updateItem "Crate", conversation: [ text: """ It's empty. """ ] activateCrate = -> map.updateItem "Crate", conversation: [{ text: """ You found a bottle of fizzy liquid and a handful of rusted old bottle caps. """ event: emptyCrate }, { text: """ STEVE: Sorry to dissapoint, but they don't keep any HARD-A around here. """ }] setSteveConversation = (conversation) -> map.characters[0].I.conversation = conversation setMarcoConversation = (conversation) -> map.characters[1].I.conversation = conversation openDoor = -> map.characters[4].I.x = -1 map.map[8][9] = "2" map.map[9][9] = "2" map.map[10][9] = "2" map.map[11][9] = "2" map.map[12][9] = "2" map.map[13][9] = "2" map.map[14][9] = "2" reviveKnightJr = -> hasElixir = false map.characters[3].I.x = 7 map.characters[3].I.y = 7 map.characters[3].I.conversation = [ text: """ KNIGHT JR: I think I'll just sit here a for a bit. """ ] map.updateItem "Knight Jr Carcass", x: -1 y: -1 events = restart: -> location.reload() crate: (dialog) -> if dialog.I.selectedOption is 0 activateCrate() else map.updateItem "Crate", conversation: [ text: """ MARCO: Jeez man, what's your fascination with that crate? """ event: activateCrate ] door: openDoor brogre0: -> setTimeout -> if dieHardPlaying convo = [{ text: """ BROGRE: So what do you say, can we borrow... BROGRE: OH SHIT! Are you guys watching DIE HARD!? BROGRE: Dude, I was asking BROGRE: DUDE shut up, can we watch it with you?! """ }, { text: """ Can the Ogre(s) join you? """ options: [ "Sure, grab a chair" "Sorry, it's kind of a goblins only thing..." ] event: "brogre" }] else convo = [{ text: """ BROGRE: So what do you say, can we borrow some salt? """ }, { text: """ MARCO: Sorry, I don't think we have any salt... """ selectedOption: 1 event: "brogre" }] showConversation convo , 0 brogre: (dialog) -> setSteveConversation [{ text: """ STEVE: Man I really want this job to work out... After I lost all that money in the stock market this is pretty much all I have left... """ }, { text: """ STEVE: And Helen said she's going to leave me if I don't start pulling off the bacon... """ }, { text: """ MARCO: I think the expression you're looking for is "jerkin' off the pig" """ }, { text: """ STEVE: Yeah, like I was saying Helen's going to leave me if I don't start jerkin' off the pig... I'm not so sure that's right either... """ event: "wiz" }, { text: """ A fire wizard wanders in. """ }, { text: """ THE WIZ: Don't all get up at once now. """ }] if dialog.I.selectedOption is 0 map.characters[2].I.x = 7 map.characters[2].I.y = 4 map.characters[2].I.conversation = [ text: """ BROGRE: Quiet I'm wa... BROGRE: SHUT UP BOTH OF YOU I'm wat... BROGRE: That's what I was saying! BROGRE: You made me miss my favorite part! """ ] setMarcoConversation [{ text: """ MARCO: Why is that ogre sitting on our lunch table? """ }] else setMarcoConversation [{ text: """ MARCO: Did you catch the game last night? """ options: [ "You know it buddy!" "Sorry, not really a fan..." ] }] setTimeout -> showConversation [{ text: """ BROGRE: Oh, I get it... looks like you guys have something planned (glances at KNIGHT JR) """ }, { text: """ BROGRE: We'll leave you to it... BROGRE: PEACE! """ event: -> map.characters[2].I.x = -1 }] , 0 round2: -> map.characters[2].I.x = 9 map.characters[2].I.y = 7 setMarcoConversation [{ text: """ MARCO: Go ask them what they wants. """ }] berserker: -> unless map.characters[6].I.x is 9 setTimeout -> map.characters[6].I.x = 9 map.characters[6].I.y = 8 showConversation [{ text: """ A wild AXE MANIAC appears! He looks like he's starving. """ }] , 0 butcher: -> map.characters[1].I.y = -1 map.addItem name: "Splat" url: "http://2.pixiecdn.com/sprites/131854/original." x: 9 y: 3 conversation: [{ text: """ That's a lot of blood. """ }] satiated: -> map.characters[6].I.conversation = [{ text: """ AXE MANIAC: Ahh, that reall hits the spot! """ }, { text: """ AXE MANIAC: Get in my greased bag of holding? """ }, { text: """ YOU: Are you coming on to me? """ event: -> if map.characters[3].I.x is 7 and map.characters[3].I.y is 7 setTimeout -> showConversation [{ text: """ KNIGHT JR is no longer confused. """ event: -> map.characters[3].I.x = 8 }, { text: """ KNIGHT JR flees in terror! """ event: -> map.characters[3].I.x = 9 }, { text: """ KNIGHT JR runs for the door. KNIGHT JRs CURSED -1 SPIKED HELMET punctures AXE MANIAC's greased scrotum! """ event: -> map.addItem name: "Splat" url: "http://2.pixiecdn.com/sprites/131854/original." x: 9 y: 8 conversation: [{ text: """ That's a lot of blood. """ }] map.characters[3].I.y = 9 }, { text: """ KNIGHT JR flees down the hallway! """ event: -> map.characters[3].I.y = 10 }, { text: """ A trapdoor in the ceiling opens and a rock falls on your KNIGHT JR's head! """ event: -> map.characters[3].I.y = -1 map.updateItem "Trap", x: -1 y: -1 map.updateItem "Knight Jr Carcass", x: 9 y: 11 }] , 0 map.characters[6].I.conversation = [{ text: "AXE MANIAC: Oww, my delicate scrotum!" }, { text: """ AXE MANIAC bleeds to death. """ }, { text: """ A tombstone appears out of nowhere! it reads... """ }, { text: """ Here lies AXE MANIAC... He died as he lived greased up and covered in blood. """ event: -> map.characters[6].I.x = -1 }] else map.characters[6].I.conversation = [{ text: """ AXE MANIAC butchers YOU AXE MANIAC picks up 17kg of GOBLIN MEAT """ }, { text: """ At least you'll make a delicious sandwich... """ }, { text: """ Better luck next time! """ event: "restart" }] }] carco: -> if hasElixir setTimeout -> showConversation [{ text: """ Maybe that fizzy liquid could help this kid... """ options: [ "Give the kid some water" "Leave him be" ] event: -> reviveKnightJr() if dialog.I.selectedOption is 0 }] , 0 knightJr: -> openDoor() map.characters[3].I.x = 9 map.characters[3].I.y = 8 if dieHardPlaying stevesText = """ STEVE: Holy shit man, we're kind of in the middle of this movie. """ else stevesText = """ STEVE: Who let you in here? """ setTimeout -> showConversation [{ text: """ **CRASH** A wild kid wearing a knight costume appears! """ }, { text: "KNIGHT JR: Prepare to die SCUM!" }, { text: stevesText }, { text: """ KNIGHT JR hits STEVE with his +1 SHORT SWORD """ }, { text: """ STEVE: You son of a bitch! That stings like a motherfucker! """ }, { text: """ MARCO throws his -1 BEER CAN OF DEPRESSION at KNIGHT JR The BEER CAN misses """ }, { text: "What do you do?" options: [ "ATTACK!" "Defend" ] event: (dialog) -> if dialog.I.selectedOption is 0 action = text: """ You hit KNIGHT JR with your FIST """ else action = text: """ You cower behind MARCO """ dialogs.unshift Dialog action }, { text: """ STEVE hits KNIGHT JR with his TARNISHED EMPLOYEE OF THE MONTH TROPHY It's super effective! """ }, { text: """ KNIGHT JR was knocked unconscious. """ event: -> map.updateItem "Knight Jr Carcass", x: 9 map.characters[3].I.x = -1 # Update dialogs for STEVE, MARCO, KNIGHT JR convo = [{ text: """ STEVE: I can't believe that just happened. I think I need an ice pack. """ }, { text: """ MARCO: And that's why they made you employee of the month! """ }, { text: """ STEVE: Do me a solid and drag that CARCASS out of the doorway """ }, { text: """ MARCO drags KNIGHT JR into the corner. """ event: -> map.updateItem "Knight Jr Carcass", x: 7 setSteveConversation [{ text: """ STEVE: Any news on that ice pack DUDER? """ }] setMarcoConversation [{ text: """ MARCO: Never a dull moment, eh DUDER? """ event: "round2" }, { text: """ A two headed ogre walks through the open door. """ }] }] setSteveConversation convo setMarcoConversation convo }] , 0 wiz: -> map.characters[5].I.x = 9 setSteveConversation [ text: """ STEVE: Gawd, another asshole... """ ] setMarcoConversation [ text: """ MARCO: I'm getting too old for this shit. """ ] fire: -> map.characters[0].I.x = -1 map.updateItem "TV", x: -1 map.updateItem "Table", x: -1 map.updateItem "Crate", x: -1 ashURLs =[ "http://1.pixiecdn.com/sprites/131845/original." "http://2.pixiecdn.com/sprites/131846/original." "http://1.pixiecdn.com/sprites/131849/original." "http://2.pixiecdn.com/sprites/131846/original." ] [[9, 2], [8, 3], [7, 4], [10, 5]].forEach ([x, y]) -> map.addItem name: "Ash" x: x y: y url: ashURLs conversation: [ text: """ It's a pile of smoldering ash. """ ] if map.characters[2].I.x is 7 setTimeout -> showConversation [{ text: """ The death of TV has enraged BROGRE! """ }, { text: """ BROGRE hits(x2) THE WIZ for 418 DMG """ }, { text: """ THE WIZ dies! """ event: -> map.characters[5].I.x = -1 map.addItem name: "Ash" x: 9 y: 8 url: ashURLs conversation: [{ text: """ It's the smoldering remains of THE WIZ. """ }] }, { text: """ BROGRE runs down the hall in a furious rage! """ event: -> map.characters[3].I.conversation = [ text: """ KNIGHT JR: Huh... did I miss something? """ event: "berserker" ] setMarcoConversation [ text: """ MARCO: STEVE's dead man... """ event: "berserker" ] map.characters[2].I.x = -1 }] , 0 else map.characters[5].I.conversation = [{ text: """ THE WIZ: Are you here to beg for the sweet release of death? """ options: ["Yes", "No"] }, { text: """ THE WIZ: BURN! """ }, { text: """ You burn. """ }, { text: """ Better luck next time! """ event: "restart" }] setTimeout -> showConversation [{ text: """ THE WIZ: I got more where that come from holms! """ }] , 0 tv1: (dialog) -> return unless dialog.I.selectedOption is 0 dieHardPlaying = true map.replaceItem 0, name: "TV" url: [ "http://2.pixiecdn.com/sprites/131830/original." "http://3.pixiecdn.com/sprites/131831/original." "http://2.pixiecdn.com/sprites/131830/original." "http://3.pixiecdn.com/sprites/131831/original." "http://1.pixiecdn.com/sprites/131829/original." ] font: "italic bold 20px monospace" conversation: [{ text: """ HANS GRUBER: You know my name but who are you? Just another American who saw too many movies as a child? Another orphan of a bankrupt culture who thinks he's John Wayne? Rambo? Marshal Dillon? """ }, { text: """ JOHN MCCLANE: Was always kinda partial to Roy Rogers actually. I really like those sequined shirts. """ }, { text: """ HANS GRUBER: Do you really think you have a chance against us, Mr. Cowboy? """ }, { text: """ JOHN MCCLANE: Yippee-ki-yay, motherfucker. """ }] keyHandler = (e) -> e.preventDefault() switch e.keyCode when 13, 32 if dialog if dialog.finished() dialog.event?(dialog) events[dialog.event]?(dialog) dialog = dialogs.shift() else dialog.I.age += 100 else map.interact player.I when 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 ;# console.log e.keyCode - 48 when 37 # Left move x: -1, y: 0 when 38 # Up move x: 0, y: -1 when 39 # Right move x: 1, y: 0 when 40 # Down move x: 0, y: 1 document.addEventListener('keydown', keyHandler, false) global.showDialog = (newDialog) -> dialog = Dialog newDialog global.showConversation = (conversation) -> dialogs = conversation.map (convo) -> Dialog convo dialog = dialogs.shift() map = require("./map")() player = require("./player") url: "http://1.pixiecdn.com/sprites/131785/original." showConversation [{ text: """ Walk around and interact with stuff by pressing the ARROW KEYS and SPACE BAR Or not, it's up to you! """ }, { text: """ Got it? """ options: [ "YEAH!" "Whatever" ] }] update = (dt) -> map.update(dt) player.update(dt) dialog?.update(dt) draw = (canvas) -> map.draw(canvas) player.draw(canvas) dialog?.draw(canvas) dt = 1/60 t = 0 step = (timestamp) -> update(dt) draw(canvas) t += dt window.requestAnimationFrame step window.requestAnimationFrame step
182192
# Canvas where we draw our duders # Text box where we display dialog # Options to choose from # Moving around # Triggered events # Die Hard Quotes http://www.imdb.com/title/tt0095016/quotes # Wall Sprites # Chair Sprites # TV Sprites # Goblin Sprites # Ogre Sprites # Hero Sprites # 3 Goblins sitting in a room in a dungeon # Chillin, watching Die Hard # Adevnturers come in and try to wreck up the place # Lvl 1 Cleric # Goblins kill the poor bastard # A two headed ogre want's to borrow some rock salt to add to Bud LightTM # Lime-A-Ritas # The ogre also wants to stay and watch die hard # YOU DECIDE # Lvl 4 Fighter # Talking to Steve # STEVE: "Remember that project I was really excited about... well BOSS says I # Shouldn't work on it any more... so forget it." # There is a chest in the room, if you try to open it steve says: Boss told us # not to mess into that. # Chest contians healing elixir and broken cassette tape # They don't keep the Hard-A in Lvl 1 loot tables # Wait, so do we work here, or is this the break room, because I've always # thought it was the break room... That Craig's List add wasn't very specific # - Steve # There is a rock trap if you try to leave the room # Steve will say: Boss says to stay in here # The rock trap will kill you # Achievements: # Die Hard: With a Vengance - Watch all of Die Hard # Hard Hat Warning - Died to a rock trap # A Winner is You - Survived all Encounters # OGRE: "This is our house!" # OGRE: "You're going DOWN scrote sac!" # YOU: "So is a scrote sac like a scrotum, or a sack of scrotums?" # Ogre kills fighter # Lvl 7 Gladiator # Axe rends <NAME> in twain # CARL: "<NAME>'s dead man..." # Carl doesn't speak for the rest of the game, sits in the corner '...' # After the gladiator encounter the rock trap will be trigered and you can # go out and find another room with some swank loot (wand of death). # Lvl 10 Thief # Use wand of death to kill thief # Lvl 13 mage # Burns the place to shit # Hell Spawn then enters and kills Mage # Grab orb of Zot # Show orb to Ogre # Ogre drops it and it shatters # Messenger comes to tell <NAME> that his project is back on! # <NAME>'s dead man... # G_G require "cornerstone" TouchCanvas = require "touch-canvas" {width, height} = require "./pixie" style = document.createElement "style" style.innerText = """ * { box-sizing: border-box; } html, body { background-color: black; margin: 0; padding: 0; overflow: hidden; } canvas { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } """ document.head.appendChild style canvas = TouchCanvas width: width height: height document.body.appendChild canvas.element() Dialog = require("./dialog") dialog = null dialogs = [] move = (p) -> if dialog dialog.move p else player.move p, map dieHardPlaying = false hasElixir = false emptyCrate = -> hasElixir = true map.updateItem "Crate", conversation: [ text: """ It's empty. """ ] activateCrate = -> map.updateItem "Crate", conversation: [{ text: """ You found a bottle of fizzy liquid and a handful of rusted old bottle caps. """ event: emptyCrate }, { text: """ STEVE: Sorry to dissapoint, but they don't keep any HARD-A around here. """ }] setSteveConversation = (conversation) -> map.characters[0].I.conversation = conversation setMarcoConversation = (conversation) -> map.characters[1].I.conversation = conversation openDoor = -> map.characters[4].I.x = -1 map.map[8][9] = "2" map.map[9][9] = "2" map.map[10][9] = "2" map.map[11][9] = "2" map.map[12][9] = "2" map.map[13][9] = "2" map.map[14][9] = "2" reviveKnightJr = -> hasElixir = false map.characters[3].I.x = 7 map.characters[3].I.y = 7 map.characters[3].I.conversation = [ text: """ KNIGHT JR: I think I'll just sit here a for a bit. """ ] map.updateItem "Knight Jr Carcass", x: -1 y: -1 events = restart: -> location.reload() crate: (dialog) -> if dialog.I.selectedOption is 0 activateCrate() else map.updateItem "Crate", conversation: [ text: """ MARCO: Jeez man, what's your fascination with that crate? """ event: activateCrate ] door: openDoor brogre0: -> setTimeout -> if dieHardPlaying convo = [{ text: """ BROGRE: So what do you say, can we borrow... BROGRE: OH SHIT! Are you guys watching DIE HARD!? BROGRE: Dude, I was asking BROGRE: DUDE shut up, can we watch it with you?! """ }, { text: """ Can the Ogre(s) join you? """ options: [ "Sure, grab a chair" "Sorry, it's kind of a goblins only thing..." ] event: "brogre" }] else convo = [{ text: """ BROGRE: So what do you say, can we borrow some salt? """ }, { text: """ MARCO: Sorry, I don't think we have any salt... """ selectedOption: 1 event: "brogre" }] showConversation convo , 0 brogre: (dialog) -> setSteveConversation [{ text: """ STEVE: Man I really want this job to work out... After I lost all that money in the stock market this is pretty much all I have left... """ }, { text: """ STEVE: And <NAME> said she's going to leave me if I don't start pulling off the bacon... """ }, { text: """ <NAME>: I think the expression you're looking for is "jerkin' off the pig" """ }, { text: """ STEVE: Yeah, like I was saying <NAME>'s going to leave me if I don't start jerkin' off the pig... I'm not so sure that's right either... """ event: "wiz" }, { text: """ A fire wizard wanders in. """ }, { text: """ THE WIZ: Don't all get up at once now. """ }] if dialog.I.selectedOption is 0 map.characters[2].I.x = 7 map.characters[2].I.y = 4 map.characters[2].I.conversation = [ text: """ BROGRE: Quiet I'm wa... BROGRE: SHUT UP BOTH OF YOU I'm wat... BROGRE: That's what I was saying! BROGRE: You made me miss my favorite part! """ ] setMarcoConversation [{ text: """ MARCO: Why is that ogre sitting on our lunch table? """ }] else setMarcoConversation [{ text: """ MARCO: Did you catch the game last night? """ options: [ "You know it buddy!" "Sorry, not really a fan..." ] }] setTimeout -> showConversation [{ text: """ BROGRE: Oh, I get it... looks like you guys have something planned (glances at KNIGHT JR) """ }, { text: """ BROGRE: We'll leave you to it... BROGRE: PEACE! """ event: -> map.characters[2].I.x = -1 }] , 0 round2: -> map.characters[2].I.x = 9 map.characters[2].I.y = 7 setMarcoConversation [{ text: """ MARCO: Go ask them what they wants. """ }] berserker: -> unless map.characters[6].I.x is 9 setTimeout -> map.characters[6].I.x = 9 map.characters[6].I.y = 8 showConversation [{ text: """ A wild AXE MANIAC appears! He looks like he's starving. """ }] , 0 butcher: -> map.characters[1].I.y = -1 map.addItem name: "Splat" url: "http://2.pixiecdn.com/sprites/131854/original." x: 9 y: 3 conversation: [{ text: """ That's a lot of blood. """ }] satiated: -> map.characters[6].I.conversation = [{ text: """ AXE MANIAC: Ahh, that reall hits the spot! """ }, { text: """ AXE MANIAC: Get in my greased bag of holding? """ }, { text: """ YOU: Are you coming on to me? """ event: -> if map.characters[3].I.x is 7 and map.characters[3].I.y is 7 setTimeout -> showConversation [{ text: """ KNIGHT JR is no longer confused. """ event: -> map.characters[3].I.x = 8 }, { text: """ KNIGHT JR flees in terror! """ event: -> map.characters[3].I.x = 9 }, { text: """ KNIGHT JR runs for the door. KNIGHT JRs CURSED -1 SPIKED HELMET punctures AXE MANIAC's greased scrotum! """ event: -> map.addItem name: "<NAME>" url: "http://2.pixiecdn.com/sprites/131854/original." x: 9 y: 8 conversation: [{ text: """ That's a lot of blood. """ }] map.characters[3].I.y = 9 }, { text: """ KNIGHT JR flees down the hallway! """ event: -> map.characters[3].I.y = 10 }, { text: """ A trapdoor in the ceiling opens and a rock falls on your KNIGHT JR's head! """ event: -> map.characters[3].I.y = -1 map.updateItem "Trap", x: -1 y: -1 map.updateItem "Knight Jr Carcass", x: 9 y: 11 }] , 0 map.characters[6].I.conversation = [{ text: "AXE MANIAC: Oww, my delicate scrotum!" }, { text: """ AXE MANIAC bleeds to death. """ }, { text: """ A tombstone appears out of nowhere! it reads... """ }, { text: """ Here lies AXE MANIAC... He died as he lived greased up and covered in blood. """ event: -> map.characters[6].I.x = -1 }] else map.characters[6].I.conversation = [{ text: """ AXE MANIAC butchers YOU AXE MANIAC picks up 17kg of GOBLIN MEAT """ }, { text: """ At least you'll make a delicious sandwich... """ }, { text: """ Better luck next time! """ event: "restart" }] }] carco: -> if hasElixir setTimeout -> showConversation [{ text: """ Maybe that fizzy liquid could help this kid... """ options: [ "Give the kid some water" "Leave him be" ] event: -> reviveKnightJr() if dialog.I.selectedOption is 0 }] , 0 knightJr: -> openDoor() map.characters[3].I.x = 9 map.characters[3].I.y = 8 if dieHardPlaying stevesText = """ STEVE: Holy shit man, we're kind of in the middle of this movie. """ else stevesText = """ STEVE: Who let you in here? """ setTimeout -> showConversation [{ text: """ **CRASH** A wild kid wearing a knight costume appears! """ }, { text: "KNIGHT JR: Prepare to die SCUM!" }, { text: stevesText }, { text: """ KNIGHT JR hits STEVE with his +1 SHORT SWORD """ }, { text: """ STEVE: You son of a bitch! That stings like a motherfucker! """ }, { text: """ MARCO throws his -1 BEER CAN OF DEPRESSION at KNIGHT JR The BEER CAN misses """ }, { text: "What do you do?" options: [ "ATTACK!" "Defend" ] event: (dialog) -> if dialog.I.selectedOption is 0 action = text: """ You hit KNIGHT JR with your FIST """ else action = text: """ You cower behind MARCO """ dialogs.unshift Dialog action }, { text: """ STEVE hits KNIGHT JR with his TARNISHED EMPLOYEE OF THE MONTH TROPHY It's super effective! """ }, { text: """ KNIGHT JR was knocked unconscious. """ event: -> map.updateItem "Knight Jr Carcass", x: 9 map.characters[3].I.x = -1 # Update dialogs for STEVE, MARCO, KNIGHT JR convo = [{ text: """ STEVE: I can't believe that just happened. I think I need an ice pack. """ }, { text: """ <NAME>ARCO: And that's why they made you employee of the month! """ }, { text: """ STEVE: Do me a solid and drag that CARCASS out of the doorway """ }, { text: """ MARCO drags KNIGHT JR into the corner. """ event: -> map.updateItem "Knight Jr Carcass", x: 7 setSteveConversation [{ text: """ STEVE: Any news on that ice pack DUDER? """ }] setMarcoConversation [{ text: """ <NAME>ARCO: Never a dull moment, eh DUDER? """ event: "round2" }, { text: """ A two headed ogre walks through the open door. """ }] }] setSteveConversation convo setMarcoConversation convo }] , 0 wiz: -> map.characters[5].I.x = 9 setSteveConversation [ text: """ STEVE: Gawd, another asshole... """ ] setMarcoConversation [ text: """ MARCO: I'm getting too old for this shit. """ ] fire: -> map.characters[0].I.x = -1 map.updateItem "TV", x: -1 map.updateItem "Table", x: -1 map.updateItem "Crate", x: -1 ashURLs =[ "http://1.pixiecdn.com/sprites/131845/original." "http://2.pixiecdn.com/sprites/131846/original." "http://1.pixiecdn.com/sprites/131849/original." "http://2.pixiecdn.com/sprites/131846/original." ] [[9, 2], [8, 3], [7, 4], [10, 5]].forEach ([x, y]) -> map.addItem name: "<NAME>" x: x y: y url: ashURLs conversation: [ text: """ It's a pile of smoldering ash. """ ] if map.characters[2].I.x is 7 setTimeout -> showConversation [{ text: """ The death of TV has enraged BROGRE! """ }, { text: """ <NAME> hits(x2) THE WIZ for 418 DMG """ }, { text: """ THE WIZ dies! """ event: -> map.characters[5].I.x = -1 map.addItem name: "<NAME>" x: 9 y: 8 url: ashURLs conversation: [{ text: """ It's the smoldering remains of THE WIZ. """ }] }, { text: """ <NAME> runs down the hall in a furious rage! """ event: -> map.characters[3].I.conversation = [ text: """ KNIGHT JR: Huh... did I miss something? """ event: "<NAME>" ] setMarcoConversation [ text: """ MARCO: STEVE's dead man... """ event: "berserker" ] map.characters[2].I.x = -1 }] , 0 else map.characters[5].I.conversation = [{ text: """ THE WIZ: Are you here to beg for the sweet release of death? """ options: ["Yes", "No"] }, { text: """ THE WIZ: BURN! """ }, { text: """ You burn. """ }, { text: """ Better luck next time! """ event: "restart" }] setTimeout -> showConversation [{ text: """ THE WIZ: I got more where that come from holms! """ }] , 0 tv1: (dialog) -> return unless dialog.I.selectedOption is 0 dieHardPlaying = true map.replaceItem 0, name: "TV" url: [ "http://2.pixiecdn.com/sprites/131830/original." "http://3.pixiecdn.com/sprites/131831/original." "http://2.pixiecdn.com/sprites/131830/original." "http://3.pixiecdn.com/sprites/131831/original." "http://1.pixiecdn.com/sprites/131829/original." ] font: "italic bold 20px monospace" conversation: [{ text: """ <NAME>: You know my name but who are you? Just another American who saw too many movies as a child? Another orphan of a bankrupt culture who thinks he's <NAME>? <NAME>? <NAME>? """ }, { text: """ <NAME>: Was always kinda partial to <NAME> <NAME> actually. I really like those sequined shirts. """ }, { text: """ <NAME>: Do you really think you have a chance against us, Mr. <NAME>? """ }, { text: """ <NAME>: Yippee-ki-yay, motherfucker. """ }] keyHandler = (e) -> e.preventDefault() switch e.keyCode when 13, 32 if dialog if dialog.finished() dialog.event?(dialog) events[dialog.event]?(dialog) dialog = dialogs.shift() else dialog.I.age += 100 else map.interact player.I when 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 ;# console.log e.keyCode - 48 when 37 # Left move x: -1, y: 0 when 38 # Up move x: 0, y: -1 when 39 # Right move x: 1, y: 0 when 40 # Down move x: 0, y: 1 document.addEventListener('keydown', keyHandler, false) global.showDialog = (newDialog) -> dialog = Dialog newDialog global.showConversation = (conversation) -> dialogs = conversation.map (convo) -> Dialog convo dialog = dialogs.shift() map = require("./map")() player = require("./player") url: "http://1.pixiecdn.com/sprites/131785/original." showConversation [{ text: """ Walk around and interact with stuff by pressing the ARROW KEYS and SPACE BAR Or not, it's up to you! """ }, { text: """ Got it? """ options: [ "YEAH!" "Whatever" ] }] update = (dt) -> map.update(dt) player.update(dt) dialog?.update(dt) draw = (canvas) -> map.draw(canvas) player.draw(canvas) dialog?.draw(canvas) dt = 1/60 t = 0 step = (timestamp) -> update(dt) draw(canvas) t += dt window.requestAnimationFrame step window.requestAnimationFrame step
true
# Canvas where we draw our duders # Text box where we display dialog # Options to choose from # Moving around # Triggered events # Die Hard Quotes http://www.imdb.com/title/tt0095016/quotes # Wall Sprites # Chair Sprites # TV Sprites # Goblin Sprites # Ogre Sprites # Hero Sprites # 3 Goblins sitting in a room in a dungeon # Chillin, watching Die Hard # Adevnturers come in and try to wreck up the place # Lvl 1 Cleric # Goblins kill the poor bastard # A two headed ogre want's to borrow some rock salt to add to Bud LightTM # Lime-A-Ritas # The ogre also wants to stay and watch die hard # YOU DECIDE # Lvl 4 Fighter # Talking to Steve # STEVE: "Remember that project I was really excited about... well BOSS says I # Shouldn't work on it any more... so forget it." # There is a chest in the room, if you try to open it steve says: Boss told us # not to mess into that. # Chest contians healing elixir and broken cassette tape # They don't keep the Hard-A in Lvl 1 loot tables # Wait, so do we work here, or is this the break room, because I've always # thought it was the break room... That Craig's List add wasn't very specific # - Steve # There is a rock trap if you try to leave the room # Steve will say: Boss says to stay in here # The rock trap will kill you # Achievements: # Die Hard: With a Vengance - Watch all of Die Hard # Hard Hat Warning - Died to a rock trap # A Winner is You - Survived all Encounters # OGRE: "This is our house!" # OGRE: "You're going DOWN scrote sac!" # YOU: "So is a scrote sac like a scrotum, or a sack of scrotums?" # Ogre kills fighter # Lvl 7 Gladiator # Axe rends PI:NAME:<NAME>END_PI in twain # CARL: "PI:NAME:<NAME>END_PI's dead man..." # Carl doesn't speak for the rest of the game, sits in the corner '...' # After the gladiator encounter the rock trap will be trigered and you can # go out and find another room with some swank loot (wand of death). # Lvl 10 Thief # Use wand of death to kill thief # Lvl 13 mage # Burns the place to shit # Hell Spawn then enters and kills Mage # Grab orb of Zot # Show orb to Ogre # Ogre drops it and it shatters # Messenger comes to tell PI:NAME:<NAME>END_PI that his project is back on! # PI:NAME:<NAME>END_PI's dead man... # G_G require "cornerstone" TouchCanvas = require "touch-canvas" {width, height} = require "./pixie" style = document.createElement "style" style.innerText = """ * { box-sizing: border-box; } html, body { background-color: black; margin: 0; padding: 0; overflow: hidden; } canvas { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } """ document.head.appendChild style canvas = TouchCanvas width: width height: height document.body.appendChild canvas.element() Dialog = require("./dialog") dialog = null dialogs = [] move = (p) -> if dialog dialog.move p else player.move p, map dieHardPlaying = false hasElixir = false emptyCrate = -> hasElixir = true map.updateItem "Crate", conversation: [ text: """ It's empty. """ ] activateCrate = -> map.updateItem "Crate", conversation: [{ text: """ You found a bottle of fizzy liquid and a handful of rusted old bottle caps. """ event: emptyCrate }, { text: """ STEVE: Sorry to dissapoint, but they don't keep any HARD-A around here. """ }] setSteveConversation = (conversation) -> map.characters[0].I.conversation = conversation setMarcoConversation = (conversation) -> map.characters[1].I.conversation = conversation openDoor = -> map.characters[4].I.x = -1 map.map[8][9] = "2" map.map[9][9] = "2" map.map[10][9] = "2" map.map[11][9] = "2" map.map[12][9] = "2" map.map[13][9] = "2" map.map[14][9] = "2" reviveKnightJr = -> hasElixir = false map.characters[3].I.x = 7 map.characters[3].I.y = 7 map.characters[3].I.conversation = [ text: """ KNIGHT JR: I think I'll just sit here a for a bit. """ ] map.updateItem "Knight Jr Carcass", x: -1 y: -1 events = restart: -> location.reload() crate: (dialog) -> if dialog.I.selectedOption is 0 activateCrate() else map.updateItem "Crate", conversation: [ text: """ MARCO: Jeez man, what's your fascination with that crate? """ event: activateCrate ] door: openDoor brogre0: -> setTimeout -> if dieHardPlaying convo = [{ text: """ BROGRE: So what do you say, can we borrow... BROGRE: OH SHIT! Are you guys watching DIE HARD!? BROGRE: Dude, I was asking BROGRE: DUDE shut up, can we watch it with you?! """ }, { text: """ Can the Ogre(s) join you? """ options: [ "Sure, grab a chair" "Sorry, it's kind of a goblins only thing..." ] event: "brogre" }] else convo = [{ text: """ BROGRE: So what do you say, can we borrow some salt? """ }, { text: """ MARCO: Sorry, I don't think we have any salt... """ selectedOption: 1 event: "brogre" }] showConversation convo , 0 brogre: (dialog) -> setSteveConversation [{ text: """ STEVE: Man I really want this job to work out... After I lost all that money in the stock market this is pretty much all I have left... """ }, { text: """ STEVE: And PI:NAME:<NAME>END_PI said she's going to leave me if I don't start pulling off the bacon... """ }, { text: """ PI:NAME:<NAME>END_PI: I think the expression you're looking for is "jerkin' off the pig" """ }, { text: """ STEVE: Yeah, like I was saying PI:NAME:<NAME>END_PI's going to leave me if I don't start jerkin' off the pig... I'm not so sure that's right either... """ event: "wiz" }, { text: """ A fire wizard wanders in. """ }, { text: """ THE WIZ: Don't all get up at once now. """ }] if dialog.I.selectedOption is 0 map.characters[2].I.x = 7 map.characters[2].I.y = 4 map.characters[2].I.conversation = [ text: """ BROGRE: Quiet I'm wa... BROGRE: SHUT UP BOTH OF YOU I'm wat... BROGRE: That's what I was saying! BROGRE: You made me miss my favorite part! """ ] setMarcoConversation [{ text: """ MARCO: Why is that ogre sitting on our lunch table? """ }] else setMarcoConversation [{ text: """ MARCO: Did you catch the game last night? """ options: [ "You know it buddy!" "Sorry, not really a fan..." ] }] setTimeout -> showConversation [{ text: """ BROGRE: Oh, I get it... looks like you guys have something planned (glances at KNIGHT JR) """ }, { text: """ BROGRE: We'll leave you to it... BROGRE: PEACE! """ event: -> map.characters[2].I.x = -1 }] , 0 round2: -> map.characters[2].I.x = 9 map.characters[2].I.y = 7 setMarcoConversation [{ text: """ MARCO: Go ask them what they wants. """ }] berserker: -> unless map.characters[6].I.x is 9 setTimeout -> map.characters[6].I.x = 9 map.characters[6].I.y = 8 showConversation [{ text: """ A wild AXE MANIAC appears! He looks like he's starving. """ }] , 0 butcher: -> map.characters[1].I.y = -1 map.addItem name: "Splat" url: "http://2.pixiecdn.com/sprites/131854/original." x: 9 y: 3 conversation: [{ text: """ That's a lot of blood. """ }] satiated: -> map.characters[6].I.conversation = [{ text: """ AXE MANIAC: Ahh, that reall hits the spot! """ }, { text: """ AXE MANIAC: Get in my greased bag of holding? """ }, { text: """ YOU: Are you coming on to me? """ event: -> if map.characters[3].I.x is 7 and map.characters[3].I.y is 7 setTimeout -> showConversation [{ text: """ KNIGHT JR is no longer confused. """ event: -> map.characters[3].I.x = 8 }, { text: """ KNIGHT JR flees in terror! """ event: -> map.characters[3].I.x = 9 }, { text: """ KNIGHT JR runs for the door. KNIGHT JRs CURSED -1 SPIKED HELMET punctures AXE MANIAC's greased scrotum! """ event: -> map.addItem name: "PI:NAME:<NAME>END_PI" url: "http://2.pixiecdn.com/sprites/131854/original." x: 9 y: 8 conversation: [{ text: """ That's a lot of blood. """ }] map.characters[3].I.y = 9 }, { text: """ KNIGHT JR flees down the hallway! """ event: -> map.characters[3].I.y = 10 }, { text: """ A trapdoor in the ceiling opens and a rock falls on your KNIGHT JR's head! """ event: -> map.characters[3].I.y = -1 map.updateItem "Trap", x: -1 y: -1 map.updateItem "Knight Jr Carcass", x: 9 y: 11 }] , 0 map.characters[6].I.conversation = [{ text: "AXE MANIAC: Oww, my delicate scrotum!" }, { text: """ AXE MANIAC bleeds to death. """ }, { text: """ A tombstone appears out of nowhere! it reads... """ }, { text: """ Here lies AXE MANIAC... He died as he lived greased up and covered in blood. """ event: -> map.characters[6].I.x = -1 }] else map.characters[6].I.conversation = [{ text: """ AXE MANIAC butchers YOU AXE MANIAC picks up 17kg of GOBLIN MEAT """ }, { text: """ At least you'll make a delicious sandwich... """ }, { text: """ Better luck next time! """ event: "restart" }] }] carco: -> if hasElixir setTimeout -> showConversation [{ text: """ Maybe that fizzy liquid could help this kid... """ options: [ "Give the kid some water" "Leave him be" ] event: -> reviveKnightJr() if dialog.I.selectedOption is 0 }] , 0 knightJr: -> openDoor() map.characters[3].I.x = 9 map.characters[3].I.y = 8 if dieHardPlaying stevesText = """ STEVE: Holy shit man, we're kind of in the middle of this movie. """ else stevesText = """ STEVE: Who let you in here? """ setTimeout -> showConversation [{ text: """ **CRASH** A wild kid wearing a knight costume appears! """ }, { text: "KNIGHT JR: Prepare to die SCUM!" }, { text: stevesText }, { text: """ KNIGHT JR hits STEVE with his +1 SHORT SWORD """ }, { text: """ STEVE: You son of a bitch! That stings like a motherfucker! """ }, { text: """ MARCO throws his -1 BEER CAN OF DEPRESSION at KNIGHT JR The BEER CAN misses """ }, { text: "What do you do?" options: [ "ATTACK!" "Defend" ] event: (dialog) -> if dialog.I.selectedOption is 0 action = text: """ You hit KNIGHT JR with your FIST """ else action = text: """ You cower behind MARCO """ dialogs.unshift Dialog action }, { text: """ STEVE hits KNIGHT JR with his TARNISHED EMPLOYEE OF THE MONTH TROPHY It's super effective! """ }, { text: """ KNIGHT JR was knocked unconscious. """ event: -> map.updateItem "Knight Jr Carcass", x: 9 map.characters[3].I.x = -1 # Update dialogs for STEVE, MARCO, KNIGHT JR convo = [{ text: """ STEVE: I can't believe that just happened. I think I need an ice pack. """ }, { text: """ PI:NAME:<NAME>END_PIARCO: And that's why they made you employee of the month! """ }, { text: """ STEVE: Do me a solid and drag that CARCASS out of the doorway """ }, { text: """ MARCO drags KNIGHT JR into the corner. """ event: -> map.updateItem "Knight Jr Carcass", x: 7 setSteveConversation [{ text: """ STEVE: Any news on that ice pack DUDER? """ }] setMarcoConversation [{ text: """ PI:NAME:<NAME>END_PIARCO: Never a dull moment, eh DUDER? """ event: "round2" }, { text: """ A two headed ogre walks through the open door. """ }] }] setSteveConversation convo setMarcoConversation convo }] , 0 wiz: -> map.characters[5].I.x = 9 setSteveConversation [ text: """ STEVE: Gawd, another asshole... """ ] setMarcoConversation [ text: """ MARCO: I'm getting too old for this shit. """ ] fire: -> map.characters[0].I.x = -1 map.updateItem "TV", x: -1 map.updateItem "Table", x: -1 map.updateItem "Crate", x: -1 ashURLs =[ "http://1.pixiecdn.com/sprites/131845/original." "http://2.pixiecdn.com/sprites/131846/original." "http://1.pixiecdn.com/sprites/131849/original." "http://2.pixiecdn.com/sprites/131846/original." ] [[9, 2], [8, 3], [7, 4], [10, 5]].forEach ([x, y]) -> map.addItem name: "PI:NAME:<NAME>END_PI" x: x y: y url: ashURLs conversation: [ text: """ It's a pile of smoldering ash. """ ] if map.characters[2].I.x is 7 setTimeout -> showConversation [{ text: """ The death of TV has enraged BROGRE! """ }, { text: """ PI:NAME:<NAME>END_PI hits(x2) THE WIZ for 418 DMG """ }, { text: """ THE WIZ dies! """ event: -> map.characters[5].I.x = -1 map.addItem name: "PI:NAME:<NAME>END_PI" x: 9 y: 8 url: ashURLs conversation: [{ text: """ It's the smoldering remains of THE WIZ. """ }] }, { text: """ PI:NAME:<NAME>END_PI runs down the hall in a furious rage! """ event: -> map.characters[3].I.conversation = [ text: """ KNIGHT JR: Huh... did I miss something? """ event: "PI:NAME:<NAME>END_PI" ] setMarcoConversation [ text: """ MARCO: STEVE's dead man... """ event: "berserker" ] map.characters[2].I.x = -1 }] , 0 else map.characters[5].I.conversation = [{ text: """ THE WIZ: Are you here to beg for the sweet release of death? """ options: ["Yes", "No"] }, { text: """ THE WIZ: BURN! """ }, { text: """ You burn. """ }, { text: """ Better luck next time! """ event: "restart" }] setTimeout -> showConversation [{ text: """ THE WIZ: I got more where that come from holms! """ }] , 0 tv1: (dialog) -> return unless dialog.I.selectedOption is 0 dieHardPlaying = true map.replaceItem 0, name: "TV" url: [ "http://2.pixiecdn.com/sprites/131830/original." "http://3.pixiecdn.com/sprites/131831/original." "http://2.pixiecdn.com/sprites/131830/original." "http://3.pixiecdn.com/sprites/131831/original." "http://1.pixiecdn.com/sprites/131829/original." ] font: "italic bold 20px monospace" conversation: [{ text: """ PI:NAME:<NAME>END_PI: You know my name but who are you? Just another American who saw too many movies as a child? Another orphan of a bankrupt culture who thinks he's PI:NAME:<NAME>END_PI? PI:NAME:<NAME>END_PI? PI:NAME:<NAME>END_PI? """ }, { text: """ PI:NAME:<NAME>END_PI: Was always kinda partial to PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI actually. I really like those sequined shirts. """ }, { text: """ PI:NAME:<NAME>END_PI: Do you really think you have a chance against us, Mr. PI:NAME:<NAME>END_PI? """ }, { text: """ PI:NAME:<NAME>END_PI: Yippee-ki-yay, motherfucker. """ }] keyHandler = (e) -> e.preventDefault() switch e.keyCode when 13, 32 if dialog if dialog.finished() dialog.event?(dialog) events[dialog.event]?(dialog) dialog = dialogs.shift() else dialog.I.age += 100 else map.interact player.I when 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 ;# console.log e.keyCode - 48 when 37 # Left move x: -1, y: 0 when 38 # Up move x: 0, y: -1 when 39 # Right move x: 1, y: 0 when 40 # Down move x: 0, y: 1 document.addEventListener('keydown', keyHandler, false) global.showDialog = (newDialog) -> dialog = Dialog newDialog global.showConversation = (conversation) -> dialogs = conversation.map (convo) -> Dialog convo dialog = dialogs.shift() map = require("./map")() player = require("./player") url: "http://1.pixiecdn.com/sprites/131785/original." showConversation [{ text: """ Walk around and interact with stuff by pressing the ARROW KEYS and SPACE BAR Or not, it's up to you! """ }, { text: """ Got it? """ options: [ "YEAH!" "Whatever" ] }] update = (dt) -> map.update(dt) player.update(dt) dialog?.update(dt) draw = (canvas) -> map.draw(canvas) player.draw(canvas) dialog?.draw(canvas) dt = 1/60 t = 0 step = (timestamp) -> update(dt) draw(canvas) t += dt window.requestAnimationFrame step window.requestAnimationFrame step
[ { "context": "force that all class methods use 'this'.\n# @author Patrick Williams\n###\n\n'use strict'\n\n#-----------------------------", "end": 98, "score": 0.9996808767318726, "start": 82, "tag": "NAME", "value": "Patrick Williams" } ]
src/rules/class-methods-use-this.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to enforce that all class methods use 'this'. # @author Patrick Williams ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce that class methods utilize `this`' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/class-methods-use-this' schema: [ type: 'object' properties: exceptMethods: type: 'array' items: type: 'string' additionalProperties: no ] messages: missingThis: "Expected 'this' to be used by class method '{{name}}'." create: (context) -> config = if context.options[0] then {...context.options[0]} else {} exceptMethods = new Set config.exceptMethods or [] stack = [] ###* # Check if the node is an instance method # @param {ASTNode} node - node to check # @returns {boolean} True if its an instance method # @private ### isInstanceMethod = (node) -> not node.static and node.kind isnt 'constructor' and node.type is 'MethodDefinition' ###* # Initializes the current context to false and pushes it onto the stack. # These booleans represent whether 'this' has been used in the context. # @returns {void} # @private ### enterFunction = (node) -> return if not isInstanceMethod(node) and node.bound stack.push no ###* # Check if the node is an instance method not excluded by config # @param {ASTNode} node - node to check # @returns {boolean} True if it is an instance method, and not excluded by config # @private ### isIncludedInstanceMethod = (node) -> isInstanceMethod(node) and not exceptMethods.has node.key.name ###* # Checks if we are leaving a function that is a method, and reports if 'this' has not been used. # Static methods and the constructor are exempt. # Then pops the context off the stack. # @param {ASTNode} node - A function node that was entered. # @returns {void} # @private ### exitFunction = (node) -> return if not isInstanceMethod(node) and node.bound methodUsesThis = stack.pop() if isIncludedInstanceMethod(node.parent) and not methodUsesThis context.report { node messageId: 'missingThis' data: name: node.parent.key.name } ###* # Mark the current context as having used 'this'. # @returns {void} # @private ### markThisUsed = -> if stack.length then stack[stack.length - 1] = yes FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction ThisExpression: markThisUsed Super: markThisUsed
120720
###* # @fileoverview Rule to enforce that all class methods use 'this'. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce that class methods utilize `this`' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/class-methods-use-this' schema: [ type: 'object' properties: exceptMethods: type: 'array' items: type: 'string' additionalProperties: no ] messages: missingThis: "Expected 'this' to be used by class method '{{name}}'." create: (context) -> config = if context.options[0] then {...context.options[0]} else {} exceptMethods = new Set config.exceptMethods or [] stack = [] ###* # Check if the node is an instance method # @param {ASTNode} node - node to check # @returns {boolean} True if its an instance method # @private ### isInstanceMethod = (node) -> not node.static and node.kind isnt 'constructor' and node.type is 'MethodDefinition' ###* # Initializes the current context to false and pushes it onto the stack. # These booleans represent whether 'this' has been used in the context. # @returns {void} # @private ### enterFunction = (node) -> return if not isInstanceMethod(node) and node.bound stack.push no ###* # Check if the node is an instance method not excluded by config # @param {ASTNode} node - node to check # @returns {boolean} True if it is an instance method, and not excluded by config # @private ### isIncludedInstanceMethod = (node) -> isInstanceMethod(node) and not exceptMethods.has node.key.name ###* # Checks if we are leaving a function that is a method, and reports if 'this' has not been used. # Static methods and the constructor are exempt. # Then pops the context off the stack. # @param {ASTNode} node - A function node that was entered. # @returns {void} # @private ### exitFunction = (node) -> return if not isInstanceMethod(node) and node.bound methodUsesThis = stack.pop() if isIncludedInstanceMethod(node.parent) and not methodUsesThis context.report { node messageId: 'missingThis' data: name: node.parent.key.name } ###* # Mark the current context as having used 'this'. # @returns {void} # @private ### markThisUsed = -> if stack.length then stack[stack.length - 1] = yes FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction ThisExpression: markThisUsed Super: markThisUsed
true
###* # @fileoverview Rule to enforce that all class methods use 'this'. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce that class methods utilize `this`' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/class-methods-use-this' schema: [ type: 'object' properties: exceptMethods: type: 'array' items: type: 'string' additionalProperties: no ] messages: missingThis: "Expected 'this' to be used by class method '{{name}}'." create: (context) -> config = if context.options[0] then {...context.options[0]} else {} exceptMethods = new Set config.exceptMethods or [] stack = [] ###* # Check if the node is an instance method # @param {ASTNode} node - node to check # @returns {boolean} True if its an instance method # @private ### isInstanceMethod = (node) -> not node.static and node.kind isnt 'constructor' and node.type is 'MethodDefinition' ###* # Initializes the current context to false and pushes it onto the stack. # These booleans represent whether 'this' has been used in the context. # @returns {void} # @private ### enterFunction = (node) -> return if not isInstanceMethod(node) and node.bound stack.push no ###* # Check if the node is an instance method not excluded by config # @param {ASTNode} node - node to check # @returns {boolean} True if it is an instance method, and not excluded by config # @private ### isIncludedInstanceMethod = (node) -> isInstanceMethod(node) and not exceptMethods.has node.key.name ###* # Checks if we are leaving a function that is a method, and reports if 'this' has not been used. # Static methods and the constructor are exempt. # Then pops the context off the stack. # @param {ASTNode} node - A function node that was entered. # @returns {void} # @private ### exitFunction = (node) -> return if not isInstanceMethod(node) and node.bound methodUsesThis = stack.pop() if isIncludedInstanceMethod(node.parent) and not methodUsesThis context.report { node messageId: 'missingThis' data: name: node.parent.key.name } ###* # Mark the current context as having used 'this'. # @returns {void} # @private ### markThisUsed = -> if stack.length then stack[stack.length - 1] = yes FunctionDeclaration: enterFunction 'FunctionDeclaration:exit': exitFunction FunctionExpression: enterFunction 'FunctionExpression:exit': exitFunction ThisExpression: markThisUsed Super: markThisUsed
[ { "context": ": 444}\n {use: 'work', system: 'email', value: 'a@b.com'}\n ]\n communication: [\n {language: {coding: ", "end": 326, "score": 0.9996395111083984, "start": 319, "tag": "EMAIL", "value": "a@b.com" }, { "context": " 'ContactPoint'\n result: ['444', 'phone|444',...
test/fhir/search_token_spec.coffee
micabe/fhirbase
0
search = require('../../src/fhir/search_token') test = require('../helpers.coffee') assert = require('assert') resource = active: true gender: 'male' type: code: 'ups' system: 'dups' text: 'hops' telecom: [ {use: 'home', system: 'phone', value: 444} {use: 'work', system: 'email', value: 'a@b.com'} ] communication: [ {language: {coding: [{code: 'us', system: 'lang'}, {code: 'en', system: 'world'}]}} ] provider: reference: 'Provider/1' identifier: [ {system: 'ssn', value: '1'} {system: 'mrn', value: '2'} ] value: value: 10 unit: "mg" system: "http://unitsofmeasure.org" code: "[mg]" specs = [ { path: ['Resource', 'active'] elementType: 'boolean' result: ['true'] order: 'true' } { path: ['Resource', 'identifier'] elementType: 'Identifier' result: ['1', 'ssn|1', '2', 'mrn|2'] order: 'ssn01' } { path: ['Resource', 'gender'] elementType: 'code' result: ['male'] order: 'male' } { path: ['Resource', 'gender'] elementType: 'string' result: ['male'] order: 'male' } { path: ['Resource', 'type'] elementType: 'Coding' result: ['ups', 'dups|ups'] order: 'dups0ups0' } { path: ['Resource', 'communication', 'language'] elementType: 'CodeableConcept' result: ['us', 'lang|us', 'en', 'world|en'] order: 'lang0us0' } { path: ['Resource', 'provider'] elementType: 'Reference' result: ['Provider/1'] order: 'Provider/1' } { path: ['Resource', 'telecom'] elementType: 'ContactPoint' result: ['444', 'phone|444', 'a@b.com', 'email|a@b.com'] order: 'phone0444' } { path: ['Resource', 'value'] elementType: 'Quantity' result: ['[mg]', 'mg', 'http://unitsofmeasure.org|[mg]', 'http://unitsofmeasure.org|mg'] order: 'http://unitsofmeasure.org0mg0[mg]' } ] describe "extract_as_token", -> specs.forEach (spec)-> it JSON.stringify(spec.path), -> metas = [ {path: ['Resource', 'unknownPath'], elementType: spec.elementType}, {path: spec.path, elementType: spec.elementType} ] res = search.fhir_extract_as_token({}, resource, metas) assert.deepEqual(res, spec.result) order = search.fhir_sort_as_token({}, resource, metas) assert.deepEqual(order, spec.order)
125846
search = require('../../src/fhir/search_token') test = require('../helpers.coffee') assert = require('assert') resource = active: true gender: 'male' type: code: 'ups' system: 'dups' text: 'hops' telecom: [ {use: 'home', system: 'phone', value: 444} {use: 'work', system: 'email', value: '<EMAIL>'} ] communication: [ {language: {coding: [{code: 'us', system: 'lang'}, {code: 'en', system: 'world'}]}} ] provider: reference: 'Provider/1' identifier: [ {system: 'ssn', value: '1'} {system: 'mrn', value: '2'} ] value: value: 10 unit: "mg" system: "http://unitsofmeasure.org" code: "[mg]" specs = [ { path: ['Resource', 'active'] elementType: 'boolean' result: ['true'] order: 'true' } { path: ['Resource', 'identifier'] elementType: 'Identifier' result: ['1', 'ssn|1', '2', 'mrn|2'] order: 'ssn01' } { path: ['Resource', 'gender'] elementType: 'code' result: ['male'] order: 'male' } { path: ['Resource', 'gender'] elementType: 'string' result: ['male'] order: 'male' } { path: ['Resource', 'type'] elementType: 'Coding' result: ['ups', 'dups|ups'] order: 'dups0ups0' } { path: ['Resource', 'communication', 'language'] elementType: 'CodeableConcept' result: ['us', 'lang|us', 'en', 'world|en'] order: 'lang0us0' } { path: ['Resource', 'provider'] elementType: 'Reference' result: ['Provider/1'] order: 'Provider/1' } { path: ['Resource', 'telecom'] elementType: 'ContactPoint' result: ['444', 'phone|444', '<EMAIL>', 'email|<EMAIL>'] order: 'phone0444' } { path: ['Resource', 'value'] elementType: 'Quantity' result: ['[mg]', 'mg', 'http://unitsofmeasure.org|[mg]', 'http://unitsofmeasure.org|mg'] order: 'http://unitsofmeasure.org0mg0[mg]' } ] describe "extract_as_token", -> specs.forEach (spec)-> it JSON.stringify(spec.path), -> metas = [ {path: ['Resource', 'unknownPath'], elementType: spec.elementType}, {path: spec.path, elementType: spec.elementType} ] res = search.fhir_extract_as_token({}, resource, metas) assert.deepEqual(res, spec.result) order = search.fhir_sort_as_token({}, resource, metas) assert.deepEqual(order, spec.order)
true
search = require('../../src/fhir/search_token') test = require('../helpers.coffee') assert = require('assert') resource = active: true gender: 'male' type: code: 'ups' system: 'dups' text: 'hops' telecom: [ {use: 'home', system: 'phone', value: 444} {use: 'work', system: 'email', value: 'PI:EMAIL:<EMAIL>END_PI'} ] communication: [ {language: {coding: [{code: 'us', system: 'lang'}, {code: 'en', system: 'world'}]}} ] provider: reference: 'Provider/1' identifier: [ {system: 'ssn', value: '1'} {system: 'mrn', value: '2'} ] value: value: 10 unit: "mg" system: "http://unitsofmeasure.org" code: "[mg]" specs = [ { path: ['Resource', 'active'] elementType: 'boolean' result: ['true'] order: 'true' } { path: ['Resource', 'identifier'] elementType: 'Identifier' result: ['1', 'ssn|1', '2', 'mrn|2'] order: 'ssn01' } { path: ['Resource', 'gender'] elementType: 'code' result: ['male'] order: 'male' } { path: ['Resource', 'gender'] elementType: 'string' result: ['male'] order: 'male' } { path: ['Resource', 'type'] elementType: 'Coding' result: ['ups', 'dups|ups'] order: 'dups0ups0' } { path: ['Resource', 'communication', 'language'] elementType: 'CodeableConcept' result: ['us', 'lang|us', 'en', 'world|en'] order: 'lang0us0' } { path: ['Resource', 'provider'] elementType: 'Reference' result: ['Provider/1'] order: 'Provider/1' } { path: ['Resource', 'telecom'] elementType: 'ContactPoint' result: ['444', 'phone|444', 'PI:EMAIL:<EMAIL>END_PI', 'email|PI:EMAIL:<EMAIL>END_PI'] order: 'phone0444' } { path: ['Resource', 'value'] elementType: 'Quantity' result: ['[mg]', 'mg', 'http://unitsofmeasure.org|[mg]', 'http://unitsofmeasure.org|mg'] order: 'http://unitsofmeasure.org0mg0[mg]' } ] describe "extract_as_token", -> specs.forEach (spec)-> it JSON.stringify(spec.path), -> metas = [ {path: ['Resource', 'unknownPath'], elementType: spec.elementType}, {path: spec.path, elementType: spec.elementType} ] res = search.fhir_extract_as_token({}, resource, metas) assert.deepEqual(res, spec.result) order = search.fhir_sort_as_token({}, resource, metas) assert.deepEqual(order, spec.order)
[ { "context": "fig)\n .type 'form'\n .send\n login: config.username\n password: config.password\n .on 'erro", "end": 734, "score": 0.9797762036323547, "start": 719, "tag": "USERNAME", "value": "config.username" }, { "context": "d\n login: config.use...
plugins/youtrack-issues/index.coffee
jacobmarshall-etc/bugsnag-notification-plugins
0
NotificationPlugin = require "../../notification-plugin" Handlebars = require "handlebars" url = require "url" cookie = require "cookie" class YouTrack extends NotificationPlugin resolveUrl = (config, path) -> url.resolve config.url, path handleCookies = (res) -> res.headers['set-cookie'].map((item) -> parsed = cookie.parse item key = Object.keys(parsed)[0] cookie.serialize key, parsed[key], path: parsed.Path ).join '; ' loginUrl = (config) -> resolveUrl config, 'rest/user/login' ticketUrl = (config) -> resolveUrl config, 'rest/issue' @fetchToken = (config, callback) -> @request .post loginUrl(config) .type 'form' .send login: config.username password: config.password .on 'error', (err) -> callback err .end (res) -> return callback res.error if res.error return callback "401: Unable to login - please check your credentials" unless res.headers['set-cookie'] callback null, handleCookies res @createTicket = (config, event, token, callback) -> @request .put ticketUrl config .type 'form' # This isn't documented .set 'Cookie', token .query project: config.project summary: @title event description: @render event .on 'error', (err) -> callback err .end (res) -> return callback res.error if res.error callback null, url: res.header.location.replace("/rest/", "/") @receiveEvent = (config, event, callback) -> if event?.trigger?.type == "linkExistingIssue" return callback(null, null) @fetchToken config, (err, token) => return callback err if err # Unable to authenticate @createTicket config, event, token, callback @render = Handlebars.compile( """ == {{trigger.message}} in {{project.name}} == '''{{error.exceptionClass}}''' in '''{{error.context}}''' {{#if error.message}}{{error.message}}{{/if}} [View on Bugsnag|{{error.url}}] == Stacktrace == {html}<pre>{{#eachSummaryFrame error.stacktrace}} {{file}}:{{lineNumber}} - {{method}}{{/eachSummaryFrame}}</pre>{html} [View full stacktrace|{{error.url}}] """ ) module.exports = YouTrack
52133
NotificationPlugin = require "../../notification-plugin" Handlebars = require "handlebars" url = require "url" cookie = require "cookie" class YouTrack extends NotificationPlugin resolveUrl = (config, path) -> url.resolve config.url, path handleCookies = (res) -> res.headers['set-cookie'].map((item) -> parsed = cookie.parse item key = Object.keys(parsed)[0] cookie.serialize key, parsed[key], path: parsed.Path ).join '; ' loginUrl = (config) -> resolveUrl config, 'rest/user/login' ticketUrl = (config) -> resolveUrl config, 'rest/issue' @fetchToken = (config, callback) -> @request .post loginUrl(config) .type 'form' .send login: config.username password: <PASSWORD> .on 'error', (err) -> callback err .end (res) -> return callback res.error if res.error return callback "401: Unable to login - please check your credentials" unless res.headers['set-cookie'] callback null, handleCookies res @createTicket = (config, event, token, callback) -> @request .put ticketUrl config .type 'form' # This isn't documented .set 'Cookie', token .query project: config.project summary: @title event description: @render event .on 'error', (err) -> callback err .end (res) -> return callback res.error if res.error callback null, url: res.header.location.replace("/rest/", "/") @receiveEvent = (config, event, callback) -> if event?.trigger?.type == "linkExistingIssue" return callback(null, null) @fetchToken config, (err, token) => return callback err if err # Unable to authenticate @createTicket config, event, token, callback @render = Handlebars.compile( """ == {{trigger.message}} in {{project.name}} == '''{{error.exceptionClass}}''' in '''{{error.context}}''' {{#if error.message}}{{error.message}}{{/if}} [View on Bugsnag|{{error.url}}] == Stacktrace == {html}<pre>{{#eachSummaryFrame error.stacktrace}} {{file}}:{{lineNumber}} - {{method}}{{/eachSummaryFrame}}</pre>{html} [View full stacktrace|{{error.url}}] """ ) module.exports = YouTrack
true
NotificationPlugin = require "../../notification-plugin" Handlebars = require "handlebars" url = require "url" cookie = require "cookie" class YouTrack extends NotificationPlugin resolveUrl = (config, path) -> url.resolve config.url, path handleCookies = (res) -> res.headers['set-cookie'].map((item) -> parsed = cookie.parse item key = Object.keys(parsed)[0] cookie.serialize key, parsed[key], path: parsed.Path ).join '; ' loginUrl = (config) -> resolveUrl config, 'rest/user/login' ticketUrl = (config) -> resolveUrl config, 'rest/issue' @fetchToken = (config, callback) -> @request .post loginUrl(config) .type 'form' .send login: config.username password: PI:PASSWORD:<PASSWORD>END_PI .on 'error', (err) -> callback err .end (res) -> return callback res.error if res.error return callback "401: Unable to login - please check your credentials" unless res.headers['set-cookie'] callback null, handleCookies res @createTicket = (config, event, token, callback) -> @request .put ticketUrl config .type 'form' # This isn't documented .set 'Cookie', token .query project: config.project summary: @title event description: @render event .on 'error', (err) -> callback err .end (res) -> return callback res.error if res.error callback null, url: res.header.location.replace("/rest/", "/") @receiveEvent = (config, event, callback) -> if event?.trigger?.type == "linkExistingIssue" return callback(null, null) @fetchToken config, (err, token) => return callback err if err # Unable to authenticate @createTicket config, event, token, callback @render = Handlebars.compile( """ == {{trigger.message}} in {{project.name}} == '''{{error.exceptionClass}}''' in '''{{error.context}}''' {{#if error.message}}{{error.message}}{{/if}} [View on Bugsnag|{{error.url}}] == Stacktrace == {html}<pre>{{#eachSummaryFrame error.stacktrace}} {{file}}:{{lineNumber}} - {{method}}{{/eachSummaryFrame}}</pre>{html} [View full stacktrace|{{error.url}}] """ ) module.exports = YouTrack
[ { "context": "orts =\n keepResponseErrors: true\n admin: [\n 'admin@abc.com'\n ]\n oauth2:\n url:\n authorize: 'https:/", "end": 73, "score": 0.9999181628227234, "start": 60, "tag": "EMAIL", "value": "admin@abc.com" }, { "context": " secret: 'client_secret'\n user:\...
vm/production.coffee
twhtanghk/docker.shell
2
module.exports = keepResponseErrors: true admin: [ 'admin@abc.com' ] oauth2: url: authorize: 'https://abc.com/auth/oauth2/authorize/' verify: 'https://abc.com/auth/oauth2/verify/' token: 'https://abc.com/auth/oauth2/token/' client: id: 'client_id' secret: 'client_secret' user: id: 'user_id' secret: 'user_secret' scope: [ 'User' ] vagrant: disk: # GB min: 20 max: 80 memory: # GB min: 2 max: 4 port: vnc: 5900 http: 8000 box: 'debian/jessie64' vm: url: 'https://abc.com/vm/api/vm' webhook: url: 'http://vncproxy.service.triangle:1337/reload' oauth2: grant_type: 'client_credentials' client: id: 'client_credentials' secret: 'client_secret'
89046
module.exports = keepResponseErrors: true admin: [ '<EMAIL>' ] oauth2: url: authorize: 'https://abc.com/auth/oauth2/authorize/' verify: 'https://abc.com/auth/oauth2/verify/' token: 'https://abc.com/auth/oauth2/token/' client: id: 'client_id' secret: 'client_secret' user: id: 'user_id' secret: 'user_secret' scope: [ 'User' ] vagrant: disk: # GB min: 20 max: 80 memory: # GB min: 2 max: 4 port: vnc: 5900 http: 8000 box: 'debian/jessie64' vm: url: 'https://abc.com/vm/api/vm' webhook: url: 'http://vncproxy.service.triangle:1337/reload' oauth2: grant_type: 'client_credentials' client: id: 'client_credentials' secret: 'client_secret'
true
module.exports = keepResponseErrors: true admin: [ 'PI:EMAIL:<EMAIL>END_PI' ] oauth2: url: authorize: 'https://abc.com/auth/oauth2/authorize/' verify: 'https://abc.com/auth/oauth2/verify/' token: 'https://abc.com/auth/oauth2/token/' client: id: 'client_id' secret: 'client_secret' user: id: 'user_id' secret: 'user_secret' scope: [ 'User' ] vagrant: disk: # GB min: 20 max: 80 memory: # GB min: 2 max: 4 port: vnc: 5900 http: 8000 box: 'debian/jessie64' vm: url: 'https://abc.com/vm/api/vm' webhook: url: 'http://vncproxy.service.triangle:1337/reload' oauth2: grant_type: 'client_credentials' client: id: 'client_credentials' secret: 'client_secret'
[ { "context": "or jQuery\n@version 2.0.1\n@author Se7enSky studio <info@se7ensky.com>\n@example <h1 class=\"text-gradient\" data-text-gra", "end": 147, "score": 0.9999268054962158, "start": 130, "tag": "EMAIL", "value": "info@se7ensky.com" }, { "context": "###! jquery-text-gradient 2....
jquery-text-gradient.coffee
SE7ENSKY/jquery-text-gradient
3
### @name jquery-text-gradient @description Simple linear text gradient plugin for jQuery @version 2.0.1 @author Se7enSky studio <info@se7ensky.com> @example <h1 class="text-gradient" data-text-gradient="#000000-#ffffff">Just an example</h1> ### ###! jquery-text-gradient 2.0.1 http://github.com/Se7enSky/jquery-text-gradient### # "431265" -> [67, 18, 101] hex2arr = (s) -> [ parseInt(s.substr(0, 2), 16) parseInt(s.substr(2, 2), 16) parseInt(s.substr(4, 2), 16) ] # [67, 18, 101] -> "431265" arr2hex = (a) -> a[0].toString(16) + a[1].toString(16) + a[2].toString(16) $.fn.textGradient = -> $.each @, -> # do lettering letters = $(@).text().split '' # $(@).html """<span>#{letters.join "</span><span>"}</span>""" # defaults from = [0, 0 ,0] to = [255, 255, 255] # read config from data-text-gradient attr configString = $(@).data 'text-gradient' if m = configString.match new RegExp '^#([0-9a-fA-F]{6})-#([0-9a-fA-F]{6})$' from = hex2arr m[1] to = hex2arr m[2] # fill with letters $(@).empty() for i in [0..letters.length-1] letter = letters[i] color = (from[j] + Math.round (to[j] - from[j]) * (i / letters.length) for j in [0..2]) $(@).append """<span style="color: ##{arr2hex color}">#{letter}</span>""" @ $(".text-gradient").textGradient()
142236
### @name jquery-text-gradient @description Simple linear text gradient plugin for jQuery @version 2.0.1 @author Se7enSky studio <<EMAIL>> @example <h1 class="text-gradient" data-text-gradient="#000000-#ffffff">Just an example</h1> ### ###! jquery-text-gradient 2.0.1 http://github.com/Se7enSky/jquery-text-gradient### # "431265" -> [67, 18, 101] hex2arr = (s) -> [ parseInt(s.substr(0, 2), 16) parseInt(s.substr(2, 2), 16) parseInt(s.substr(4, 2), 16) ] # [67, 18, 101] -> "431265" arr2hex = (a) -> a[0].toString(16) + a[1].toString(16) + a[2].toString(16) $.fn.textGradient = -> $.each @, -> # do lettering letters = $(@).text().split '' # $(@).html """<span>#{letters.join "</span><span>"}</span>""" # defaults from = [0, 0 ,0] to = [255, 255, 255] # read config from data-text-gradient attr configString = $(@).data 'text-gradient' if m = configString.match new RegExp '^#([0-9a-fA-F]{6})-#([0-9a-fA-F]{6})$' from = hex2arr m[1] to = hex2arr m[2] # fill with letters $(@).empty() for i in [0..letters.length-1] letter = letters[i] color = (from[j] + Math.round (to[j] - from[j]) * (i / letters.length) for j in [0..2]) $(@).append """<span style="color: ##{arr2hex color}">#{letter}</span>""" @ $(".text-gradient").textGradient()
true
### @name jquery-text-gradient @description Simple linear text gradient plugin for jQuery @version 2.0.1 @author Se7enSky studio <PI:EMAIL:<EMAIL>END_PI> @example <h1 class="text-gradient" data-text-gradient="#000000-#ffffff">Just an example</h1> ### ###! jquery-text-gradient 2.0.1 http://github.com/Se7enSky/jquery-text-gradient### # "431265" -> [67, 18, 101] hex2arr = (s) -> [ parseInt(s.substr(0, 2), 16) parseInt(s.substr(2, 2), 16) parseInt(s.substr(4, 2), 16) ] # [67, 18, 101] -> "431265" arr2hex = (a) -> a[0].toString(16) + a[1].toString(16) + a[2].toString(16) $.fn.textGradient = -> $.each @, -> # do lettering letters = $(@).text().split '' # $(@).html """<span>#{letters.join "</span><span>"}</span>""" # defaults from = [0, 0 ,0] to = [255, 255, 255] # read config from data-text-gradient attr configString = $(@).data 'text-gradient' if m = configString.match new RegExp '^#([0-9a-fA-F]{6})-#([0-9a-fA-F]{6})$' from = hex2arr m[1] to = hex2arr m[2] # fill with letters $(@).empty() for i in [0..letters.length-1] letter = letters[i] color = (from[j] + Math.round (to[j] - from[j]) * (i / letters.length) for j in [0..2]) $(@).append """<span style="color: ##{arr2hex color}">#{letter}</span>""" @ $(".text-gradient").textGradient()
[ { "context": "# Mike Bostock's margin convention\nmargin = \n top: 20, \n ", "end": 14, "score": 0.9287949800491333, "start": 2, "tag": "NAME", "value": "Mike Bostock" } ]
Problem2/coffee/linegraph.coffee
rlucioni/cs171-hw3-lucioni-renzo
1
# Mike Bostock's margin convention margin = top: 20, bottom: 20, left: 20, right: 20 canvasWidth = 1100 - margin.left - margin.right canvasHeight = 600 - margin.top - margin.bottom svg = d3.select("#vis").append("svg") .attr("width", canvasWidth + margin.left + margin.right) .attr("height", canvasHeight + margin.top + margin.top) .append("g") .attr("transform", "translate(#{margin.left}, #{margin.top})") boundingBox = x: 100, y: 0, width: canvasWidth - 100, height: canvasHeight - 50 # Relevant CSV column headers orgs = ["us_census", "pop_reference", "un_desa", "hyde", "maddison"] # For adding space between labels and axes labelPadding = 7 xScale = d3.scale.linear().range([0, boundingBox.width]) yScale = d3.scale.linear().range([boundingBox.height, 0]) xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") yAxis = d3.svg.axis() .scale(yScale) .orient("left") line = d3.svg.line() .interpolate("linear") .x((d) -> xScale(d.year)) .y((d) -> yScale(d.estimate)) color = d3.scale.ordinal() .domain(orgs) .range(colorbrewer.Set1[5]) generateLineGraph = (dataset) -> xScale.domain(d3.extent(dataset.allYears)) yScale.domain([0, d3.max(dataset.allEstimates)]) frame = svg.append("g") .attr("transform", "translate(#{boundingBox.x}, #{boundingBox.y})") frame.append("g").attr("class", "x axis") .attr("transform", "translate(0, #{boundingBox.height})") .call(xAxis) frame.append("g").attr("class", "y axis") .call(yAxis) frame.append("text") .attr("class", "x label") .attr("text-anchor", "end") .attr("x", boundingBox.width) .attr("y", boundingBox.height - labelPadding) .text("Year") frame.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("y", labelPadding) .attr("dy", ".75em") .attr("transform", "rotate(-90)") .text("Population") for org in orgs frame.append("path") .datum(dataset[org]) .attr("class", "line") .attr("d", line) .style("stroke", color(org)) frame.selectAll(".point.#{org}") .data((dataset[org])) .enter() .append("circle") .attr("class", (d) -> if d.interpolated "point #{org} interpolated" else return "point #{org}" ) .attr("cx", (d) -> xScale(d.year)) .attr("cy", (d) -> yScale(d.estimate)) .attr("r", 3) # Interpolated data points are outlined in black .style("stroke", (d) -> if d.interpolated return "black" else return color(org) ) d3.csv("populationEstimates.csv", (data) -> dataset = {} for org in orgs dataset[org] = [] # Fill dataset with data from CSV, ignoring blank estimates for row in data year = row.year for org in orgs estimate = row[org] if estimate != "" dataset[org].push({year: +year, estimate: +estimate}) # Compile lists of all years and all estimates allYears = [] allEstimates = [] for org, data of dataset for point in data year = point.year if year not in allYears allYears.push(year) estimate = point.estimate if estimate not in allEstimates allEstimates.push(estimate) # Sort list of all years so that we can pull ordered slices from it dataset.allYears = allYears.sort() dataset.allEstimates = allEstimates # Use interpolation to fill in missing values for each organization's estimates for org in orgs # Compile lists of years and estimates from this organization years = [] estimates = [] for point in dataset[org] years.push(point.year) estimates.push(point.estimate) interpolator = d3.scale.linear() .domain(years) .range(estimates) interpolatedData = [] # Only consider years between the years for which this organization has made estimates relevantYears = allYears[allYears.indexOf(years[0])..allYears.indexOf(years[years.length - 1])] for year in relevantYears estimate = interpolator(year) # Boolean to determine if estimate is interpolated - used for coloring interpolated = true if year in years # Means that estimate was part of original dataset interpolated = false interpolatedData.push({year: year, estimate: estimate, interpolated: interpolated}) dataset[org] = interpolatedData generateLineGraph(dataset) )
52395
# <NAME>'s margin convention margin = top: 20, bottom: 20, left: 20, right: 20 canvasWidth = 1100 - margin.left - margin.right canvasHeight = 600 - margin.top - margin.bottom svg = d3.select("#vis").append("svg") .attr("width", canvasWidth + margin.left + margin.right) .attr("height", canvasHeight + margin.top + margin.top) .append("g") .attr("transform", "translate(#{margin.left}, #{margin.top})") boundingBox = x: 100, y: 0, width: canvasWidth - 100, height: canvasHeight - 50 # Relevant CSV column headers orgs = ["us_census", "pop_reference", "un_desa", "hyde", "maddison"] # For adding space between labels and axes labelPadding = 7 xScale = d3.scale.linear().range([0, boundingBox.width]) yScale = d3.scale.linear().range([boundingBox.height, 0]) xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") yAxis = d3.svg.axis() .scale(yScale) .orient("left") line = d3.svg.line() .interpolate("linear") .x((d) -> xScale(d.year)) .y((d) -> yScale(d.estimate)) color = d3.scale.ordinal() .domain(orgs) .range(colorbrewer.Set1[5]) generateLineGraph = (dataset) -> xScale.domain(d3.extent(dataset.allYears)) yScale.domain([0, d3.max(dataset.allEstimates)]) frame = svg.append("g") .attr("transform", "translate(#{boundingBox.x}, #{boundingBox.y})") frame.append("g").attr("class", "x axis") .attr("transform", "translate(0, #{boundingBox.height})") .call(xAxis) frame.append("g").attr("class", "y axis") .call(yAxis) frame.append("text") .attr("class", "x label") .attr("text-anchor", "end") .attr("x", boundingBox.width) .attr("y", boundingBox.height - labelPadding) .text("Year") frame.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("y", labelPadding) .attr("dy", ".75em") .attr("transform", "rotate(-90)") .text("Population") for org in orgs frame.append("path") .datum(dataset[org]) .attr("class", "line") .attr("d", line) .style("stroke", color(org)) frame.selectAll(".point.#{org}") .data((dataset[org])) .enter() .append("circle") .attr("class", (d) -> if d.interpolated "point #{org} interpolated" else return "point #{org}" ) .attr("cx", (d) -> xScale(d.year)) .attr("cy", (d) -> yScale(d.estimate)) .attr("r", 3) # Interpolated data points are outlined in black .style("stroke", (d) -> if d.interpolated return "black" else return color(org) ) d3.csv("populationEstimates.csv", (data) -> dataset = {} for org in orgs dataset[org] = [] # Fill dataset with data from CSV, ignoring blank estimates for row in data year = row.year for org in orgs estimate = row[org] if estimate != "" dataset[org].push({year: +year, estimate: +estimate}) # Compile lists of all years and all estimates allYears = [] allEstimates = [] for org, data of dataset for point in data year = point.year if year not in allYears allYears.push(year) estimate = point.estimate if estimate not in allEstimates allEstimates.push(estimate) # Sort list of all years so that we can pull ordered slices from it dataset.allYears = allYears.sort() dataset.allEstimates = allEstimates # Use interpolation to fill in missing values for each organization's estimates for org in orgs # Compile lists of years and estimates from this organization years = [] estimates = [] for point in dataset[org] years.push(point.year) estimates.push(point.estimate) interpolator = d3.scale.linear() .domain(years) .range(estimates) interpolatedData = [] # Only consider years between the years for which this organization has made estimates relevantYears = allYears[allYears.indexOf(years[0])..allYears.indexOf(years[years.length - 1])] for year in relevantYears estimate = interpolator(year) # Boolean to determine if estimate is interpolated - used for coloring interpolated = true if year in years # Means that estimate was part of original dataset interpolated = false interpolatedData.push({year: year, estimate: estimate, interpolated: interpolated}) dataset[org] = interpolatedData generateLineGraph(dataset) )
true
# PI:NAME:<NAME>END_PI's margin convention margin = top: 20, bottom: 20, left: 20, right: 20 canvasWidth = 1100 - margin.left - margin.right canvasHeight = 600 - margin.top - margin.bottom svg = d3.select("#vis").append("svg") .attr("width", canvasWidth + margin.left + margin.right) .attr("height", canvasHeight + margin.top + margin.top) .append("g") .attr("transform", "translate(#{margin.left}, #{margin.top})") boundingBox = x: 100, y: 0, width: canvasWidth - 100, height: canvasHeight - 50 # Relevant CSV column headers orgs = ["us_census", "pop_reference", "un_desa", "hyde", "maddison"] # For adding space between labels and axes labelPadding = 7 xScale = d3.scale.linear().range([0, boundingBox.width]) yScale = d3.scale.linear().range([boundingBox.height, 0]) xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") yAxis = d3.svg.axis() .scale(yScale) .orient("left") line = d3.svg.line() .interpolate("linear") .x((d) -> xScale(d.year)) .y((d) -> yScale(d.estimate)) color = d3.scale.ordinal() .domain(orgs) .range(colorbrewer.Set1[5]) generateLineGraph = (dataset) -> xScale.domain(d3.extent(dataset.allYears)) yScale.domain([0, d3.max(dataset.allEstimates)]) frame = svg.append("g") .attr("transform", "translate(#{boundingBox.x}, #{boundingBox.y})") frame.append("g").attr("class", "x axis") .attr("transform", "translate(0, #{boundingBox.height})") .call(xAxis) frame.append("g").attr("class", "y axis") .call(yAxis) frame.append("text") .attr("class", "x label") .attr("text-anchor", "end") .attr("x", boundingBox.width) .attr("y", boundingBox.height - labelPadding) .text("Year") frame.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("y", labelPadding) .attr("dy", ".75em") .attr("transform", "rotate(-90)") .text("Population") for org in orgs frame.append("path") .datum(dataset[org]) .attr("class", "line") .attr("d", line) .style("stroke", color(org)) frame.selectAll(".point.#{org}") .data((dataset[org])) .enter() .append("circle") .attr("class", (d) -> if d.interpolated "point #{org} interpolated" else return "point #{org}" ) .attr("cx", (d) -> xScale(d.year)) .attr("cy", (d) -> yScale(d.estimate)) .attr("r", 3) # Interpolated data points are outlined in black .style("stroke", (d) -> if d.interpolated return "black" else return color(org) ) d3.csv("populationEstimates.csv", (data) -> dataset = {} for org in orgs dataset[org] = [] # Fill dataset with data from CSV, ignoring blank estimates for row in data year = row.year for org in orgs estimate = row[org] if estimate != "" dataset[org].push({year: +year, estimate: +estimate}) # Compile lists of all years and all estimates allYears = [] allEstimates = [] for org, data of dataset for point in data year = point.year if year not in allYears allYears.push(year) estimate = point.estimate if estimate not in allEstimates allEstimates.push(estimate) # Sort list of all years so that we can pull ordered slices from it dataset.allYears = allYears.sort() dataset.allEstimates = allEstimates # Use interpolation to fill in missing values for each organization's estimates for org in orgs # Compile lists of years and estimates from this organization years = [] estimates = [] for point in dataset[org] years.push(point.year) estimates.push(point.estimate) interpolator = d3.scale.linear() .domain(years) .range(estimates) interpolatedData = [] # Only consider years between the years for which this organization has made estimates relevantYears = allYears[allYears.indexOf(years[0])..allYears.indexOf(years[years.length - 1])] for year in relevantYears estimate = interpolator(year) # Boolean to determine if estimate is interpolated - used for coloring interpolated = true if year in years # Means that estimate was part of original dataset interpolated = false interpolatedData.push({year: year, estimate: estimate, interpolated: interpolated}) dataset[org] = interpolatedData generateLineGraph(dataset) )
[ { "context": "([0-9]+)-([0-9]+)$/\n .constant 'RECAPTCHA_KEY', '6LetW5MUAAAAAHYqwbTCL2RkMLOLfqPr901s90z1'\n\n# Infinite scroll throttling\nangular.module 'in", "end": 950, "score": 0.9997671842575073, "start": 910, "tag": "KEY", "value": "6LetW5MUAAAAAHYqwbTCL2RkMLOLfqPr901s90z1" } ]
frontend/src/app.coffee
greysteil/evaluator
1
angular.module 'evaluator', ['ngResource', 'ui.router', 'ui.router.title', 'evaluatorTemplates', 'satellizer', 'LocalStorageModule', 'ngAnimate', 'angulartics', 'angulartics.google.analytics', 'infinite-scroll', 'ngFileUpload', 'ngFileSaver', 'ngMaterial', 'ngMessages', 'ngAria' ] # Configuration blocks. angular.module 'evaluator' .config ($compileProvider) -> $compileProvider.debugInfoEnabled false angular.module 'evaluator' .config (localStorageServiceProvider) -> localStorageServiceProvider.setPrefix('evaluator') angular.module 'evaluator' .config ($urlMatcherFactoryProvider) -> $urlMatcherFactoryProvider.strictMode false # Defines constants for use within our app. angular.module 'evaluator' .constant 'apiHost', '/api' .constant 'baseHost', '/' .constant 'defaultPageSize', 15 .constant 'GUC_ID_REGEX', /^([0-9]+)-([0-9]+)$/ .constant 'RECAPTCHA_KEY', '6LetW5MUAAAAAHYqwbTCL2RkMLOLfqPr901s90z1' # Infinite scroll throttling angular.module 'infinite-scroll' .value 'THROTTLE_MILLISECONDS', 250 angular.module 'evaluator' .run ($rootScope) -> $rootScope.$on '$viewContentLoaded', -> window.scroll 0, 0 contentOffsetHandler = -> wrap = $ '#pageWrap' content = $ '.content' if wrap.hasClass 'open' y = window.scrollY xoffset = Math.tan(35 * Math.PI / 180) * y content.css('left', "-#{xoffset}px") else content.css('left', '0') return $(window).scroll contentOffsetHandler $rootScope.$on 'toggled', contentOffsetHandler
116950
angular.module 'evaluator', ['ngResource', 'ui.router', 'ui.router.title', 'evaluatorTemplates', 'satellizer', 'LocalStorageModule', 'ngAnimate', 'angulartics', 'angulartics.google.analytics', 'infinite-scroll', 'ngFileUpload', 'ngFileSaver', 'ngMaterial', 'ngMessages', 'ngAria' ] # Configuration blocks. angular.module 'evaluator' .config ($compileProvider) -> $compileProvider.debugInfoEnabled false angular.module 'evaluator' .config (localStorageServiceProvider) -> localStorageServiceProvider.setPrefix('evaluator') angular.module 'evaluator' .config ($urlMatcherFactoryProvider) -> $urlMatcherFactoryProvider.strictMode false # Defines constants for use within our app. angular.module 'evaluator' .constant 'apiHost', '/api' .constant 'baseHost', '/' .constant 'defaultPageSize', 15 .constant 'GUC_ID_REGEX', /^([0-9]+)-([0-9]+)$/ .constant 'RECAPTCHA_KEY', '<KEY>' # Infinite scroll throttling angular.module 'infinite-scroll' .value 'THROTTLE_MILLISECONDS', 250 angular.module 'evaluator' .run ($rootScope) -> $rootScope.$on '$viewContentLoaded', -> window.scroll 0, 0 contentOffsetHandler = -> wrap = $ '#pageWrap' content = $ '.content' if wrap.hasClass 'open' y = window.scrollY xoffset = Math.tan(35 * Math.PI / 180) * y content.css('left', "-#{xoffset}px") else content.css('left', '0') return $(window).scroll contentOffsetHandler $rootScope.$on 'toggled', contentOffsetHandler
true
angular.module 'evaluator', ['ngResource', 'ui.router', 'ui.router.title', 'evaluatorTemplates', 'satellizer', 'LocalStorageModule', 'ngAnimate', 'angulartics', 'angulartics.google.analytics', 'infinite-scroll', 'ngFileUpload', 'ngFileSaver', 'ngMaterial', 'ngMessages', 'ngAria' ] # Configuration blocks. angular.module 'evaluator' .config ($compileProvider) -> $compileProvider.debugInfoEnabled false angular.module 'evaluator' .config (localStorageServiceProvider) -> localStorageServiceProvider.setPrefix('evaluator') angular.module 'evaluator' .config ($urlMatcherFactoryProvider) -> $urlMatcherFactoryProvider.strictMode false # Defines constants for use within our app. angular.module 'evaluator' .constant 'apiHost', '/api' .constant 'baseHost', '/' .constant 'defaultPageSize', 15 .constant 'GUC_ID_REGEX', /^([0-9]+)-([0-9]+)$/ .constant 'RECAPTCHA_KEY', 'PI:KEY:<KEY>END_PI' # Infinite scroll throttling angular.module 'infinite-scroll' .value 'THROTTLE_MILLISECONDS', 250 angular.module 'evaluator' .run ($rootScope) -> $rootScope.$on '$viewContentLoaded', -> window.scroll 0, 0 contentOffsetHandler = -> wrap = $ '#pageWrap' content = $ '.content' if wrap.hasClass 'open' y = window.scrollY xoffset = Math.tan(35 * Math.PI / 180) * y content.css('left', "-#{xoffset}px") else content.css('left', '0') return $(window).scroll contentOffsetHandler $rootScope.$on 'toggled', contentOffsetHandler
[ { "context": "YAML file.)\n #\n # Example:\n # [{ name: 'a test',\n # body: \"implementation void[] [", "end": 3055, "score": 0.7610293030738831, "start": 3054, "tag": "NAME", "value": "a" }, { "context": "AML file.)\n #\n # Example:\n # [{ name: 'a test'...
code/Paws/Source/rule.coffee
mitchellurgero/illacceptanything
1
require('./utilities.coffee').infect global Paws = require './Paws.coffee' infect global, Paws # FIXME: Refactor this entire thing to use isaacs' `node-tap` module.exports = Rule = class Rule extends Thing @construct: (schema, collection = Collection.current())-> return null unless schema.name? or schema.body? name = new Label schema.name ? '<untitled>' body = if schema.body new Execution Paws.parse schema.body else new Native -> rule.NYI() # XXX: Each rule in its own Unit? rule = new Rule {unit: new reactor.Unit}, name, body, collection if schema.eventually rule.eventually switch schema.eventually when 'pass' then new Native -> rule.pass() when 'fail' then new Native -> rule.fail() else new Execution Paws.parse schema.eventually return rule #--- # NOTE: Expects an environment similar to Execution.synchronous's `this`. Must contain `.unit`, # and may contain `.caller`. constructor: constructify(return:@) ({@caller, @unit}, @title, @body, @collection = Collection.current())-> @title = new Label @title unless @title instanceof Label if @caller? @body.locals = @caller.clone().locals else @body.locals.inject Paws.primitives 'infrastructure' @body.locals.inject Paws.primitives 'implementation' @body.locals.inject primitives.generate_block_locals this this .inject primitives.generate_members this if @caller @collection.push this maintain_locals: (@locals)-> @body.locals.inject @locals dispatch: -> return if @dispatched Paws.notice '-- Dispatching:', Paws.inspect this @dispatched = true @unit.once 'flushed', => @flushed = true @unit.once 'flushed', @eventually_listener if @eventually_listener? @unit.stage @body pass: -> @status = true; @complete() fail: -> @status = false; @complete() NYI: -> @status = 'NYI'; @complete() complete: -> Paws.info "-- Completed (#{@status}):", Paws.inspect this @unit.removeListener 'flushed', @eventually_listener if @eventually_listener? @emit 'complete', @status # FIXME: repeated calls? eventually: (block)-> block.locals.inject @body.locals if not @flushed Paws.info "-- Registering 'eventually' for ", Paws.inspect this @eventually_listener = => Paws.info "-- Firing 'eventually' for ", Paws.inspect this @unit.stage block, undefined @unit.once 'flushed', @eventually_listener if @dispatched else Paws.info "-- Immediately firing 'eventually' for already-flushed ", Paws.inspect this @unit.stage block, undefined Rule.Collection = Collection = class Collection # Construct a Collection (and member Rules) from an array of rule-structures (usually from a # Rulebook / YAML file.) # # Example: # [{ name: 'a test', # body: "implementation void[] [pass[]]" # eventually: 'fail' }, # ... ] #--- # TODO: Nested Collections @from: (schemas)-> collection = new Collection collection.rules = _.filter _.map schemas, (schema)-> Rule.construct schema return collection _current = undefined @current: -> _current ?= new Collection constructor: -> @rules = new Array @activate() unless _current? activate: -> _current = this push: (rules...)-> _.map rules, (rule)=> rule.once('complete', => @print rule) if @reporting @rules.push rule rule.dispatch() if @dispatching dispatch: -> @dispatching = true _.map @rules, (rule)=> rule.dispatch() report: -> @reporting = true process.stdout.write "TAP version 13\n" _.map @rules, (rule)=> if rule.status? then @print rule else rule.once 'complete', => @print rule # This will close the suite, outputting no more TAP and dispatching no further tests. It will # also print the TAP 'plan' line, telling the harness how many tests were run. #--- # FIXME: Tests *already dispatched* might output after this is called. # XXX: Vaguely convinced this is un-asynchronous. o_O complete: -> @dispatching = false @reporting = false process.stdout.write "1..#{@rules.length}\n" # Prints a line for a completed rule. print: (rule)-> number = @rules.indexOf(rule) + 1 status = switch rule.status when true then 'ok' when false then 'not ok' when 'NYI' then 'not ok' else rule.status directive = " # TODO" if rule.status == 'pending' process.stdout.write "#{status} #{number} #{rule.title.alien}#{directive||''}\n" # Fucking Node.js. ddis primitives = require('./primitives/specification.coffee')
85048
require('./utilities.coffee').infect global Paws = require './Paws.coffee' infect global, Paws # FIXME: Refactor this entire thing to use isaacs' `node-tap` module.exports = Rule = class Rule extends Thing @construct: (schema, collection = Collection.current())-> return null unless schema.name? or schema.body? name = new Label schema.name ? '<untitled>' body = if schema.body new Execution Paws.parse schema.body else new Native -> rule.NYI() # XXX: Each rule in its own Unit? rule = new Rule {unit: new reactor.Unit}, name, body, collection if schema.eventually rule.eventually switch schema.eventually when 'pass' then new Native -> rule.pass() when 'fail' then new Native -> rule.fail() else new Execution Paws.parse schema.eventually return rule #--- # NOTE: Expects an environment similar to Execution.synchronous's `this`. Must contain `.unit`, # and may contain `.caller`. constructor: constructify(return:@) ({@caller, @unit}, @title, @body, @collection = Collection.current())-> @title = new Label @title unless @title instanceof Label if @caller? @body.locals = @caller.clone().locals else @body.locals.inject Paws.primitives 'infrastructure' @body.locals.inject Paws.primitives 'implementation' @body.locals.inject primitives.generate_block_locals this this .inject primitives.generate_members this if @caller @collection.push this maintain_locals: (@locals)-> @body.locals.inject @locals dispatch: -> return if @dispatched Paws.notice '-- Dispatching:', Paws.inspect this @dispatched = true @unit.once 'flushed', => @flushed = true @unit.once 'flushed', @eventually_listener if @eventually_listener? @unit.stage @body pass: -> @status = true; @complete() fail: -> @status = false; @complete() NYI: -> @status = 'NYI'; @complete() complete: -> Paws.info "-- Completed (#{@status}):", Paws.inspect this @unit.removeListener 'flushed', @eventually_listener if @eventually_listener? @emit 'complete', @status # FIXME: repeated calls? eventually: (block)-> block.locals.inject @body.locals if not @flushed Paws.info "-- Registering 'eventually' for ", Paws.inspect this @eventually_listener = => Paws.info "-- Firing 'eventually' for ", Paws.inspect this @unit.stage block, undefined @unit.once 'flushed', @eventually_listener if @dispatched else Paws.info "-- Immediately firing 'eventually' for already-flushed ", Paws.inspect this @unit.stage block, undefined Rule.Collection = Collection = class Collection # Construct a Collection (and member Rules) from an array of rule-structures (usually from a # Rulebook / YAML file.) # # Example: # [{ name: '<NAME> <NAME>', # body: "implementation void[] [pass[]]" # eventually: 'fail' }, # ... ] #--- # TODO: Nested Collections @from: (schemas)-> collection = new Collection collection.rules = _.filter _.map schemas, (schema)-> Rule.construct schema return collection _current = undefined @current: -> _current ?= new Collection constructor: -> @rules = new Array @activate() unless _current? activate: -> _current = this push: (rules...)-> _.map rules, (rule)=> rule.once('complete', => @print rule) if @reporting @rules.push rule rule.dispatch() if @dispatching dispatch: -> @dispatching = true _.map @rules, (rule)=> rule.dispatch() report: -> @reporting = true process.stdout.write "TAP version 13\n" _.map @rules, (rule)=> if rule.status? then @print rule else rule.once 'complete', => @print rule # This will close the suite, outputting no more TAP and dispatching no further tests. It will # also print the TAP 'plan' line, telling the harness how many tests were run. #--- # FIXME: Tests *already dispatched* might output after this is called. # XXX: Vaguely convinced this is un-asynchronous. o_O complete: -> @dispatching = false @reporting = false process.stdout.write "1..#{@rules.length}\n" # Prints a line for a completed rule. print: (rule)-> number = @rules.indexOf(rule) + 1 status = switch rule.status when true then 'ok' when false then 'not ok' when 'NYI' then 'not ok' else rule.status directive = " # TODO" if rule.status == 'pending' process.stdout.write "#{status} #{number} #{rule.title.alien}#{directive||''}\n" # Fucking Node.js. ddis primitives = require('./primitives/specification.coffee')
true
require('./utilities.coffee').infect global Paws = require './Paws.coffee' infect global, Paws # FIXME: Refactor this entire thing to use isaacs' `node-tap` module.exports = Rule = class Rule extends Thing @construct: (schema, collection = Collection.current())-> return null unless schema.name? or schema.body? name = new Label schema.name ? '<untitled>' body = if schema.body new Execution Paws.parse schema.body else new Native -> rule.NYI() # XXX: Each rule in its own Unit? rule = new Rule {unit: new reactor.Unit}, name, body, collection if schema.eventually rule.eventually switch schema.eventually when 'pass' then new Native -> rule.pass() when 'fail' then new Native -> rule.fail() else new Execution Paws.parse schema.eventually return rule #--- # NOTE: Expects an environment similar to Execution.synchronous's `this`. Must contain `.unit`, # and may contain `.caller`. constructor: constructify(return:@) ({@caller, @unit}, @title, @body, @collection = Collection.current())-> @title = new Label @title unless @title instanceof Label if @caller? @body.locals = @caller.clone().locals else @body.locals.inject Paws.primitives 'infrastructure' @body.locals.inject Paws.primitives 'implementation' @body.locals.inject primitives.generate_block_locals this this .inject primitives.generate_members this if @caller @collection.push this maintain_locals: (@locals)-> @body.locals.inject @locals dispatch: -> return if @dispatched Paws.notice '-- Dispatching:', Paws.inspect this @dispatched = true @unit.once 'flushed', => @flushed = true @unit.once 'flushed', @eventually_listener if @eventually_listener? @unit.stage @body pass: -> @status = true; @complete() fail: -> @status = false; @complete() NYI: -> @status = 'NYI'; @complete() complete: -> Paws.info "-- Completed (#{@status}):", Paws.inspect this @unit.removeListener 'flushed', @eventually_listener if @eventually_listener? @emit 'complete', @status # FIXME: repeated calls? eventually: (block)-> block.locals.inject @body.locals if not @flushed Paws.info "-- Registering 'eventually' for ", Paws.inspect this @eventually_listener = => Paws.info "-- Firing 'eventually' for ", Paws.inspect this @unit.stage block, undefined @unit.once 'flushed', @eventually_listener if @dispatched else Paws.info "-- Immediately firing 'eventually' for already-flushed ", Paws.inspect this @unit.stage block, undefined Rule.Collection = Collection = class Collection # Construct a Collection (and member Rules) from an array of rule-structures (usually from a # Rulebook / YAML file.) # # Example: # [{ name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI', # body: "implementation void[] [pass[]]" # eventually: 'fail' }, # ... ] #--- # TODO: Nested Collections @from: (schemas)-> collection = new Collection collection.rules = _.filter _.map schemas, (schema)-> Rule.construct schema return collection _current = undefined @current: -> _current ?= new Collection constructor: -> @rules = new Array @activate() unless _current? activate: -> _current = this push: (rules...)-> _.map rules, (rule)=> rule.once('complete', => @print rule) if @reporting @rules.push rule rule.dispatch() if @dispatching dispatch: -> @dispatching = true _.map @rules, (rule)=> rule.dispatch() report: -> @reporting = true process.stdout.write "TAP version 13\n" _.map @rules, (rule)=> if rule.status? then @print rule else rule.once 'complete', => @print rule # This will close the suite, outputting no more TAP and dispatching no further tests. It will # also print the TAP 'plan' line, telling the harness how many tests were run. #--- # FIXME: Tests *already dispatched* might output after this is called. # XXX: Vaguely convinced this is un-asynchronous. o_O complete: -> @dispatching = false @reporting = false process.stdout.write "1..#{@rules.length}\n" # Prints a line for a completed rule. print: (rule)-> number = @rules.indexOf(rule) + 1 status = switch rule.status when true then 'ok' when false then 'not ok' when 'NYI' then 'not ok' else rule.status directive = " # TODO" if rule.status == 'pending' process.stdout.write "#{status} #{number} #{rule.title.alien}#{directive||''}\n" # Fucking Node.js. ddis primitives = require('./primitives/specification.coffee')
[ { "context": "s-show-move-comments').move_comments {csrfToken: \"foobar\", target: \"/foo/\"}\n plugin_move_comments = sho", "end": 351, "score": 0.676948070526123, "start": 345, "tag": "PASSWORD", "value": "foobar" } ]
spirit/static/spirit/scripts/test/suites/move_comments-spec.coffee
rterehov/Spirit
1
describe "move_comments plugin tests", -> show_move_comments = null plugin_move_comments = null MoveComment = null beforeEach -> fixtures = do jasmine.getFixtures fixtures.fixturesPath = 'base/test/fixtures/' loadFixtures 'move_comments.html' show_move_comments = $('.js-show-move-comments').move_comments {csrfToken: "foobar", target: "/foo/"} plugin_move_comments = show_move_comments.first().data 'plugin_move_comments' MoveComment = $.fn.move_comments.MoveComment it "doesnt break selector chaining", -> expect(show_move_comments).toEqual $('.js-show-move-comments') expect(show_move_comments.length).toEqual 1 it "shows the move form on click", -> expect($(".move-comments").is ":visible").toEqual false expect($(".move-comment-checkbox").length).toEqual 0 $('.js-show-move-comments').trigger 'click' expect($(".move-comments").is ":visible").toEqual true expect($(".move-comment-checkbox").length).toEqual 2 it "prevents the default click behaviour on show move comments", -> event = {type: 'click', stopPropagation: (->), preventDefault: (->)} stopPropagation = spyOn event, 'stopPropagation' preventDefault = spyOn event, 'preventDefault' show_move_comments.first().trigger event expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled() it "prevents the default click behaviour on submit", -> event = {type: 'click', stopPropagation: (->), preventDefault: (->)} stopPropagation = spyOn event, 'stopPropagation' preventDefault = spyOn event, 'preventDefault' spyOn plugin_move_comments, 'formSubmit' $(".js-move-comments").trigger event expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled() it "submits the form", -> formSubmit = spyOn plugin_move_comments, 'formSubmit' $('.js-show-move-comments').trigger 'click' $( ".js-move-comments" ).trigger 'click' expect(formSubmit).toHaveBeenCalled() expect($("form").last().attr('action')).toEqual "/foo/" expect($("form").last().is ":visible").toEqual false expect($("input[name=csrfmiddlewaretoken]").val()).toEqual "foobar" expect($("input[name=topic]").val()).toEqual "10" expect($("form").last().find("input[name=comments]").length).toEqual 2
110766
describe "move_comments plugin tests", -> show_move_comments = null plugin_move_comments = null MoveComment = null beforeEach -> fixtures = do jasmine.getFixtures fixtures.fixturesPath = 'base/test/fixtures/' loadFixtures 'move_comments.html' show_move_comments = $('.js-show-move-comments').move_comments {csrfToken: "<PASSWORD>", target: "/foo/"} plugin_move_comments = show_move_comments.first().data 'plugin_move_comments' MoveComment = $.fn.move_comments.MoveComment it "doesnt break selector chaining", -> expect(show_move_comments).toEqual $('.js-show-move-comments') expect(show_move_comments.length).toEqual 1 it "shows the move form on click", -> expect($(".move-comments").is ":visible").toEqual false expect($(".move-comment-checkbox").length).toEqual 0 $('.js-show-move-comments').trigger 'click' expect($(".move-comments").is ":visible").toEqual true expect($(".move-comment-checkbox").length).toEqual 2 it "prevents the default click behaviour on show move comments", -> event = {type: 'click', stopPropagation: (->), preventDefault: (->)} stopPropagation = spyOn event, 'stopPropagation' preventDefault = spyOn event, 'preventDefault' show_move_comments.first().trigger event expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled() it "prevents the default click behaviour on submit", -> event = {type: 'click', stopPropagation: (->), preventDefault: (->)} stopPropagation = spyOn event, 'stopPropagation' preventDefault = spyOn event, 'preventDefault' spyOn plugin_move_comments, 'formSubmit' $(".js-move-comments").trigger event expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled() it "submits the form", -> formSubmit = spyOn plugin_move_comments, 'formSubmit' $('.js-show-move-comments').trigger 'click' $( ".js-move-comments" ).trigger 'click' expect(formSubmit).toHaveBeenCalled() expect($("form").last().attr('action')).toEqual "/foo/" expect($("form").last().is ":visible").toEqual false expect($("input[name=csrfmiddlewaretoken]").val()).toEqual "foobar" expect($("input[name=topic]").val()).toEqual "10" expect($("form").last().find("input[name=comments]").length).toEqual 2
true
describe "move_comments plugin tests", -> show_move_comments = null plugin_move_comments = null MoveComment = null beforeEach -> fixtures = do jasmine.getFixtures fixtures.fixturesPath = 'base/test/fixtures/' loadFixtures 'move_comments.html' show_move_comments = $('.js-show-move-comments').move_comments {csrfToken: "PI:PASSWORD:<PASSWORD>END_PI", target: "/foo/"} plugin_move_comments = show_move_comments.first().data 'plugin_move_comments' MoveComment = $.fn.move_comments.MoveComment it "doesnt break selector chaining", -> expect(show_move_comments).toEqual $('.js-show-move-comments') expect(show_move_comments.length).toEqual 1 it "shows the move form on click", -> expect($(".move-comments").is ":visible").toEqual false expect($(".move-comment-checkbox").length).toEqual 0 $('.js-show-move-comments').trigger 'click' expect($(".move-comments").is ":visible").toEqual true expect($(".move-comment-checkbox").length).toEqual 2 it "prevents the default click behaviour on show move comments", -> event = {type: 'click', stopPropagation: (->), preventDefault: (->)} stopPropagation = spyOn event, 'stopPropagation' preventDefault = spyOn event, 'preventDefault' show_move_comments.first().trigger event expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled() it "prevents the default click behaviour on submit", -> event = {type: 'click', stopPropagation: (->), preventDefault: (->)} stopPropagation = spyOn event, 'stopPropagation' preventDefault = spyOn event, 'preventDefault' spyOn plugin_move_comments, 'formSubmit' $(".js-move-comments").trigger event expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled() it "submits the form", -> formSubmit = spyOn plugin_move_comments, 'formSubmit' $('.js-show-move-comments').trigger 'click' $( ".js-move-comments" ).trigger 'click' expect(formSubmit).toHaveBeenCalled() expect($("form").last().attr('action')).toEqual "/foo/" expect($("form").last().is ":visible").toEqual false expect($("input[name=csrfmiddlewaretoken]").val()).toEqual "foobar" expect($("input[name=topic]").val()).toEqual "10" expect($("form").last().find("input[name=comments]").length).toEqual 2
[ { "context": "Age\"+\"\\t\"+\"Name\"+\"\\n\"\nrow1 = \"0\"+\"\\t\"+\" 21\"+\"\\t\"+\"Rob\"+\"\\n\"\nrow2 = \"1\"+\"\\t\"+\" 22\"+\"\\t\"+\"bob\"+\"\\n\"\n\nwrit", "end": 163, "score": 0.9997656941413879, "start": 160, "tag": "NAME", "value": "Rob" }, { "context": "\" 21\"+\"\\t\"+\"R...
excel/xls1.coffee
rankun203/ModernWebStudy
0
#!/usr/bin/env coffee fs = require 'fs' writeStream = fs.createWriteStream 'file.xls' header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n" row1 = "0"+"\t"+" 21"+"\t"+"Rob"+"\n" row2 = "1"+"\t"+" 22"+"\t"+"bob"+"\n" writeStream.write header writeStream.write row1 writeStream.write row2 writeStream.close()
53362
#!/usr/bin/env coffee fs = require 'fs' writeStream = fs.createWriteStream 'file.xls' header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n" row1 = "0"+"\t"+" 21"+"\t"+"<NAME>"+"\n" row2 = "1"+"\t"+" 22"+"\t"+"<NAME>"+"\n" writeStream.write header writeStream.write row1 writeStream.write row2 writeStream.close()
true
#!/usr/bin/env coffee fs = require 'fs' writeStream = fs.createWriteStream 'file.xls' header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n" row1 = "0"+"\t"+" 21"+"\t"+"PI:NAME:<NAME>END_PI"+"\n" row2 = "1"+"\t"+" 22"+"\t"+"PI:NAME:<NAME>END_PI"+"\n" writeStream.write header writeStream.write row1 writeStream.write row2 writeStream.close()
[ { "context": "image of lod curves linked to plot of lod curves\n# Karl W Broman\n\niplotMScanone_noeff = (widgetdiv, lod_data, time", "end": 87, "score": 0.9998754262924194, "start": 74, "tag": "NAME", "value": "Karl W Broman" } ]
inst/htmlwidgets/lib/qtlcharts/iplotMScanone_noeff.coffee
Alanocallaghan/qtlcharts
0
# iplotMScanone_noeff: image of lod curves linked to plot of lod curves # Karl W Broman iplotMScanone_noeff = (widgetdiv, lod_data, times, chartOpts) -> # chartOpts start height = chartOpts?.height ? 700 # height of chart in pixels width = chartOpts?.width ? 1000 # width of chart in pixels wleft = chartOpts?.wleft ? width*0.65 # width of left panels in pixels htop = chartOpts?.htop ? height/2 # height of top panels in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:0} # margins in pixels (left, top, right, bottom, inner) axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes in pixels rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of lighter background rectangle altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of darker background rectangle nullcolor = chartOpts?.nullcolor ? "#E6E6E6" # color for pixels with null values chrlinecolor = chartOpts?.chrlinecolor ? "" # color of lines between chromosomes (if "", leave off) chrlinewidth = chartOpts?.chrlinewidth ? 2 # width of lines between chromosomes colors = chartOpts?.colors ? ["slateblue", "white", "crimson"] # heat map colors zlim = chartOpts?.zlim ? null # z-axis limits zthresh = chartOpts?.zthresh ? null # lower z-axis threshold for display in heat map xlab = chartOpts?.xlab ? null # x-axis label for LOD heatmap) ylab = chartOpts?.ylab ? "" # y-axis label for LOD heatmap (also used as x-axis label on effect plot) zlab = chartOpts?.zlab ? "LOD score" # z-axis label for LOD heatmap (really just used as y-axis label in the two slices) linecolor = chartOpts?.linecolor ? "darkslateblue" # color of LOD curves linewidth = chartOpts?.linewidth ? 2 # width of LOD curves pointsize = chartOpts?.pointsize ? 0 # size of points in vertical slice (default = 0 corresponds plotting curves rather than points) pointcolor = chartOpts?.pointcolor ? "slateblue" # color of points in vertical slice pointcolorhilit = chartOpts?.pointcolorhilit ? "crimson" # color of highlighted point in vertical slice pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle for points in vertical slice nxticks = chartOpts?.nxticks ? 5 # no. ticks in x-axis on right-hand panel, if quantitative scale xticks = chartOpts?.xticks ? null # tick positions in x-axis on right-hand panel, if quantitative scale # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' widgetdivid = d3.select(widgetdiv).attr('id') # make sure list args have all necessary bits margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5}) axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) wright = width - wleft hbot = height - htop # fill in zlim zmax = d3panels.matrixMaxAbs(lod_data.lod) zlim = zlim ? [-zmax, 0, zmax] # a bit more data set up if times? lod_data.y = times else lod_data.ycat = lod_data.lodname # hash for [chr][pos] -> posindex lod_data.posIndexByChr = d3panels.reorgByChr(lod_data.chrname, lod_data.chr, (i for i of lod_data.pos)) # use the lod labels for the lod names lod_data.lodname = lod_labels if lod_labels? # create chrname, chrstart, chrend if missing lod_data.chrname = d3panels.unique(lod_data.chr) unless lod_data.chrname? unless lod_data.chrstart? lod_data.chrstart = [] for c in lod_data.chrname these_pos = (lod_data.pos[i] for i of lod_data.chr when lod_data.chr[i] == c) lod_data.chrstart.push(d3.min(these_pos)) unless lod_data.chrend? lod_data.chrend = [] for c in lod_data.chrname these_pos = (lod_data.pos[i] for i of lod_data.chr when lod_data.chr[i] == c) lod_data.chrend.push(d3.max(these_pos)) # phenotype x-axis x = if times? then times else (i for i of lod_data.lod[0]) xlim = if times? then d3.extent(times) else [-0.5, x.length-0.5] nxticks = if times? then nxticks else 0 xticks = if times? then xticks else null # set up heatmap mylodheatmap = d3panels.lodheatmap({ height:htop width:wleft margin:margin axispos:axispos titlepos:titlepos chrGap:chrGap rectcolor:rectcolor altrectcolor:altrectcolor chrlinecolor:chrlinecolor chrlinewidth:chrlinewidth colors:colors zlim:zlim zthresh:zthresh ylab:ylab yticks:xticks nyticks:nxticks nullcolor:nullcolor tipclass:widgetdivid}) # add the heatmap svg = d3.select(widgetdiv).select("svg") g_heatmap = svg.append("g") .attr("id", "heatmap") mylodheatmap(g_heatmap, lod_data) # lod vs position (horizontal) panel horpanel = d3panels.chrpanelframe({ height:hbot width:wleft margin:margin axispos:axispos titlepos:titlepos chrGap:chrGap rectcolor:rectcolor altrectcolor:altrectcolor chrlinecolor:chrlinecolor chrlinewidth:chrlinewidth xlab:xlab ylab:zlab ylim:[0, zlim[2]*1.05] tipclass:widgetdivid}) # create empty panel g_horpanel = svg.append("g") .attr("transform", "translate(0,#{htop})") .attr("id", "lodchart") horpanel(g_horpanel, {chr:lod_data.chrname, start:lod_data.chrstart, end:lod_data.chrend}) # plot lod curves for selected lod column horslice = null plotHorSlice = (lodcolumn) -> horslice = d3panels.add_lodcurve({ linecolor: linecolor linewidth: linewidth pointsize: 0 pointcolor: "" pointstroke: ""}) horslice(horpanel, { chr:lod_data.chr pos:lod_data.pos marker:lod_data.marker lod:(d3panels.abs(lod_data.lod[i][lodcolumn]) for i of lod_data.pos) chrname:lod_data.chrname}) # lod versus phenotype (vertical) panel verpanel = d3panels.panelframe({ height:htop width:wright margin:margin axispos:axispos titlepos:titlepos xlab:ylab ylab:zlab rectcolor:rectcolor xlim: xlim ylim:[0, zlim[2]*1.05] nxticks:nxticks xticks:xticks tipclass:widgetdivid}) g_verpanel = svg.append("g") .attr("transform", "translate(#{wleft},0)") .attr("id", "curvechart") verpanel(g_verpanel) # add x-axis test if qualitative x-axis scale unless times? verpanel_axis_text = g_verpanel.append("g") .attr("class", "x axis") .append("text") .text("") .attr("y", htop-margin.bottom+axispos.xlabel) verpanel_xscale = verpanel.xscale() # plot lod versus phenotype curve verslice = null plotVerSlice = (posindex) -> if pointsize > 0 # plot points rather than curves verslice = d3panels.add_points({ pointsize:pointsize pointcolor:pointcolor pointstroke:pointstroke}) verslice(verpanel, { x:x y:(lod_data.lod[posindex][i] for i of lod_data.lod[posindex])}) else # plot curves rather than points verslice = d3panels.add_curves({ linecolor:linecolor linewidth:linewidth}) verslice(verpanel, { x:[x] y:[(lod_data.lod[posindex][i] for i of lod_data.lod[posindex])]}) mylodheatmap.cells() .on "mouseover", (d) -> plotHorSlice(d.lodindex) g_horpanel.select("g.title text").text("#{lod_data.lodname[d.lodindex]}") plotVerSlice(lod_data.posIndexByChr[d.chr][d.posindex]) p = d3.format(".1f")(d.pos) g_verpanel.select("g.title text").text("#{d.chr}@#{p}") unless times? verpanel_axis_text.text("#{lod_data.lodname[d.lodindex]}") .attr("x", verpanel_xscale(d.lodindex)) if pointsize > 0 verslice.points() .attr("fill", (z,i) -> return pointcolorhilit if i==d.lodindex pointcolor) .on "mouseout", (d) -> horslice.remove() if horslice? verslice.remove() if verslice? g_horpanel.select("g.title text").text("") g_verpanel.select("g.title text").text("") verpanel_axis_text.text("") unless times? if pointsize > 0 verslice.points().attr("fill", pointcolor) if chartOpts.heading? d3.select("div#htmlwidget_container") .insert("h2", ":first-child") .html(chartOpts.heading) .style("font-family", "sans-serif") if chartOpts.caption? d3.select("body") .append("p") .attr("class", "caption") .html(chartOpts.caption) if chartOpts.footer? d3.select("body") .append("div") .html(chartOpts.footer) .style("font-family", "sans-serif")
193592
# iplotMScanone_noeff: image of lod curves linked to plot of lod curves # <NAME> iplotMScanone_noeff = (widgetdiv, lod_data, times, chartOpts) -> # chartOpts start height = chartOpts?.height ? 700 # height of chart in pixels width = chartOpts?.width ? 1000 # width of chart in pixels wleft = chartOpts?.wleft ? width*0.65 # width of left panels in pixels htop = chartOpts?.htop ? height/2 # height of top panels in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:0} # margins in pixels (left, top, right, bottom, inner) axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes in pixels rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of lighter background rectangle altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of darker background rectangle nullcolor = chartOpts?.nullcolor ? "#E6E6E6" # color for pixels with null values chrlinecolor = chartOpts?.chrlinecolor ? "" # color of lines between chromosomes (if "", leave off) chrlinewidth = chartOpts?.chrlinewidth ? 2 # width of lines between chromosomes colors = chartOpts?.colors ? ["slateblue", "white", "crimson"] # heat map colors zlim = chartOpts?.zlim ? null # z-axis limits zthresh = chartOpts?.zthresh ? null # lower z-axis threshold for display in heat map xlab = chartOpts?.xlab ? null # x-axis label for LOD heatmap) ylab = chartOpts?.ylab ? "" # y-axis label for LOD heatmap (also used as x-axis label on effect plot) zlab = chartOpts?.zlab ? "LOD score" # z-axis label for LOD heatmap (really just used as y-axis label in the two slices) linecolor = chartOpts?.linecolor ? "darkslateblue" # color of LOD curves linewidth = chartOpts?.linewidth ? 2 # width of LOD curves pointsize = chartOpts?.pointsize ? 0 # size of points in vertical slice (default = 0 corresponds plotting curves rather than points) pointcolor = chartOpts?.pointcolor ? "slateblue" # color of points in vertical slice pointcolorhilit = chartOpts?.pointcolorhilit ? "crimson" # color of highlighted point in vertical slice pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle for points in vertical slice nxticks = chartOpts?.nxticks ? 5 # no. ticks in x-axis on right-hand panel, if quantitative scale xticks = chartOpts?.xticks ? null # tick positions in x-axis on right-hand panel, if quantitative scale # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' widgetdivid = d3.select(widgetdiv).attr('id') # make sure list args have all necessary bits margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5}) axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) wright = width - wleft hbot = height - htop # fill in zlim zmax = d3panels.matrixMaxAbs(lod_data.lod) zlim = zlim ? [-zmax, 0, zmax] # a bit more data set up if times? lod_data.y = times else lod_data.ycat = lod_data.lodname # hash for [chr][pos] -> posindex lod_data.posIndexByChr = d3panels.reorgByChr(lod_data.chrname, lod_data.chr, (i for i of lod_data.pos)) # use the lod labels for the lod names lod_data.lodname = lod_labels if lod_labels? # create chrname, chrstart, chrend if missing lod_data.chrname = d3panels.unique(lod_data.chr) unless lod_data.chrname? unless lod_data.chrstart? lod_data.chrstart = [] for c in lod_data.chrname these_pos = (lod_data.pos[i] for i of lod_data.chr when lod_data.chr[i] == c) lod_data.chrstart.push(d3.min(these_pos)) unless lod_data.chrend? lod_data.chrend = [] for c in lod_data.chrname these_pos = (lod_data.pos[i] for i of lod_data.chr when lod_data.chr[i] == c) lod_data.chrend.push(d3.max(these_pos)) # phenotype x-axis x = if times? then times else (i for i of lod_data.lod[0]) xlim = if times? then d3.extent(times) else [-0.5, x.length-0.5] nxticks = if times? then nxticks else 0 xticks = if times? then xticks else null # set up heatmap mylodheatmap = d3panels.lodheatmap({ height:htop width:wleft margin:margin axispos:axispos titlepos:titlepos chrGap:chrGap rectcolor:rectcolor altrectcolor:altrectcolor chrlinecolor:chrlinecolor chrlinewidth:chrlinewidth colors:colors zlim:zlim zthresh:zthresh ylab:ylab yticks:xticks nyticks:nxticks nullcolor:nullcolor tipclass:widgetdivid}) # add the heatmap svg = d3.select(widgetdiv).select("svg") g_heatmap = svg.append("g") .attr("id", "heatmap") mylodheatmap(g_heatmap, lod_data) # lod vs position (horizontal) panel horpanel = d3panels.chrpanelframe({ height:hbot width:wleft margin:margin axispos:axispos titlepos:titlepos chrGap:chrGap rectcolor:rectcolor altrectcolor:altrectcolor chrlinecolor:chrlinecolor chrlinewidth:chrlinewidth xlab:xlab ylab:zlab ylim:[0, zlim[2]*1.05] tipclass:widgetdivid}) # create empty panel g_horpanel = svg.append("g") .attr("transform", "translate(0,#{htop})") .attr("id", "lodchart") horpanel(g_horpanel, {chr:lod_data.chrname, start:lod_data.chrstart, end:lod_data.chrend}) # plot lod curves for selected lod column horslice = null plotHorSlice = (lodcolumn) -> horslice = d3panels.add_lodcurve({ linecolor: linecolor linewidth: linewidth pointsize: 0 pointcolor: "" pointstroke: ""}) horslice(horpanel, { chr:lod_data.chr pos:lod_data.pos marker:lod_data.marker lod:(d3panels.abs(lod_data.lod[i][lodcolumn]) for i of lod_data.pos) chrname:lod_data.chrname}) # lod versus phenotype (vertical) panel verpanel = d3panels.panelframe({ height:htop width:wright margin:margin axispos:axispos titlepos:titlepos xlab:ylab ylab:zlab rectcolor:rectcolor xlim: xlim ylim:[0, zlim[2]*1.05] nxticks:nxticks xticks:xticks tipclass:widgetdivid}) g_verpanel = svg.append("g") .attr("transform", "translate(#{wleft},0)") .attr("id", "curvechart") verpanel(g_verpanel) # add x-axis test if qualitative x-axis scale unless times? verpanel_axis_text = g_verpanel.append("g") .attr("class", "x axis") .append("text") .text("") .attr("y", htop-margin.bottom+axispos.xlabel) verpanel_xscale = verpanel.xscale() # plot lod versus phenotype curve verslice = null plotVerSlice = (posindex) -> if pointsize > 0 # plot points rather than curves verslice = d3panels.add_points({ pointsize:pointsize pointcolor:pointcolor pointstroke:pointstroke}) verslice(verpanel, { x:x y:(lod_data.lod[posindex][i] for i of lod_data.lod[posindex])}) else # plot curves rather than points verslice = d3panels.add_curves({ linecolor:linecolor linewidth:linewidth}) verslice(verpanel, { x:[x] y:[(lod_data.lod[posindex][i] for i of lod_data.lod[posindex])]}) mylodheatmap.cells() .on "mouseover", (d) -> plotHorSlice(d.lodindex) g_horpanel.select("g.title text").text("#{lod_data.lodname[d.lodindex]}") plotVerSlice(lod_data.posIndexByChr[d.chr][d.posindex]) p = d3.format(".1f")(d.pos) g_verpanel.select("g.title text").text("#{d.chr}@#{p}") unless times? verpanel_axis_text.text("#{lod_data.lodname[d.lodindex]}") .attr("x", verpanel_xscale(d.lodindex)) if pointsize > 0 verslice.points() .attr("fill", (z,i) -> return pointcolorhilit if i==d.lodindex pointcolor) .on "mouseout", (d) -> horslice.remove() if horslice? verslice.remove() if verslice? g_horpanel.select("g.title text").text("") g_verpanel.select("g.title text").text("") verpanel_axis_text.text("") unless times? if pointsize > 0 verslice.points().attr("fill", pointcolor) if chartOpts.heading? d3.select("div#htmlwidget_container") .insert("h2", ":first-child") .html(chartOpts.heading) .style("font-family", "sans-serif") if chartOpts.caption? d3.select("body") .append("p") .attr("class", "caption") .html(chartOpts.caption) if chartOpts.footer? d3.select("body") .append("div") .html(chartOpts.footer) .style("font-family", "sans-serif")
true
# iplotMScanone_noeff: image of lod curves linked to plot of lod curves # PI:NAME:<NAME>END_PI iplotMScanone_noeff = (widgetdiv, lod_data, times, chartOpts) -> # chartOpts start height = chartOpts?.height ? 700 # height of chart in pixels width = chartOpts?.width ? 1000 # width of chart in pixels wleft = chartOpts?.wleft ? width*0.65 # width of left panels in pixels htop = chartOpts?.htop ? height/2 # height of top panels in pixels margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:0} # margins in pixels (left, top, right, bottom, inner) axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel) titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes in pixels rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of lighter background rectangle altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of darker background rectangle nullcolor = chartOpts?.nullcolor ? "#E6E6E6" # color for pixels with null values chrlinecolor = chartOpts?.chrlinecolor ? "" # color of lines between chromosomes (if "", leave off) chrlinewidth = chartOpts?.chrlinewidth ? 2 # width of lines between chromosomes colors = chartOpts?.colors ? ["slateblue", "white", "crimson"] # heat map colors zlim = chartOpts?.zlim ? null # z-axis limits zthresh = chartOpts?.zthresh ? null # lower z-axis threshold for display in heat map xlab = chartOpts?.xlab ? null # x-axis label for LOD heatmap) ylab = chartOpts?.ylab ? "" # y-axis label for LOD heatmap (also used as x-axis label on effect plot) zlab = chartOpts?.zlab ? "LOD score" # z-axis label for LOD heatmap (really just used as y-axis label in the two slices) linecolor = chartOpts?.linecolor ? "darkslateblue" # color of LOD curves linewidth = chartOpts?.linewidth ? 2 # width of LOD curves pointsize = chartOpts?.pointsize ? 0 # size of points in vertical slice (default = 0 corresponds plotting curves rather than points) pointcolor = chartOpts?.pointcolor ? "slateblue" # color of points in vertical slice pointcolorhilit = chartOpts?.pointcolorhilit ? "crimson" # color of highlighted point in vertical slice pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle for points in vertical slice nxticks = chartOpts?.nxticks ? 5 # no. ticks in x-axis on right-hand panel, if quantitative scale xticks = chartOpts?.xticks ? null # tick positions in x-axis on right-hand panel, if quantitative scale # chartOpts end chartdivid = chartOpts?.chartdivid ? 'chart' widgetdivid = d3.select(widgetdiv).attr('id') # make sure list args have all necessary bits margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5}) axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5}) wright = width - wleft hbot = height - htop # fill in zlim zmax = d3panels.matrixMaxAbs(lod_data.lod) zlim = zlim ? [-zmax, 0, zmax] # a bit more data set up if times? lod_data.y = times else lod_data.ycat = lod_data.lodname # hash for [chr][pos] -> posindex lod_data.posIndexByChr = d3panels.reorgByChr(lod_data.chrname, lod_data.chr, (i for i of lod_data.pos)) # use the lod labels for the lod names lod_data.lodname = lod_labels if lod_labels? # create chrname, chrstart, chrend if missing lod_data.chrname = d3panels.unique(lod_data.chr) unless lod_data.chrname? unless lod_data.chrstart? lod_data.chrstart = [] for c in lod_data.chrname these_pos = (lod_data.pos[i] for i of lod_data.chr when lod_data.chr[i] == c) lod_data.chrstart.push(d3.min(these_pos)) unless lod_data.chrend? lod_data.chrend = [] for c in lod_data.chrname these_pos = (lod_data.pos[i] for i of lod_data.chr when lod_data.chr[i] == c) lod_data.chrend.push(d3.max(these_pos)) # phenotype x-axis x = if times? then times else (i for i of lod_data.lod[0]) xlim = if times? then d3.extent(times) else [-0.5, x.length-0.5] nxticks = if times? then nxticks else 0 xticks = if times? then xticks else null # set up heatmap mylodheatmap = d3panels.lodheatmap({ height:htop width:wleft margin:margin axispos:axispos titlepos:titlepos chrGap:chrGap rectcolor:rectcolor altrectcolor:altrectcolor chrlinecolor:chrlinecolor chrlinewidth:chrlinewidth colors:colors zlim:zlim zthresh:zthresh ylab:ylab yticks:xticks nyticks:nxticks nullcolor:nullcolor tipclass:widgetdivid}) # add the heatmap svg = d3.select(widgetdiv).select("svg") g_heatmap = svg.append("g") .attr("id", "heatmap") mylodheatmap(g_heatmap, lod_data) # lod vs position (horizontal) panel horpanel = d3panels.chrpanelframe({ height:hbot width:wleft margin:margin axispos:axispos titlepos:titlepos chrGap:chrGap rectcolor:rectcolor altrectcolor:altrectcolor chrlinecolor:chrlinecolor chrlinewidth:chrlinewidth xlab:xlab ylab:zlab ylim:[0, zlim[2]*1.05] tipclass:widgetdivid}) # create empty panel g_horpanel = svg.append("g") .attr("transform", "translate(0,#{htop})") .attr("id", "lodchart") horpanel(g_horpanel, {chr:lod_data.chrname, start:lod_data.chrstart, end:lod_data.chrend}) # plot lod curves for selected lod column horslice = null plotHorSlice = (lodcolumn) -> horslice = d3panels.add_lodcurve({ linecolor: linecolor linewidth: linewidth pointsize: 0 pointcolor: "" pointstroke: ""}) horslice(horpanel, { chr:lod_data.chr pos:lod_data.pos marker:lod_data.marker lod:(d3panels.abs(lod_data.lod[i][lodcolumn]) for i of lod_data.pos) chrname:lod_data.chrname}) # lod versus phenotype (vertical) panel verpanel = d3panels.panelframe({ height:htop width:wright margin:margin axispos:axispos titlepos:titlepos xlab:ylab ylab:zlab rectcolor:rectcolor xlim: xlim ylim:[0, zlim[2]*1.05] nxticks:nxticks xticks:xticks tipclass:widgetdivid}) g_verpanel = svg.append("g") .attr("transform", "translate(#{wleft},0)") .attr("id", "curvechart") verpanel(g_verpanel) # add x-axis test if qualitative x-axis scale unless times? verpanel_axis_text = g_verpanel.append("g") .attr("class", "x axis") .append("text") .text("") .attr("y", htop-margin.bottom+axispos.xlabel) verpanel_xscale = verpanel.xscale() # plot lod versus phenotype curve verslice = null plotVerSlice = (posindex) -> if pointsize > 0 # plot points rather than curves verslice = d3panels.add_points({ pointsize:pointsize pointcolor:pointcolor pointstroke:pointstroke}) verslice(verpanel, { x:x y:(lod_data.lod[posindex][i] for i of lod_data.lod[posindex])}) else # plot curves rather than points verslice = d3panels.add_curves({ linecolor:linecolor linewidth:linewidth}) verslice(verpanel, { x:[x] y:[(lod_data.lod[posindex][i] for i of lod_data.lod[posindex])]}) mylodheatmap.cells() .on "mouseover", (d) -> plotHorSlice(d.lodindex) g_horpanel.select("g.title text").text("#{lod_data.lodname[d.lodindex]}") plotVerSlice(lod_data.posIndexByChr[d.chr][d.posindex]) p = d3.format(".1f")(d.pos) g_verpanel.select("g.title text").text("#{d.chr}@#{p}") unless times? verpanel_axis_text.text("#{lod_data.lodname[d.lodindex]}") .attr("x", verpanel_xscale(d.lodindex)) if pointsize > 0 verslice.points() .attr("fill", (z,i) -> return pointcolorhilit if i==d.lodindex pointcolor) .on "mouseout", (d) -> horslice.remove() if horslice? verslice.remove() if verslice? g_horpanel.select("g.title text").text("") g_verpanel.select("g.title text").text("") verpanel_axis_text.text("") unless times? if pointsize > 0 verslice.points().attr("fill", pointcolor) if chartOpts.heading? d3.select("div#htmlwidget_container") .insert("h2", ":first-child") .html(chartOpts.heading) .style("font-family", "sans-serif") if chartOpts.caption? d3.select("body") .append("p") .attr("class", "caption") .html(chartOpts.caption) if chartOpts.footer? d3.select("body") .append("div") .html(chartOpts.footer) .style("font-family", "sans-serif")
[ { "context": "ント連携:\"\n and: \"と\"\n back: \"戻る\"\n changePassword: \"パスワードを変更する\"\n choosePassword: \"パスワードを選ぶ\"\n clickAgree: ", "end": 142, "score": 0.8702144622802734, "start": 137, "tag": "PASSWORD", "value": "パスワード" }, { "context": "\n and: \"と\"\n back: \"戻る\"\n change...
t9n/ja.coffee
coWorkr-InSights/meteor-accounts-t9n
80
#Language: Japanese #Translators: y-ich and exKAZUu ja = t9Name: '日本語' add: "アカウント連携:" and: "と" back: "戻る" changePassword: "パスワードを変更する" choosePassword: "パスワードを選ぶ" clickAgree: "アカウント登録をクリックすると、次の内容に同意したことになります。" configure: "設定する" createAccount: "新しいアカウントの登録" currentPassword: "現在のパスワード" dontHaveAnAccount: "まだアカウントをお持ちでない場合は" Email: "メールアドレス" email: "メールアドレス" emailAddress: "メールアドレス" emailResetLink: "パスワードリセットのメールを送る" forgotPassword: "パスワードをお忘れですか?" ifYouAlreadyHaveAnAccount: "既にアカウントをお持ちの場合は" newPassword: "新しいパスワード" newPasswordAgain: "新しいパスワード(確認)" optional: "オプション" OR: "または" password: "パスワード" passwordAgain: "パスワード(確認)" privacyPolicy: "プライバシーポリシー" remove: "連携の解除:" resetYourPassword: "パスワードのリセット" setPassword: "パスワードを設定する" sign: "署名" signIn: "ログイン" signin: "ログイン" signOut: "ログアウト" signUp: "アカウント登録" signupCode: "登録用コード" signUpWithYourEmailAddress: "メールアドレスで登録する" terms: "利用規約" updateYourPassword: "パスワードを変更する" username: "ユーザー名" usernameOrEmail: "ユーザー名またはメールアドレス" with: ":" maxAllowedLength: "最大文字数" minRequiredLength: "最低文字数" resendVerificationEmail: "認証メールの再送" resendVerificationEmailLink_pre: "認証メールが届いていない場合は" resendVerificationEmailLink_link: "再送" info: emailSent: "メールを送りました" emailVerified: "メールアドレスを確認しました" passwordChanged: "パスワードを変更しました" passwordReset: "パスワードをリセットしました" error: emailRequired: "メールアドレスを入力してください。" minChar: "パスワードの文字数が足りません。" pwdsDontMatch: "パスワードが一致しません。" pwOneDigit: "パスワードに1文字以上の数字を含めてください。" pwOneLetter: "パスワードに1文字以上のアルファベットを含めてください。" signInRequired: "その操作にはログインが必要です。" signupCodeIncorrect: "登録用コードが間違っています。" signupCodeRequired: "登録用コードが必要です。" usernameIsEmail: "ユーザー名にメールアドレスは使えません。" usernameRequired: "ユーザー名が必要です。" accounts: #---- accounts-base #"@" + domain + " email required" #"A login handler should return a result or undefined" "Email already exists.": "そのメールアドレスは既に登録されています。" "Email doesn't match the criteria.": "正しいメールアドレスを入力してください。" "Invalid login token": "無効なログイントークンです。" "Login forbidden": "ログインできません。" #"Service " + options.service + " already configured" "Service unknown": "不明なサービスです" "Unrecognized options for login request": "不明なログインオプションです" "User validation failed": "ユーザ認証に失敗しました" "Username already exists.": "そのユーザー名は既に使われています。" "You are not logged in.": "ログインしていません。" "You've been logged out by the server. Please log in again.": "既にログアウトしています。再度ログインしてください。" "Your session has expired. Please log in again.": "セッションが切れました。再度ログインしてください。" "Already verified": "認証済です" #---- accounts-oauth "No matching login attempt found": "対応するログイン試行が見つかりません" #---- accounts-password-client "Password is old. Please reset your password.": "古いパスワードです。パスワードをリセットしてください。" #---- accounts-password "Incorrect password": "パスワードが正しくありません" "Invalid email": "無効なメールアドレスです" "Must be logged in": "ログインが必要です" "Need to set a username or email": "ユーザー名かメールアドレスを入力してください" "old password format": "古いパスワード形式です" "Password may not be empty": "パスワードを入力してください" "Signups forbidden": "アカウントを登録できません" "Token expired": "無効なトークンです" "Token has invalid email address": "トークンに無効なメールアドレスが含まれています" "User has no password set": "パスワードが設定されていません" "User not found": "ユーザー名が見つかりません" "Verify email link expired": "期限の切れた認証メールのリンクです" "Verify email link is for unknown address": "不明なメールアドレスに対する認証メールのリンクです" "At least 1 digit, 1 lowercase and 1 uppercase": "数字、小文字、大文字をそれぞれ1文字以上入力してください" "Please verify your email first. Check the email and follow the link!": "まず認証メールが届いているか確認して、リンクを押してください!" "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "新しいメールを送信しました。もしメールが届いていなければ、迷惑メールに分類されていないか確認してください。" #---- match "Match failed": "一致しません" #---- Misc... "Unknown error": "不明なエラー" T9n?.map "ja", ja module?.exports = ja
126330
#Language: Japanese #Translators: y-ich and exKAZUu ja = t9Name: '日本語' add: "アカウント連携:" and: "と" back: "戻る" changePassword: "<PASSWORD>を<PASSWORD>する" choosePassword: "<PASSWORD>" clickAgree: "アカウント登録をクリックすると、次の内容に同意したことになります。" configure: "設定する" createAccount: "新しいアカウントの登録" currentPassword: "<PASSWORD>" dontHaveAnAccount: "まだアカウントをお持ちでない場合は" Email: "メールアドレス" email: "メールアドレス" emailAddress: "メールアドレス" emailResetLink: "パスワードリセットのメールを送る" forgotPassword: "<PASSWORD>ですか?" ifYouAlreadyHaveAnAccount: "既にアカウントをお持ちの場合は" newPassword: "<PASSWORD>" newPasswordAgain: "<PASSWORD>)" optional: "オプション" OR: "または" password: "<PASSWORD>" passwordAgain: "<PASSWORD>)" privacyPolicy: "プライバシーポリシー" remove: "連携の解除:" resetYourPassword: "<PASSWORD>" setPassword: "<PASSWORD>" sign: "署名" signIn: "ログイン" signin: "ログイン" signOut: "ログアウト" signUp: "アカウント登録" signupCode: "登録用コード" signUpWithYourEmailAddress: "メールアドレスで登録する" terms: "利用規約" updateYourPassword: "<PASSWORD>を変更する" username: "ユーザー名" usernameOrEmail: "ユーザー名またはメールアドレス" with: ":" maxAllowedLength: "最大文字数" minRequiredLength: "最低文字数" resendVerificationEmail: "認証メールの再送" resendVerificationEmailLink_pre: "認証メールが届いていない場合は" resendVerificationEmailLink_link: "再送" info: emailSent: "メールを送りました" emailVerified: "メールアドレスを確認しました" passwordChanged: "<PASSWORD>" passwordReset: "パスワードをリセットしました" error: emailRequired: "メールアドレスを入力してください。" minChar: "パスワードの文字数が足りません。" pwdsDontMatch: "パスワードが一致しません。" pwOneDigit: "パスワードに1文字以上の数字を含めてください。" pwOneLetter: "パスワードに1文字以上のアルファベットを含めてください。" signInRequired: "その操作にはログインが必要です。" signupCodeIncorrect: "登録用コードが間違っています。" signupCodeRequired: "登録用コードが必要です。" usernameIsEmail: "ユーザー名にメールアドレスは使えません。" usernameRequired: "ユーザー名が必要です。" accounts: #---- accounts-base #"@" + domain + " email required" #"A login handler should return a result or undefined" "Email already exists.": "そのメールアドレスは既に登録されています。" "Email doesn't match the criteria.": "正しいメールアドレスを入力してください。" "Invalid login token": "無効なログイントークンです。" "Login forbidden": "ログインできません。" #"Service " + options.service + " already configured" "Service unknown": "不明なサービスです" "Unrecognized options for login request": "不明なログインオプションです" "User validation failed": "ユーザ認証に失敗しました" "Username already exists.": "そのユーザー名は既に使われています。" "You are not logged in.": "ログインしていません。" "You've been logged out by the server. Please log in again.": "既にログアウトしています。再度ログインしてください。" "Your session has expired. Please log in again.": "セッションが切れました。再度ログインしてください。" "Already verified": "認証済です" #---- accounts-oauth "No matching login attempt found": "対応するログイン試行が見つかりません" #---- accounts-password-client "Password is old. Please reset your password.": "古いパスワードです。パスワードをリセットしてください。" #---- accounts-password "Incorrect password": "パスワードが正しくありません" "Invalid email": "無効なメールアドレスです" "Must be logged in": "ログインが必要です" "Need to set a username or email": "ユーザー名かメールアドレスを入力してください" "old password format": "古いパスワード形式です" "Password may not be empty": "パスワードを入力してください" "Signups forbidden": "アカウントを登録できません" "Token expired": "無効なトークンです" "Token has invalid email address": "トークンに無効なメールアドレスが含まれています" "User has no password set": "パスワードが設定されていません" "User not found": "ユーザー名が見つかりません" "Verify email link expired": "期限の切れた認証メールのリンクです" "Verify email link is for unknown address": "不明なメールアドレスに対する認証メールのリンクです" "At least 1 digit, 1 lowercase and 1 uppercase": "数字、小文字、大文字をそれぞれ1文字以上入力してください" "Please verify your email first. Check the email and follow the link!": "まず認証メールが届いているか確認して、リンクを押してください!" "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "新しいメールを送信しました。もしメールが届いていなければ、迷惑メールに分類されていないか確認してください。" #---- match "Match failed": "一致しません" #---- Misc... "Unknown error": "不明なエラー" T9n?.map "ja", ja module?.exports = ja
true
#Language: Japanese #Translators: y-ich and exKAZUu ja = t9Name: '日本語' add: "アカウント連携:" and: "と" back: "戻る" changePassword: "PI:PASSWORD:<PASSWORD>END_PIをPI:PASSWORD:<PASSWORD>END_PIする" choosePassword: "PI:PASSWORD:<PASSWORD>END_PI" clickAgree: "アカウント登録をクリックすると、次の内容に同意したことになります。" configure: "設定する" createAccount: "新しいアカウントの登録" currentPassword: "PI:PASSWORD:<PASSWORD>END_PI" dontHaveAnAccount: "まだアカウントをお持ちでない場合は" Email: "メールアドレス" email: "メールアドレス" emailAddress: "メールアドレス" emailResetLink: "パスワードリセットのメールを送る" forgotPassword: "PI:PASSWORD:<PASSWORD>END_PIですか?" ifYouAlreadyHaveAnAccount: "既にアカウントをお持ちの場合は" newPassword: "PI:PASSWORD:<PASSWORD>END_PI" newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI)" optional: "オプション" OR: "または" password: "PI:PASSWORD:<PASSWORD>END_PI" passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI)" privacyPolicy: "プライバシーポリシー" remove: "連携の解除:" resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI" setPassword: "PI:PASSWORD:<PASSWORD>END_PI" sign: "署名" signIn: "ログイン" signin: "ログイン" signOut: "ログアウト" signUp: "アカウント登録" signupCode: "登録用コード" signUpWithYourEmailAddress: "メールアドレスで登録する" terms: "利用規約" updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PIを変更する" username: "ユーザー名" usernameOrEmail: "ユーザー名またはメールアドレス" with: ":" maxAllowedLength: "最大文字数" minRequiredLength: "最低文字数" resendVerificationEmail: "認証メールの再送" resendVerificationEmailLink_pre: "認証メールが届いていない場合は" resendVerificationEmailLink_link: "再送" info: emailSent: "メールを送りました" emailVerified: "メールアドレスを確認しました" passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI" passwordReset: "パスワードをリセットしました" error: emailRequired: "メールアドレスを入力してください。" minChar: "パスワードの文字数が足りません。" pwdsDontMatch: "パスワードが一致しません。" pwOneDigit: "パスワードに1文字以上の数字を含めてください。" pwOneLetter: "パスワードに1文字以上のアルファベットを含めてください。" signInRequired: "その操作にはログインが必要です。" signupCodeIncorrect: "登録用コードが間違っています。" signupCodeRequired: "登録用コードが必要です。" usernameIsEmail: "ユーザー名にメールアドレスは使えません。" usernameRequired: "ユーザー名が必要です。" accounts: #---- accounts-base #"@" + domain + " email required" #"A login handler should return a result or undefined" "Email already exists.": "そのメールアドレスは既に登録されています。" "Email doesn't match the criteria.": "正しいメールアドレスを入力してください。" "Invalid login token": "無効なログイントークンです。" "Login forbidden": "ログインできません。" #"Service " + options.service + " already configured" "Service unknown": "不明なサービスです" "Unrecognized options for login request": "不明なログインオプションです" "User validation failed": "ユーザ認証に失敗しました" "Username already exists.": "そのユーザー名は既に使われています。" "You are not logged in.": "ログインしていません。" "You've been logged out by the server. Please log in again.": "既にログアウトしています。再度ログインしてください。" "Your session has expired. Please log in again.": "セッションが切れました。再度ログインしてください。" "Already verified": "認証済です" #---- accounts-oauth "No matching login attempt found": "対応するログイン試行が見つかりません" #---- accounts-password-client "Password is old. Please reset your password.": "古いパスワードです。パスワードをリセットしてください。" #---- accounts-password "Incorrect password": "パスワードが正しくありません" "Invalid email": "無効なメールアドレスです" "Must be logged in": "ログインが必要です" "Need to set a username or email": "ユーザー名かメールアドレスを入力してください" "old password format": "古いパスワード形式です" "Password may not be empty": "パスワードを入力してください" "Signups forbidden": "アカウントを登録できません" "Token expired": "無効なトークンです" "Token has invalid email address": "トークンに無効なメールアドレスが含まれています" "User has no password set": "パスワードが設定されていません" "User not found": "ユーザー名が見つかりません" "Verify email link expired": "期限の切れた認証メールのリンクです" "Verify email link is for unknown address": "不明なメールアドレスに対する認証メールのリンクです" "At least 1 digit, 1 lowercase and 1 uppercase": "数字、小文字、大文字をそれぞれ1文字以上入力してください" "Please verify your email first. Check the email and follow the link!": "まず認証メールが届いているか確認して、リンクを押してください!" "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "新しいメールを送信しました。もしメールが届いていなければ、迷惑メールに分類されていないか確認してください。" #---- match "Match failed": "一致しません" #---- Misc... "Unknown error": "不明なエラー" T9n?.map "ja", ja module?.exports = ja
[ { "context": " field `_to`', (done) ->\n User.create [{name: 'Matteo'}, {name: 'Antonio'}], (err, users) ->\n retu", "end": 1236, "score": 0.9996916651725769, "start": 1230, "tag": "NAME", "value": "Matteo" }, { "context": "ne) ->\n User.create [{name: 'Matteo'}, {name: 'A...
test/crud/edge.test.coffee
mrbatista/loopback-connector-arangodb
15
## This test written in mocha+should.js should = require('./../init'); describe 'edge', () -> db = null User = null Friend = null FriendCustom = null before (done) -> db = getDataSource() User = db.define('User', { fullId: {type: String, _id: true}, name: {type: String} email: {type: String}, age: Number, }, updateOnLoad: true); Friend = db.define('Friend', { _id: {type: String, _id: true}, _from: {type: String, _from: true}, _to: {type: String, _to: true}, label: {type: String} }, {updateOnLoad: true, arangodb: {edge: true}}); FriendCustom = db.define('FriendCustom', { fullId: {type: String, _id: true}, from: {type: String, _from: true, required: true}, to: {type: String, _to: true, required: true}, label: {type: String} }, { updateOnLoad: true, arangodb: { collection: 'Friend', edge: true } }); db.automigrate done; beforeEach (done) -> User.destroyAll -> Friend.destroyAll done after (done) -> User.destroyAll -> Friend.destroyAll done it 'should report error create edge without field `_to`', (done) -> User.create [{name: 'Matteo'}, {name: 'Antonio'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_from: users[0].fullId, label: 'friend'}, (err) -> should.exist(err) err.name.should.equal('ArangoError') err.code.should.equal(400) err.message.should.match(/^\'to\' is missing, expecting|invalid edge attribute|edge attribute missing or invalid/) done() it 'should report error create edge without field `_from`', (done) -> User.create [{name: 'Matteo'}, {name: 'Antonio'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_to: users[0].fullId, label: 'friend'}, (err) -> should.exist(err) err.name.should.equal('ArangoError') err.code.should.equal(400) err.message.should.match(/^\'from\' is missing, expecting|invalid edge attribute|edge attribute missing or invalid/) done() it 'create edge should return default fields _to and _from', (done) -> User.create [{name: 'Matteo'}, {name: 'Antonio'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_from: users[0].fullId, _to: users[1].fullId, label: 'friend'}, (err, friend) -> return done err if err should.exist(friend) should.exist(friend.id) should.exist(friend._id) friend._from.should.equal(users[0].fullId) friend._to.should.equal(users[1].fullId) friend.label.should.equal('friend') done() it 'create edge should return custom fields `to` and `from` defined as `_to` and `_from`', (done) -> User.create [{name: 'Matteo'}, {name: 'Antonio'}], (err, users) -> return done err if err users.should.have.length(2) FriendCustom.create {from: users[1].fullId, to: users[0].fullId, label: 'friend'}, (err, friend) -> return done err if err should.exist(friend) should.exist(friend.id) should.exist(friend.fullId) friend.from.should.equal(users[1].fullId) friend.to.should.equal(users[0].fullId) friend.label.should.equal('friend') done()
211272
## This test written in mocha+should.js should = require('./../init'); describe 'edge', () -> db = null User = null Friend = null FriendCustom = null before (done) -> db = getDataSource() User = db.define('User', { fullId: {type: String, _id: true}, name: {type: String} email: {type: String}, age: Number, }, updateOnLoad: true); Friend = db.define('Friend', { _id: {type: String, _id: true}, _from: {type: String, _from: true}, _to: {type: String, _to: true}, label: {type: String} }, {updateOnLoad: true, arangodb: {edge: true}}); FriendCustom = db.define('FriendCustom', { fullId: {type: String, _id: true}, from: {type: String, _from: true, required: true}, to: {type: String, _to: true, required: true}, label: {type: String} }, { updateOnLoad: true, arangodb: { collection: 'Friend', edge: true } }); db.automigrate done; beforeEach (done) -> User.destroyAll -> Friend.destroyAll done after (done) -> User.destroyAll -> Friend.destroyAll done it 'should report error create edge without field `_to`', (done) -> User.create [{name: '<NAME>'}, {name: '<NAME>'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_from: users[0].fullId, label: 'friend'}, (err) -> should.exist(err) err.name.should.equal('ArangoError') err.code.should.equal(400) err.message.should.match(/^\'to\' is missing, expecting|invalid edge attribute|edge attribute missing or invalid/) done() it 'should report error create edge without field `_from`', (done) -> User.create [{name: '<NAME>'}, {name: '<NAME>'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_to: users[0].fullId, label: 'friend'}, (err) -> should.exist(err) err.name.should.equal('ArangoError') err.code.should.equal(400) err.message.should.match(/^\'from\' is missing, expecting|invalid edge attribute|edge attribute missing or invalid/) done() it 'create edge should return default fields _to and _from', (done) -> User.create [{name: '<NAME>'}, {name: '<NAME>'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_from: users[0].fullId, _to: users[1].fullId, label: 'friend'}, (err, friend) -> return done err if err should.exist(friend) should.exist(friend.id) should.exist(friend._id) friend._from.should.equal(users[0].fullId) friend._to.should.equal(users[1].fullId) friend.label.should.equal('friend') done() it 'create edge should return custom fields `to` and `from` defined as `_to` and `_from`', (done) -> User.create [{name: '<NAME>'}, {name: '<NAME>'}], (err, users) -> return done err if err users.should.have.length(2) FriendCustom.create {from: users[1].fullId, to: users[0].fullId, label: 'friend'}, (err, friend) -> return done err if err should.exist(friend) should.exist(friend.id) should.exist(friend.fullId) friend.from.should.equal(users[1].fullId) friend.to.should.equal(users[0].fullId) friend.label.should.equal('friend') done()
true
## This test written in mocha+should.js should = require('./../init'); describe 'edge', () -> db = null User = null Friend = null FriendCustom = null before (done) -> db = getDataSource() User = db.define('User', { fullId: {type: String, _id: true}, name: {type: String} email: {type: String}, age: Number, }, updateOnLoad: true); Friend = db.define('Friend', { _id: {type: String, _id: true}, _from: {type: String, _from: true}, _to: {type: String, _to: true}, label: {type: String} }, {updateOnLoad: true, arangodb: {edge: true}}); FriendCustom = db.define('FriendCustom', { fullId: {type: String, _id: true}, from: {type: String, _from: true, required: true}, to: {type: String, _to: true, required: true}, label: {type: String} }, { updateOnLoad: true, arangodb: { collection: 'Friend', edge: true } }); db.automigrate done; beforeEach (done) -> User.destroyAll -> Friend.destroyAll done after (done) -> User.destroyAll -> Friend.destroyAll done it 'should report error create edge without field `_to`', (done) -> User.create [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_from: users[0].fullId, label: 'friend'}, (err) -> should.exist(err) err.name.should.equal('ArangoError') err.code.should.equal(400) err.message.should.match(/^\'to\' is missing, expecting|invalid edge attribute|edge attribute missing or invalid/) done() it 'should report error create edge without field `_from`', (done) -> User.create [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_to: users[0].fullId, label: 'friend'}, (err) -> should.exist(err) err.name.should.equal('ArangoError') err.code.should.equal(400) err.message.should.match(/^\'from\' is missing, expecting|invalid edge attribute|edge attribute missing or invalid/) done() it 'create edge should return default fields _to and _from', (done) -> User.create [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}], (err, users) -> return done err if err users.should.have.length(2) Friend.create {_from: users[0].fullId, _to: users[1].fullId, label: 'friend'}, (err, friend) -> return done err if err should.exist(friend) should.exist(friend.id) should.exist(friend._id) friend._from.should.equal(users[0].fullId) friend._to.should.equal(users[1].fullId) friend.label.should.equal('friend') done() it 'create edge should return custom fields `to` and `from` defined as `_to` and `_from`', (done) -> User.create [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}], (err, users) -> return done err if err users.should.have.length(2) FriendCustom.create {from: users[1].fullId, to: users[0].fullId, label: 'friend'}, (err, friend) -> return done err if err should.exist(friend) should.exist(friend.id) should.exist(friend.fullId) friend.from.should.equal(users[1].fullId) friend.to.should.equal(users[0].fullId) friend.label.should.equal('friend') done()
[ { "context": "low copy of given object', ->\n obj = {name: 'des'}\n straightCopy = obj\n straightCopy.nam", "end": 5907, "score": 0.9845188856124878, "start": 5904, "tag": "NAME", "value": "des" }, { "context": " straightCopy = obj\n straightCopy.name = 'subash...
spec/demo/spec/javascripts/amp4e-components-rails/lib/utils_spec.coffee
desoleary/amp4e-components-rails
0
describe 'AMP4e.Utils', -> describe 'escapeRegex', -> it 'escapes special regex characters in a string', -> ## the first backslash escapes the backslash in the string and makes it ## easier to check for escaped characters esc = '\\' # standard pattern delimiter expect(AMP4e.Utils.escapeRegex('/')).to.eql "#{esc}/" # escape expect(AMP4e.Utils.escapeRegex(esc)).to.eql "#{esc}#{esc}" # anchors expect(AMP4e.Utils.escapeRegex('^')).to.eql "#{esc}^" expect(AMP4e.Utils.escapeRegex('$')).to.eql "#{esc}$" # quantifiers expect(AMP4e.Utils.escapeRegex('+')).to.eql "#{esc}+" expect(AMP4e.Utils.escapeRegex('?')).to.eql "#{esc}?" expect(AMP4e.Utils.escapeRegex('*')).to.eql "#{esc}*" expect(AMP4e.Utils.escapeRegex('{')).to.eql "#{esc}{" expect(AMP4e.Utils.escapeRegex('}')).to.eql "#{esc}}" # any character expect(AMP4e.Utils.escapeRegex('.')).to.eql "#{esc}." # subgroup expect(AMP4e.Utils.escapeRegex('(')).to.eql "#{esc}(" expect(AMP4e.Utils.escapeRegex(')')).to.eql "#{esc})" # "or" expect(AMP4e.Utils.escapeRegex('|')).to.eql "#{esc}|" # character class expect(AMP4e.Utils.escapeRegex('[')).to.eql "#{esc}[" expect(AMP4e.Utils.escapeRegex(']')).to.eql "#{esc}]" expect(AMP4e.Utils.escapeRegex('-')).to.eql "#{esc}-" describe 'toBoolean', -> it 'converts text to boolean', -> expect(AMP4e.Utils.toBoolean(' true ')).to.eql(true) expect(AMP4e.Utils.toBoolean('true')).to.eql(true) expect(AMP4e.Utils.toBoolean(true)).to.eql(true) expect(AMP4e.Utils.toBoolean(' false ')).to.eql(false) expect(AMP4e.Utils.toBoolean('false')).to.eql(false) expect(AMP4e.Utils.toBoolean(false)).to.eql(false) expect(AMP4e.Utils.toBoolean('adsklj')).to.eql('adsklj') expect(AMP4e.Utils.toBoolean(undefined)).to.eql(undefined ) expect(AMP4e.Utils.toBoolean({})).to.eql({}) expect(AMP4e.Utils.toBoolean([])).to.eql([]) describe 'toInteger', -> it 'converts numeric to integer', -> expect(AMP4e.Utils.toInteger('123')).to.eql(123) expect(AMP4e.Utils.toInteger('-123')).to.eql(-123) expect(AMP4e.Utils.toInteger(123)).to.eql(123) expect(AMP4e.Utils.toInteger(-123)).to.eql(-123) expect(AMP4e.Utils.toInteger('123d')).to.eql('123d') describe 'trim', -> it 'trims spaces at the start or end of a string', -> expect(AMP4e.Utils.trim(' abc 123')).to.eql('abc 123') it 'removes empty strings from an array', -> expect(AMP4e.Utils.trim([' ', '', '123'])).to.eql(['123']) it "returns the original object if it isn't an array or string", -> expect(AMP4e.Utils.trim({a:1})).to.eql({a:1}) describe 'isBlank', -> it 'returns true when given an undefined or null value', -> expect(AMP4e.Utils.isBlank(undefined)).to.eql(true) expect(AMP4e.Utils.isBlank(null)).to.eql(true) it 'returns true when given the string "null" (which is dumb and wrong but we might be stuck with it)', -> # 'null' is a non-blank string and should obviously NOT return true; # unfortunately we might rely on it somewhere, so it may not be safe to # fix it expect(AMP4e.Utils.isBlank('null')).to.eql(true) it 'returns true when given an empty string', -> expect(AMP4e.Utils.isBlank('')).to.eql(true) it 'returns true when given a string containing only spaces', -> expect(AMP4e.Utils.isBlank(' ')).to.eql(true) it 'returns true when given an empty object', -> expect(AMP4e.Utils.isBlank({})).to.eql(true) it 'returns true when given an empty array', -> expect(AMP4e.Utils.isBlank([])).to.eql(true) it 'returns false when given a non-blank string', -> expect(AMP4e.Utils.isBlank('s')).to.eql(false) it 'returns false when given a non-empty object', -> expect(AMP4e.Utils.isBlank({a: 'b'})).to.eql(false) it 'returns false when given a non-empty array', -> expect(AMP4e.Utils.isBlank([1])).to.eql(false) describe 'isNumeric', -> it 'returns true when given valid number', -> expect(AMP4e.Utils.isNumeric(Number.MAX_VALUE)).to.eql(true) expect(AMP4e.Utils.isNumeric(Number.MIN_VALUE)).to.eql(true) it 'returns false when given a non-number value', -> expect(AMP4e.Utils.isNumeric('')).to.eql(false) expect(AMP4e.Utils.isNumeric(' ')).to.eql(false) expect(AMP4e.Utils.isNumeric(null)).to.eql(false) expect(AMP4e.Utils.isNumeric('1234a')).to.eql(false) describe 'inspect', -> it 'inspects given object', -> obj = {some_property_name: 'some.property.value'} result = AMP4e.Utils.inspect(obj) expect(result).to.eql('"some_property_name" (string) => some.property.value') describe 'stringToList', -> it 'converts a string to a list', -> expect(AMP4e.Utils.stringToList('1234,1235')).to.eql(['1234', '1235']) expect(AMP4e.Utils.stringToList(' ')).to.be.empty expect(AMP4e.Utils.stringToList(undefined)).to.be.empty expect(AMP4e.Utils.stringToList(null)).to.be.empty expect(AMP4e.Utils.stringToList({})).to.be.empty expect(AMP4e.Utils.stringToList([])).to.be.empty it 'returns the original value if it is not string', -> expect(AMP4e.Utils.stringToList({name: 'des'})).to.eql({name: 'des'}) describe 'deepCopy', -> it 'returns the given argument if the argument is null', -> expect(AMP4e.Utils.deepCopy(null)).to.eql(null) expect(AMP4e.Utils.deepCopy(undefined)).to.eql(undefined) expect(AMP4e.Utils.deepCopy([])).to.eql([]) expect(AMP4e.Utils.deepCopy({})).to.eql({}) it 'returns the given argument if the argument is not an object', -> expect(AMP4e.Utils.deepCopy('some.string')).to.eql('some.string') it 'returns an shallow copy of given object', -> obj = {name: 'des'} straightCopy = obj straightCopy.name = 'subashis' expect(obj.name).to.eql('subashis') clone = AMP4e.Utils.deepCopy(obj) clone.name = 'des' expect(clone.name).to.eql('des') expect(obj.name).to.eql('subashis') describe 'format', -> it 'formats strings', -> expect(AMP4e.Utils.format("is too short (minimum is {0})", 5)).to.eql("is too short (minimum is 5)") describe 'camelCaseToUnderscore', -> it 'converts camelcase to underscore format', -> expect(AMP4e.Utils.camelCaseToUnderscore('NotificationAnnouncement')).to.eql('notification_announcement') it 'converts camelcase to another format', -> expect(AMP4e.Utils.camelCaseToUnderscore('NotificationAnnouncement', '-')).to.eql('notification-announcement') describe 'toLowerCase', -> it 'converts mixed case to lower case', -> expect(AMP4e.Utils.toLowerCase('toLowerCase')).to.eql('tolowercase') it 'returns original argument if not a string', -> expect(AMP4e.Utils.toLowerCase(1234)).to.eql(1234) describe 'capitalizeFirstLetter', -> it 'capitalizes first letter of sentence', -> expect(AMP4e.Utils.capitalizeFirstLetter('first letter of sentence should be capitalized')).to.eql('First letter of sentence should be capitalized') it 'does not change capital first letter', -> expect(AMP4e.Utils.capitalizeFirstLetter('Already capital')).to.eql('Already capital') it 'does not fail for empty string', -> expect(AMP4e.Utils.capitalizeFirstLetter('')).to.eql('') describe 'replaceAll', -> it 'replaces all occurrences in string', -> expect(AMP4e.Utils.replaceAll('http://url?a=b&AMP4e;c=d&AMP4e;e=f&AMP4e;g=h', '&AMP4e;', '&')).to.eql('http://url?a=b&c=d&e=f&g=h') it 'does not replace anything when substring not found', -> expect(AMP4e.Utils.replaceAll('some string with some words', 'another', 'string')).to.eql('some string with some words') it 'does not replace anything when substring is not string', -> expect(AMP4e.Utils.replaceAll('this is string', 1, 2)).to.eql('this is string') describe 'tokenKeys', -> it 'gets the unique keys embedded in a string', -> string = "If you're planning to {verb}, you should {verb} soon, or {consequence}" tokens = AMP4e.Utils.tokenKeys(string, '{', '}') expect(tokens).to.eql ['verb', 'consequence'] describe 'parameterize', -> it 'replaces spaces and special characters with a hyphen', -> expect(AMP4e.Utils.parameterize('john roderick')).to.eql 'john-roderick' # using `$` here also confirms the regex is properly escaped it 'replaces spaces and special characters with a custom separator', -> expect(AMP4e.Utils.parameterize('john roderick', separator: '$')).to.eql 'john$roderick' it 'trims extra separators from the start and end', -> expect(AMP4e.Utils.parameterize('$john roderick?')).to.eql 'john-roderick' it 'trims extra adjacent separators', -> expect(AMP4e.Utils.parameterize('john roderick')).to.eql 'john-roderick' it 'converts characters to lowercase', -> expect(AMP4e.Utils.parameterize('John Roderick')).to.eql 'john-roderick' it 'preserves case when the option is set', -> expect(AMP4e.Utils.parameterize('John Roderick', preserveCase: true)).to.eql 'John-Roderick' describe 'parseUrl', -> url = 'http://exAMP4ele.com:12345/path/to/resource?search=search%20term&option=5' it 'returns the base URL', -> expect(AMP4e.Utils.parseUrl(url).baseURL).to.eql 'http://exAMP4ele.com:12345/path/to/' it 'returns the document', -> expect(AMP4e.Utils.parseUrl(url).document).to.eql 'resource' it 'returns the domain', -> expect(AMP4e.Utils.parseUrl(url).domain).to.eql 'exAMP4ele.com' it 'returns the fullUrl', -> expect(AMP4e.Utils.parseUrl(url).fullUrl).to.eql url it 'returns the current parameters as a query string', -> theUrl = AMP4e.Utils.parseUrl(url) delete theUrl.params.option expect(theUrl.getQueryString()).to.eql 'search=search%20term' it 'returns the query string as an object', -> expect(AMP4e.Utils.parseUrl(url).params).to.eql search: 'search term' option: '5' it 'decodes + as spaces in parameters', -> expect(AMP4e.Utils.parseUrl('http://exAMP4ele.com/page?key+with+spaces=find+the+thing').params).to.eql {'key with spaces': 'find the thing'} it 'returns multi-value parameters as an array', -> expect(AMP4e.Utils.parseUrl('http://exAMP4ele.com/page?id%5B%5D=5&id%5B%5D=12').params).to.eql {id: ['5','12']} it 'returns the components of the path', -> expect(AMP4e.Utils.parseUrl(url).pathParts).to.eql ['path', 'to'] it 'returns the port', -> expect(AMP4e.Utils.parseUrl(url).port).to.eql 12345 it 'returns the protocol', -> expect(AMP4e.Utils.parseUrl(url).protocol).to.eql 'http' it 'returns the query', -> expect(AMP4e.Utils.parseUrl(url).query).to.eql 'search=search%20term&option=5' it 'returns the route', -> expect(AMP4e.Utils.parseUrl(url).route).to.eql '/path/to/resource?search=search%20term&option=5' describe 'pathVar', -> object = null beforeEach -> object = top: 'one' more: stuff: ['a','b'] it 'gets the value of a shallow object reference', -> expect(AMP4e.Utils.pathVar(object, 'top')).to.eql object.top it 'gets the value of a deep object reference', -> expect(AMP4e.Utils.pathVar(object, 'more.stuff')).to.eql object.more.stuff it 'sets the value of a shallow object reference', -> AMP4e.Utils.pathVar(object, 'top', 'two') expect(object.top).to.eql 'two' it 'sets the value of a deep object reference', -> AMP4e.Utils.pathVar(object, 'more.stuff', 5) expect(object.more.stuff).to.eql 5 it "returns undefined if a reference doesn't exist", -> expect(AMP4e.Utils.pathVar(object, 'non.existent.path')).to.eql undefined describe 'sum', -> it 'returns the sum of an array', -> expect(AMP4e.Utils.sum([1,2,3])).to.eql 6 context 'if the argument is not an array', -> consoleErrorStub = null beforeEach -> # stub this so we don't litter the actual console while running tests consoleErrorStub = sinon.stub(window.console, 'error') afterEach -> consoleErrorStub.restore() it 'returns undefined', -> expect(AMP4e.Utils.sum('derp')).to.eql undefined it 'writes to console.error', -> AMP4e.Utils.sum('derp') expect(consoleErrorStub.calledOnce).to.eql true describe 'typeOf', -> it "returns {} → 'object'", -> expect(AMP4e.Utils.typeOf {}).to.eql 'object' it "returns [] → 'array'", -> expect(AMP4e.Utils.typeOf []).to.eql 'array' it "returns '' → 'string'", -> expect(AMP4e.Utils.typeOf '').to.eql 'string' it "returns 1 → 'number'", -> expect(AMP4e.Utils.typeOf 1).to.eql 'number' it "returns // → 'regexp'", -> expect(AMP4e.Utils.typeOf(/xx/)).to.eql 'regexp' it "returns true → 'boolean'", -> expect(AMP4e.Utils.typeOf true).to.eql 'boolean' describe 'isEmail', -> context 'valid emails', -> valid_emails = ["a+b@plus-in-local.com", "a_b@underscore-in-local.com", "user@exAMP4ele.com", " user@exAMP4ele.com ", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@letters-in-local.org", "01234567890@numbers-in-local.net", "a@single-character-in-local.org", "one-character-third-level@a.exAMP4ele.com", "single-character-in-sld@x.org", "local@dash-in-sld.com", "letters-in-sld@123.com", "one-letter-sld@x.org", "uncommon-tld@sld.museum", "uncommon-tld@sld.travel", "uncommon-tld@sld.mobi", "country-code-tld@sld.uk", "country-code-tld@sld.rw", "local@sld.newTLD", "local@sub.domains.com", "aaa@bbb.co.jp", "nigel.worthington@big.co.uk", "f@c.com", "areallylongnameaasdfasdfasdfasdf@asdfasdfasdfasdfasdf.ab.cd.ef.gh.co.ca"] for email in valid_emails do (email) -> it "considers #{email} to be valid", -> expect(AMP4e.Utils.isEmail(email)).to.eql(true) context 'invalid emails', -> invalid_emails = [ "", "a", "a@", "a@b.", "f@s", "f@s.c", "@bar.com", "test@exAMP4ele.com@exAMP4ele.com", "test@", "@missing-local.org", "a b@space-in-local.com", "! \#$%\`|@invalid-characters-in-local.org", "<>@[]\`|@even-more-invalid-characters-in-local.org", "missing-sld@.com", "invalid-characters-in-sld@! \"\#$%(),/;<>_[]\`|.org", "missing-dot-before-tld@com", "missing-tld@sld.", " ", "missing-at-sign.net", "unbracketed-IP@127.0.0.1", "invalid-ip@127.0.0.1.26", "another-invalid-ip@127.0.0.256", "IP-and-port@127.0.0.1:25", "the-local-part-is-invalid-if-it-is-longer-than-sixty-four-characters@sld.net", "user@exAMP4ele.com\n<script>alert('hello')</script>" ] for email in invalid_emails do (email) -> it "considers #{email} to be invalid", -> expect(AMP4e.Utils.isEmail(email)).to.eql(false) describe 'isUrl', -> # https://github.com/jquery-validation/jquery-validation/blob/master/test/methods.js context 'valid urls', -> valid_urls = [ "http://bassistance.de/jquery/plugin.php?bla=blu", "https://bassistance.de/jquery/plugin.php?bla=blu", "http://www.føtex.dk/", "http://bösendorfer.de/", "http://142.42.1.1" ] for url in valid_urls do (url) -> it "considers #{url} to be valid", -> expect(AMP4e.Utils.isUrl(url)).to.eql(true) context 'invalid urls', -> invalid_urls = [ "htp://code.jquery.com/jquery-1.11.3.min.js", "http://192.168.8.", "http://bassistance", "http://bassistance.", "http://bassistance,de", "http://bassistance;de", "http://.bassistancede", "bassistance.de" ] for url in invalid_urls do (url) -> it "considers #{url} to be invalid", -> expect(AMP4e.Utils.isEmail(url)).to.eql(false)
70142
describe 'AMP4e.Utils', -> describe 'escapeRegex', -> it 'escapes special regex characters in a string', -> ## the first backslash escapes the backslash in the string and makes it ## easier to check for escaped characters esc = '\\' # standard pattern delimiter expect(AMP4e.Utils.escapeRegex('/')).to.eql "#{esc}/" # escape expect(AMP4e.Utils.escapeRegex(esc)).to.eql "#{esc}#{esc}" # anchors expect(AMP4e.Utils.escapeRegex('^')).to.eql "#{esc}^" expect(AMP4e.Utils.escapeRegex('$')).to.eql "#{esc}$" # quantifiers expect(AMP4e.Utils.escapeRegex('+')).to.eql "#{esc}+" expect(AMP4e.Utils.escapeRegex('?')).to.eql "#{esc}?" expect(AMP4e.Utils.escapeRegex('*')).to.eql "#{esc}*" expect(AMP4e.Utils.escapeRegex('{')).to.eql "#{esc}{" expect(AMP4e.Utils.escapeRegex('}')).to.eql "#{esc}}" # any character expect(AMP4e.Utils.escapeRegex('.')).to.eql "#{esc}." # subgroup expect(AMP4e.Utils.escapeRegex('(')).to.eql "#{esc}(" expect(AMP4e.Utils.escapeRegex(')')).to.eql "#{esc})" # "or" expect(AMP4e.Utils.escapeRegex('|')).to.eql "#{esc}|" # character class expect(AMP4e.Utils.escapeRegex('[')).to.eql "#{esc}[" expect(AMP4e.Utils.escapeRegex(']')).to.eql "#{esc}]" expect(AMP4e.Utils.escapeRegex('-')).to.eql "#{esc}-" describe 'toBoolean', -> it 'converts text to boolean', -> expect(AMP4e.Utils.toBoolean(' true ')).to.eql(true) expect(AMP4e.Utils.toBoolean('true')).to.eql(true) expect(AMP4e.Utils.toBoolean(true)).to.eql(true) expect(AMP4e.Utils.toBoolean(' false ')).to.eql(false) expect(AMP4e.Utils.toBoolean('false')).to.eql(false) expect(AMP4e.Utils.toBoolean(false)).to.eql(false) expect(AMP4e.Utils.toBoolean('adsklj')).to.eql('adsklj') expect(AMP4e.Utils.toBoolean(undefined)).to.eql(undefined ) expect(AMP4e.Utils.toBoolean({})).to.eql({}) expect(AMP4e.Utils.toBoolean([])).to.eql([]) describe 'toInteger', -> it 'converts numeric to integer', -> expect(AMP4e.Utils.toInteger('123')).to.eql(123) expect(AMP4e.Utils.toInteger('-123')).to.eql(-123) expect(AMP4e.Utils.toInteger(123)).to.eql(123) expect(AMP4e.Utils.toInteger(-123)).to.eql(-123) expect(AMP4e.Utils.toInteger('123d')).to.eql('123d') describe 'trim', -> it 'trims spaces at the start or end of a string', -> expect(AMP4e.Utils.trim(' abc 123')).to.eql('abc 123') it 'removes empty strings from an array', -> expect(AMP4e.Utils.trim([' ', '', '123'])).to.eql(['123']) it "returns the original object if it isn't an array or string", -> expect(AMP4e.Utils.trim({a:1})).to.eql({a:1}) describe 'isBlank', -> it 'returns true when given an undefined or null value', -> expect(AMP4e.Utils.isBlank(undefined)).to.eql(true) expect(AMP4e.Utils.isBlank(null)).to.eql(true) it 'returns true when given the string "null" (which is dumb and wrong but we might be stuck with it)', -> # 'null' is a non-blank string and should obviously NOT return true; # unfortunately we might rely on it somewhere, so it may not be safe to # fix it expect(AMP4e.Utils.isBlank('null')).to.eql(true) it 'returns true when given an empty string', -> expect(AMP4e.Utils.isBlank('')).to.eql(true) it 'returns true when given a string containing only spaces', -> expect(AMP4e.Utils.isBlank(' ')).to.eql(true) it 'returns true when given an empty object', -> expect(AMP4e.Utils.isBlank({})).to.eql(true) it 'returns true when given an empty array', -> expect(AMP4e.Utils.isBlank([])).to.eql(true) it 'returns false when given a non-blank string', -> expect(AMP4e.Utils.isBlank('s')).to.eql(false) it 'returns false when given a non-empty object', -> expect(AMP4e.Utils.isBlank({a: 'b'})).to.eql(false) it 'returns false when given a non-empty array', -> expect(AMP4e.Utils.isBlank([1])).to.eql(false) describe 'isNumeric', -> it 'returns true when given valid number', -> expect(AMP4e.Utils.isNumeric(Number.MAX_VALUE)).to.eql(true) expect(AMP4e.Utils.isNumeric(Number.MIN_VALUE)).to.eql(true) it 'returns false when given a non-number value', -> expect(AMP4e.Utils.isNumeric('')).to.eql(false) expect(AMP4e.Utils.isNumeric(' ')).to.eql(false) expect(AMP4e.Utils.isNumeric(null)).to.eql(false) expect(AMP4e.Utils.isNumeric('1234a')).to.eql(false) describe 'inspect', -> it 'inspects given object', -> obj = {some_property_name: 'some.property.value'} result = AMP4e.Utils.inspect(obj) expect(result).to.eql('"some_property_name" (string) => some.property.value') describe 'stringToList', -> it 'converts a string to a list', -> expect(AMP4e.Utils.stringToList('1234,1235')).to.eql(['1234', '1235']) expect(AMP4e.Utils.stringToList(' ')).to.be.empty expect(AMP4e.Utils.stringToList(undefined)).to.be.empty expect(AMP4e.Utils.stringToList(null)).to.be.empty expect(AMP4e.Utils.stringToList({})).to.be.empty expect(AMP4e.Utils.stringToList([])).to.be.empty it 'returns the original value if it is not string', -> expect(AMP4e.Utils.stringToList({name: 'des'})).to.eql({name: 'des'}) describe 'deepCopy', -> it 'returns the given argument if the argument is null', -> expect(AMP4e.Utils.deepCopy(null)).to.eql(null) expect(AMP4e.Utils.deepCopy(undefined)).to.eql(undefined) expect(AMP4e.Utils.deepCopy([])).to.eql([]) expect(AMP4e.Utils.deepCopy({})).to.eql({}) it 'returns the given argument if the argument is not an object', -> expect(AMP4e.Utils.deepCopy('some.string')).to.eql('some.string') it 'returns an shallow copy of given object', -> obj = {name: '<NAME>'} straightCopy = obj straightCopy.name = '<NAME>' expect(obj.name).to.eql('<NAME>') clone = AMP4e.Utils.deepCopy(obj) clone.name = '<NAME>' expect(clone.name).to.eql('<NAME>') expect(obj.name).to.eql('<NAME>') describe 'format', -> it 'formats strings', -> expect(AMP4e.Utils.format("is too short (minimum is {0})", 5)).to.eql("is too short (minimum is 5)") describe 'camelCaseToUnderscore', -> it 'converts camelcase to underscore format', -> expect(AMP4e.Utils.camelCaseToUnderscore('NotificationAnnouncement')).to.eql('notification_announcement') it 'converts camelcase to another format', -> expect(AMP4e.Utils.camelCaseToUnderscore('NotificationAnnouncement', '-')).to.eql('notification-announcement') describe 'toLowerCase', -> it 'converts mixed case to lower case', -> expect(AMP4e.Utils.toLowerCase('toLowerCase')).to.eql('tolowercase') it 'returns original argument if not a string', -> expect(AMP4e.Utils.toLowerCase(1234)).to.eql(1234) describe 'capitalizeFirstLetter', -> it 'capitalizes first letter of sentence', -> expect(AMP4e.Utils.capitalizeFirstLetter('first letter of sentence should be capitalized')).to.eql('First letter of sentence should be capitalized') it 'does not change capital first letter', -> expect(AMP4e.Utils.capitalizeFirstLetter('Already capital')).to.eql('Already capital') it 'does not fail for empty string', -> expect(AMP4e.Utils.capitalizeFirstLetter('')).to.eql('') describe 'replaceAll', -> it 'replaces all occurrences in string', -> expect(AMP4e.Utils.replaceAll('http://url?a=b&AMP4e;c=d&AMP4e;e=f&AMP4e;g=h', '&AMP4e;', '&')).to.eql('http://url?a=b&c=d&e=f&g=h') it 'does not replace anything when substring not found', -> expect(AMP4e.Utils.replaceAll('some string with some words', 'another', 'string')).to.eql('some string with some words') it 'does not replace anything when substring is not string', -> expect(AMP4e.Utils.replaceAll('this is string', 1, 2)).to.eql('this is string') describe 'tokenKeys', -> it 'gets the unique keys embedded in a string', -> string = "If you're planning to {verb}, you should {verb} soon, or {consequence}" tokens = AMP4e.Utils.tokenKeys(string, '{', '}') expect(tokens).to.eql ['verb', 'consequence'] describe 'parameterize', -> it 'replaces spaces and special characters with a hyphen', -> expect(AMP4e.Utils.parameterize('<NAME>')).to.eql '<NAME>-<NAME>' # using `$` here also confirms the regex is properly escaped it 'replaces spaces and special characters with a custom separator', -> expect(AMP4e.Utils.parameterize('<NAME>', separator: '$')).to.eql '<NAME>$ro<NAME>' it 'trims extra separators from the start and end', -> expect(AMP4e.Utils.parameterize('$<NAME>?')).to.eql '<NAME>-<NAME>' it 'trims extra adjacent separators', -> expect(AMP4e.Utils.parameterize('<NAME> <NAME>')).to.eql '<NAME>-<NAME>' it 'converts characters to lowercase', -> expect(AMP4e.Utils.parameterize('<NAME>')).to.eql '<NAME>-<NAME>' it 'preserves case when the option is set', -> expect(AMP4e.Utils.parameterize('<NAME>', preserveCase: true)).to.eql '<NAME>' describe 'parseUrl', -> url = 'http://exAMP4ele.com:12345/path/to/resource?search=search%20term&option=5' it 'returns the base URL', -> expect(AMP4e.Utils.parseUrl(url).baseURL).to.eql 'http://exAMP4ele.com:12345/path/to/' it 'returns the document', -> expect(AMP4e.Utils.parseUrl(url).document).to.eql 'resource' it 'returns the domain', -> expect(AMP4e.Utils.parseUrl(url).domain).to.eql 'exAMP4ele.com' it 'returns the fullUrl', -> expect(AMP4e.Utils.parseUrl(url).fullUrl).to.eql url it 'returns the current parameters as a query string', -> theUrl = AMP4e.Utils.parseUrl(url) delete theUrl.params.option expect(theUrl.getQueryString()).to.eql 'search=search%20term' it 'returns the query string as an object', -> expect(AMP4e.Utils.parseUrl(url).params).to.eql search: 'search term' option: '5' it 'decodes + as spaces in parameters', -> expect(AMP4e.Utils.parseUrl('http://exAMP4ele.com/page?key+with+spaces=find+the+thing').params).to.eql {'key with spaces': 'find the thing'} it 'returns multi-value parameters as an array', -> expect(AMP4e.Utils.parseUrl('http://exAMP4ele.com/page?id%5B%5D=5&id%5B%5D=12').params).to.eql {id: ['5','12']} it 'returns the components of the path', -> expect(AMP4e.Utils.parseUrl(url).pathParts).to.eql ['path', 'to'] it 'returns the port', -> expect(AMP4e.Utils.parseUrl(url).port).to.eql 12345 it 'returns the protocol', -> expect(AMP4e.Utils.parseUrl(url).protocol).to.eql 'http' it 'returns the query', -> expect(AMP4e.Utils.parseUrl(url).query).to.eql 'search=search%20term&option=5' it 'returns the route', -> expect(AMP4e.Utils.parseUrl(url).route).to.eql '/path/to/resource?search=search%20term&option=5' describe 'pathVar', -> object = null beforeEach -> object = top: 'one' more: stuff: ['a','b'] it 'gets the value of a shallow object reference', -> expect(AMP4e.Utils.pathVar(object, 'top')).to.eql object.top it 'gets the value of a deep object reference', -> expect(AMP4e.Utils.pathVar(object, 'more.stuff')).to.eql object.more.stuff it 'sets the value of a shallow object reference', -> AMP4e.Utils.pathVar(object, 'top', 'two') expect(object.top).to.eql 'two' it 'sets the value of a deep object reference', -> AMP4e.Utils.pathVar(object, 'more.stuff', 5) expect(object.more.stuff).to.eql 5 it "returns undefined if a reference doesn't exist", -> expect(AMP4e.Utils.pathVar(object, 'non.existent.path')).to.eql undefined describe 'sum', -> it 'returns the sum of an array', -> expect(AMP4e.Utils.sum([1,2,3])).to.eql 6 context 'if the argument is not an array', -> consoleErrorStub = null beforeEach -> # stub this so we don't litter the actual console while running tests consoleErrorStub = sinon.stub(window.console, 'error') afterEach -> consoleErrorStub.restore() it 'returns undefined', -> expect(AMP4e.Utils.sum('derp')).to.eql undefined it 'writes to console.error', -> AMP4e.Utils.sum('derp') expect(consoleErrorStub.calledOnce).to.eql true describe 'typeOf', -> it "returns {} → 'object'", -> expect(AMP4e.Utils.typeOf {}).to.eql 'object' it "returns [] → 'array'", -> expect(AMP4e.Utils.typeOf []).to.eql 'array' it "returns '' → 'string'", -> expect(AMP4e.Utils.typeOf '').to.eql 'string' it "returns 1 → 'number'", -> expect(AMP4e.Utils.typeOf 1).to.eql 'number' it "returns // → 'regexp'", -> expect(AMP4e.Utils.typeOf(/xx/)).to.eql 'regexp' it "returns true → 'boolean'", -> expect(AMP4e.Utils.typeOf true).to.eql 'boolean' describe 'isEmail', -> context 'valid emails', -> valid_emails = ["<EMAIL>", "<EMAIL>", "<EMAIL>", " <EMAIL> ", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>", "<EMAIL>"] for email in valid_emails do (email) -> it "considers #{email} to be valid", -> expect(AMP4e.Utils.isEmail(email)).to.eql(true) context 'invalid emails', -> invalid_emails = [ "", "a", "a@", "a@b.", "f@s", "<EMAIL>", "@bar.com", "<EMAIL>", "test@", "@missing-local.org", "a <EMAIL>", "! \#$%\`|@invalid-characters-in-local.org", "<>@[]\`|@even-more-invalid-characters-in-local.org", "missing-sld@.com", "invalid-characters-in-sld@! \"\#$%(),/;<>_[]\`|.org", "missing-dot-before-tld@com", "missing-tld@sld.", " ", "missing-at-sign.net", "unbracketed-IP@127.0.0.1", "invalid-ip@127.0.0.1.26", "another-invalid-ip@127.0.0.256", "IP-and-port@127.0.0.1:25", "the<EMAIL>-local-part<EMAIL>-is<EMAIL>-invalid<EMAIL>-if<EMAIL>-it-<EMAIL>", "<EMAIL>\n<script>alert('hello')</script>" ] for email in invalid_emails do (email) -> it "considers #{email} to be invalid", -> expect(AMP4e.Utils.isEmail(email)).to.eql(false) describe 'isUrl', -> # https://github.com/jquery-validation/jquery-validation/blob/master/test/methods.js context 'valid urls', -> valid_urls = [ "http://bassistance.de/jquery/plugin.php?bla=blu", "https://bassistance.de/jquery/plugin.php?bla=blu", "http://www.føtex.dk/", "http://bösendorfer.de/", "http://172.16.17.32" ] for url in valid_urls do (url) -> it "considers #{url} to be valid", -> expect(AMP4e.Utils.isUrl(url)).to.eql(true) context 'invalid urls', -> invalid_urls = [ "htp://code.jquery.com/jquery-1.11.3.min.js", "http://192.168.8.", "http://bassistance", "http://bassistance.", "http://bassistance,de", "http://bassistance;de", "http://.bassistancede", "bassistance.de" ] for url in invalid_urls do (url) -> it "considers #{url} to be invalid", -> expect(AMP4e.Utils.isEmail(url)).to.eql(false)
true
describe 'AMP4e.Utils', -> describe 'escapeRegex', -> it 'escapes special regex characters in a string', -> ## the first backslash escapes the backslash in the string and makes it ## easier to check for escaped characters esc = '\\' # standard pattern delimiter expect(AMP4e.Utils.escapeRegex('/')).to.eql "#{esc}/" # escape expect(AMP4e.Utils.escapeRegex(esc)).to.eql "#{esc}#{esc}" # anchors expect(AMP4e.Utils.escapeRegex('^')).to.eql "#{esc}^" expect(AMP4e.Utils.escapeRegex('$')).to.eql "#{esc}$" # quantifiers expect(AMP4e.Utils.escapeRegex('+')).to.eql "#{esc}+" expect(AMP4e.Utils.escapeRegex('?')).to.eql "#{esc}?" expect(AMP4e.Utils.escapeRegex('*')).to.eql "#{esc}*" expect(AMP4e.Utils.escapeRegex('{')).to.eql "#{esc}{" expect(AMP4e.Utils.escapeRegex('}')).to.eql "#{esc}}" # any character expect(AMP4e.Utils.escapeRegex('.')).to.eql "#{esc}." # subgroup expect(AMP4e.Utils.escapeRegex('(')).to.eql "#{esc}(" expect(AMP4e.Utils.escapeRegex(')')).to.eql "#{esc})" # "or" expect(AMP4e.Utils.escapeRegex('|')).to.eql "#{esc}|" # character class expect(AMP4e.Utils.escapeRegex('[')).to.eql "#{esc}[" expect(AMP4e.Utils.escapeRegex(']')).to.eql "#{esc}]" expect(AMP4e.Utils.escapeRegex('-')).to.eql "#{esc}-" describe 'toBoolean', -> it 'converts text to boolean', -> expect(AMP4e.Utils.toBoolean(' true ')).to.eql(true) expect(AMP4e.Utils.toBoolean('true')).to.eql(true) expect(AMP4e.Utils.toBoolean(true)).to.eql(true) expect(AMP4e.Utils.toBoolean(' false ')).to.eql(false) expect(AMP4e.Utils.toBoolean('false')).to.eql(false) expect(AMP4e.Utils.toBoolean(false)).to.eql(false) expect(AMP4e.Utils.toBoolean('adsklj')).to.eql('adsklj') expect(AMP4e.Utils.toBoolean(undefined)).to.eql(undefined ) expect(AMP4e.Utils.toBoolean({})).to.eql({}) expect(AMP4e.Utils.toBoolean([])).to.eql([]) describe 'toInteger', -> it 'converts numeric to integer', -> expect(AMP4e.Utils.toInteger('123')).to.eql(123) expect(AMP4e.Utils.toInteger('-123')).to.eql(-123) expect(AMP4e.Utils.toInteger(123)).to.eql(123) expect(AMP4e.Utils.toInteger(-123)).to.eql(-123) expect(AMP4e.Utils.toInteger('123d')).to.eql('123d') describe 'trim', -> it 'trims spaces at the start or end of a string', -> expect(AMP4e.Utils.trim(' abc 123')).to.eql('abc 123') it 'removes empty strings from an array', -> expect(AMP4e.Utils.trim([' ', '', '123'])).to.eql(['123']) it "returns the original object if it isn't an array or string", -> expect(AMP4e.Utils.trim({a:1})).to.eql({a:1}) describe 'isBlank', -> it 'returns true when given an undefined or null value', -> expect(AMP4e.Utils.isBlank(undefined)).to.eql(true) expect(AMP4e.Utils.isBlank(null)).to.eql(true) it 'returns true when given the string "null" (which is dumb and wrong but we might be stuck with it)', -> # 'null' is a non-blank string and should obviously NOT return true; # unfortunately we might rely on it somewhere, so it may not be safe to # fix it expect(AMP4e.Utils.isBlank('null')).to.eql(true) it 'returns true when given an empty string', -> expect(AMP4e.Utils.isBlank('')).to.eql(true) it 'returns true when given a string containing only spaces', -> expect(AMP4e.Utils.isBlank(' ')).to.eql(true) it 'returns true when given an empty object', -> expect(AMP4e.Utils.isBlank({})).to.eql(true) it 'returns true when given an empty array', -> expect(AMP4e.Utils.isBlank([])).to.eql(true) it 'returns false when given a non-blank string', -> expect(AMP4e.Utils.isBlank('s')).to.eql(false) it 'returns false when given a non-empty object', -> expect(AMP4e.Utils.isBlank({a: 'b'})).to.eql(false) it 'returns false when given a non-empty array', -> expect(AMP4e.Utils.isBlank([1])).to.eql(false) describe 'isNumeric', -> it 'returns true when given valid number', -> expect(AMP4e.Utils.isNumeric(Number.MAX_VALUE)).to.eql(true) expect(AMP4e.Utils.isNumeric(Number.MIN_VALUE)).to.eql(true) it 'returns false when given a non-number value', -> expect(AMP4e.Utils.isNumeric('')).to.eql(false) expect(AMP4e.Utils.isNumeric(' ')).to.eql(false) expect(AMP4e.Utils.isNumeric(null)).to.eql(false) expect(AMP4e.Utils.isNumeric('1234a')).to.eql(false) describe 'inspect', -> it 'inspects given object', -> obj = {some_property_name: 'some.property.value'} result = AMP4e.Utils.inspect(obj) expect(result).to.eql('"some_property_name" (string) => some.property.value') describe 'stringToList', -> it 'converts a string to a list', -> expect(AMP4e.Utils.stringToList('1234,1235')).to.eql(['1234', '1235']) expect(AMP4e.Utils.stringToList(' ')).to.be.empty expect(AMP4e.Utils.stringToList(undefined)).to.be.empty expect(AMP4e.Utils.stringToList(null)).to.be.empty expect(AMP4e.Utils.stringToList({})).to.be.empty expect(AMP4e.Utils.stringToList([])).to.be.empty it 'returns the original value if it is not string', -> expect(AMP4e.Utils.stringToList({name: 'des'})).to.eql({name: 'des'}) describe 'deepCopy', -> it 'returns the given argument if the argument is null', -> expect(AMP4e.Utils.deepCopy(null)).to.eql(null) expect(AMP4e.Utils.deepCopy(undefined)).to.eql(undefined) expect(AMP4e.Utils.deepCopy([])).to.eql([]) expect(AMP4e.Utils.deepCopy({})).to.eql({}) it 'returns the given argument if the argument is not an object', -> expect(AMP4e.Utils.deepCopy('some.string')).to.eql('some.string') it 'returns an shallow copy of given object', -> obj = {name: 'PI:NAME:<NAME>END_PI'} straightCopy = obj straightCopy.name = 'PI:NAME:<NAME>END_PI' expect(obj.name).to.eql('PI:NAME:<NAME>END_PI') clone = AMP4e.Utils.deepCopy(obj) clone.name = 'PI:NAME:<NAME>END_PI' expect(clone.name).to.eql('PI:NAME:<NAME>END_PI') expect(obj.name).to.eql('PI:NAME:<NAME>END_PI') describe 'format', -> it 'formats strings', -> expect(AMP4e.Utils.format("is too short (minimum is {0})", 5)).to.eql("is too short (minimum is 5)") describe 'camelCaseToUnderscore', -> it 'converts camelcase to underscore format', -> expect(AMP4e.Utils.camelCaseToUnderscore('NotificationAnnouncement')).to.eql('notification_announcement') it 'converts camelcase to another format', -> expect(AMP4e.Utils.camelCaseToUnderscore('NotificationAnnouncement', '-')).to.eql('notification-announcement') describe 'toLowerCase', -> it 'converts mixed case to lower case', -> expect(AMP4e.Utils.toLowerCase('toLowerCase')).to.eql('tolowercase') it 'returns original argument if not a string', -> expect(AMP4e.Utils.toLowerCase(1234)).to.eql(1234) describe 'capitalizeFirstLetter', -> it 'capitalizes first letter of sentence', -> expect(AMP4e.Utils.capitalizeFirstLetter('first letter of sentence should be capitalized')).to.eql('First letter of sentence should be capitalized') it 'does not change capital first letter', -> expect(AMP4e.Utils.capitalizeFirstLetter('Already capital')).to.eql('Already capital') it 'does not fail for empty string', -> expect(AMP4e.Utils.capitalizeFirstLetter('')).to.eql('') describe 'replaceAll', -> it 'replaces all occurrences in string', -> expect(AMP4e.Utils.replaceAll('http://url?a=b&AMP4e;c=d&AMP4e;e=f&AMP4e;g=h', '&AMP4e;', '&')).to.eql('http://url?a=b&c=d&e=f&g=h') it 'does not replace anything when substring not found', -> expect(AMP4e.Utils.replaceAll('some string with some words', 'another', 'string')).to.eql('some string with some words') it 'does not replace anything when substring is not string', -> expect(AMP4e.Utils.replaceAll('this is string', 1, 2)).to.eql('this is string') describe 'tokenKeys', -> it 'gets the unique keys embedded in a string', -> string = "If you're planning to {verb}, you should {verb} soon, or {consequence}" tokens = AMP4e.Utils.tokenKeys(string, '{', '}') expect(tokens).to.eql ['verb', 'consequence'] describe 'parameterize', -> it 'replaces spaces and special characters with a hyphen', -> expect(AMP4e.Utils.parameterize('PI:NAME:<NAME>END_PI')).to.eql 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' # using `$` here also confirms the regex is properly escaped it 'replaces spaces and special characters with a custom separator', -> expect(AMP4e.Utils.parameterize('PI:NAME:<NAME>END_PI', separator: '$')).to.eql 'PI:NAME:<NAME>END_PI$roPI:NAME:<NAME>END_PI' it 'trims extra separators from the start and end', -> expect(AMP4e.Utils.parameterize('$PI:NAME:<NAME>END_PI?')).to.eql 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' it 'trims extra adjacent separators', -> expect(AMP4e.Utils.parameterize('PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI')).to.eql 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' it 'converts characters to lowercase', -> expect(AMP4e.Utils.parameterize('PI:NAME:<NAME>END_PI')).to.eql 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' it 'preserves case when the option is set', -> expect(AMP4e.Utils.parameterize('PI:NAME:<NAME>END_PI', preserveCase: true)).to.eql 'PI:NAME:<NAME>END_PI' describe 'parseUrl', -> url = 'http://exAMP4ele.com:12345/path/to/resource?search=search%20term&option=5' it 'returns the base URL', -> expect(AMP4e.Utils.parseUrl(url).baseURL).to.eql 'http://exAMP4ele.com:12345/path/to/' it 'returns the document', -> expect(AMP4e.Utils.parseUrl(url).document).to.eql 'resource' it 'returns the domain', -> expect(AMP4e.Utils.parseUrl(url).domain).to.eql 'exAMP4ele.com' it 'returns the fullUrl', -> expect(AMP4e.Utils.parseUrl(url).fullUrl).to.eql url it 'returns the current parameters as a query string', -> theUrl = AMP4e.Utils.parseUrl(url) delete theUrl.params.option expect(theUrl.getQueryString()).to.eql 'search=search%20term' it 'returns the query string as an object', -> expect(AMP4e.Utils.parseUrl(url).params).to.eql search: 'search term' option: '5' it 'decodes + as spaces in parameters', -> expect(AMP4e.Utils.parseUrl('http://exAMP4ele.com/page?key+with+spaces=find+the+thing').params).to.eql {'key with spaces': 'find the thing'} it 'returns multi-value parameters as an array', -> expect(AMP4e.Utils.parseUrl('http://exAMP4ele.com/page?id%5B%5D=5&id%5B%5D=12').params).to.eql {id: ['5','12']} it 'returns the components of the path', -> expect(AMP4e.Utils.parseUrl(url).pathParts).to.eql ['path', 'to'] it 'returns the port', -> expect(AMP4e.Utils.parseUrl(url).port).to.eql 12345 it 'returns the protocol', -> expect(AMP4e.Utils.parseUrl(url).protocol).to.eql 'http' it 'returns the query', -> expect(AMP4e.Utils.parseUrl(url).query).to.eql 'search=search%20term&option=5' it 'returns the route', -> expect(AMP4e.Utils.parseUrl(url).route).to.eql '/path/to/resource?search=search%20term&option=5' describe 'pathVar', -> object = null beforeEach -> object = top: 'one' more: stuff: ['a','b'] it 'gets the value of a shallow object reference', -> expect(AMP4e.Utils.pathVar(object, 'top')).to.eql object.top it 'gets the value of a deep object reference', -> expect(AMP4e.Utils.pathVar(object, 'more.stuff')).to.eql object.more.stuff it 'sets the value of a shallow object reference', -> AMP4e.Utils.pathVar(object, 'top', 'two') expect(object.top).to.eql 'two' it 'sets the value of a deep object reference', -> AMP4e.Utils.pathVar(object, 'more.stuff', 5) expect(object.more.stuff).to.eql 5 it "returns undefined if a reference doesn't exist", -> expect(AMP4e.Utils.pathVar(object, 'non.existent.path')).to.eql undefined describe 'sum', -> it 'returns the sum of an array', -> expect(AMP4e.Utils.sum([1,2,3])).to.eql 6 context 'if the argument is not an array', -> consoleErrorStub = null beforeEach -> # stub this so we don't litter the actual console while running tests consoleErrorStub = sinon.stub(window.console, 'error') afterEach -> consoleErrorStub.restore() it 'returns undefined', -> expect(AMP4e.Utils.sum('derp')).to.eql undefined it 'writes to console.error', -> AMP4e.Utils.sum('derp') expect(consoleErrorStub.calledOnce).to.eql true describe 'typeOf', -> it "returns {} → 'object'", -> expect(AMP4e.Utils.typeOf {}).to.eql 'object' it "returns [] → 'array'", -> expect(AMP4e.Utils.typeOf []).to.eql 'array' it "returns '' → 'string'", -> expect(AMP4e.Utils.typeOf '').to.eql 'string' it "returns 1 → 'number'", -> expect(AMP4e.Utils.typeOf 1).to.eql 'number' it "returns // → 'regexp'", -> expect(AMP4e.Utils.typeOf(/xx/)).to.eql 'regexp' it "returns true → 'boolean'", -> expect(AMP4e.Utils.typeOf true).to.eql 'boolean' describe 'isEmail', -> context 'valid emails', -> valid_emails = ["PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", " PI:EMAIL:<EMAIL>END_PI ", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI"] for email in valid_emails do (email) -> it "considers #{email} to be valid", -> expect(AMP4e.Utils.isEmail(email)).to.eql(true) context 'invalid emails', -> invalid_emails = [ "", "a", "a@", "a@b.", "f@s", "PI:EMAIL:<EMAIL>END_PI", "@bar.com", "PI:EMAIL:<EMAIL>END_PI", "test@", "@missing-local.org", "a PI:EMAIL:<EMAIL>END_PI", "! \#$%\`|@invalid-characters-in-local.org", "<>@[]\`|@even-more-invalid-characters-in-local.org", "missing-sld@.com", "invalid-characters-in-sld@! \"\#$%(),/;<>_[]\`|.org", "missing-dot-before-tld@com", "missing-tld@sld.", " ", "missing-at-sign.net", "unbracketed-IP@127.0.0.1", "invalid-ip@127.0.0.1.26", "another-invalid-ip@127.0.0.256", "IP-and-port@127.0.0.1:25", "thePI:EMAIL:<EMAIL>END_PI-local-partPI:EMAIL:<EMAIL>END_PI-isPI:EMAIL:<EMAIL>END_PI-invalidPI:EMAIL:<EMAIL>END_PI-ifPI:EMAIL:<EMAIL>END_PI-it-PI:EMAIL:<EMAIL>END_PI", "PI:EMAIL:<EMAIL>END_PI\n<script>alert('hello')</script>" ] for email in invalid_emails do (email) -> it "considers #{email} to be invalid", -> expect(AMP4e.Utils.isEmail(email)).to.eql(false) describe 'isUrl', -> # https://github.com/jquery-validation/jquery-validation/blob/master/test/methods.js context 'valid urls', -> valid_urls = [ "http://bassistance.de/jquery/plugin.php?bla=blu", "https://bassistance.de/jquery/plugin.php?bla=blu", "http://www.føtex.dk/", "http://bösendorfer.de/", "http://PI:IP_ADDRESS:172.16.17.32END_PI" ] for url in valid_urls do (url) -> it "considers #{url} to be valid", -> expect(AMP4e.Utils.isUrl(url)).to.eql(true) context 'invalid urls', -> invalid_urls = [ "htp://code.jquery.com/jquery-1.11.3.min.js", "http://192.168.8.", "http://bassistance", "http://bassistance.", "http://bassistance,de", "http://bassistance;de", "http://.bassistancede", "bassistance.de" ] for url in invalid_urls do (url) -> it "considers #{url} to be invalid", -> expect(AMP4e.Utils.isEmail(url)).to.eql(false)
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9994750022888184, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-timers-ordering.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") Timer = process.binding("timer_wrap").Timer i = undefined N = 30 last_i = 0 last_ts = 0 start = Timer.now() f = (i) -> if i <= N # check order assert.equal i, last_i + 1, "order is broken: " + i + " != " + last_i + " + 1" last_i = i # check that this iteration is fired at least 1ms later than the previous now = Timer.now() console.log i, now assert now >= last_ts + 1, "current ts " + now + " < prev ts " + last_ts + " + 1" last_ts = now # schedule next iteration setTimeout f, 1, i + 1 return f 1
136257
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") Timer = process.binding("timer_wrap").Timer i = undefined N = 30 last_i = 0 last_ts = 0 start = Timer.now() f = (i) -> if i <= N # check order assert.equal i, last_i + 1, "order is broken: " + i + " != " + last_i + " + 1" last_i = i # check that this iteration is fired at least 1ms later than the previous now = Timer.now() console.log i, now assert now >= last_ts + 1, "current ts " + now + " < prev ts " + last_ts + " + 1" last_ts = now # schedule next iteration setTimeout f, 1, i + 1 return f 1
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") Timer = process.binding("timer_wrap").Timer i = undefined N = 30 last_i = 0 last_ts = 0 start = Timer.now() f = (i) -> if i <= N # check order assert.equal i, last_i + 1, "order is broken: " + i + " != " + last_i + " + 1" last_i = i # check that this iteration is fired at least 1ms later than the previous now = Timer.now() console.log i, now assert now >= last_ts + 1, "current ts " + now + " < prev ts " + last_ts + " + 1" last_ts = now # schedule next iteration setTimeout f, 1, i + 1 return f 1
[ { "context": "iusX: 20\n # size = byte._getRadiusSize key: 'radiusX', fallback: 0\n # expect(size).toBe 20\n # ", "end": 39474, "score": 0.9676435589790344, "start": 39467, "tag": "KEY", "value": "radiusX" }, { "context": "new Byte\n # size = byte._getRadiusSize key...
spec/shape.coffee
jcansdale-test/mojs
3,556
Byte = mojs.Shape Shape = mojs.Shape Bit = mojs.shapesMap.getShape('bit') Thenable = mojs.Thenable Tunable = mojs.Tunable Tweenable = mojs.Tweenable Rect = mojs.shapesMap.getShape('rect') h = mojs.helpers ns = 'http://www.w3.org/2000/svg' svg = document.createElementNS?(ns, 'svg') # console.log = -> console.warn = -> console.error = -> describe 'Shape ->', -> describe '_vars method', -> it 'should have own _vars function ->', -> byte = new Byte expect(byte._vars).toBeDefined() expect(-> byte._vars()).not.toThrow() it 'should call _vars super method', -> byte = new Byte expect(byte._history.length).toBe 1 it 'should save passed _o.masterModule to _masterModule', -> obj = {} byte = new Byte masterModule: obj byte._masterModule = null byte._vars() expect(byte._masterModule).toBe obj it 'should set `_isChained` based on `prevChainModule` option', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 byte._isChained = null byte._vars() expect(byte._isChained).toBe true # old # it 'should save passed _o.positionEl to el', -> # obj = document.createElement 'div' # byte = new Byte positionEl: obj # byte.el = null # byte._vars() # expect(byte.el).toBe obj # old # it 'should save passed _o.shiftEl to el', -> # obj = document.createElement 'div' # byte = new Byte shiftEl: obj # byte.el = null # byte._vars() # expect(byte.el).toBe obj it 'should save passed _o.prevChainModule to _prevChainModule', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 byte._prevChainModule = null byte._vars() expect(byte._prevChainModule).toBe byte0 describe 'extension ->', -> it 'should extend Tweenable class', -> byte = new Byte expect(byte instanceof Tweenable).toBe(true) it 'should extend Thenable class', -> byte = new Byte expect(byte instanceof Thenable).toBe(true) describe 'defaults object ->', -> it 'should have defaults object', -> byte = new Byte expect(byte._defaults).toBeDefined() expect(byte._defaults.parent).toBe document.body expect(byte._defaults.className).toBe '' expect(byte._defaults.shape).toBe 'circle' expect(byte._defaults.stroke).toBe 'transparent' expect(byte._defaults.strokeOpacity).toBe 1 expect(byte._defaults.strokeLinecap).toBe '' expect(byte._defaults.strokeWidth).toBe 2 expect(byte._defaults.strokeDasharray).toBe 0 expect(byte._defaults.strokeDashoffset).toBe 0 expect(byte._defaults.fill).toBe 'deeppink' expect(byte._defaults.fillOpacity).toBe 1 expect(byte._defaults.isSoftHide).toBe true expect(byte._defaults.isForce3d).toBe false expect(byte._defaults.left).toBe '50%' expect(byte._defaults.top).toBe '50%' expect(byte._defaults.x).toBe 0 expect(byte._defaults.y).toBe 0 expect(byte._defaults.rotate).toBe 0 expect(byte._defaults.scale).toEqual 1 expect(byte._defaults.scaleX).toBe null expect(byte._defaults.scaleY).toBe null expect(byte._defaults.origin).toBe '50% 50%' expect(byte._defaults.rx).toBe 0 expect(byte._defaults.ry).toBe 0 expect(byte._defaults.opacity).toBe 1 expect(byte._defaults.points).toBe 3 expect(byte._defaults.duration).toBe 400 expect(byte._defaults.radius).toBe 50 expect(byte._defaults.radiusX).toBe null expect(byte._defaults.radiusY).toBe null expect(byte._defaults.isShowEnd).toBe true expect(byte._defaults.isShowStart).toBe false expect(byte._defaults.isRefreshState).toBe true # nope # expect(byte._defaults.size).toBe null expect(byte._defaults.width).toBe null expect(byte._defaults.height).toBe null # expect(byte._defaults.sizeGap).toBe 0 expect(byte._defaults.isWithShape).toBe true expect(byte._defaults.callbacksContext).toBe byte describe '_applyCallbackOverrides ->', -> it 'should create callbackOverrides object on passed object', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) expect(typeof obj.callbackOverrides).toBe 'object' # not null expect(obj.callbackOverrides).toBe obj.callbackOverrides describe 'onUpdate callback override ->', -> it 'should override this._o.onUpdate', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) expect(typeof obj.callbackOverrides.onUpdate).toBe 'function' it 'should call _setProgress ', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) spyOn tr, '_setProgress' easedProgress = .25 progress = .2 obj.callbackOverrides.onUpdate easedProgress, progress expect(tr._setProgress).toHaveBeenCalledWith easedProgress, progress it 'should not override onUpdate function if exists', -> isRightScope = null; args = null options = { easing: 'Linear.None', onUpdate:-> isRightScope = @ is tr args = arguments } tr = new Shape options expect(typeof tr._o.onUpdate).toBe 'function' tr.timeline.setProgress 0 tr.timeline.setProgress .1 expect(isRightScope).toBe true expect(args[0]).toBe .1 expect(args[1]).toBe .1 expect(args[2]).toBe true expect(args[3]).toBe false it 'should call _setProgress method', -> options = { easing: 'Linear.None', onUpdate:-> } obj = {} tr = new Shape options tr.timeline.setProgress 0 spyOn tr, '_setProgress' progress = .1 tr.timeline.setProgress progress expect(tr._setProgress.calls.first().args[0]).toBeCloseTo progress, 5 describe 'onStart callback override ->', -> it 'should override this._o.onStart', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onStart).toBe 'function' it 'should call _show if isForward and !_isChained', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onStart true expect(tr._show).toHaveBeenCalled() it 'should not call _show if _isChained', -> tr = new Shape masterModule: new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onStart true expect(tr._show).not.toHaveBeenCalled() it 'should call _hide if not isForward and !_isChained', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).toHaveBeenCalled() it 'should not call _hide if not isForward and _isChained', -> tr = new Shape masterModule: new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if not isForward and isShowStart', -> tr = new Shape isShowStart: true obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).not.toHaveBeenCalled() describe 'onComplete callback override ->', -> it 'should override this._o.onComplete', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onComplete).toBe 'function' it 'should call _show if !isForward', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).toHaveBeenCalled() it 'should call _show if !isForward and _isLastInChain()', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).toHaveBeenCalled() it 'should call _show if !isForward and _isLastInChain() #2', -> tr = new Shape().then radius: 0 el = tr._modules[1] obj = {} el._applyCallbackOverrides( obj ) spyOn el, '_show' obj.callbackOverrides.onComplete false expect(el._show).toHaveBeenCalled() it 'should not call _show if !isForward and not _isLastInChain', -> tr = new Shape().then radius: 0 obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).not.toHaveBeenCalled() it 'should call _hide if isForward and !isShowEnd', -> tr = new Shape isShowEnd: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).toHaveBeenCalled() it 'should not call _hide if isForward but isShowEnd', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should call _hide if isForward and _isLastInChain', -> tr = new Shape isShowEnd: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).toHaveBeenCalled() it 'should call not _hide if isForward and !_isLastInChain', -> tr = new Shape(isShowEnd: false).then({ radius: 0 }) # module = tr._modules[1] obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if isForward and _isLastInChain but isShowEnd', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if isForward but !_isLastInChain and isShowEnd', -> tr = new Shape().then radius: 0 obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() describe 'onRefresh callback override ->', -> it 'should override this._o.onRefresh', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onRefresh).toBe 'function' it 'should call _refreshBefore if isBefore', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh true expect(tr._refreshBefore).toHaveBeenCalled() it 'should not call _refreshBefore if !isBefore', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh false expect(tr._refreshBefore).not.toHaveBeenCalled() it 'should not call _refreshBefore if !isRefreshState', -> tr = new Shape isRefreshState: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh true expect(tr._refreshBefore).not.toHaveBeenCalled() describe '_transformTweenOptions method', -> it 'should call _applyCallbackOverrides with _o', -> tr = new Shape spyOn tr, '_applyCallbackOverrides' tr._transformTweenOptions() expect(tr._applyCallbackOverrides).toHaveBeenCalledWith tr._o describe 'options object ->', -> it 'should receive empty options object by default', -> byte = new Byte expect(byte._o).toBeDefined() it 'should receive options object', -> byte = new Byte option: 1 expect(byte._o.option).toBe 1 describe 'index option ->', -> it 'should receive index option', -> byte = new Shape index: 5 expect(byte._index).toBe 5 it 'should fallback to 0', -> byte = new Shape expect(byte._index).toBe 0 describe 'options history ->', -> it 'should have history array', -> byte = new Byte expect(h.isArray(byte._history)).toBe true it 'should save options to history array', -> byte = new Byte radius: 20 expect(byte._history.length).toBe 1 describe 'size calculations ->', -> it 'should not calculate size el size if size was passed', -> byte = new Byte radius: 10 strokeWidth: 5 width: 400 height: 200 expect(byte._props.shapeWidth).toBe(400) expect(byte._props.shapeHeight).toBe(200) describe 'opacity set ->', -> it 'should set opacity regarding units', -> byte = new Byte opacity: .5, isShowStart: true expect(byte.el.style.opacity).toBe '0.5' it 'should animate opacity', (dfr)-> byte = new Byte opacity: { 1: 0} duration: 100 onComplete:-> expect(byte.el.style.opacity).toBe('0'); dfr() byte.play() describe 'position set ->', -> describe 'x/y coordinates ->', -> it 'should set position regarding units', -> byte = new Byte left: 100, top: 50 expect(byte.el.style.left).toBe '100px' expect(byte.el.style.top) .toBe '50px' it 'should animate position', (dfr)-> byte = new Byte left: {100: '200px'} duration: 100 onComplete:-> expect(byte.el.style.left).toBe('200px'); dfr() byte.play() it 'should warn when x/y animated position and not foreign context',-> spyOn console, 'warn' byte = new Byte left: {100: '200px'} byte.play() expect(console.warn).toHaveBeenCalled() it 'should notwarn when x/y animated position and foreign context',-> spyOn console, 'warn' byte = new Byte left: {100: '200px'}, ctx: svg byte.play() expect(console.warn).not.toHaveBeenCalled() it 'should animate position regarding units', (dfr)-> byte = new Byte left: {'20%': '50%'} duration: 100 byte.play() setTimeout -> expect(byte.el.style.left) .toBe '50%' dfr() , 500 it 'end unit that were not specified should fallback to start unit', ()-> byte = new Byte left: {'20%': 50} duration: 200 byte.play() expect(byte._deltas.left.start.unit).toBe '%' expect(byte._deltas.left.end.unit) .toBe '%' it 'should fallback to end units if units are different', (dfr)-> byte = new Byte left: {'20%': '50px'} duration: 200 onComplete:-> expect(byte.el.style.left).toBe('50px'); dfr() byte.play() it 'should set position regarding units #2', -> byte = new Byte x: 100 y: 50, isShowStart: true s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isNormal = tr is 'translate(100px, 50px) rotate(0deg) scale(1, 1)' isIE = tr is 'translate(100px, 50px) rotate(0deg) scale(1)' expect(isNormal or isIE).toBe true it 'should animate shift position', (dfr)-> byte = new Byte x: {100: '200px'} duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(200px, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(200px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(200px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(200px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true dfr() byte.play() it 'should animate position regarding units #3', (dfr)-> byte = new Byte x: {'20%': '50%'} duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(50%, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(50%, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(50%, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(50%) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true dfr() byte.play() it 'should fallback to end units if units are differnt', (dfr)-> byte = new Byte x: { '20%': '50px' } y: { 0 : '50%' } duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr1 = tr is 'translate(50px, 50%) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(50px, 50%) rotate(0deg) scale(1)' expect(isTr1 or isTr2).toBe true dfr() byte.play() describe '_render method ->', -> it 'should call _createShape method', -> byte = new Byte radius: 25 spyOn byte, '_createShape' byte._isRendered = false byte._render() expect(byte._createShape).toHaveBeenCalled() it 'should set _isRendered to true', -> byte = new Byte radius: 25 expect(byte._isRendered).toBe true byte._isRendered = false; byte._render() expect(byte._isRendered).toBe true it 'should not call _createShape method if already rendered', -> byte = new Byte radius: 25 spyOn byte, '_createShape' byte._isRendered = true byte._render() expect(byte._createShape).not.toHaveBeenCalled() it 'should set `el` and `shape` if `_isChained`', -> byte0 = new Byte radius: 25 byte = new Byte prevChainModule: byte0 masterModule: byte0 expect(byte.el).toBe byte0.el expect(byte.shapeModule).toBe byte0.shapeModule it 'should not call _createShape method if _isChained', -> byte0 = new Byte byte = new Byte radius: 25 prevChainModule: byte0 masterModule: byte0 spyOn byte, '_createShape' byte._o.el = byte0.el byte._o.shapeModule = byte0.shapeModule byte._render() expect(byte._createShape).not.toHaveBeenCalled() it 'should call `_setProgress(0)` if not `_isChained`', -> byte = new Byte spyOn byte, '_setProgress' byte._isRendered = false byte._render() expect(byte._setProgress).toHaveBeenCalledWith(0, 0) it 'should not call `_setProgress(0)` if not `_isFirstInChain()`', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 spyOn byte, '_setProgress' byte._isRendered = false byte._render() expect(byte._setProgress).not.toHaveBeenCalledWith(0) it 'should call _setElStyles method', -> byte = new Byte radius: 25 spyOn byte, '_setElStyles' byte._isRendered = false byte._render() expect(byte._setElStyles).toHaveBeenCalled() it 'should not call _setElStyles method if _isChained', -> byte = new Byte prevChainModule: new Byte masterModule: new Byte spyOn byte, '_setElStyles' byte._isRendered = true byte._render() expect(byte._setElStyles).not.toHaveBeenCalled() it 'should call _show method if `isShowStart`', -> byte = new Byte isShowStart: true spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).toHaveBeenCalled() it 'should call not _show method if not `isShowStart`', -> byte = new Byte isShowStart: false spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).not.toHaveBeenCalled() it 'should not _show method if `_isChained`', -> byte = new Byte isShowStart: true, prevChainModule: new Byte masterModule: new Byte spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).not.toHaveBeenCalled() it 'should call _hide method if not `isShowStart`', -> byte = new Byte isShowStart: false spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).toHaveBeenCalled() it 'should call not _hide method if `isShowStart`', -> byte = new Byte isShowStart: true spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).not.toHaveBeenCalled() it 'should not _hide method if `_isChained`', -> byte = new Byte isShowStart: false, prevChainModule: new Byte masterModule: new Byte spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).not.toHaveBeenCalled() describe '_setElStyles method ->', -> it 'should set dimentions and position of the `el`', -> byte = new Byte radius: 25 byte.el.style.position = 'static' byte.el.style.width = '0px' byte.el.style.height = '0px' byte.el.style[ 'margin-left' ] = '0px' byte.el.style[ 'margin-top' ] = '0px' byte._setElStyles() expect( byte.el.style.position ).toBe 'absolute' expect( byte.el.style.width ).toBe "#{byte._props.shapeWidth}px" expect( byte.el.style.height ).toBe "#{byte._props.shapeHeight}px" expect( byte.el.style[ 'margin-left' ] ) .toBe "-#{byte._props.shapeWidth/2}px" expect( byte.el.style[ 'margin-top' ] ) .toBe "-#{byte._props.shapeHeight/2}px" it 'should set `backface-visibility` if `isForce3d`', -> byte = new Byte radius: 25, isForce3d: true style = byte.el.style bv = style[ 'backface-visibility' ] prefixedBv = style[ "#{mojs.h.prefix.css}backface-visibility" ] expect( bv or prefixedBv ).toBe 'hidden' it 'should not set `backface-visibility` if `isForce3d`', -> byte = new Byte radius: 25 style = byte.el.style bv = style[ 'backface-visibility' ] prefixedBv = style[ "#{mojs.h.prefix.css}backface-visibility" ] expect( bv or prefixedBv ).not.toBe 'hidden' describe '_draw method ->', -> # nope # it 'should call _setProp method', -> # byte = new Byte radius: 25 # spyOn byte.shapeModule, 'setProp' # byte._draw() # expect(byte.shapeModule.setProp).toHaveBeenCalled() it 'should set all attributes to shape\'s properties', -> byte = new Byte radius: 25, x: 20, y: 30, rx: 15, ry: 25 stroke: 'red' strokeWidth: 2 strokeOpacity: .5 strokeLinecap: 'round' strokeDasharray: 200 strokeDashoffset: 100 fill: 'cyan' fillOpacity: .5 radius: 100 radiusX: 22 radiusY: { 20: 0 } points: 4 byte._draw() # old # expect(byte.shapeModule._props.x).toBe byte._origin.x # old # expect(byte.shapeModule._props.y).toBe byte._origin.y expect(byte.shapeModule._props.rx).toBe byte._props.rx expect(byte.shapeModule._props.ry).toBe byte._props.ry expect(byte.shapeModule._props.stroke).toBe byte._props.stroke expect(byte.shapeModule._props['stroke-width']).toBe byte._props.strokeWidth expect(byte.shapeModule._props['stroke-opacity']).toBe byte._props.strokeOpacity expect(byte.shapeModule._props['stroke-linecap']).toBe byte._props.strokeLinecap expect(byte.shapeModule._props['stroke-dasharray']).toBe byte._props.strokeDasharray[0].value + ' ' expect(byte.shapeModule._props['stroke-dashoffset']).toBe byte._props.strokeDashoffset[0].value + ' ' expect(byte.shapeModule._props['fill']).toBe byte._props.fill expect(byte.shapeModule._props['fill-opacity']).toBe byte._props.fillOpacity expect(byte.shapeModule._props['radius']).toBe byte._props.radius expect(byte.shapeModule._props['radiusX']).toBe byte._props.radiusX expect(byte.shapeModule._props['radiusY']).toBe byte._props.radiusY expect(byte.shapeModule._props['points']).toBe byte._props.points # old # expect(byte.shapeModule._props['transform']).toBe byte._calcShapeTransform() it 'should call bit._draw method', -> byte = new Byte radius: 25 spyOn byte.shapeModule, '_draw' byte._draw() expect(byte.shapeModule._draw).toHaveBeenCalled() it 'should call _drawEl method', -> byte = new Byte radius: 25 spyOn byte, '_drawEl' byte._draw() expect(byte._drawEl).toHaveBeenCalled() it 'should receive the current progress', -> byte = new Byte radius: 25 spyOn byte, '_draw' byte._setProgress .5 expect(byte._draw).toHaveBeenCalledWith .5 describe '_drawEl method ->', -> it 'should set el positions and transforms', -> byte = new Byte radius: 25, top: 10, isShowStart: true expect(byte.el.style.top) .toBe '10px' expect(byte.el.style.opacity) .toBe '1' expect(byte.el.style.left).toBe '50%' s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set new values', -> byte = new Byte radius: 25, top: 10 byte._draw() byte._props.left = '1px' byte._draw() expect(byte.el.style.left).toBe '1px' expect(byte._lastSet.left.value) .toBe '1px' it 'should not set old values', -> byte = new Byte radius: 25, y: 10 byte._draw() byte._draw() expect(byte._lastSet.x.value) .toBe '0' it 'should return true if there is no el', -> byte = new Byte radius: 25 byte.el = null expect(byte._drawEl()).toBe true it 'should set transform if rotation is changed', -> byte = new Byte rotate: 25 byte._draw() byte._props.rotate = 26 byte._draw() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(26deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(26deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(26deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(26deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true # expect(byte.el.style["#{h.prefix.css}transform"]).toBe resultStr it 'should not set transform if rotation changed #2', -> byte = new Byte rotate: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if scaleX changed', -> byte = new Byte scaleX: 25 byte._draw() spyOn byte, '_fillTransform' byte._props.scaleX = 24 byte._draw() expect(byte._fillTransform).toHaveBeenCalled() it 'should not set transform if scaleX not changed', -> byte = new Byte scaleX: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if scaleY changed', -> byte = new Byte scaleY: 25 byte._draw() spyOn byte, '_fillTransform' byte._props.scaleY = 24 byte._draw() expect(byte._fillTransform).toHaveBeenCalled() it 'should not set transform if scaleY not changed', -> byte = new Byte scaleY: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if one of the x, y or scale changed', -> byte = new Byte radius: 25, top: 10, ctx: svg byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if x changed', -> byte = new Byte radius: 25, top: 10, x: { 0: 10 } byte._props.x = '4px' spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(4px, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(4px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(4px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(4px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set transform if y changed', -> byte = new Byte radius: 25, top: 10, y: { 0: 10 } byte._props.y = '4px' spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 4px) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 4px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 4px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px, 4px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set transform if scale changed', -> byte = new Byte radius: 25, top: 10, scale: { 0: 10 } byte._props.scale = 3 spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() # resultStr = 'scale(3) translate(0, 0) rotate(0deg)' # expect(byte.el.style['transform']).toBe resultStr style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(3, 3)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(3, 3)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(3)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(3)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set `transform-origin` if `origin`', -> byte = new Byte origin: '50% 30%' byte._drawEl() prop = 'transform-origin' style = byte.el.style tr = style[ prop ] or style["#{mojs.h.prefix.css}#{prop}"] isOr1 = tr is '50% 30% ' isOr2 = tr is '50% 30%' isOr3 = tr is '50% 30% 0px' expect(isOr1 or isOr2 or isOr3).toBe true it 'should set `transform-origin` if `origin` changed', -> byte = new Byte origin: '50% 30%' spyOn(byte, '_fillOrigin').and.callThrough() byte._props.origin = byte._parseStrokeDashOption( 'origin', '50% 40%'); byte._drawEl() prop = 'transform-origin' style = byte.el.style tr = style[ prop ] or style["#{mojs.h.prefix.css}#{prop}"] isOr1 = tr is '50% 40% ' isOr2 = tr is '50% 40%' isOr3 = tr is '50% 40% 0px' expect(isOr1 or isOr2 or isOr3).toBe true expect(byte._fillOrigin).toHaveBeenCalled() it 'should not set `transform-origin` if `origin`', -> byte = new Byte origin: '50% 30%' byte._draw() spyOn(byte, '_fillOrigin').and.callThrough() byte._draw() expect(byte._fillOrigin).not.toHaveBeenCalled() it 'should set `transform-origin` if `origin` in `_deltas`', -> byte = new Byte origin: { '50% 30%': '50% 0'} spyOn(byte, '_fillOrigin').and.callThrough() byte._drawEl() byte._drawEl() expect(byte._fillOrigin.calls.count()).toBe 2 describe '_isPropChanged method ->', -> it 'should return bool showing if prop was changed after the last set', -> byte = new Byte radius: 25, y: 10 byte._props.left = '20px' expect(byte._isPropChanged 'left').toBe true byte._props.left = '20px' expect(byte._isPropChanged 'left').toBe false it 'should add prop object to lastSet if undefined', -> byte = new Byte radius: 25, y: 10 byte._isPropChanged('x') expect(byte._lastSet.x).toBeDefined() describe 'delta calculations ->', -> it 'should skip delta for excludePropsDelta object', -> byte = new Byte radius: {45: 55} byte._skipPropsDelta = radius: 1 byte._extendDefaults() expect(byte._deltas.radius).not.toBeDefined() describe 'numeric values ->', -> it 'should calculate delta', -> byte = new Byte radius: {25: 75} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25 expect(radiusDelta.delta) .toBe 50 expect(radiusDelta.type) .toBe 'number' it 'should calculate delta with string arguments', -> byte = new Byte radius: {'25': '75'} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25 expect(radiusDelta.delta) .toBe 50 it 'should calculate delta with float arguments', -> byte = new Byte radius: {'25.50': 75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25.5 expect(radiusDelta.delta) .toBe 50 it 'should calculate delta with negative start arguments', -> byte = new Byte radius: {'-25.50': 75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe -25.5 expect(radiusDelta.delta) .toBe 101 it 'should calculate delta with negative end arguments', -> byte = new Byte radius: {'25.50': -75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25.5 expect(radiusDelta.end) .toBe -75.5 expect(radiusDelta.delta) .toBe -101 describe 'color values ->', -> it 'should calculate color delta', -> byte = new Byte stroke: {'#000': 'rgb(255,255,255)'} colorDelta = byte._deltas.stroke expect(colorDelta.start.r) .toBe 0 expect(colorDelta.end.r) .toBe 255 expect(colorDelta.delta.r) .toBe 255 expect(colorDelta.type) .toBe 'color' it 'should ignore stroke-linecap prop, use start prop and warn', -> byte = null spyOn console, 'warn' fun = -> byte = new Byte strokeLinecap: {'round': 'butt'} expect(-> fun()).not.toThrow() expect(console.warn).toHaveBeenCalled() expect(byte._deltas.strokeLinecap).not.toBeDefined() describe 'unit values ->', -> it 'should calculate unit delta', -> byte = new Byte x: {'0%': '100%'} xDelta = byte._deltas.x expect(xDelta.start.string) .toBe '0' expect(xDelta.end.string) .toBe '100%' expect(xDelta.delta) .toBe 100 expect(xDelta.type) .toBe 'unit' describe 'tween-related values ->', -> it 'should not calc delta for tween related props', -> byte = new Byte duration: { 2000: 1000 } expect(byte._deltas.duration).not.toBeDefined() describe '_setProgress method ->', -> it 'should set Shapeion progress', -> byte = new Byte radius: {'25.50': -75.50} byte._setProgress .5 expect(byte._progress).toBe .5 it 'should set value progress', -> byte = new Byte radius: {'25': 75} byte._setProgress .5 expect(byte._props.radius).toBe 50 it 'should call _calcCurrentProps', -> byte = new Byte radius: {'25': 75} spyOn byte, '_calcCurrentProps' byte._setProgress .5, .35 expect(byte._calcCurrentProps).toHaveBeenCalledWith .5, .35 it 'not to thow', -> byte = new Byte radius: {'25': 75}, ctx: svg expect(-> byte._show()).not.toThrow() it 'should set color value progress and only int', -> byte = new Byte stroke: {'#000': 'rgb(255,255,255)'} colorDelta = byte._deltas.stroke byte._setProgress .5 expect(byte._props.stroke).toBe 'rgba(127,127,127,1)' it 'should set color value progress for delta starting with 0', -> byte = new Byte stroke: {'#000': 'rgb(0,255,255)'} colorDelta = byte._deltas.stroke byte._setProgress .5 expect(byte._props.stroke).toBe 'rgba(0,127,127,1)' describe 'strokeDash.. values', -> it 'should set strokeDasharray/strokeDashoffset value progress', -> byte = new Byte strokeDasharray: {'200 100': '400'} byte._setProgress .5 expect(byte._props.strokeDasharray[0].value).toBe 300 expect(byte._props.strokeDasharray[0].unit) .toBe 'px' expect(byte._props.strokeDasharray[1].value).toBe 50 expect(byte._props.strokeDasharray[1].unit) .toBe 'px' it 'should set strokeDasharray/strokeDashoffset with percents', -> byte = new Byte type: 'circle' strokeDasharray: {'0% 200': '100%'} radius: 100 byte._setProgress .5 expect(byte._props.strokeDasharray[0].value).toBe 50 expect(byte._props.strokeDasharray[0].unit) .toBe '%' expect(byte._props.strokeDasharray[1].value).toBe 100 expect(byte._props.strokeDasharray[1].unit) .toBe 'px' it 'should parse non-deltas strokeDasharray/strokeDashoffset values', -> byte = new Byte type: 'circle' strokeDasharray: '100%' radius: 100 expect(byte._props.strokeDasharray[0].value).toBe 100 expect(byte._props.strokeDasharray[0].unit).toBe '%' it 'should parse multiple strokeDash.. values', -> byte = new Byte strokeDasharray: '7 100 7' expect(h.isArray(byte._props.strokeDasharray)).toBe true expect(byte._props.strokeDasharray.length).toBe 3 expect(byte._props.strokeDasharray[0].value).toBe 7 expect(byte._props.strokeDasharray[1].value).toBe 100 expect(byte._props.strokeDasharray[2].value).toBe 7 it 'should parse num values', -> byte = new Byte strokeDasharray: 7 expect(h.isArray(byte._props.strokeDasharray)).toBe true expect(byte._props.strokeDasharray.length) .toBe 1 describe '_getRadiusSize method ->', -> it 'should return max from delatas if key is defined', -> byte = new Byte radiusX: 20: 30 size = byte._getRadiusSize 'radiusX' expect(size).toBe 30 # it 'should return props\' value if delats\' one is not defined ', -> # byte = new Byte radiusX: 20 # size = byte._getRadiusSize key: 'radiusX', fallback: 0 # expect(size).toBe 20 # it 'should fallback to passed fallback option', -> # byte = new Byte # size = byte._getRadiusSize key: 'radiusX', fallback: 0 # expect(size).toBe 0 # it 'should fallback to 0 by default', -> # byte = new Byte # size = byte._getRadiusSize key: 'radiusX' # expect(size).toBe 0 # not now # describe 'isForeign flag ->', -> # it 'should not be set by default', -> # byte = new Byte # expect(byte.isForeign).toBe false # it 'should be set if context was passed', -> # byte = new Byte ctx: svg # expect(byte.isForeign).toBe true # it 'if context passed el should be bit\'s el', -> # byte = new Byte ctx: svg # expect(byte.el).toBe byte.shapeModule.el # describe 'foreign bit option ->', -> # it 'should receive a foreign bit to work with', -> # svg = document.createElementNS?(ns, 'svg') # bit = document.createElementNS?(ns, 'rect') # svg.appendChild bit # byte = new Shape bit: bit # expect(byte.shapeModule.el).toBe bit # it 'should set isForeignBit flag', -> # svg = document.createElementNS?(ns, 'svg') # bit = document.createElementNS?(ns, 'rect') # svg.appendChild bit # byte = new Byte bit: bit # expect(byte.isForeignBit).toBe true describe '_increaseSizeWithEasing method ->', -> it 'should increase size based on easing - elastic.out', -> tr = new Shape easing: 'elastic.out' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.25 it 'should increase size based on easing - elastic.inout', -> tr = new Shape easing: 'elastic.inout' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.25 it 'should increase size based on easing - back.out', -> tr = new Shape easing: 'back.out' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.1 it 'should increase size based on easing - back.inout', -> tr = new Shape easing: 'back.inout' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.1 # nope # describe '_increaseSizeWithBitRatio method ->', -> # it 'should increase size based on bit ratio', -> # tr = new Shape shape: 'equal' # tr._props.size = 1 # tr._increaseSizeWithBitRatio() # expect(tr._props.size).toBe tr.shapeModule._props.ratio # it 'should increase size based 2 gap sizes', -> # gap = 20 # tr = new Shape shape: 'equal', sizeGap: gap # tr._props.size = 1 # tr._increaseSizeWithBitRatio() # expect(tr._props.size).toBe tr.shapeModule._props.ratio + 2*gap describe 'callbacksContext option ->', -> it 'should pass the options to the tween', -> obj = {}; isRightContext = null tr = new Shape callbacksContext: obj onUpdate:-> isRightContext = @ is obj tr.setProgress 0 tr.setProgress .1 expect(isRightContext).toBe true it 'should pass the options to the timeline', -> obj = {}; isRightContext = null tr = new Shape callbacksContext: obj timeline: { onUpdate:-> isRightContext = @ is obj } tr.setProgress 0 tr.setProgress .1 expect(isRightContext).toBe true describe '_fillTransform method ->', -> it 'return tranform string of the el', -> tr = new Shape x: 100, y: 100, rotate: 50, scaleX: 2, scaleY: 3 expect(tr._fillTransform()) .toBe 'translate(100px, 100px) rotate(50deg) scale(2, 3)' describe '_fillOrigin method ->', -> it 'return tranform-origin string of the el', -> tr = new Shape x: 100, y: 100, origin: '50% 30%' expect(tr._fillOrigin()).toBe '50% 30% ' it 'return tranform-origin string of the el with delta', -> tr = new Shape x: 100, y: 100, easing: 'linear.none', origin: { '0% 0%' : '50% 200%' } tr.setProgress 0 tr.setProgress .5 expect(tr._fillOrigin()).toBe '25% 100% ' describe 'el creation ->', -> describe 'el ->', -> it 'should create el', -> byte = new Byte radius: 25 expect(byte.el.tagName.toLowerCase()).toBe 'div' style = byte.el.style expect(style[ 'position' ]).toBe 'absolute' expect(style[ 'width' ]).toBe '52px' expect(style[ 'height' ]).toBe '52px' # expect(style[ 'display' ]).toBe 'none' # expect(byte.el.style.opacity) .toBe 1 expect(byte.el.getAttribute('data-name')).toBe('mojs-shape') it 'should add `class` to `el`', -> className = 'some-class' byte = new Byte radius: 25, className: className expect(byte.el.getAttribute('class')).toBe className it 'should create bit based on shape option or fallback to circle', -> byte = new Byte radius: 25 shape: 'rect' byte2 = new Byte radius: 25 expect(byte.shapeModule._props.tag).toBe 'rect' expect(byte2.shapeModule._props.tag).toBe 'ellipse' # describe '_hide method ->' , -> # it 'should set `display` of `el` to `none`', -> # byte = new Byte radius: 25, isSoftHide: false # byte.el.style[ 'display' ] = 'block' # byte._hide() # expect( byte.el.style[ 'display' ] ).toBe 'none' # it 'should set `_isShown` to false', -> # byte = new Byte radius: 25, isSoftHide: false # byte._isShown = true # byte._hide() # expect( byte._isShown ).toBe false # describe 'isSoftHide option ->', -> # it 'should set `opacity` of `el` to `0`', -> # byte = new Byte radius: 25, isSoftHide: true # byte.el.style[ 'opacity' ] = '.5' # byte._hide() # expect( byte.el.style[ 'opacity' ] ).toBe '0' # it 'should set scale to 0', -> # byte = new Byte # radius: 25, # isSoftHide: true # byte._hide() # style = byte.el.style # tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ] # expect( tr ).toBe 'scale(0)' # describe '_show method ->' , -> # it 'should set `display` of `el` to `block`', -> # byte = new Byte radius: 25, isSoftHide: false # byte.el.style[ 'display' ] = 'none' # byte._show() # expect( byte.el.style[ 'display' ] ).toBe 'block' # it 'should set `_isShown` to true', -> # byte = new Byte radius: 25, isSoftHide: false # byte._isShown = true # byte._show() # expect( byte._isShown ).toBe true # describe 'isSoftHide option ->', -> # it 'should set `opacity` of `el` to `_props.opacity`', -> # byte = new Byte radius: 25, isSoftHide: true, opacity: .2 # byte.el.style[ 'opacity' ] = '0' # byte._show() # expect( byte.el.style[ 'opacity' ] ).toBe "#{byte._props.opacity}" # it 'should set `transform` to normal', -> # byte = new Byte radius: 25, isSoftHide: true, opacity: .2 # byte.el.style[ 'opacity' ] = '0' # byte.el.style[ 'transform' ] = 'none' # byte._show() # style = byte.el.style # tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ] # expect( tr ).toBe byte._fillTransform() describe '_createShape method', -> it 'should create shape module based on `_props` shape', -> byte = new Byte shape: 'rect' byte.shapeModule = null byte._createShape() expect(byte.shapeModule instanceof mojs.shapesMap.rect).toBe true it 'should not create if !isWithShape', -> byte = new Byte shape: 'rect', isWithShape: false spyOn byte, '_getShapeSize' byte.shapeModule = null byte._createShape() expect(byte.shapeModule).toBeFalsy() expect(byte._getShapeSize).toHaveBeenCalled() it 'should send `width` and `height` to the `shape` module', -> byte = new Byte shape: 'rect', radius: 50, radiusY: 75, strokeWidth: { 0: 10 } byte.shapeModule = null byte._createShape() expect(byte.shapeModule._props.width).toBe 2*50 + 10 expect(byte.shapeModule._props.height).toBe 2*75 + 10 expect(byte.shapeModule._props.parent).toBe byte.el it 'should save `width` and `height` to the `_props` module', -> byte = new Byte shape: 'rect', radius: 50, radiusY: 75, strokeWidth: { 0: 10 } byte.shapeModule = null byte._createShape() expect(byte._props.shapeWidth).toBe 2*50 + 10 expect(byte._props.shapeHeight).toBe 2*75 + 10 describe '_getMaxRadius method ->', -> it 'should return maximum radius ', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75 spyOn(byte, '_getRadiusSize').and.callThrough() expect(byte._getMaxRadius( 'radiusX' )).toBe 50 expect(byte._getMaxRadius( 'radiusY' )).toBe 75 expect( byte._getRadiusSize ).toHaveBeenCalledWith 'radiusX', 50 describe '_getMaxStroke method ->', -> it 'should get maximum value of the strokeWidth if delta', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: { 20 : 0} expect( byte._getMaxStroke() ).toBe 20 it 'should get maximum value of the strokeWidth if delta', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: { 0 : 20 } expect( byte._getMaxStroke() ).toBe 20 it 'should get maximum value of the strokeWidth if static value', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: 10 expect( byte._getMaxStroke() ).toBe 10 describe '_getShapeSize method', -> it 'should call _getMaxStroke method', -> byte = new Byte spyOn byte, '_getMaxStroke' byte._getShapeSize() expect( byte._getMaxStroke ).toHaveBeenCalled() it 'should call _getMaxRadius method', -> byte = new Byte spyOn byte, '_getMaxRadius' byte._getShapeSize() expect( byte._getMaxRadius ).toHaveBeenCalledWith 'radiusX' it 'should call _getMaxRadius method', -> byte = new Byte spyOn byte, '_getMaxRadius' byte._getShapeSize() expect( byte._getMaxRadius ).toHaveBeenCalledWith 'radiusY' it 'should save size to the _props', -> byte = new Byte byte._props.shapeWidth = 0 byte._props.shapeHeight = 0 byte._getShapeSize() p = byte._props stroke = byte._getMaxStroke() expect( p.shapeWidth ).toBe 2*byte._getMaxRadius( 'radiusX' ) + stroke expect( p.shapeHeight ).toBe 2*byte._getMaxRadius( 'radiusY' ) + stroke describe '_getMaxSizeInChain method ->', -> it 'should call _getShapeSize on every module', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) ms = shape._modules spyOn ms[0], '_getShapeSize' spyOn ms[1], '_getShapeSize' spyOn ms[2], '_getShapeSize' shape._getMaxSizeInChain() expect( ms[0]._getShapeSize ).toHaveBeenCalled() expect( ms[1]._getShapeSize ).toHaveBeenCalled() expect( ms[2]._getShapeSize ).toHaveBeenCalled() it 'should set the largest size to shapeModule', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) largest = shape._modules[2] shapeModule = shape.shapeModule spyOn shapeModule, '_setSize' shape._getMaxSizeInChain() expect( shapeModule._setSize ) .toHaveBeenCalledWith largest._props.shapeWidth, largest._props.shapeHeight it 'should call _setElSizeStyles method', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) largest = shape._modules[2] spyOn shape, '_setElSizeStyles' shape._getMaxSizeInChain() expect( shape._setElSizeStyles ) .toHaveBeenCalledWith largest._props.shapeWidth, largest._props.shapeHeight describe '_setElSizeStyles method ->', -> it 'should set `width`, `height` and `margins` to the `el` styles', -> shape = new Shape() style = shape.el.style style[ 'width' ] = '0px' style[ 'height' ] = '0px' style[ 'margin-left' ] = '0px' style[ 'margin-right' ] = '0px' shape._setElSizeStyles( 100, 200 ) expect( style[ 'width' ] ).toBe '100px' expect( style[ 'height' ] ).toBe '200px' expect( style[ 'margin-left' ] ).toBe '-50px' expect( style[ 'margin-top' ] ).toBe '-100px' describe 'then method ->', -> it 'should call super', -> obj = {} shape = new Shape() spyOn Thenable::, 'then' shape.then( obj ) expect( Thenable::then ).toHaveBeenCalledWith obj it 'should return this', -> shape = new Shape() result = shape.then( {} ) expect( result ).toBe shape it 'should call _getMaxSizeInChain method', -> shape = new Shape() spyOn shape, '_getMaxSizeInChain' shape.then({}) expect( shape._getMaxSizeInChain ).toHaveBeenCalled() describe 'tune method ->', -> it 'should call super', -> obj = {} shape = new Shape() spyOn Tunable::, 'tune' shape.tune( obj ) expect( Tunable::tune ).toHaveBeenCalledWith obj it 'should return this', -> shape = new Shape() result = shape.tune( {} ) expect( result ).toBe shape it 'should call _getMaxSizeInChain method', -> shape = new Shape() spyOn shape, '_getMaxSizeInChain' shape.tune({}) expect( shape._getMaxSizeInChain ).toHaveBeenCalled() describe '_refreshBefore method ->', -> it 'should call `_show` method is `isShowStart`', -> shape = new Shape isShowStart: true spyOn shape, '_show' shape._refreshBefore() expect( shape._show ).toHaveBeenCalled() it 'should call `_hide` method is not `isShowStart`', -> shape = new Shape spyOn shape, '_hide' shape._refreshBefore() expect( shape._hide ).toHaveBeenCalled() it 'should call `_setProgress` with `0, 0`', -> shape = new Shape spyOn shape, '_setProgress' shape._refreshBefore() expect( shape._setProgress ).toHaveBeenCalledWith 0, 0 it 'should call `_setProgress` with tweens eased progress', -> shape = new Shape easing: (k)-> return 1 spyOn shape, '_setProgress' shape._refreshBefore() expect( shape._setProgress ).toHaveBeenCalledWith 1, 0 describe '_showByTransform method ->', -> it 'should call _drawEl method', -> shape = new Shape easing: (k)-> return 1 spyOn shape, '_drawEl' shape._showByTransform() expect( shape._drawEl ).toHaveBeenCalled() it 'should update scale', -> shape = new Shape easing: (k)-> return 1 shape.el.style.transform = 'scale(0)' shape.el.style["#{mojs.h.prefix.css}transform"] = 'scale(0)' shape._showByTransform() s = shape.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true
142785
Byte = mojs.Shape Shape = mojs.Shape Bit = mojs.shapesMap.getShape('bit') Thenable = mojs.Thenable Tunable = mojs.Tunable Tweenable = mojs.Tweenable Rect = mojs.shapesMap.getShape('rect') h = mojs.helpers ns = 'http://www.w3.org/2000/svg' svg = document.createElementNS?(ns, 'svg') # console.log = -> console.warn = -> console.error = -> describe 'Shape ->', -> describe '_vars method', -> it 'should have own _vars function ->', -> byte = new Byte expect(byte._vars).toBeDefined() expect(-> byte._vars()).not.toThrow() it 'should call _vars super method', -> byte = new Byte expect(byte._history.length).toBe 1 it 'should save passed _o.masterModule to _masterModule', -> obj = {} byte = new Byte masterModule: obj byte._masterModule = null byte._vars() expect(byte._masterModule).toBe obj it 'should set `_isChained` based on `prevChainModule` option', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 byte._isChained = null byte._vars() expect(byte._isChained).toBe true # old # it 'should save passed _o.positionEl to el', -> # obj = document.createElement 'div' # byte = new Byte positionEl: obj # byte.el = null # byte._vars() # expect(byte.el).toBe obj # old # it 'should save passed _o.shiftEl to el', -> # obj = document.createElement 'div' # byte = new Byte shiftEl: obj # byte.el = null # byte._vars() # expect(byte.el).toBe obj it 'should save passed _o.prevChainModule to _prevChainModule', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 byte._prevChainModule = null byte._vars() expect(byte._prevChainModule).toBe byte0 describe 'extension ->', -> it 'should extend Tweenable class', -> byte = new Byte expect(byte instanceof Tweenable).toBe(true) it 'should extend Thenable class', -> byte = new Byte expect(byte instanceof Thenable).toBe(true) describe 'defaults object ->', -> it 'should have defaults object', -> byte = new Byte expect(byte._defaults).toBeDefined() expect(byte._defaults.parent).toBe document.body expect(byte._defaults.className).toBe '' expect(byte._defaults.shape).toBe 'circle' expect(byte._defaults.stroke).toBe 'transparent' expect(byte._defaults.strokeOpacity).toBe 1 expect(byte._defaults.strokeLinecap).toBe '' expect(byte._defaults.strokeWidth).toBe 2 expect(byte._defaults.strokeDasharray).toBe 0 expect(byte._defaults.strokeDashoffset).toBe 0 expect(byte._defaults.fill).toBe 'deeppink' expect(byte._defaults.fillOpacity).toBe 1 expect(byte._defaults.isSoftHide).toBe true expect(byte._defaults.isForce3d).toBe false expect(byte._defaults.left).toBe '50%' expect(byte._defaults.top).toBe '50%' expect(byte._defaults.x).toBe 0 expect(byte._defaults.y).toBe 0 expect(byte._defaults.rotate).toBe 0 expect(byte._defaults.scale).toEqual 1 expect(byte._defaults.scaleX).toBe null expect(byte._defaults.scaleY).toBe null expect(byte._defaults.origin).toBe '50% 50%' expect(byte._defaults.rx).toBe 0 expect(byte._defaults.ry).toBe 0 expect(byte._defaults.opacity).toBe 1 expect(byte._defaults.points).toBe 3 expect(byte._defaults.duration).toBe 400 expect(byte._defaults.radius).toBe 50 expect(byte._defaults.radiusX).toBe null expect(byte._defaults.radiusY).toBe null expect(byte._defaults.isShowEnd).toBe true expect(byte._defaults.isShowStart).toBe false expect(byte._defaults.isRefreshState).toBe true # nope # expect(byte._defaults.size).toBe null expect(byte._defaults.width).toBe null expect(byte._defaults.height).toBe null # expect(byte._defaults.sizeGap).toBe 0 expect(byte._defaults.isWithShape).toBe true expect(byte._defaults.callbacksContext).toBe byte describe '_applyCallbackOverrides ->', -> it 'should create callbackOverrides object on passed object', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) expect(typeof obj.callbackOverrides).toBe 'object' # not null expect(obj.callbackOverrides).toBe obj.callbackOverrides describe 'onUpdate callback override ->', -> it 'should override this._o.onUpdate', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) expect(typeof obj.callbackOverrides.onUpdate).toBe 'function' it 'should call _setProgress ', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) spyOn tr, '_setProgress' easedProgress = .25 progress = .2 obj.callbackOverrides.onUpdate easedProgress, progress expect(tr._setProgress).toHaveBeenCalledWith easedProgress, progress it 'should not override onUpdate function if exists', -> isRightScope = null; args = null options = { easing: 'Linear.None', onUpdate:-> isRightScope = @ is tr args = arguments } tr = new Shape options expect(typeof tr._o.onUpdate).toBe 'function' tr.timeline.setProgress 0 tr.timeline.setProgress .1 expect(isRightScope).toBe true expect(args[0]).toBe .1 expect(args[1]).toBe .1 expect(args[2]).toBe true expect(args[3]).toBe false it 'should call _setProgress method', -> options = { easing: 'Linear.None', onUpdate:-> } obj = {} tr = new Shape options tr.timeline.setProgress 0 spyOn tr, '_setProgress' progress = .1 tr.timeline.setProgress progress expect(tr._setProgress.calls.first().args[0]).toBeCloseTo progress, 5 describe 'onStart callback override ->', -> it 'should override this._o.onStart', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onStart).toBe 'function' it 'should call _show if isForward and !_isChained', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onStart true expect(tr._show).toHaveBeenCalled() it 'should not call _show if _isChained', -> tr = new Shape masterModule: new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onStart true expect(tr._show).not.toHaveBeenCalled() it 'should call _hide if not isForward and !_isChained', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).toHaveBeenCalled() it 'should not call _hide if not isForward and _isChained', -> tr = new Shape masterModule: new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if not isForward and isShowStart', -> tr = new Shape isShowStart: true obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).not.toHaveBeenCalled() describe 'onComplete callback override ->', -> it 'should override this._o.onComplete', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onComplete).toBe 'function' it 'should call _show if !isForward', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).toHaveBeenCalled() it 'should call _show if !isForward and _isLastInChain()', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).toHaveBeenCalled() it 'should call _show if !isForward and _isLastInChain() #2', -> tr = new Shape().then radius: 0 el = tr._modules[1] obj = {} el._applyCallbackOverrides( obj ) spyOn el, '_show' obj.callbackOverrides.onComplete false expect(el._show).toHaveBeenCalled() it 'should not call _show if !isForward and not _isLastInChain', -> tr = new Shape().then radius: 0 obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).not.toHaveBeenCalled() it 'should call _hide if isForward and !isShowEnd', -> tr = new Shape isShowEnd: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).toHaveBeenCalled() it 'should not call _hide if isForward but isShowEnd', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should call _hide if isForward and _isLastInChain', -> tr = new Shape isShowEnd: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).toHaveBeenCalled() it 'should call not _hide if isForward and !_isLastInChain', -> tr = new Shape(isShowEnd: false).then({ radius: 0 }) # module = tr._modules[1] obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if isForward and _isLastInChain but isShowEnd', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if isForward but !_isLastInChain and isShowEnd', -> tr = new Shape().then radius: 0 obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() describe 'onRefresh callback override ->', -> it 'should override this._o.onRefresh', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onRefresh).toBe 'function' it 'should call _refreshBefore if isBefore', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh true expect(tr._refreshBefore).toHaveBeenCalled() it 'should not call _refreshBefore if !isBefore', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh false expect(tr._refreshBefore).not.toHaveBeenCalled() it 'should not call _refreshBefore if !isRefreshState', -> tr = new Shape isRefreshState: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh true expect(tr._refreshBefore).not.toHaveBeenCalled() describe '_transformTweenOptions method', -> it 'should call _applyCallbackOverrides with _o', -> tr = new Shape spyOn tr, '_applyCallbackOverrides' tr._transformTweenOptions() expect(tr._applyCallbackOverrides).toHaveBeenCalledWith tr._o describe 'options object ->', -> it 'should receive empty options object by default', -> byte = new Byte expect(byte._o).toBeDefined() it 'should receive options object', -> byte = new Byte option: 1 expect(byte._o.option).toBe 1 describe 'index option ->', -> it 'should receive index option', -> byte = new Shape index: 5 expect(byte._index).toBe 5 it 'should fallback to 0', -> byte = new Shape expect(byte._index).toBe 0 describe 'options history ->', -> it 'should have history array', -> byte = new Byte expect(h.isArray(byte._history)).toBe true it 'should save options to history array', -> byte = new Byte radius: 20 expect(byte._history.length).toBe 1 describe 'size calculations ->', -> it 'should not calculate size el size if size was passed', -> byte = new Byte radius: 10 strokeWidth: 5 width: 400 height: 200 expect(byte._props.shapeWidth).toBe(400) expect(byte._props.shapeHeight).toBe(200) describe 'opacity set ->', -> it 'should set opacity regarding units', -> byte = new Byte opacity: .5, isShowStart: true expect(byte.el.style.opacity).toBe '0.5' it 'should animate opacity', (dfr)-> byte = new Byte opacity: { 1: 0} duration: 100 onComplete:-> expect(byte.el.style.opacity).toBe('0'); dfr() byte.play() describe 'position set ->', -> describe 'x/y coordinates ->', -> it 'should set position regarding units', -> byte = new Byte left: 100, top: 50 expect(byte.el.style.left).toBe '100px' expect(byte.el.style.top) .toBe '50px' it 'should animate position', (dfr)-> byte = new Byte left: {100: '200px'} duration: 100 onComplete:-> expect(byte.el.style.left).toBe('200px'); dfr() byte.play() it 'should warn when x/y animated position and not foreign context',-> spyOn console, 'warn' byte = new Byte left: {100: '200px'} byte.play() expect(console.warn).toHaveBeenCalled() it 'should notwarn when x/y animated position and foreign context',-> spyOn console, 'warn' byte = new Byte left: {100: '200px'}, ctx: svg byte.play() expect(console.warn).not.toHaveBeenCalled() it 'should animate position regarding units', (dfr)-> byte = new Byte left: {'20%': '50%'} duration: 100 byte.play() setTimeout -> expect(byte.el.style.left) .toBe '50%' dfr() , 500 it 'end unit that were not specified should fallback to start unit', ()-> byte = new Byte left: {'20%': 50} duration: 200 byte.play() expect(byte._deltas.left.start.unit).toBe '%' expect(byte._deltas.left.end.unit) .toBe '%' it 'should fallback to end units if units are different', (dfr)-> byte = new Byte left: {'20%': '50px'} duration: 200 onComplete:-> expect(byte.el.style.left).toBe('50px'); dfr() byte.play() it 'should set position regarding units #2', -> byte = new Byte x: 100 y: 50, isShowStart: true s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isNormal = tr is 'translate(100px, 50px) rotate(0deg) scale(1, 1)' isIE = tr is 'translate(100px, 50px) rotate(0deg) scale(1)' expect(isNormal or isIE).toBe true it 'should animate shift position', (dfr)-> byte = new Byte x: {100: '200px'} duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(200px, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(200px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(200px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(200px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true dfr() byte.play() it 'should animate position regarding units #3', (dfr)-> byte = new Byte x: {'20%': '50%'} duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(50%, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(50%, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(50%, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(50%) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true dfr() byte.play() it 'should fallback to end units if units are differnt', (dfr)-> byte = new Byte x: { '20%': '50px' } y: { 0 : '50%' } duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr1 = tr is 'translate(50px, 50%) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(50px, 50%) rotate(0deg) scale(1)' expect(isTr1 or isTr2).toBe true dfr() byte.play() describe '_render method ->', -> it 'should call _createShape method', -> byte = new Byte radius: 25 spyOn byte, '_createShape' byte._isRendered = false byte._render() expect(byte._createShape).toHaveBeenCalled() it 'should set _isRendered to true', -> byte = new Byte radius: 25 expect(byte._isRendered).toBe true byte._isRendered = false; byte._render() expect(byte._isRendered).toBe true it 'should not call _createShape method if already rendered', -> byte = new Byte radius: 25 spyOn byte, '_createShape' byte._isRendered = true byte._render() expect(byte._createShape).not.toHaveBeenCalled() it 'should set `el` and `shape` if `_isChained`', -> byte0 = new Byte radius: 25 byte = new Byte prevChainModule: byte0 masterModule: byte0 expect(byte.el).toBe byte0.el expect(byte.shapeModule).toBe byte0.shapeModule it 'should not call _createShape method if _isChained', -> byte0 = new Byte byte = new Byte radius: 25 prevChainModule: byte0 masterModule: byte0 spyOn byte, '_createShape' byte._o.el = byte0.el byte._o.shapeModule = byte0.shapeModule byte._render() expect(byte._createShape).not.toHaveBeenCalled() it 'should call `_setProgress(0)` if not `_isChained`', -> byte = new Byte spyOn byte, '_setProgress' byte._isRendered = false byte._render() expect(byte._setProgress).toHaveBeenCalledWith(0, 0) it 'should not call `_setProgress(0)` if not `_isFirstInChain()`', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 spyOn byte, '_setProgress' byte._isRendered = false byte._render() expect(byte._setProgress).not.toHaveBeenCalledWith(0) it 'should call _setElStyles method', -> byte = new Byte radius: 25 spyOn byte, '_setElStyles' byte._isRendered = false byte._render() expect(byte._setElStyles).toHaveBeenCalled() it 'should not call _setElStyles method if _isChained', -> byte = new Byte prevChainModule: new Byte masterModule: new Byte spyOn byte, '_setElStyles' byte._isRendered = true byte._render() expect(byte._setElStyles).not.toHaveBeenCalled() it 'should call _show method if `isShowStart`', -> byte = new Byte isShowStart: true spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).toHaveBeenCalled() it 'should call not _show method if not `isShowStart`', -> byte = new Byte isShowStart: false spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).not.toHaveBeenCalled() it 'should not _show method if `_isChained`', -> byte = new Byte isShowStart: true, prevChainModule: new Byte masterModule: new Byte spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).not.toHaveBeenCalled() it 'should call _hide method if not `isShowStart`', -> byte = new Byte isShowStart: false spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).toHaveBeenCalled() it 'should call not _hide method if `isShowStart`', -> byte = new Byte isShowStart: true spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).not.toHaveBeenCalled() it 'should not _hide method if `_isChained`', -> byte = new Byte isShowStart: false, prevChainModule: new Byte masterModule: new Byte spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).not.toHaveBeenCalled() describe '_setElStyles method ->', -> it 'should set dimentions and position of the `el`', -> byte = new Byte radius: 25 byte.el.style.position = 'static' byte.el.style.width = '0px' byte.el.style.height = '0px' byte.el.style[ 'margin-left' ] = '0px' byte.el.style[ 'margin-top' ] = '0px' byte._setElStyles() expect( byte.el.style.position ).toBe 'absolute' expect( byte.el.style.width ).toBe "#{byte._props.shapeWidth}px" expect( byte.el.style.height ).toBe "#{byte._props.shapeHeight}px" expect( byte.el.style[ 'margin-left' ] ) .toBe "-#{byte._props.shapeWidth/2}px" expect( byte.el.style[ 'margin-top' ] ) .toBe "-#{byte._props.shapeHeight/2}px" it 'should set `backface-visibility` if `isForce3d`', -> byte = new Byte radius: 25, isForce3d: true style = byte.el.style bv = style[ 'backface-visibility' ] prefixedBv = style[ "#{mojs.h.prefix.css}backface-visibility" ] expect( bv or prefixedBv ).toBe 'hidden' it 'should not set `backface-visibility` if `isForce3d`', -> byte = new Byte radius: 25 style = byte.el.style bv = style[ 'backface-visibility' ] prefixedBv = style[ "#{mojs.h.prefix.css}backface-visibility" ] expect( bv or prefixedBv ).not.toBe 'hidden' describe '_draw method ->', -> # nope # it 'should call _setProp method', -> # byte = new Byte radius: 25 # spyOn byte.shapeModule, 'setProp' # byte._draw() # expect(byte.shapeModule.setProp).toHaveBeenCalled() it 'should set all attributes to shape\'s properties', -> byte = new Byte radius: 25, x: 20, y: 30, rx: 15, ry: 25 stroke: 'red' strokeWidth: 2 strokeOpacity: .5 strokeLinecap: 'round' strokeDasharray: 200 strokeDashoffset: 100 fill: 'cyan' fillOpacity: .5 radius: 100 radiusX: 22 radiusY: { 20: 0 } points: 4 byte._draw() # old # expect(byte.shapeModule._props.x).toBe byte._origin.x # old # expect(byte.shapeModule._props.y).toBe byte._origin.y expect(byte.shapeModule._props.rx).toBe byte._props.rx expect(byte.shapeModule._props.ry).toBe byte._props.ry expect(byte.shapeModule._props.stroke).toBe byte._props.stroke expect(byte.shapeModule._props['stroke-width']).toBe byte._props.strokeWidth expect(byte.shapeModule._props['stroke-opacity']).toBe byte._props.strokeOpacity expect(byte.shapeModule._props['stroke-linecap']).toBe byte._props.strokeLinecap expect(byte.shapeModule._props['stroke-dasharray']).toBe byte._props.strokeDasharray[0].value + ' ' expect(byte.shapeModule._props['stroke-dashoffset']).toBe byte._props.strokeDashoffset[0].value + ' ' expect(byte.shapeModule._props['fill']).toBe byte._props.fill expect(byte.shapeModule._props['fill-opacity']).toBe byte._props.fillOpacity expect(byte.shapeModule._props['radius']).toBe byte._props.radius expect(byte.shapeModule._props['radiusX']).toBe byte._props.radiusX expect(byte.shapeModule._props['radiusY']).toBe byte._props.radiusY expect(byte.shapeModule._props['points']).toBe byte._props.points # old # expect(byte.shapeModule._props['transform']).toBe byte._calcShapeTransform() it 'should call bit._draw method', -> byte = new Byte radius: 25 spyOn byte.shapeModule, '_draw' byte._draw() expect(byte.shapeModule._draw).toHaveBeenCalled() it 'should call _drawEl method', -> byte = new Byte radius: 25 spyOn byte, '_drawEl' byte._draw() expect(byte._drawEl).toHaveBeenCalled() it 'should receive the current progress', -> byte = new Byte radius: 25 spyOn byte, '_draw' byte._setProgress .5 expect(byte._draw).toHaveBeenCalledWith .5 describe '_drawEl method ->', -> it 'should set el positions and transforms', -> byte = new Byte radius: 25, top: 10, isShowStart: true expect(byte.el.style.top) .toBe '10px' expect(byte.el.style.opacity) .toBe '1' expect(byte.el.style.left).toBe '50%' s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set new values', -> byte = new Byte radius: 25, top: 10 byte._draw() byte._props.left = '1px' byte._draw() expect(byte.el.style.left).toBe '1px' expect(byte._lastSet.left.value) .toBe '1px' it 'should not set old values', -> byte = new Byte radius: 25, y: 10 byte._draw() byte._draw() expect(byte._lastSet.x.value) .toBe '0' it 'should return true if there is no el', -> byte = new Byte radius: 25 byte.el = null expect(byte._drawEl()).toBe true it 'should set transform if rotation is changed', -> byte = new Byte rotate: 25 byte._draw() byte._props.rotate = 26 byte._draw() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(26deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(26deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(26deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(26deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true # expect(byte.el.style["#{h.prefix.css}transform"]).toBe resultStr it 'should not set transform if rotation changed #2', -> byte = new Byte rotate: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if scaleX changed', -> byte = new Byte scaleX: 25 byte._draw() spyOn byte, '_fillTransform' byte._props.scaleX = 24 byte._draw() expect(byte._fillTransform).toHaveBeenCalled() it 'should not set transform if scaleX not changed', -> byte = new Byte scaleX: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if scaleY changed', -> byte = new Byte scaleY: 25 byte._draw() spyOn byte, '_fillTransform' byte._props.scaleY = 24 byte._draw() expect(byte._fillTransform).toHaveBeenCalled() it 'should not set transform if scaleY not changed', -> byte = new Byte scaleY: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if one of the x, y or scale changed', -> byte = new Byte radius: 25, top: 10, ctx: svg byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if x changed', -> byte = new Byte radius: 25, top: 10, x: { 0: 10 } byte._props.x = '4px' spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(4px, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(4px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(4px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(4px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set transform if y changed', -> byte = new Byte radius: 25, top: 10, y: { 0: 10 } byte._props.y = '4px' spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 4px) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 4px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 4px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px, 4px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set transform if scale changed', -> byte = new Byte radius: 25, top: 10, scale: { 0: 10 } byte._props.scale = 3 spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() # resultStr = 'scale(3) translate(0, 0) rotate(0deg)' # expect(byte.el.style['transform']).toBe resultStr style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(3, 3)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(3, 3)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(3)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(3)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set `transform-origin` if `origin`', -> byte = new Byte origin: '50% 30%' byte._drawEl() prop = 'transform-origin' style = byte.el.style tr = style[ prop ] or style["#{mojs.h.prefix.css}#{prop}"] isOr1 = tr is '50% 30% ' isOr2 = tr is '50% 30%' isOr3 = tr is '50% 30% 0px' expect(isOr1 or isOr2 or isOr3).toBe true it 'should set `transform-origin` if `origin` changed', -> byte = new Byte origin: '50% 30%' spyOn(byte, '_fillOrigin').and.callThrough() byte._props.origin = byte._parseStrokeDashOption( 'origin', '50% 40%'); byte._drawEl() prop = 'transform-origin' style = byte.el.style tr = style[ prop ] or style["#{mojs.h.prefix.css}#{prop}"] isOr1 = tr is '50% 40% ' isOr2 = tr is '50% 40%' isOr3 = tr is '50% 40% 0px' expect(isOr1 or isOr2 or isOr3).toBe true expect(byte._fillOrigin).toHaveBeenCalled() it 'should not set `transform-origin` if `origin`', -> byte = new Byte origin: '50% 30%' byte._draw() spyOn(byte, '_fillOrigin').and.callThrough() byte._draw() expect(byte._fillOrigin).not.toHaveBeenCalled() it 'should set `transform-origin` if `origin` in `_deltas`', -> byte = new Byte origin: { '50% 30%': '50% 0'} spyOn(byte, '_fillOrigin').and.callThrough() byte._drawEl() byte._drawEl() expect(byte._fillOrigin.calls.count()).toBe 2 describe '_isPropChanged method ->', -> it 'should return bool showing if prop was changed after the last set', -> byte = new Byte radius: 25, y: 10 byte._props.left = '20px' expect(byte._isPropChanged 'left').toBe true byte._props.left = '20px' expect(byte._isPropChanged 'left').toBe false it 'should add prop object to lastSet if undefined', -> byte = new Byte radius: 25, y: 10 byte._isPropChanged('x') expect(byte._lastSet.x).toBeDefined() describe 'delta calculations ->', -> it 'should skip delta for excludePropsDelta object', -> byte = new Byte radius: {45: 55} byte._skipPropsDelta = radius: 1 byte._extendDefaults() expect(byte._deltas.radius).not.toBeDefined() describe 'numeric values ->', -> it 'should calculate delta', -> byte = new Byte radius: {25: 75} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25 expect(radiusDelta.delta) .toBe 50 expect(radiusDelta.type) .toBe 'number' it 'should calculate delta with string arguments', -> byte = new Byte radius: {'25': '75'} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25 expect(radiusDelta.delta) .toBe 50 it 'should calculate delta with float arguments', -> byte = new Byte radius: {'25.50': 75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25.5 expect(radiusDelta.delta) .toBe 50 it 'should calculate delta with negative start arguments', -> byte = new Byte radius: {'-25.50': 75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe -25.5 expect(radiusDelta.delta) .toBe 101 it 'should calculate delta with negative end arguments', -> byte = new Byte radius: {'25.50': -75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25.5 expect(radiusDelta.end) .toBe -75.5 expect(radiusDelta.delta) .toBe -101 describe 'color values ->', -> it 'should calculate color delta', -> byte = new Byte stroke: {'#000': 'rgb(255,255,255)'} colorDelta = byte._deltas.stroke expect(colorDelta.start.r) .toBe 0 expect(colorDelta.end.r) .toBe 255 expect(colorDelta.delta.r) .toBe 255 expect(colorDelta.type) .toBe 'color' it 'should ignore stroke-linecap prop, use start prop and warn', -> byte = null spyOn console, 'warn' fun = -> byte = new Byte strokeLinecap: {'round': 'butt'} expect(-> fun()).not.toThrow() expect(console.warn).toHaveBeenCalled() expect(byte._deltas.strokeLinecap).not.toBeDefined() describe 'unit values ->', -> it 'should calculate unit delta', -> byte = new Byte x: {'0%': '100%'} xDelta = byte._deltas.x expect(xDelta.start.string) .toBe '0' expect(xDelta.end.string) .toBe '100%' expect(xDelta.delta) .toBe 100 expect(xDelta.type) .toBe 'unit' describe 'tween-related values ->', -> it 'should not calc delta for tween related props', -> byte = new Byte duration: { 2000: 1000 } expect(byte._deltas.duration).not.toBeDefined() describe '_setProgress method ->', -> it 'should set Shapeion progress', -> byte = new Byte radius: {'25.50': -75.50} byte._setProgress .5 expect(byte._progress).toBe .5 it 'should set value progress', -> byte = new Byte radius: {'25': 75} byte._setProgress .5 expect(byte._props.radius).toBe 50 it 'should call _calcCurrentProps', -> byte = new Byte radius: {'25': 75} spyOn byte, '_calcCurrentProps' byte._setProgress .5, .35 expect(byte._calcCurrentProps).toHaveBeenCalledWith .5, .35 it 'not to thow', -> byte = new Byte radius: {'25': 75}, ctx: svg expect(-> byte._show()).not.toThrow() it 'should set color value progress and only int', -> byte = new Byte stroke: {'#000': 'rgb(255,255,255)'} colorDelta = byte._deltas.stroke byte._setProgress .5 expect(byte._props.stroke).toBe 'rgba(127,127,127,1)' it 'should set color value progress for delta starting with 0', -> byte = new Byte stroke: {'#000': 'rgb(0,255,255)'} colorDelta = byte._deltas.stroke byte._setProgress .5 expect(byte._props.stroke).toBe 'rgba(0,127,127,1)' describe 'strokeDash.. values', -> it 'should set strokeDasharray/strokeDashoffset value progress', -> byte = new Byte strokeDasharray: {'200 100': '400'} byte._setProgress .5 expect(byte._props.strokeDasharray[0].value).toBe 300 expect(byte._props.strokeDasharray[0].unit) .toBe 'px' expect(byte._props.strokeDasharray[1].value).toBe 50 expect(byte._props.strokeDasharray[1].unit) .toBe 'px' it 'should set strokeDasharray/strokeDashoffset with percents', -> byte = new Byte type: 'circle' strokeDasharray: {'0% 200': '100%'} radius: 100 byte._setProgress .5 expect(byte._props.strokeDasharray[0].value).toBe 50 expect(byte._props.strokeDasharray[0].unit) .toBe '%' expect(byte._props.strokeDasharray[1].value).toBe 100 expect(byte._props.strokeDasharray[1].unit) .toBe 'px' it 'should parse non-deltas strokeDasharray/strokeDashoffset values', -> byte = new Byte type: 'circle' strokeDasharray: '100%' radius: 100 expect(byte._props.strokeDasharray[0].value).toBe 100 expect(byte._props.strokeDasharray[0].unit).toBe '%' it 'should parse multiple strokeDash.. values', -> byte = new Byte strokeDasharray: '7 100 7' expect(h.isArray(byte._props.strokeDasharray)).toBe true expect(byte._props.strokeDasharray.length).toBe 3 expect(byte._props.strokeDasharray[0].value).toBe 7 expect(byte._props.strokeDasharray[1].value).toBe 100 expect(byte._props.strokeDasharray[2].value).toBe 7 it 'should parse num values', -> byte = new Byte strokeDasharray: 7 expect(h.isArray(byte._props.strokeDasharray)).toBe true expect(byte._props.strokeDasharray.length) .toBe 1 describe '_getRadiusSize method ->', -> it 'should return max from delatas if key is defined', -> byte = new Byte radiusX: 20: 30 size = byte._getRadiusSize 'radiusX' expect(size).toBe 30 # it 'should return props\' value if delats\' one is not defined ', -> # byte = new Byte radiusX: 20 # size = byte._getRadiusSize key: '<KEY>', fallback: 0 # expect(size).toBe 20 # it 'should fallback to passed fallback option', -> # byte = new Byte # size = byte._getRadiusSize key: '<KEY>', fallback: 0 # expect(size).toBe 0 # it 'should fallback to 0 by default', -> # byte = new Byte # size = byte._getRadiusSize key: '<KEY>' # expect(size).toBe 0 # not now # describe 'isForeign flag ->', -> # it 'should not be set by default', -> # byte = new Byte # expect(byte.isForeign).toBe false # it 'should be set if context was passed', -> # byte = new Byte ctx: svg # expect(byte.isForeign).toBe true # it 'if context passed el should be bit\'s el', -> # byte = new Byte ctx: svg # expect(byte.el).toBe byte.shapeModule.el # describe 'foreign bit option ->', -> # it 'should receive a foreign bit to work with', -> # svg = document.createElementNS?(ns, 'svg') # bit = document.createElementNS?(ns, 'rect') # svg.appendChild bit # byte = new Shape bit: bit # expect(byte.shapeModule.el).toBe bit # it 'should set isForeignBit flag', -> # svg = document.createElementNS?(ns, 'svg') # bit = document.createElementNS?(ns, 'rect') # svg.appendChild bit # byte = new Byte bit: bit # expect(byte.isForeignBit).toBe true describe '_increaseSizeWithEasing method ->', -> it 'should increase size based on easing - elastic.out', -> tr = new Shape easing: 'elastic.out' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.25 it 'should increase size based on easing - elastic.inout', -> tr = new Shape easing: 'elastic.inout' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.25 it 'should increase size based on easing - back.out', -> tr = new Shape easing: 'back.out' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.1 it 'should increase size based on easing - back.inout', -> tr = new Shape easing: 'back.inout' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.1 # nope # describe '_increaseSizeWithBitRatio method ->', -> # it 'should increase size based on bit ratio', -> # tr = new Shape shape: 'equal' # tr._props.size = 1 # tr._increaseSizeWithBitRatio() # expect(tr._props.size).toBe tr.shapeModule._props.ratio # it 'should increase size based 2 gap sizes', -> # gap = 20 # tr = new Shape shape: 'equal', sizeGap: gap # tr._props.size = 1 # tr._increaseSizeWithBitRatio() # expect(tr._props.size).toBe tr.shapeModule._props.ratio + 2*gap describe 'callbacksContext option ->', -> it 'should pass the options to the tween', -> obj = {}; isRightContext = null tr = new Shape callbacksContext: obj onUpdate:-> isRightContext = @ is obj tr.setProgress 0 tr.setProgress .1 expect(isRightContext).toBe true it 'should pass the options to the timeline', -> obj = {}; isRightContext = null tr = new Shape callbacksContext: obj timeline: { onUpdate:-> isRightContext = @ is obj } tr.setProgress 0 tr.setProgress .1 expect(isRightContext).toBe true describe '_fillTransform method ->', -> it 'return tranform string of the el', -> tr = new Shape x: 100, y: 100, rotate: 50, scaleX: 2, scaleY: 3 expect(tr._fillTransform()) .toBe 'translate(100px, 100px) rotate(50deg) scale(2, 3)' describe '_fillOrigin method ->', -> it 'return tranform-origin string of the el', -> tr = new Shape x: 100, y: 100, origin: '50% 30%' expect(tr._fillOrigin()).toBe '50% 30% ' it 'return tranform-origin string of the el with delta', -> tr = new Shape x: 100, y: 100, easing: 'linear.none', origin: { '0% 0%' : '50% 200%' } tr.setProgress 0 tr.setProgress .5 expect(tr._fillOrigin()).toBe '25% 100% ' describe 'el creation ->', -> describe 'el ->', -> it 'should create el', -> byte = new Byte radius: 25 expect(byte.el.tagName.toLowerCase()).toBe 'div' style = byte.el.style expect(style[ 'position' ]).toBe 'absolute' expect(style[ 'width' ]).toBe '52px' expect(style[ 'height' ]).toBe '52px' # expect(style[ 'display' ]).toBe 'none' # expect(byte.el.style.opacity) .toBe 1 expect(byte.el.getAttribute('data-name')).toBe('mojs-shape') it 'should add `class` to `el`', -> className = 'some-class' byte = new Byte radius: 25, className: className expect(byte.el.getAttribute('class')).toBe className it 'should create bit based on shape option or fallback to circle', -> byte = new Byte radius: 25 shape: 'rect' byte2 = new Byte radius: 25 expect(byte.shapeModule._props.tag).toBe 'rect' expect(byte2.shapeModule._props.tag).toBe 'ellipse' # describe '_hide method ->' , -> # it 'should set `display` of `el` to `none`', -> # byte = new Byte radius: 25, isSoftHide: false # byte.el.style[ 'display' ] = 'block' # byte._hide() # expect( byte.el.style[ 'display' ] ).toBe 'none' # it 'should set `_isShown` to false', -> # byte = new Byte radius: 25, isSoftHide: false # byte._isShown = true # byte._hide() # expect( byte._isShown ).toBe false # describe 'isSoftHide option ->', -> # it 'should set `opacity` of `el` to `0`', -> # byte = new Byte radius: 25, isSoftHide: true # byte.el.style[ 'opacity' ] = '.5' # byte._hide() # expect( byte.el.style[ 'opacity' ] ).toBe '0' # it 'should set scale to 0', -> # byte = new Byte # radius: 25, # isSoftHide: true # byte._hide() # style = byte.el.style # tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ] # expect( tr ).toBe 'scale(0)' # describe '_show method ->' , -> # it 'should set `display` of `el` to `block`', -> # byte = new Byte radius: 25, isSoftHide: false # byte.el.style[ 'display' ] = 'none' # byte._show() # expect( byte.el.style[ 'display' ] ).toBe 'block' # it 'should set `_isShown` to true', -> # byte = new Byte radius: 25, isSoftHide: false # byte._isShown = true # byte._show() # expect( byte._isShown ).toBe true # describe 'isSoftHide option ->', -> # it 'should set `opacity` of `el` to `_props.opacity`', -> # byte = new Byte radius: 25, isSoftHide: true, opacity: .2 # byte.el.style[ 'opacity' ] = '0' # byte._show() # expect( byte.el.style[ 'opacity' ] ).toBe "#{byte._props.opacity}" # it 'should set `transform` to normal', -> # byte = new Byte radius: 25, isSoftHide: true, opacity: .2 # byte.el.style[ 'opacity' ] = '0' # byte.el.style[ 'transform' ] = 'none' # byte._show() # style = byte.el.style # tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ] # expect( tr ).toBe byte._fillTransform() describe '_createShape method', -> it 'should create shape module based on `_props` shape', -> byte = new Byte shape: 'rect' byte.shapeModule = null byte._createShape() expect(byte.shapeModule instanceof mojs.shapesMap.rect).toBe true it 'should not create if !isWithShape', -> byte = new Byte shape: 'rect', isWithShape: false spyOn byte, '_getShapeSize' byte.shapeModule = null byte._createShape() expect(byte.shapeModule).toBeFalsy() expect(byte._getShapeSize).toHaveBeenCalled() it 'should send `width` and `height` to the `shape` module', -> byte = new Byte shape: 'rect', radius: 50, radiusY: 75, strokeWidth: { 0: 10 } byte.shapeModule = null byte._createShape() expect(byte.shapeModule._props.width).toBe 2*50 + 10 expect(byte.shapeModule._props.height).toBe 2*75 + 10 expect(byte.shapeModule._props.parent).toBe byte.el it 'should save `width` and `height` to the `_props` module', -> byte = new Byte shape: 'rect', radius: 50, radiusY: 75, strokeWidth: { 0: 10 } byte.shapeModule = null byte._createShape() expect(byte._props.shapeWidth).toBe 2*50 + 10 expect(byte._props.shapeHeight).toBe 2*75 + 10 describe '_getMaxRadius method ->', -> it 'should return maximum radius ', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75 spyOn(byte, '_getRadiusSize').and.callThrough() expect(byte._getMaxRadius( 'radiusX' )).toBe 50 expect(byte._getMaxRadius( 'radiusY' )).toBe 75 expect( byte._getRadiusSize ).toHaveBeenCalledWith 'radiusX', 50 describe '_getMaxStroke method ->', -> it 'should get maximum value of the strokeWidth if delta', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: { 20 : 0} expect( byte._getMaxStroke() ).toBe 20 it 'should get maximum value of the strokeWidth if delta', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: { 0 : 20 } expect( byte._getMaxStroke() ).toBe 20 it 'should get maximum value of the strokeWidth if static value', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: 10 expect( byte._getMaxStroke() ).toBe 10 describe '_getShapeSize method', -> it 'should call _getMaxStroke method', -> byte = new Byte spyOn byte, '_getMaxStroke' byte._getShapeSize() expect( byte._getMaxStroke ).toHaveBeenCalled() it 'should call _getMaxRadius method', -> byte = new Byte spyOn byte, '_getMaxRadius' byte._getShapeSize() expect( byte._getMaxRadius ).toHaveBeenCalledWith 'radiusX' it 'should call _getMaxRadius method', -> byte = new Byte spyOn byte, '_getMaxRadius' byte._getShapeSize() expect( byte._getMaxRadius ).toHaveBeenCalledWith 'radiusY' it 'should save size to the _props', -> byte = new Byte byte._props.shapeWidth = 0 byte._props.shapeHeight = 0 byte._getShapeSize() p = byte._props stroke = byte._getMaxStroke() expect( p.shapeWidth ).toBe 2*byte._getMaxRadius( 'radiusX' ) + stroke expect( p.shapeHeight ).toBe 2*byte._getMaxRadius( 'radiusY' ) + stroke describe '_getMaxSizeInChain method ->', -> it 'should call _getShapeSize on every module', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) ms = shape._modules spyOn ms[0], '_getShapeSize' spyOn ms[1], '_getShapeSize' spyOn ms[2], '_getShapeSize' shape._getMaxSizeInChain() expect( ms[0]._getShapeSize ).toHaveBeenCalled() expect( ms[1]._getShapeSize ).toHaveBeenCalled() expect( ms[2]._getShapeSize ).toHaveBeenCalled() it 'should set the largest size to shapeModule', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) largest = shape._modules[2] shapeModule = shape.shapeModule spyOn shapeModule, '_setSize' shape._getMaxSizeInChain() expect( shapeModule._setSize ) .toHaveBeenCalledWith largest._props.shapeWidth, largest._props.shapeHeight it 'should call _setElSizeStyles method', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) largest = shape._modules[2] spyOn shape, '_setElSizeStyles' shape._getMaxSizeInChain() expect( shape._setElSizeStyles ) .toHaveBeenCalledWith largest._props.shapeWidth, largest._props.shapeHeight describe '_setElSizeStyles method ->', -> it 'should set `width`, `height` and `margins` to the `el` styles', -> shape = new Shape() style = shape.el.style style[ 'width' ] = '0px' style[ 'height' ] = '0px' style[ 'margin-left' ] = '0px' style[ 'margin-right' ] = '0px' shape._setElSizeStyles( 100, 200 ) expect( style[ 'width' ] ).toBe '100px' expect( style[ 'height' ] ).toBe '200px' expect( style[ 'margin-left' ] ).toBe '-50px' expect( style[ 'margin-top' ] ).toBe '-100px' describe 'then method ->', -> it 'should call super', -> obj = {} shape = new Shape() spyOn Thenable::, 'then' shape.then( obj ) expect( Thenable::then ).toHaveBeenCalledWith obj it 'should return this', -> shape = new Shape() result = shape.then( {} ) expect( result ).toBe shape it 'should call _getMaxSizeInChain method', -> shape = new Shape() spyOn shape, '_getMaxSizeInChain' shape.then({}) expect( shape._getMaxSizeInChain ).toHaveBeenCalled() describe 'tune method ->', -> it 'should call super', -> obj = {} shape = new Shape() spyOn Tunable::, 'tune' shape.tune( obj ) expect( Tunable::tune ).toHaveBeenCalledWith obj it 'should return this', -> shape = new Shape() result = shape.tune( {} ) expect( result ).toBe shape it 'should call _getMaxSizeInChain method', -> shape = new Shape() spyOn shape, '_getMaxSizeInChain' shape.tune({}) expect( shape._getMaxSizeInChain ).toHaveBeenCalled() describe '_refreshBefore method ->', -> it 'should call `_show` method is `isShowStart`', -> shape = new Shape isShowStart: true spyOn shape, '_show' shape._refreshBefore() expect( shape._show ).toHaveBeenCalled() it 'should call `_hide` method is not `isShowStart`', -> shape = new Shape spyOn shape, '_hide' shape._refreshBefore() expect( shape._hide ).toHaveBeenCalled() it 'should call `_setProgress` with `0, 0`', -> shape = new Shape spyOn shape, '_setProgress' shape._refreshBefore() expect( shape._setProgress ).toHaveBeenCalledWith 0, 0 it 'should call `_setProgress` with tweens eased progress', -> shape = new Shape easing: (k)-> return 1 spyOn shape, '_setProgress' shape._refreshBefore() expect( shape._setProgress ).toHaveBeenCalledWith 1, 0 describe '_showByTransform method ->', -> it 'should call _drawEl method', -> shape = new Shape easing: (k)-> return 1 spyOn shape, '_drawEl' shape._showByTransform() expect( shape._drawEl ).toHaveBeenCalled() it 'should update scale', -> shape = new Shape easing: (k)-> return 1 shape.el.style.transform = 'scale(0)' shape.el.style["#{mojs.h.prefix.css}transform"] = 'scale(0)' shape._showByTransform() s = shape.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true
true
Byte = mojs.Shape Shape = mojs.Shape Bit = mojs.shapesMap.getShape('bit') Thenable = mojs.Thenable Tunable = mojs.Tunable Tweenable = mojs.Tweenable Rect = mojs.shapesMap.getShape('rect') h = mojs.helpers ns = 'http://www.w3.org/2000/svg' svg = document.createElementNS?(ns, 'svg') # console.log = -> console.warn = -> console.error = -> describe 'Shape ->', -> describe '_vars method', -> it 'should have own _vars function ->', -> byte = new Byte expect(byte._vars).toBeDefined() expect(-> byte._vars()).not.toThrow() it 'should call _vars super method', -> byte = new Byte expect(byte._history.length).toBe 1 it 'should save passed _o.masterModule to _masterModule', -> obj = {} byte = new Byte masterModule: obj byte._masterModule = null byte._vars() expect(byte._masterModule).toBe obj it 'should set `_isChained` based on `prevChainModule` option', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 byte._isChained = null byte._vars() expect(byte._isChained).toBe true # old # it 'should save passed _o.positionEl to el', -> # obj = document.createElement 'div' # byte = new Byte positionEl: obj # byte.el = null # byte._vars() # expect(byte.el).toBe obj # old # it 'should save passed _o.shiftEl to el', -> # obj = document.createElement 'div' # byte = new Byte shiftEl: obj # byte.el = null # byte._vars() # expect(byte.el).toBe obj it 'should save passed _o.prevChainModule to _prevChainModule', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 byte._prevChainModule = null byte._vars() expect(byte._prevChainModule).toBe byte0 describe 'extension ->', -> it 'should extend Tweenable class', -> byte = new Byte expect(byte instanceof Tweenable).toBe(true) it 'should extend Thenable class', -> byte = new Byte expect(byte instanceof Thenable).toBe(true) describe 'defaults object ->', -> it 'should have defaults object', -> byte = new Byte expect(byte._defaults).toBeDefined() expect(byte._defaults.parent).toBe document.body expect(byte._defaults.className).toBe '' expect(byte._defaults.shape).toBe 'circle' expect(byte._defaults.stroke).toBe 'transparent' expect(byte._defaults.strokeOpacity).toBe 1 expect(byte._defaults.strokeLinecap).toBe '' expect(byte._defaults.strokeWidth).toBe 2 expect(byte._defaults.strokeDasharray).toBe 0 expect(byte._defaults.strokeDashoffset).toBe 0 expect(byte._defaults.fill).toBe 'deeppink' expect(byte._defaults.fillOpacity).toBe 1 expect(byte._defaults.isSoftHide).toBe true expect(byte._defaults.isForce3d).toBe false expect(byte._defaults.left).toBe '50%' expect(byte._defaults.top).toBe '50%' expect(byte._defaults.x).toBe 0 expect(byte._defaults.y).toBe 0 expect(byte._defaults.rotate).toBe 0 expect(byte._defaults.scale).toEqual 1 expect(byte._defaults.scaleX).toBe null expect(byte._defaults.scaleY).toBe null expect(byte._defaults.origin).toBe '50% 50%' expect(byte._defaults.rx).toBe 0 expect(byte._defaults.ry).toBe 0 expect(byte._defaults.opacity).toBe 1 expect(byte._defaults.points).toBe 3 expect(byte._defaults.duration).toBe 400 expect(byte._defaults.radius).toBe 50 expect(byte._defaults.radiusX).toBe null expect(byte._defaults.radiusY).toBe null expect(byte._defaults.isShowEnd).toBe true expect(byte._defaults.isShowStart).toBe false expect(byte._defaults.isRefreshState).toBe true # nope # expect(byte._defaults.size).toBe null expect(byte._defaults.width).toBe null expect(byte._defaults.height).toBe null # expect(byte._defaults.sizeGap).toBe 0 expect(byte._defaults.isWithShape).toBe true expect(byte._defaults.callbacksContext).toBe byte describe '_applyCallbackOverrides ->', -> it 'should create callbackOverrides object on passed object', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) expect(typeof obj.callbackOverrides).toBe 'object' # not null expect(obj.callbackOverrides).toBe obj.callbackOverrides describe 'onUpdate callback override ->', -> it 'should override this._o.onUpdate', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) expect(typeof obj.callbackOverrides.onUpdate).toBe 'function' it 'should call _setProgress ', -> tr = new Shape obj = {} tr._applyCallbackOverrides(obj) spyOn tr, '_setProgress' easedProgress = .25 progress = .2 obj.callbackOverrides.onUpdate easedProgress, progress expect(tr._setProgress).toHaveBeenCalledWith easedProgress, progress it 'should not override onUpdate function if exists', -> isRightScope = null; args = null options = { easing: 'Linear.None', onUpdate:-> isRightScope = @ is tr args = arguments } tr = new Shape options expect(typeof tr._o.onUpdate).toBe 'function' tr.timeline.setProgress 0 tr.timeline.setProgress .1 expect(isRightScope).toBe true expect(args[0]).toBe .1 expect(args[1]).toBe .1 expect(args[2]).toBe true expect(args[3]).toBe false it 'should call _setProgress method', -> options = { easing: 'Linear.None', onUpdate:-> } obj = {} tr = new Shape options tr.timeline.setProgress 0 spyOn tr, '_setProgress' progress = .1 tr.timeline.setProgress progress expect(tr._setProgress.calls.first().args[0]).toBeCloseTo progress, 5 describe 'onStart callback override ->', -> it 'should override this._o.onStart', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onStart).toBe 'function' it 'should call _show if isForward and !_isChained', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onStart true expect(tr._show).toHaveBeenCalled() it 'should not call _show if _isChained', -> tr = new Shape masterModule: new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onStart true expect(tr._show).not.toHaveBeenCalled() it 'should call _hide if not isForward and !_isChained', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).toHaveBeenCalled() it 'should not call _hide if not isForward and _isChained', -> tr = new Shape masterModule: new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if not isForward and isShowStart', -> tr = new Shape isShowStart: true obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onStart false expect(tr._hide).not.toHaveBeenCalled() describe 'onComplete callback override ->', -> it 'should override this._o.onComplete', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onComplete).toBe 'function' it 'should call _show if !isForward', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).toHaveBeenCalled() it 'should call _show if !isForward and _isLastInChain()', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).toHaveBeenCalled() it 'should call _show if !isForward and _isLastInChain() #2', -> tr = new Shape().then radius: 0 el = tr._modules[1] obj = {} el._applyCallbackOverrides( obj ) spyOn el, '_show' obj.callbackOverrides.onComplete false expect(el._show).toHaveBeenCalled() it 'should not call _show if !isForward and not _isLastInChain', -> tr = new Shape().then radius: 0 obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_show' obj.callbackOverrides.onComplete false expect(tr._show).not.toHaveBeenCalled() it 'should call _hide if isForward and !isShowEnd', -> tr = new Shape isShowEnd: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).toHaveBeenCalled() it 'should not call _hide if isForward but isShowEnd', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should call _hide if isForward and _isLastInChain', -> tr = new Shape isShowEnd: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).toHaveBeenCalled() it 'should call not _hide if isForward and !_isLastInChain', -> tr = new Shape(isShowEnd: false).then({ radius: 0 }) # module = tr._modules[1] obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if isForward and _isLastInChain but isShowEnd', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() it 'should not call _hide if isForward but !_isLastInChain and isShowEnd', -> tr = new Shape().then radius: 0 obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_hide' obj.callbackOverrides.onComplete true expect(tr._hide).not.toHaveBeenCalled() describe 'onRefresh callback override ->', -> it 'should override this._o.onRefresh', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) expect(typeof obj.callbackOverrides.onRefresh).toBe 'function' it 'should call _refreshBefore if isBefore', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh true expect(tr._refreshBefore).toHaveBeenCalled() it 'should not call _refreshBefore if !isBefore', -> tr = new Shape obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh false expect(tr._refreshBefore).not.toHaveBeenCalled() it 'should not call _refreshBefore if !isRefreshState', -> tr = new Shape isRefreshState: false obj = {} tr._applyCallbackOverrides( obj ) spyOn tr, '_refreshBefore' obj.callbackOverrides.onRefresh true expect(tr._refreshBefore).not.toHaveBeenCalled() describe '_transformTweenOptions method', -> it 'should call _applyCallbackOverrides with _o', -> tr = new Shape spyOn tr, '_applyCallbackOverrides' tr._transformTweenOptions() expect(tr._applyCallbackOverrides).toHaveBeenCalledWith tr._o describe 'options object ->', -> it 'should receive empty options object by default', -> byte = new Byte expect(byte._o).toBeDefined() it 'should receive options object', -> byte = new Byte option: 1 expect(byte._o.option).toBe 1 describe 'index option ->', -> it 'should receive index option', -> byte = new Shape index: 5 expect(byte._index).toBe 5 it 'should fallback to 0', -> byte = new Shape expect(byte._index).toBe 0 describe 'options history ->', -> it 'should have history array', -> byte = new Byte expect(h.isArray(byte._history)).toBe true it 'should save options to history array', -> byte = new Byte radius: 20 expect(byte._history.length).toBe 1 describe 'size calculations ->', -> it 'should not calculate size el size if size was passed', -> byte = new Byte radius: 10 strokeWidth: 5 width: 400 height: 200 expect(byte._props.shapeWidth).toBe(400) expect(byte._props.shapeHeight).toBe(200) describe 'opacity set ->', -> it 'should set opacity regarding units', -> byte = new Byte opacity: .5, isShowStart: true expect(byte.el.style.opacity).toBe '0.5' it 'should animate opacity', (dfr)-> byte = new Byte opacity: { 1: 0} duration: 100 onComplete:-> expect(byte.el.style.opacity).toBe('0'); dfr() byte.play() describe 'position set ->', -> describe 'x/y coordinates ->', -> it 'should set position regarding units', -> byte = new Byte left: 100, top: 50 expect(byte.el.style.left).toBe '100px' expect(byte.el.style.top) .toBe '50px' it 'should animate position', (dfr)-> byte = new Byte left: {100: '200px'} duration: 100 onComplete:-> expect(byte.el.style.left).toBe('200px'); dfr() byte.play() it 'should warn when x/y animated position and not foreign context',-> spyOn console, 'warn' byte = new Byte left: {100: '200px'} byte.play() expect(console.warn).toHaveBeenCalled() it 'should notwarn when x/y animated position and foreign context',-> spyOn console, 'warn' byte = new Byte left: {100: '200px'}, ctx: svg byte.play() expect(console.warn).not.toHaveBeenCalled() it 'should animate position regarding units', (dfr)-> byte = new Byte left: {'20%': '50%'} duration: 100 byte.play() setTimeout -> expect(byte.el.style.left) .toBe '50%' dfr() , 500 it 'end unit that were not specified should fallback to start unit', ()-> byte = new Byte left: {'20%': 50} duration: 200 byte.play() expect(byte._deltas.left.start.unit).toBe '%' expect(byte._deltas.left.end.unit) .toBe '%' it 'should fallback to end units if units are different', (dfr)-> byte = new Byte left: {'20%': '50px'} duration: 200 onComplete:-> expect(byte.el.style.left).toBe('50px'); dfr() byte.play() it 'should set position regarding units #2', -> byte = new Byte x: 100 y: 50, isShowStart: true s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isNormal = tr is 'translate(100px, 50px) rotate(0deg) scale(1, 1)' isIE = tr is 'translate(100px, 50px) rotate(0deg) scale(1)' expect(isNormal or isIE).toBe true it 'should animate shift position', (dfr)-> byte = new Byte x: {100: '200px'} duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(200px, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(200px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(200px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(200px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true dfr() byte.play() it 'should animate position regarding units #3', (dfr)-> byte = new Byte x: {'20%': '50%'} duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(50%, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(50%, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(50%, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(50%) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true dfr() byte.play() it 'should fallback to end units if units are differnt', (dfr)-> byte = new Byte x: { '20%': '50px' } y: { 0 : '50%' } duration: 200 onComplete:-> s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr1 = tr is 'translate(50px, 50%) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(50px, 50%) rotate(0deg) scale(1)' expect(isTr1 or isTr2).toBe true dfr() byte.play() describe '_render method ->', -> it 'should call _createShape method', -> byte = new Byte radius: 25 spyOn byte, '_createShape' byte._isRendered = false byte._render() expect(byte._createShape).toHaveBeenCalled() it 'should set _isRendered to true', -> byte = new Byte radius: 25 expect(byte._isRendered).toBe true byte._isRendered = false; byte._render() expect(byte._isRendered).toBe true it 'should not call _createShape method if already rendered', -> byte = new Byte radius: 25 spyOn byte, '_createShape' byte._isRendered = true byte._render() expect(byte._createShape).not.toHaveBeenCalled() it 'should set `el` and `shape` if `_isChained`', -> byte0 = new Byte radius: 25 byte = new Byte prevChainModule: byte0 masterModule: byte0 expect(byte.el).toBe byte0.el expect(byte.shapeModule).toBe byte0.shapeModule it 'should not call _createShape method if _isChained', -> byte0 = new Byte byte = new Byte radius: 25 prevChainModule: byte0 masterModule: byte0 spyOn byte, '_createShape' byte._o.el = byte0.el byte._o.shapeModule = byte0.shapeModule byte._render() expect(byte._createShape).not.toHaveBeenCalled() it 'should call `_setProgress(0)` if not `_isChained`', -> byte = new Byte spyOn byte, '_setProgress' byte._isRendered = false byte._render() expect(byte._setProgress).toHaveBeenCalledWith(0, 0) it 'should not call `_setProgress(0)` if not `_isFirstInChain()`', -> byte0 = new Byte byte = new Byte prevChainModule: byte0 masterModule: byte0 spyOn byte, '_setProgress' byte._isRendered = false byte._render() expect(byte._setProgress).not.toHaveBeenCalledWith(0) it 'should call _setElStyles method', -> byte = new Byte radius: 25 spyOn byte, '_setElStyles' byte._isRendered = false byte._render() expect(byte._setElStyles).toHaveBeenCalled() it 'should not call _setElStyles method if _isChained', -> byte = new Byte prevChainModule: new Byte masterModule: new Byte spyOn byte, '_setElStyles' byte._isRendered = true byte._render() expect(byte._setElStyles).not.toHaveBeenCalled() it 'should call _show method if `isShowStart`', -> byte = new Byte isShowStart: true spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).toHaveBeenCalled() it 'should call not _show method if not `isShowStart`', -> byte = new Byte isShowStart: false spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).not.toHaveBeenCalled() it 'should not _show method if `_isChained`', -> byte = new Byte isShowStart: true, prevChainModule: new Byte masterModule: new Byte spyOn byte, '_show' byte._isRendered = false byte._render() expect(byte._show).not.toHaveBeenCalled() it 'should call _hide method if not `isShowStart`', -> byte = new Byte isShowStart: false spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).toHaveBeenCalled() it 'should call not _hide method if `isShowStart`', -> byte = new Byte isShowStart: true spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).not.toHaveBeenCalled() it 'should not _hide method if `_isChained`', -> byte = new Byte isShowStart: false, prevChainModule: new Byte masterModule: new Byte spyOn byte, '_hide' byte._isRendered = false byte._render() expect(byte._hide).not.toHaveBeenCalled() describe '_setElStyles method ->', -> it 'should set dimentions and position of the `el`', -> byte = new Byte radius: 25 byte.el.style.position = 'static' byte.el.style.width = '0px' byte.el.style.height = '0px' byte.el.style[ 'margin-left' ] = '0px' byte.el.style[ 'margin-top' ] = '0px' byte._setElStyles() expect( byte.el.style.position ).toBe 'absolute' expect( byte.el.style.width ).toBe "#{byte._props.shapeWidth}px" expect( byte.el.style.height ).toBe "#{byte._props.shapeHeight}px" expect( byte.el.style[ 'margin-left' ] ) .toBe "-#{byte._props.shapeWidth/2}px" expect( byte.el.style[ 'margin-top' ] ) .toBe "-#{byte._props.shapeHeight/2}px" it 'should set `backface-visibility` if `isForce3d`', -> byte = new Byte radius: 25, isForce3d: true style = byte.el.style bv = style[ 'backface-visibility' ] prefixedBv = style[ "#{mojs.h.prefix.css}backface-visibility" ] expect( bv or prefixedBv ).toBe 'hidden' it 'should not set `backface-visibility` if `isForce3d`', -> byte = new Byte radius: 25 style = byte.el.style bv = style[ 'backface-visibility' ] prefixedBv = style[ "#{mojs.h.prefix.css}backface-visibility" ] expect( bv or prefixedBv ).not.toBe 'hidden' describe '_draw method ->', -> # nope # it 'should call _setProp method', -> # byte = new Byte radius: 25 # spyOn byte.shapeModule, 'setProp' # byte._draw() # expect(byte.shapeModule.setProp).toHaveBeenCalled() it 'should set all attributes to shape\'s properties', -> byte = new Byte radius: 25, x: 20, y: 30, rx: 15, ry: 25 stroke: 'red' strokeWidth: 2 strokeOpacity: .5 strokeLinecap: 'round' strokeDasharray: 200 strokeDashoffset: 100 fill: 'cyan' fillOpacity: .5 radius: 100 radiusX: 22 radiusY: { 20: 0 } points: 4 byte._draw() # old # expect(byte.shapeModule._props.x).toBe byte._origin.x # old # expect(byte.shapeModule._props.y).toBe byte._origin.y expect(byte.shapeModule._props.rx).toBe byte._props.rx expect(byte.shapeModule._props.ry).toBe byte._props.ry expect(byte.shapeModule._props.stroke).toBe byte._props.stroke expect(byte.shapeModule._props['stroke-width']).toBe byte._props.strokeWidth expect(byte.shapeModule._props['stroke-opacity']).toBe byte._props.strokeOpacity expect(byte.shapeModule._props['stroke-linecap']).toBe byte._props.strokeLinecap expect(byte.shapeModule._props['stroke-dasharray']).toBe byte._props.strokeDasharray[0].value + ' ' expect(byte.shapeModule._props['stroke-dashoffset']).toBe byte._props.strokeDashoffset[0].value + ' ' expect(byte.shapeModule._props['fill']).toBe byte._props.fill expect(byte.shapeModule._props['fill-opacity']).toBe byte._props.fillOpacity expect(byte.shapeModule._props['radius']).toBe byte._props.radius expect(byte.shapeModule._props['radiusX']).toBe byte._props.radiusX expect(byte.shapeModule._props['radiusY']).toBe byte._props.radiusY expect(byte.shapeModule._props['points']).toBe byte._props.points # old # expect(byte.shapeModule._props['transform']).toBe byte._calcShapeTransform() it 'should call bit._draw method', -> byte = new Byte radius: 25 spyOn byte.shapeModule, '_draw' byte._draw() expect(byte.shapeModule._draw).toHaveBeenCalled() it 'should call _drawEl method', -> byte = new Byte radius: 25 spyOn byte, '_drawEl' byte._draw() expect(byte._drawEl).toHaveBeenCalled() it 'should receive the current progress', -> byte = new Byte radius: 25 spyOn byte, '_draw' byte._setProgress .5 expect(byte._draw).toHaveBeenCalledWith .5 describe '_drawEl method ->', -> it 'should set el positions and transforms', -> byte = new Byte radius: 25, top: 10, isShowStart: true expect(byte.el.style.top) .toBe '10px' expect(byte.el.style.opacity) .toBe '1' expect(byte.el.style.left).toBe '50%' s = byte.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set new values', -> byte = new Byte radius: 25, top: 10 byte._draw() byte._props.left = '1px' byte._draw() expect(byte.el.style.left).toBe '1px' expect(byte._lastSet.left.value) .toBe '1px' it 'should not set old values', -> byte = new Byte radius: 25, y: 10 byte._draw() byte._draw() expect(byte._lastSet.x.value) .toBe '0' it 'should return true if there is no el', -> byte = new Byte radius: 25 byte.el = null expect(byte._drawEl()).toBe true it 'should set transform if rotation is changed', -> byte = new Byte rotate: 25 byte._draw() byte._props.rotate = 26 byte._draw() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(26deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(26deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(26deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(26deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true # expect(byte.el.style["#{h.prefix.css}transform"]).toBe resultStr it 'should not set transform if rotation changed #2', -> byte = new Byte rotate: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if scaleX changed', -> byte = new Byte scaleX: 25 byte._draw() spyOn byte, '_fillTransform' byte._props.scaleX = 24 byte._draw() expect(byte._fillTransform).toHaveBeenCalled() it 'should not set transform if scaleX not changed', -> byte = new Byte scaleX: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if scaleY changed', -> byte = new Byte scaleY: 25 byte._draw() spyOn byte, '_fillTransform' byte._props.scaleY = 24 byte._draw() expect(byte._fillTransform).toHaveBeenCalled() it 'should not set transform if scaleY not changed', -> byte = new Byte scaleY: 25 byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if one of the x, y or scale changed', -> byte = new Byte radius: 25, top: 10, ctx: svg byte._draw() spyOn byte, '_fillTransform' byte._draw() expect(byte._fillTransform).not.toHaveBeenCalled() it 'should set transform if x changed', -> byte = new Byte radius: 25, top: 10, x: { 0: 10 } byte._props.x = '4px' spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(4px, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(4px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(4px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(4px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set transform if y changed', -> byte = new Byte radius: 25, top: 10, y: { 0: 10 } byte._props.y = '4px' spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 4px) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 4px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 4px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px, 4px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set transform if scale changed', -> byte = new Byte radius: 25, top: 10, scale: { 0: 10 } byte._props.scale = 3 spyOn(byte, '_fillTransform').and.callThrough() byte._draw() expect(byte._fillTransform).toHaveBeenCalled() # resultStr = 'scale(3) translate(0, 0) rotate(0deg)' # expect(byte.el.style['transform']).toBe resultStr style = byte.el.style tr = style['transform'] or style["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(3, 3)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(3, 3)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(3)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(3)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true it 'should set `transform-origin` if `origin`', -> byte = new Byte origin: '50% 30%' byte._drawEl() prop = 'transform-origin' style = byte.el.style tr = style[ prop ] or style["#{mojs.h.prefix.css}#{prop}"] isOr1 = tr is '50% 30% ' isOr2 = tr is '50% 30%' isOr3 = tr is '50% 30% 0px' expect(isOr1 or isOr2 or isOr3).toBe true it 'should set `transform-origin` if `origin` changed', -> byte = new Byte origin: '50% 30%' spyOn(byte, '_fillOrigin').and.callThrough() byte._props.origin = byte._parseStrokeDashOption( 'origin', '50% 40%'); byte._drawEl() prop = 'transform-origin' style = byte.el.style tr = style[ prop ] or style["#{mojs.h.prefix.css}#{prop}"] isOr1 = tr is '50% 40% ' isOr2 = tr is '50% 40%' isOr3 = tr is '50% 40% 0px' expect(isOr1 or isOr2 or isOr3).toBe true expect(byte._fillOrigin).toHaveBeenCalled() it 'should not set `transform-origin` if `origin`', -> byte = new Byte origin: '50% 30%' byte._draw() spyOn(byte, '_fillOrigin').and.callThrough() byte._draw() expect(byte._fillOrigin).not.toHaveBeenCalled() it 'should set `transform-origin` if `origin` in `_deltas`', -> byte = new Byte origin: { '50% 30%': '50% 0'} spyOn(byte, '_fillOrigin').and.callThrough() byte._drawEl() byte._drawEl() expect(byte._fillOrigin.calls.count()).toBe 2 describe '_isPropChanged method ->', -> it 'should return bool showing if prop was changed after the last set', -> byte = new Byte radius: 25, y: 10 byte._props.left = '20px' expect(byte._isPropChanged 'left').toBe true byte._props.left = '20px' expect(byte._isPropChanged 'left').toBe false it 'should add prop object to lastSet if undefined', -> byte = new Byte radius: 25, y: 10 byte._isPropChanged('x') expect(byte._lastSet.x).toBeDefined() describe 'delta calculations ->', -> it 'should skip delta for excludePropsDelta object', -> byte = new Byte radius: {45: 55} byte._skipPropsDelta = radius: 1 byte._extendDefaults() expect(byte._deltas.radius).not.toBeDefined() describe 'numeric values ->', -> it 'should calculate delta', -> byte = new Byte radius: {25: 75} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25 expect(radiusDelta.delta) .toBe 50 expect(radiusDelta.type) .toBe 'number' it 'should calculate delta with string arguments', -> byte = new Byte radius: {'25': '75'} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25 expect(radiusDelta.delta) .toBe 50 it 'should calculate delta with float arguments', -> byte = new Byte radius: {'25.50': 75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25.5 expect(radiusDelta.delta) .toBe 50 it 'should calculate delta with negative start arguments', -> byte = new Byte radius: {'-25.50': 75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe -25.5 expect(radiusDelta.delta) .toBe 101 it 'should calculate delta with negative end arguments', -> byte = new Byte radius: {'25.50': -75.50} radiusDelta = byte._deltas.radius expect(radiusDelta.start) .toBe 25.5 expect(radiusDelta.end) .toBe -75.5 expect(radiusDelta.delta) .toBe -101 describe 'color values ->', -> it 'should calculate color delta', -> byte = new Byte stroke: {'#000': 'rgb(255,255,255)'} colorDelta = byte._deltas.stroke expect(colorDelta.start.r) .toBe 0 expect(colorDelta.end.r) .toBe 255 expect(colorDelta.delta.r) .toBe 255 expect(colorDelta.type) .toBe 'color' it 'should ignore stroke-linecap prop, use start prop and warn', -> byte = null spyOn console, 'warn' fun = -> byte = new Byte strokeLinecap: {'round': 'butt'} expect(-> fun()).not.toThrow() expect(console.warn).toHaveBeenCalled() expect(byte._deltas.strokeLinecap).not.toBeDefined() describe 'unit values ->', -> it 'should calculate unit delta', -> byte = new Byte x: {'0%': '100%'} xDelta = byte._deltas.x expect(xDelta.start.string) .toBe '0' expect(xDelta.end.string) .toBe '100%' expect(xDelta.delta) .toBe 100 expect(xDelta.type) .toBe 'unit' describe 'tween-related values ->', -> it 'should not calc delta for tween related props', -> byte = new Byte duration: { 2000: 1000 } expect(byte._deltas.duration).not.toBeDefined() describe '_setProgress method ->', -> it 'should set Shapeion progress', -> byte = new Byte radius: {'25.50': -75.50} byte._setProgress .5 expect(byte._progress).toBe .5 it 'should set value progress', -> byte = new Byte radius: {'25': 75} byte._setProgress .5 expect(byte._props.radius).toBe 50 it 'should call _calcCurrentProps', -> byte = new Byte radius: {'25': 75} spyOn byte, '_calcCurrentProps' byte._setProgress .5, .35 expect(byte._calcCurrentProps).toHaveBeenCalledWith .5, .35 it 'not to thow', -> byte = new Byte radius: {'25': 75}, ctx: svg expect(-> byte._show()).not.toThrow() it 'should set color value progress and only int', -> byte = new Byte stroke: {'#000': 'rgb(255,255,255)'} colorDelta = byte._deltas.stroke byte._setProgress .5 expect(byte._props.stroke).toBe 'rgba(127,127,127,1)' it 'should set color value progress for delta starting with 0', -> byte = new Byte stroke: {'#000': 'rgb(0,255,255)'} colorDelta = byte._deltas.stroke byte._setProgress .5 expect(byte._props.stroke).toBe 'rgba(0,127,127,1)' describe 'strokeDash.. values', -> it 'should set strokeDasharray/strokeDashoffset value progress', -> byte = new Byte strokeDasharray: {'200 100': '400'} byte._setProgress .5 expect(byte._props.strokeDasharray[0].value).toBe 300 expect(byte._props.strokeDasharray[0].unit) .toBe 'px' expect(byte._props.strokeDasharray[1].value).toBe 50 expect(byte._props.strokeDasharray[1].unit) .toBe 'px' it 'should set strokeDasharray/strokeDashoffset with percents', -> byte = new Byte type: 'circle' strokeDasharray: {'0% 200': '100%'} radius: 100 byte._setProgress .5 expect(byte._props.strokeDasharray[0].value).toBe 50 expect(byte._props.strokeDasharray[0].unit) .toBe '%' expect(byte._props.strokeDasharray[1].value).toBe 100 expect(byte._props.strokeDasharray[1].unit) .toBe 'px' it 'should parse non-deltas strokeDasharray/strokeDashoffset values', -> byte = new Byte type: 'circle' strokeDasharray: '100%' radius: 100 expect(byte._props.strokeDasharray[0].value).toBe 100 expect(byte._props.strokeDasharray[0].unit).toBe '%' it 'should parse multiple strokeDash.. values', -> byte = new Byte strokeDasharray: '7 100 7' expect(h.isArray(byte._props.strokeDasharray)).toBe true expect(byte._props.strokeDasharray.length).toBe 3 expect(byte._props.strokeDasharray[0].value).toBe 7 expect(byte._props.strokeDasharray[1].value).toBe 100 expect(byte._props.strokeDasharray[2].value).toBe 7 it 'should parse num values', -> byte = new Byte strokeDasharray: 7 expect(h.isArray(byte._props.strokeDasharray)).toBe true expect(byte._props.strokeDasharray.length) .toBe 1 describe '_getRadiusSize method ->', -> it 'should return max from delatas if key is defined', -> byte = new Byte radiusX: 20: 30 size = byte._getRadiusSize 'radiusX' expect(size).toBe 30 # it 'should return props\' value if delats\' one is not defined ', -> # byte = new Byte radiusX: 20 # size = byte._getRadiusSize key: 'PI:KEY:<KEY>END_PI', fallback: 0 # expect(size).toBe 20 # it 'should fallback to passed fallback option', -> # byte = new Byte # size = byte._getRadiusSize key: 'PI:KEY:<KEY>END_PI', fallback: 0 # expect(size).toBe 0 # it 'should fallback to 0 by default', -> # byte = new Byte # size = byte._getRadiusSize key: 'PI:KEY:<KEY>END_PI' # expect(size).toBe 0 # not now # describe 'isForeign flag ->', -> # it 'should not be set by default', -> # byte = new Byte # expect(byte.isForeign).toBe false # it 'should be set if context was passed', -> # byte = new Byte ctx: svg # expect(byte.isForeign).toBe true # it 'if context passed el should be bit\'s el', -> # byte = new Byte ctx: svg # expect(byte.el).toBe byte.shapeModule.el # describe 'foreign bit option ->', -> # it 'should receive a foreign bit to work with', -> # svg = document.createElementNS?(ns, 'svg') # bit = document.createElementNS?(ns, 'rect') # svg.appendChild bit # byte = new Shape bit: bit # expect(byte.shapeModule.el).toBe bit # it 'should set isForeignBit flag', -> # svg = document.createElementNS?(ns, 'svg') # bit = document.createElementNS?(ns, 'rect') # svg.appendChild bit # byte = new Byte bit: bit # expect(byte.isForeignBit).toBe true describe '_increaseSizeWithEasing method ->', -> it 'should increase size based on easing - elastic.out', -> tr = new Shape easing: 'elastic.out' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.25 it 'should increase size based on easing - elastic.inout', -> tr = new Shape easing: 'elastic.inout' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.25 it 'should increase size based on easing - back.out', -> tr = new Shape easing: 'back.out' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.1 it 'should increase size based on easing - back.inout', -> tr = new Shape easing: 'back.inout' tr._props.size = 1 tr._increaseSizeWithEasing() expect(tr._props.size).toBe 1.1 # nope # describe '_increaseSizeWithBitRatio method ->', -> # it 'should increase size based on bit ratio', -> # tr = new Shape shape: 'equal' # tr._props.size = 1 # tr._increaseSizeWithBitRatio() # expect(tr._props.size).toBe tr.shapeModule._props.ratio # it 'should increase size based 2 gap sizes', -> # gap = 20 # tr = new Shape shape: 'equal', sizeGap: gap # tr._props.size = 1 # tr._increaseSizeWithBitRatio() # expect(tr._props.size).toBe tr.shapeModule._props.ratio + 2*gap describe 'callbacksContext option ->', -> it 'should pass the options to the tween', -> obj = {}; isRightContext = null tr = new Shape callbacksContext: obj onUpdate:-> isRightContext = @ is obj tr.setProgress 0 tr.setProgress .1 expect(isRightContext).toBe true it 'should pass the options to the timeline', -> obj = {}; isRightContext = null tr = new Shape callbacksContext: obj timeline: { onUpdate:-> isRightContext = @ is obj } tr.setProgress 0 tr.setProgress .1 expect(isRightContext).toBe true describe '_fillTransform method ->', -> it 'return tranform string of the el', -> tr = new Shape x: 100, y: 100, rotate: 50, scaleX: 2, scaleY: 3 expect(tr._fillTransform()) .toBe 'translate(100px, 100px) rotate(50deg) scale(2, 3)' describe '_fillOrigin method ->', -> it 'return tranform-origin string of the el', -> tr = new Shape x: 100, y: 100, origin: '50% 30%' expect(tr._fillOrigin()).toBe '50% 30% ' it 'return tranform-origin string of the el with delta', -> tr = new Shape x: 100, y: 100, easing: 'linear.none', origin: { '0% 0%' : '50% 200%' } tr.setProgress 0 tr.setProgress .5 expect(tr._fillOrigin()).toBe '25% 100% ' describe 'el creation ->', -> describe 'el ->', -> it 'should create el', -> byte = new Byte radius: 25 expect(byte.el.tagName.toLowerCase()).toBe 'div' style = byte.el.style expect(style[ 'position' ]).toBe 'absolute' expect(style[ 'width' ]).toBe '52px' expect(style[ 'height' ]).toBe '52px' # expect(style[ 'display' ]).toBe 'none' # expect(byte.el.style.opacity) .toBe 1 expect(byte.el.getAttribute('data-name')).toBe('mojs-shape') it 'should add `class` to `el`', -> className = 'some-class' byte = new Byte radius: 25, className: className expect(byte.el.getAttribute('class')).toBe className it 'should create bit based on shape option or fallback to circle', -> byte = new Byte radius: 25 shape: 'rect' byte2 = new Byte radius: 25 expect(byte.shapeModule._props.tag).toBe 'rect' expect(byte2.shapeModule._props.tag).toBe 'ellipse' # describe '_hide method ->' , -> # it 'should set `display` of `el` to `none`', -> # byte = new Byte radius: 25, isSoftHide: false # byte.el.style[ 'display' ] = 'block' # byte._hide() # expect( byte.el.style[ 'display' ] ).toBe 'none' # it 'should set `_isShown` to false', -> # byte = new Byte radius: 25, isSoftHide: false # byte._isShown = true # byte._hide() # expect( byte._isShown ).toBe false # describe 'isSoftHide option ->', -> # it 'should set `opacity` of `el` to `0`', -> # byte = new Byte radius: 25, isSoftHide: true # byte.el.style[ 'opacity' ] = '.5' # byte._hide() # expect( byte.el.style[ 'opacity' ] ).toBe '0' # it 'should set scale to 0', -> # byte = new Byte # radius: 25, # isSoftHide: true # byte._hide() # style = byte.el.style # tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ] # expect( tr ).toBe 'scale(0)' # describe '_show method ->' , -> # it 'should set `display` of `el` to `block`', -> # byte = new Byte radius: 25, isSoftHide: false # byte.el.style[ 'display' ] = 'none' # byte._show() # expect( byte.el.style[ 'display' ] ).toBe 'block' # it 'should set `_isShown` to true', -> # byte = new Byte radius: 25, isSoftHide: false # byte._isShown = true # byte._show() # expect( byte._isShown ).toBe true # describe 'isSoftHide option ->', -> # it 'should set `opacity` of `el` to `_props.opacity`', -> # byte = new Byte radius: 25, isSoftHide: true, opacity: .2 # byte.el.style[ 'opacity' ] = '0' # byte._show() # expect( byte.el.style[ 'opacity' ] ).toBe "#{byte._props.opacity}" # it 'should set `transform` to normal', -> # byte = new Byte radius: 25, isSoftHide: true, opacity: .2 # byte.el.style[ 'opacity' ] = '0' # byte.el.style[ 'transform' ] = 'none' # byte._show() # style = byte.el.style # tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ] # expect( tr ).toBe byte._fillTransform() describe '_createShape method', -> it 'should create shape module based on `_props` shape', -> byte = new Byte shape: 'rect' byte.shapeModule = null byte._createShape() expect(byte.shapeModule instanceof mojs.shapesMap.rect).toBe true it 'should not create if !isWithShape', -> byte = new Byte shape: 'rect', isWithShape: false spyOn byte, '_getShapeSize' byte.shapeModule = null byte._createShape() expect(byte.shapeModule).toBeFalsy() expect(byte._getShapeSize).toHaveBeenCalled() it 'should send `width` and `height` to the `shape` module', -> byte = new Byte shape: 'rect', radius: 50, radiusY: 75, strokeWidth: { 0: 10 } byte.shapeModule = null byte._createShape() expect(byte.shapeModule._props.width).toBe 2*50 + 10 expect(byte.shapeModule._props.height).toBe 2*75 + 10 expect(byte.shapeModule._props.parent).toBe byte.el it 'should save `width` and `height` to the `_props` module', -> byte = new Byte shape: 'rect', radius: 50, radiusY: 75, strokeWidth: { 0: 10 } byte.shapeModule = null byte._createShape() expect(byte._props.shapeWidth).toBe 2*50 + 10 expect(byte._props.shapeHeight).toBe 2*75 + 10 describe '_getMaxRadius method ->', -> it 'should return maximum radius ', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75 spyOn(byte, '_getRadiusSize').and.callThrough() expect(byte._getMaxRadius( 'radiusX' )).toBe 50 expect(byte._getMaxRadius( 'radiusY' )).toBe 75 expect( byte._getRadiusSize ).toHaveBeenCalledWith 'radiusX', 50 describe '_getMaxStroke method ->', -> it 'should get maximum value of the strokeWidth if delta', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: { 20 : 0} expect( byte._getMaxStroke() ).toBe 20 it 'should get maximum value of the strokeWidth if delta', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: { 0 : 20 } expect( byte._getMaxStroke() ).toBe 20 it 'should get maximum value of the strokeWidth if static value', -> byte = new Byte shape: 'rect', radius: {50: 0}, radiusY: 75, strokeWidth: 10 expect( byte._getMaxStroke() ).toBe 10 describe '_getShapeSize method', -> it 'should call _getMaxStroke method', -> byte = new Byte spyOn byte, '_getMaxStroke' byte._getShapeSize() expect( byte._getMaxStroke ).toHaveBeenCalled() it 'should call _getMaxRadius method', -> byte = new Byte spyOn byte, '_getMaxRadius' byte._getShapeSize() expect( byte._getMaxRadius ).toHaveBeenCalledWith 'radiusX' it 'should call _getMaxRadius method', -> byte = new Byte spyOn byte, '_getMaxRadius' byte._getShapeSize() expect( byte._getMaxRadius ).toHaveBeenCalledWith 'radiusY' it 'should save size to the _props', -> byte = new Byte byte._props.shapeWidth = 0 byte._props.shapeHeight = 0 byte._getShapeSize() p = byte._props stroke = byte._getMaxStroke() expect( p.shapeWidth ).toBe 2*byte._getMaxRadius( 'radiusX' ) + stroke expect( p.shapeHeight ).toBe 2*byte._getMaxRadius( 'radiusY' ) + stroke describe '_getMaxSizeInChain method ->', -> it 'should call _getShapeSize on every module', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) ms = shape._modules spyOn ms[0], '_getShapeSize' spyOn ms[1], '_getShapeSize' spyOn ms[2], '_getShapeSize' shape._getMaxSizeInChain() expect( ms[0]._getShapeSize ).toHaveBeenCalled() expect( ms[1]._getShapeSize ).toHaveBeenCalled() expect( ms[2]._getShapeSize ).toHaveBeenCalled() it 'should set the largest size to shapeModule', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) largest = shape._modules[2] shapeModule = shape.shapeModule spyOn shapeModule, '_setSize' shape._getMaxSizeInChain() expect( shapeModule._setSize ) .toHaveBeenCalledWith largest._props.shapeWidth, largest._props.shapeHeight it 'should call _setElSizeStyles method', -> shape = new Shape().then( radius: 0 ).then( radius: 100 ) largest = shape._modules[2] spyOn shape, '_setElSizeStyles' shape._getMaxSizeInChain() expect( shape._setElSizeStyles ) .toHaveBeenCalledWith largest._props.shapeWidth, largest._props.shapeHeight describe '_setElSizeStyles method ->', -> it 'should set `width`, `height` and `margins` to the `el` styles', -> shape = new Shape() style = shape.el.style style[ 'width' ] = '0px' style[ 'height' ] = '0px' style[ 'margin-left' ] = '0px' style[ 'margin-right' ] = '0px' shape._setElSizeStyles( 100, 200 ) expect( style[ 'width' ] ).toBe '100px' expect( style[ 'height' ] ).toBe '200px' expect( style[ 'margin-left' ] ).toBe '-50px' expect( style[ 'margin-top' ] ).toBe '-100px' describe 'then method ->', -> it 'should call super', -> obj = {} shape = new Shape() spyOn Thenable::, 'then' shape.then( obj ) expect( Thenable::then ).toHaveBeenCalledWith obj it 'should return this', -> shape = new Shape() result = shape.then( {} ) expect( result ).toBe shape it 'should call _getMaxSizeInChain method', -> shape = new Shape() spyOn shape, '_getMaxSizeInChain' shape.then({}) expect( shape._getMaxSizeInChain ).toHaveBeenCalled() describe 'tune method ->', -> it 'should call super', -> obj = {} shape = new Shape() spyOn Tunable::, 'tune' shape.tune( obj ) expect( Tunable::tune ).toHaveBeenCalledWith obj it 'should return this', -> shape = new Shape() result = shape.tune( {} ) expect( result ).toBe shape it 'should call _getMaxSizeInChain method', -> shape = new Shape() spyOn shape, '_getMaxSizeInChain' shape.tune({}) expect( shape._getMaxSizeInChain ).toHaveBeenCalled() describe '_refreshBefore method ->', -> it 'should call `_show` method is `isShowStart`', -> shape = new Shape isShowStart: true spyOn shape, '_show' shape._refreshBefore() expect( shape._show ).toHaveBeenCalled() it 'should call `_hide` method is not `isShowStart`', -> shape = new Shape spyOn shape, '_hide' shape._refreshBefore() expect( shape._hide ).toHaveBeenCalled() it 'should call `_setProgress` with `0, 0`', -> shape = new Shape spyOn shape, '_setProgress' shape._refreshBefore() expect( shape._setProgress ).toHaveBeenCalledWith 0, 0 it 'should call `_setProgress` with tweens eased progress', -> shape = new Shape easing: (k)-> return 1 spyOn shape, '_setProgress' shape._refreshBefore() expect( shape._setProgress ).toHaveBeenCalledWith 1, 0 describe '_showByTransform method ->', -> it 'should call _drawEl method', -> shape = new Shape easing: (k)-> return 1 spyOn shape, '_drawEl' shape._showByTransform() expect( shape._drawEl ).toHaveBeenCalled() it 'should update scale', -> shape = new Shape easing: (k)-> return 1 shape.el.style.transform = 'scale(0)' shape.el.style["#{mojs.h.prefix.css}transform"] = 'scale(0)' shape._showByTransform() s = shape.el.style tr = s.transform or s["#{mojs.h.prefix.css}transform"] isTr = tr is 'translate(0, 0) rotate(0deg) scale(1, 1)' isTr2 = tr is 'translate(0px, 0px) rotate(0deg) scale(1, 1)' isTr3 = tr is 'translate(0px, 0px) rotate(0deg) scale(1)' isTr4 = tr is 'translate(0px) rotate(0deg) scale(1)' expect(isTr or isTr2 or isTr3 or isTr4).toBe true
[ { "context": "tor:true} ];\n \n rows:() -> [\n {id:1, name:\"Oli Bob\", progress:12, gender:\"male\", rating:1, col:\"red\"", "end": 724, "score": 0.9998405575752258, "start": 717, "tag": "NAME", "value": "Oli Bob" }, { "context": "\"red\", dob:\"19/02/1984\", car:1},\n {id...
src/data/table/Demo.coffee
axiom6/aug
0
class Demo constructor:() -> cols:() -> [ {title:"Name", field:"name", editor:"input"}, {title:"Progress", field:"progress", hozAlign:"left", formatter:"progress", editor:true}, {title:"Gender", field:"gender", width:95, editor:"select", editorParams:{values:["male", "female"]}}, {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100, editor:true}, {title:"Color", field:"col", width:130, editor:"input"}, {title:"Birth", field:"dob", width:130, sorter:"date", hozAlign:"center"}, {title:"Driver", field:"car", width:90, hozAlign:"center", formatter:"tickCross", sorter:"boolean", editor:true} ]; rows:() -> [ {id:1, name:"Oli Bob", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1}, {id:2, name:"Mary May", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true}, {id:3, name:"Christine Lobowski", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"}, {id:4, name:"Brendon Philips", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"}, {id:5, name:"Margret Marmajuke", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"}, {id:6, name:"Frank Harbours", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1} ]; opts:() -> { columns: @cols(), # Column specs data: @rows(), # load row data from array height:'98%', # Height inside comp pane layout:"fitDataTable", # fit columns to width of table fitColumns fitDataFill fitDataTable responsiveLayout:"hide", # hide columns that dont fit on the table tooltips:true, # show tool tips on cells addRowPos:"top", # when adding a new row, add it to the top of the table history:true, # allow undo and redo actions on the table pagination:"local", # paginate the data paginationSize:7, # allow 7 rows per page of data movableColumns:true, # allow column order to be changed resizableRows:true, # allow row order to be changed initialSort:[{column:"name", dir:"asc"}] } export default Demo
32279
class Demo constructor:() -> cols:() -> [ {title:"Name", field:"name", editor:"input"}, {title:"Progress", field:"progress", hozAlign:"left", formatter:"progress", editor:true}, {title:"Gender", field:"gender", width:95, editor:"select", editorParams:{values:["male", "female"]}}, {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100, editor:true}, {title:"Color", field:"col", width:130, editor:"input"}, {title:"Birth", field:"dob", width:130, sorter:"date", hozAlign:"center"}, {title:"Driver", field:"car", width:90, hozAlign:"center", formatter:"tickCross", sorter:"boolean", editor:true} ]; rows:() -> [ {id:1, name:"<NAME>", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1}, {id:2, name:"<NAME>", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true}, {id:3, name:"<NAME>", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"}, {id:4, name:"<NAME>", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"}, {id:5, name:"<NAME>", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"}, {id:6, name:"<NAME>", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1} ]; opts:() -> { columns: @cols(), # Column specs data: @rows(), # load row data from array height:'98%', # Height inside comp pane layout:"fitDataTable", # fit columns to width of table fitColumns fitDataFill fitDataTable responsiveLayout:"hide", # hide columns that dont fit on the table tooltips:true, # show tool tips on cells addRowPos:"top", # when adding a new row, add it to the top of the table history:true, # allow undo and redo actions on the table pagination:"local", # paginate the data paginationSize:7, # allow 7 rows per page of data movableColumns:true, # allow column order to be changed resizableRows:true, # allow row order to be changed initialSort:[{column:"name", dir:"asc"}] } export default Demo
true
class Demo constructor:() -> cols:() -> [ {title:"Name", field:"name", editor:"input"}, {title:"Progress", field:"progress", hozAlign:"left", formatter:"progress", editor:true}, {title:"Gender", field:"gender", width:95, editor:"select", editorParams:{values:["male", "female"]}}, {title:"Rating", field:"rating", formatter:"star", hozAlign:"center", width:100, editor:true}, {title:"Color", field:"col", width:130, editor:"input"}, {title:"Birth", field:"dob", width:130, sorter:"date", hozAlign:"center"}, {title:"Driver", field:"car", width:90, hozAlign:"center", formatter:"tickCross", sorter:"boolean", editor:true} ]; rows:() -> [ {id:1, name:"PI:NAME:<NAME>END_PI", progress:12, gender:"male", rating:1, col:"red", dob:"19/02/1984", car:1}, {id:2, name:"PI:NAME:<NAME>END_PI", progress:1, gender:"female", rating:2, col:"blue", dob:"14/05/1982", car:true}, {id:3, name:"PI:NAME:<NAME>END_PI", progress:42, gender:"female", rating:0, col:"green", dob:"22/05/1982", car:"true"}, {id:4, name:"PI:NAME:<NAME>END_PI", progress:100, gender:"male", rating:1, col:"orange", dob:"01/08/1980"}, {id:5, name:"PI:NAME:<NAME>END_PI", progress:16, gender:"female", rating:5, col:"yellow", dob:"31/01/1999"}, {id:6, name:"PI:NAME:<NAME>END_PI", progress:38, gender:"male", rating:4, col:"red", dob:"12/05/1966", car:1} ]; opts:() -> { columns: @cols(), # Column specs data: @rows(), # load row data from array height:'98%', # Height inside comp pane layout:"fitDataTable", # fit columns to width of table fitColumns fitDataFill fitDataTable responsiveLayout:"hide", # hide columns that dont fit on the table tooltips:true, # show tool tips on cells addRowPos:"top", # when adding a new row, add it to the top of the table history:true, # allow undo and redo actions on the table pagination:"local", # paginate the data paginationSize:7, # allow 7 rows per page of data movableColumns:true, # allow column order to be changed resizableRows:true, # allow row order to be changed initialSort:[{column:"name", dir:"asc"}] } export default Demo
[ { "context": "###\n *\n * jQuery TruncateLines by Gary Hepting\n * https://github.com/ghepting/jquery-truncate-l", "end": 47, "score": 0.9998990893363953, "start": 35, "tag": "NAME", "value": "Gary Hepting" }, { "context": "ncateLines by Gary Hepting\n * https://github.com/gheptin...
src/coffee/plugins/jquery-truncateLines.coffee
cesperanc/groundwork
0
### * * jQuery TruncateLines by Gary Hepting * https://github.com/ghepting/jquery-truncate-lines * * Open source under the MIT License. * * Copyright © 2013 Gary Hepting. All rights reserved. * ### (($) -> delayedAdjustTruncation = [] truncateIndex = 0 class TruncateLines constructor: (el) -> @el = el @index = truncateIndex++ @text = $(@el).text() $(@el).attr('data-text',@text) @words = @text.trim().split(" ") @lines = parseInt($(@el).attr('data-truncate')) @truncate() @adjustOnResize() truncate: -> @measure() @setContent() reset: -> $(@el).text(@text) .css('max-height', 'none') .attr('data-truncated', 'false') measure: -> @reset() $(@el).html(".") @singleLineHeight = $(@el).outerHeight() i = 1 while i++ < @lines $(@el).append("<br>.") @maxLinesHeight = $(@el).outerHeight() empty: -> $(@el).html("") setContent: -> @reset() truncated = false @addWords(@words.length) if @tooBig() # binary build-up the string -- Thanks @BananaNeil :] @addNumberWordsThatFit() $(@el).css('max-height', @maxLinesHeight + 'px') $(@el).attr('data-truncated', true) addNumberWordsThatFit: -> cant = @words.length can = 0 mid = Math.floor(@words.length/2) while can+1 != cant @addWords(can + mid) if @tooBig() cant = can + mid else can = can + mid mid = Math.floor(mid/2) || 1 @addWords(can) $(@el).html( @trimTrailingPunctuation( $(@el).html() ) ) addWords: (num) -> $(@el).html(@words.slice(0,num).join(" ")) tooBig: -> $(@el).outerHeight() > @maxLinesHeight adjustOnResize: -> $(window).on 'resize', => clearTimeout(delayedAdjustTruncation[@index]) delayedAdjustTruncation[@index] = setTimeout(=> @truncate() , 20) trimTrailingPunctuation: (str) -> str.replace(/(,$)|(\.$)|(\:$)|(\;$)|(\?$)|(\!$)/g, "") (($) -> truncateInitialized = false truncatedLineElements = [] $.fn.truncateLines = -> unless truncateInitialized $('head').append(' <style type="text/css"> [data-truncated="true"] { overflow: hidden; } [data-truncated="true"]:after { content: "..."; position: absolute; } </style>') @each -> truncatedLineElements.push( new TruncateLines(@) ) ) $ (($) -> $(window).load -> $("[data-truncate]").truncateLines() )($) ) jQuery.noConflict()
125512
### * * jQuery TruncateLines by <NAME> * https://github.com/ghepting/jquery-truncate-lines * * Open source under the MIT License. * * Copyright © 2013 <NAME>. All rights reserved. * ### (($) -> delayedAdjustTruncation = [] truncateIndex = 0 class TruncateLines constructor: (el) -> @el = el @index = truncateIndex++ @text = $(@el).text() $(@el).attr('data-text',@text) @words = @text.trim().split(" ") @lines = parseInt($(@el).attr('data-truncate')) @truncate() @adjustOnResize() truncate: -> @measure() @setContent() reset: -> $(@el).text(@text) .css('max-height', 'none') .attr('data-truncated', 'false') measure: -> @reset() $(@el).html(".") @singleLineHeight = $(@el).outerHeight() i = 1 while i++ < @lines $(@el).append("<br>.") @maxLinesHeight = $(@el).outerHeight() empty: -> $(@el).html("") setContent: -> @reset() truncated = false @addWords(@words.length) if @tooBig() # binary build-up the string -- Thanks @BananaNeil :] @addNumberWordsThatFit() $(@el).css('max-height', @maxLinesHeight + 'px') $(@el).attr('data-truncated', true) addNumberWordsThatFit: -> cant = @words.length can = 0 mid = Math.floor(@words.length/2) while can+1 != cant @addWords(can + mid) if @tooBig() cant = can + mid else can = can + mid mid = Math.floor(mid/2) || 1 @addWords(can) $(@el).html( @trimTrailingPunctuation( $(@el).html() ) ) addWords: (num) -> $(@el).html(@words.slice(0,num).join(" ")) tooBig: -> $(@el).outerHeight() > @maxLinesHeight adjustOnResize: -> $(window).on 'resize', => clearTimeout(delayedAdjustTruncation[@index]) delayedAdjustTruncation[@index] = setTimeout(=> @truncate() , 20) trimTrailingPunctuation: (str) -> str.replace(/(,$)|(\.$)|(\:$)|(\;$)|(\?$)|(\!$)/g, "") (($) -> truncateInitialized = false truncatedLineElements = [] $.fn.truncateLines = -> unless truncateInitialized $('head').append(' <style type="text/css"> [data-truncated="true"] { overflow: hidden; } [data-truncated="true"]:after { content: "..."; position: absolute; } </style>') @each -> truncatedLineElements.push( new TruncateLines(@) ) ) $ (($) -> $(window).load -> $("[data-truncate]").truncateLines() )($) ) jQuery.noConflict()
true
### * * jQuery TruncateLines by PI:NAME:<NAME>END_PI * https://github.com/ghepting/jquery-truncate-lines * * Open source under the MIT License. * * Copyright © 2013 PI:NAME:<NAME>END_PI. All rights reserved. * ### (($) -> delayedAdjustTruncation = [] truncateIndex = 0 class TruncateLines constructor: (el) -> @el = el @index = truncateIndex++ @text = $(@el).text() $(@el).attr('data-text',@text) @words = @text.trim().split(" ") @lines = parseInt($(@el).attr('data-truncate')) @truncate() @adjustOnResize() truncate: -> @measure() @setContent() reset: -> $(@el).text(@text) .css('max-height', 'none') .attr('data-truncated', 'false') measure: -> @reset() $(@el).html(".") @singleLineHeight = $(@el).outerHeight() i = 1 while i++ < @lines $(@el).append("<br>.") @maxLinesHeight = $(@el).outerHeight() empty: -> $(@el).html("") setContent: -> @reset() truncated = false @addWords(@words.length) if @tooBig() # binary build-up the string -- Thanks @BananaNeil :] @addNumberWordsThatFit() $(@el).css('max-height', @maxLinesHeight + 'px') $(@el).attr('data-truncated', true) addNumberWordsThatFit: -> cant = @words.length can = 0 mid = Math.floor(@words.length/2) while can+1 != cant @addWords(can + mid) if @tooBig() cant = can + mid else can = can + mid mid = Math.floor(mid/2) || 1 @addWords(can) $(@el).html( @trimTrailingPunctuation( $(@el).html() ) ) addWords: (num) -> $(@el).html(@words.slice(0,num).join(" ")) tooBig: -> $(@el).outerHeight() > @maxLinesHeight adjustOnResize: -> $(window).on 'resize', => clearTimeout(delayedAdjustTruncation[@index]) delayedAdjustTruncation[@index] = setTimeout(=> @truncate() , 20) trimTrailingPunctuation: (str) -> str.replace(/(,$)|(\.$)|(\:$)|(\;$)|(\?$)|(\!$)/g, "") (($) -> truncateInitialized = false truncatedLineElements = [] $.fn.truncateLines = -> unless truncateInitialized $('head').append(' <style type="text/css"> [data-truncated="true"] { overflow: hidden; } [data-truncated="true"]:after { content: "..."; position: absolute; } </style>') @each -> truncatedLineElements.push( new TruncateLines(@) ) ) $ (($) -> $(window).load -> $("[data-truncate]").truncateLines() )($) ) jQuery.noConflict()
[ { "context": "#\n# Author: Peter K. Lee (peter@corenova.com)\n#\n# All rights reserved. Thi", "end": 24, "score": 0.9998723268508911, "start": 12, "tag": "NAME", "value": "Peter K. Lee" }, { "context": "#\n# Author: Peter K. Lee (peter@corenova.com)\n#\n# All rights reserved. This pr...
spec/promise-module.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 # module.exports = '/opnfv-promise/promise/capacity/total': (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'pools') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev '/opnfv-promise/promise/capacity/reserved', (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'reservations') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev # rebind to be a computed property '/opnfv-promise/promise/capacity/usage': (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'allocations') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev # rebind to be a computed property '/opnfv-promise/promise/capacity/available': (prev) -> @computed (-> total = @get 'total' reserved = @get 'reserved' usage = @get 'usage' for k, v of total when v? total[k] -= reserved[k] if reserved[k]? total[k] -= usage[k] if usage[k]? total ), type: prev '/opnfv-promise/create-reservation': (input, output, done) -> # 1. create the reservation record (empty) reservation = @create 'ResourceReservation' reservations = @access 'promise.reservations' # 2. update the record with requested input reservation.invoke 'update', input.get() .then (res) -> # 3. save the record and add to list res.save() .then -> reservations.push res output.set result: 'ok', message: 'reservation request accepted' output.set 'reservation-id', res.id done() .catch (err) -> output.set result: 'error', message: err done() .catch (err) -> output.set result: 'conflict', message: err done()
116450
# # 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 # module.exports = '/opnfv-promise/promise/capacity/total': (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'pools') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev '/opnfv-promise/promise/capacity/reserved', (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'reservations') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev # rebind to be a computed property '/opnfv-promise/promise/capacity/usage': (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'allocations') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev # rebind to be a computed property '/opnfv-promise/promise/capacity/available': (prev) -> @computed (-> total = @get 'total' reserved = @get 'reserved' usage = @get 'usage' for k, v of total when v? total[k] -= reserved[k] if reserved[k]? total[k] -= usage[k] if usage[k]? total ), type: prev '/opnfv-promise/create-reservation': (input, output, done) -> # 1. create the reservation record (empty) reservation = @create 'ResourceReservation' reservations = @access 'promise.reservations' # 2. update the record with requested input reservation.invoke 'update', input.get() .then (res) -> # 3. save the record and add to list res.save() .then -> reservations.push res output.set result: 'ok', message: 'reservation request accepted' output.set 'reservation-id', res.id done() .catch (err) -> output.set result: 'error', message: err done() .catch (err) -> output.set result: 'conflict', message: err done()
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 # module.exports = '/opnfv-promise/promise/capacity/total': (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'pools') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev '/opnfv-promise/promise/capacity/reserved', (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'reservations') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev # rebind to be a computed property '/opnfv-promise/promise/capacity/usage': (prev) -> @computed (-> combine = (a, b) -> for k, v of b.capacity when v? a[k] ?= 0 a[k] += v return a (@parent.get 'allocations') .filter (entry) -> entry.active is true .reduce combine, {} ), type: prev # rebind to be a computed property '/opnfv-promise/promise/capacity/available': (prev) -> @computed (-> total = @get 'total' reserved = @get 'reserved' usage = @get 'usage' for k, v of total when v? total[k] -= reserved[k] if reserved[k]? total[k] -= usage[k] if usage[k]? total ), type: prev '/opnfv-promise/create-reservation': (input, output, done) -> # 1. create the reservation record (empty) reservation = @create 'ResourceReservation' reservations = @access 'promise.reservations' # 2. update the record with requested input reservation.invoke 'update', input.get() .then (res) -> # 3. save the record and add to list res.save() .then -> reservations.push res output.set result: 'ok', message: 'reservation request accepted' output.set 'reservation-id', res.id done() .catch (err) -> output.set result: 'error', message: err done() .catch (err) -> output.set result: 'conflict', message: err done()
[ { "context": "\n\n\t\t@token = ''\n\t\tfor i in [0...32]\n\t\t\t@token += 'X1NFBWiez6YmcjIEtr89wRfgs7vq0u3AhZKOPdMTnLaVGJlby4HQU25CkSDopx'[_.random(61)]\n\n\t\t@announce @token, =>\n\t\t\t@peer.o", "end": 1222, "score": 0.9990503191947937, "start": 1160, "tag": "KEY", "value": "X1NFBWiez6Ymc...
assets/js/brdgd.coffee
hjr265/brdgd
1
utils = ellipsis: (text, length) -> if text.length <= length return text pre = text.slice 0, Math.floor(length / 2) suf = text.slice -Math.floor(length / 2) return pre + '...' + suf escape: (text) -> $('<div></div>').text(text).text() class Brdgd constructor: (config) -> @config = config @peer = null announce: (id, done) -> if typeof done is 'undefined' done = id id = null if @peer @peer.destroy() @peer = null _announce = (ices) => @peer = new Peer id, host: @config.PEERJS_HOST port: @config.PEERJS_PORT path: @config.PEERJS_PATH key: @config.PEERJS_KEY config: iceServers: ices debug: @config.PEERJS_LOG @peer.on 'open', -> done() ices = [] ices.push url: "stun:#{@config.STUN_HOST}:#{@config.STUN_PORT}" if @config.TURN_HOST $.get '/api/v1/turn/credential', (credential) => ices.push url: "turn:#{credential.username}@#{@config.TURN_HOST}:#{@config.TURN_PORT}" credential: credential.password _announce ices else _announce ices expose: (file) -> @reset() @file = file @token = '' for i in [0...32] @token += 'X1NFBWiez6YmcjIEtr89wRfgs7vq0u3AhZKOPdMTnLaVGJlby4HQU25CkSDopx'[_.random(61)] @announce @token, => @peer.on 'connection', (conn) => conn.on 'open', => conn.send 'meta' conn.send name: @file.name size: @file.size type: @file.type conn.on 'close', (data) => conn.on 'data', (data) => switch data when 'body' conn.send 'body' $progress = $('<div class="progress active"><div class="progress-bar" style="width: 0"></div></div>').css('width', $('#buttons').width()) $('#container').append $progress sent = 0 more = => if sent is @file.size _.delay -> $progress.fadeOut -> $(@).detach() , 500 return part = @file.slice sent, sent + 1048576 conn.send part sent += part.size $('.progress-bar', $progress).css 'width', Math.floor(sent * 100 / @file.size) + '%' _.delay more, 100 more() $('#buttons').empty().append $('<button class="btn disabled"></button>').html utils.escape(utils.ellipsis(@file.name, 16)) + ' (' + numeral(@file.size).format('0 b') + ')' $('#buttons').append $('<button class="btn btn-danger animated flipInY"></button>').html('<i class="fa fa-times"></i> ').on 'click', => @reset() history.pushState null, null, '/' $('#address').tooltip placement: 'bottom' title: 'Share this URL' trigger: 'manual' $('#address').tooltip 'show' grope: (token) -> if token is @token return @reset() @token = token @announce => mode = '' meta = null have = 0 parts = [] blob = null conn = @peer.connect @token, reliable: true conn.on 'data', (data) => switch mode when '' mode = data when 'meta' meta = data mode = '' $('#buttons .btn:first').html utils.escape(utils.ellipsis(meta.name, 16)) + ' (' + numeral(meta.size).format('0 b') + ')' $('#buttons').append $('<button class="btn btn-primary animated flipInY"></button>').html('<i class="fa fa-download"></i> ').on 'click', => if mode return if !meta return if have is meta.size $('#download').trigger 'click' else conn.send 'body' $('#buttons .btn:nth-child(2)').html '<i class="fa fa-spinner fa-spin"></i>' $('#container').append $('<div class="progress active animated fadeIn"><div class="progress-bar" style="width: 0"></div></div>').css('width', $('#buttons').width()) break when 'body' parts.push data have += data.byteLength $('.progress .progress-bar').css 'width', Math.floor(have * 100 / meta.size) + '%' if have is meta.size mode = 'done' blob = new Blob parts, type: meta.type _.delay -> $('.progress').fadeOut -> $(@).detach() $('#buttons .btn:nth-child(2)').detach() $('#buttons').addClass('animated pulse').append $('<a class="btn btn-primary"><i class="fa fa-save"></i></a>').attr href: URL.createObjectURL blob download: meta.name , 500 break $('#buttons').empty().append $('<button class="btn disabled"></button>').text('Retrieving metadata..') reset: -> if @peer @peer.destroy() @peer = null @token = '' @file = null $('#buttons').empty().append $('<button class="btn btn-primary" title="" data-="" data-=""></button>').text('Choose file..').on 'click', => $input = $('<input type="file">').on 'change', (event) => @expose(event.target.files[0]) history.pushState null, null, "/#{@token}" $input.trigger 'click' $('#address').tooltip 'destroy' $('.progress').detach() brdgd = new Brdgd $('script[data-config]').data('config') $(window).on 'popstate', -> token = location.pathname.replace /^\/(.+)$/, '$1' if token.match /^[a-zA-Z0-9]{32}$/ brdgd.grope token else switch token when 'about' else brdgd.reset() $(window).trigger 'popstate' $('a[href="/"]').on 'click', (event) -> event.preventDefault() brdgd.reset() history.pushState null, null, '/' $('body').on 'webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', '*', -> $(@).removeClass 'animated flipInY flipInY fadeIn pulse bounceInDown flipInX' $('h1').addClass 'animated bounceInDown' $('#buttons').addClass 'animated flipInX'
201363
utils = ellipsis: (text, length) -> if text.length <= length return text pre = text.slice 0, Math.floor(length / 2) suf = text.slice -Math.floor(length / 2) return pre + '...' + suf escape: (text) -> $('<div></div>').text(text).text() class Brdgd constructor: (config) -> @config = config @peer = null announce: (id, done) -> if typeof done is 'undefined' done = id id = null if @peer @peer.destroy() @peer = null _announce = (ices) => @peer = new Peer id, host: @config.PEERJS_HOST port: @config.PEERJS_PORT path: @config.PEERJS_PATH key: @config.PEERJS_KEY config: iceServers: ices debug: @config.PEERJS_LOG @peer.on 'open', -> done() ices = [] ices.push url: "stun:#{@config.STUN_HOST}:#{@config.STUN_PORT}" if @config.TURN_HOST $.get '/api/v1/turn/credential', (credential) => ices.push url: "turn:#{credential.username}@#{@config.TURN_HOST}:#{@config.TURN_PORT}" credential: credential.password _announce ices else _announce ices expose: (file) -> @reset() @file = file @token = '' for i in [0...32] @token += '<KEY>'[_.random(61)] @announce @token, => @peer.on 'connection', (conn) => conn.on 'open', => conn.send 'meta' conn.send name: @file.name size: @file.size type: @file.type conn.on 'close', (data) => conn.on 'data', (data) => switch data when 'body' conn.send 'body' $progress = $('<div class="progress active"><div class="progress-bar" style="width: 0"></div></div>').css('width', $('#buttons').width()) $('#container').append $progress sent = 0 more = => if sent is @file.size _.delay -> $progress.fadeOut -> $(@).detach() , 500 return part = @file.slice sent, sent + 1048576 conn.send part sent += part.size $('.progress-bar', $progress).css 'width', Math.floor(sent * 100 / @file.size) + '%' _.delay more, 100 more() $('#buttons').empty().append $('<button class="btn disabled"></button>').html utils.escape(utils.ellipsis(@file.name, 16)) + ' (' + numeral(@file.size).format('0 b') + ')' $('#buttons').append $('<button class="btn btn-danger animated flipInY"></button>').html('<i class="fa fa-times"></i> ').on 'click', => @reset() history.pushState null, null, '/' $('#address').tooltip placement: 'bottom' title: 'Share this URL' trigger: 'manual' $('#address').tooltip 'show' grope: (token) -> if token is @token return @reset() @token = token @announce => mode = '' meta = null have = 0 parts = [] blob = null conn = @peer.connect @token, reliable: true conn.on 'data', (data) => switch mode when '' mode = data when 'meta' meta = data mode = '' $('#buttons .btn:first').html utils.escape(utils.ellipsis(meta.name, 16)) + ' (' + numeral(meta.size).format('0 b') + ')' $('#buttons').append $('<button class="btn btn-primary animated flipInY"></button>').html('<i class="fa fa-download"></i> ').on 'click', => if mode return if !meta return if have is meta.size $('#download').trigger 'click' else conn.send 'body' $('#buttons .btn:nth-child(2)').html '<i class="fa fa-spinner fa-spin"></i>' $('#container').append $('<div class="progress active animated fadeIn"><div class="progress-bar" style="width: 0"></div></div>').css('width', $('#buttons').width()) break when 'body' parts.push data have += data.byteLength $('.progress .progress-bar').css 'width', Math.floor(have * 100 / meta.size) + '%' if have is meta.size mode = 'done' blob = new Blob parts, type: meta.type _.delay -> $('.progress').fadeOut -> $(@).detach() $('#buttons .btn:nth-child(2)').detach() $('#buttons').addClass('animated pulse').append $('<a class="btn btn-primary"><i class="fa fa-save"></i></a>').attr href: URL.createObjectURL blob download: meta.name , 500 break $('#buttons').empty().append $('<button class="btn disabled"></button>').text('Retrieving metadata..') reset: -> if @peer @peer.destroy() @peer = null @token = '' @file = null $('#buttons').empty().append $('<button class="btn btn-primary" title="" data-="" data-=""></button>').text('Choose file..').on 'click', => $input = $('<input type="file">').on 'change', (event) => @expose(event.target.files[0]) history.pushState null, null, "/#{@token}" $input.trigger 'click' $('#address').tooltip 'destroy' $('.progress').detach() brdgd = new Brdgd $('script[data-config]').data('config') $(window).on 'popstate', -> token = location.pathname.replace /^\/(.+)$/, '$1' if token.match /^[a-zA-Z0-9]{32}$/ brdgd.grope token else switch token when 'about' else brdgd.reset() $(window).trigger 'popstate' $('a[href="/"]').on 'click', (event) -> event.preventDefault() brdgd.reset() history.pushState null, null, '/' $('body').on 'webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', '*', -> $(@).removeClass 'animated flipInY flipInY fadeIn pulse bounceInDown flipInX' $('h1').addClass 'animated bounceInDown' $('#buttons').addClass 'animated flipInX'
true
utils = ellipsis: (text, length) -> if text.length <= length return text pre = text.slice 0, Math.floor(length / 2) suf = text.slice -Math.floor(length / 2) return pre + '...' + suf escape: (text) -> $('<div></div>').text(text).text() class Brdgd constructor: (config) -> @config = config @peer = null announce: (id, done) -> if typeof done is 'undefined' done = id id = null if @peer @peer.destroy() @peer = null _announce = (ices) => @peer = new Peer id, host: @config.PEERJS_HOST port: @config.PEERJS_PORT path: @config.PEERJS_PATH key: @config.PEERJS_KEY config: iceServers: ices debug: @config.PEERJS_LOG @peer.on 'open', -> done() ices = [] ices.push url: "stun:#{@config.STUN_HOST}:#{@config.STUN_PORT}" if @config.TURN_HOST $.get '/api/v1/turn/credential', (credential) => ices.push url: "turn:#{credential.username}@#{@config.TURN_HOST}:#{@config.TURN_PORT}" credential: credential.password _announce ices else _announce ices expose: (file) -> @reset() @file = file @token = '' for i in [0...32] @token += 'PI:KEY:<KEY>END_PI'[_.random(61)] @announce @token, => @peer.on 'connection', (conn) => conn.on 'open', => conn.send 'meta' conn.send name: @file.name size: @file.size type: @file.type conn.on 'close', (data) => conn.on 'data', (data) => switch data when 'body' conn.send 'body' $progress = $('<div class="progress active"><div class="progress-bar" style="width: 0"></div></div>').css('width', $('#buttons').width()) $('#container').append $progress sent = 0 more = => if sent is @file.size _.delay -> $progress.fadeOut -> $(@).detach() , 500 return part = @file.slice sent, sent + 1048576 conn.send part sent += part.size $('.progress-bar', $progress).css 'width', Math.floor(sent * 100 / @file.size) + '%' _.delay more, 100 more() $('#buttons').empty().append $('<button class="btn disabled"></button>').html utils.escape(utils.ellipsis(@file.name, 16)) + ' (' + numeral(@file.size).format('0 b') + ')' $('#buttons').append $('<button class="btn btn-danger animated flipInY"></button>').html('<i class="fa fa-times"></i> ').on 'click', => @reset() history.pushState null, null, '/' $('#address').tooltip placement: 'bottom' title: 'Share this URL' trigger: 'manual' $('#address').tooltip 'show' grope: (token) -> if token is @token return @reset() @token = token @announce => mode = '' meta = null have = 0 parts = [] blob = null conn = @peer.connect @token, reliable: true conn.on 'data', (data) => switch mode when '' mode = data when 'meta' meta = data mode = '' $('#buttons .btn:first').html utils.escape(utils.ellipsis(meta.name, 16)) + ' (' + numeral(meta.size).format('0 b') + ')' $('#buttons').append $('<button class="btn btn-primary animated flipInY"></button>').html('<i class="fa fa-download"></i> ').on 'click', => if mode return if !meta return if have is meta.size $('#download').trigger 'click' else conn.send 'body' $('#buttons .btn:nth-child(2)').html '<i class="fa fa-spinner fa-spin"></i>' $('#container').append $('<div class="progress active animated fadeIn"><div class="progress-bar" style="width: 0"></div></div>').css('width', $('#buttons').width()) break when 'body' parts.push data have += data.byteLength $('.progress .progress-bar').css 'width', Math.floor(have * 100 / meta.size) + '%' if have is meta.size mode = 'done' blob = new Blob parts, type: meta.type _.delay -> $('.progress').fadeOut -> $(@).detach() $('#buttons .btn:nth-child(2)').detach() $('#buttons').addClass('animated pulse').append $('<a class="btn btn-primary"><i class="fa fa-save"></i></a>').attr href: URL.createObjectURL blob download: meta.name , 500 break $('#buttons').empty().append $('<button class="btn disabled"></button>').text('Retrieving metadata..') reset: -> if @peer @peer.destroy() @peer = null @token = '' @file = null $('#buttons').empty().append $('<button class="btn btn-primary" title="" data-="" data-=""></button>').text('Choose file..').on 'click', => $input = $('<input type="file">').on 'change', (event) => @expose(event.target.files[0]) history.pushState null, null, "/#{@token}" $input.trigger 'click' $('#address').tooltip 'destroy' $('.progress').detach() brdgd = new Brdgd $('script[data-config]').data('config') $(window).on 'popstate', -> token = location.pathname.replace /^\/(.+)$/, '$1' if token.match /^[a-zA-Z0-9]{32}$/ brdgd.grope token else switch token when 'about' else brdgd.reset() $(window).trigger 'popstate' $('a[href="/"]').on 'click', (event) -> event.preventDefault() brdgd.reset() history.pushState null, null, '/' $('body').on 'webkitAnimationEnd mozAnimationEnd oAnimationEnd animationEnd', '*', -> $(@).removeClass 'animated flipInY flipInY fadeIn pulse bounceInDown flipInX' $('h1').addClass 'animated bounceInDown' $('#buttons').addClass 'animated flipInX'
[ { "context": " plant: 1\n quantity: 12\n plantName: 'Narzisse'\n plantPriceInCents: 200\n }\n {\n i", "end": 751, "score": 0.7191799283027649, "start": 743, "tag": "NAME", "value": "Narzisse" }, { "context": " plant: 2\n quantity: 3\n plantN...
app/models/order-item.coffee
koenig/moosi
0
`import DS from 'ember-data'` `import divideWithHundret from '../utils/divide-with-hundret'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] OrderItem = DS.Model.extend order: belongsTo 'order' plant: belongsTo 'plant' plantName: attr 'string' plantPriceInCents: attr 'number', defaultValue: 0 quantity: attr 'number', defaultValue: 0 done: attr 'boolean', defaultValue: false plantPrice: divideWithHundret 'plantPriceInCents' totalInCents: Em.computed 'plantPriceInCents', 'quantity', -> @get('plantPriceInCents') * @get('quantity') totalPrice: divideWithHundret 'totalInCents' OrderItem.reopenClass FIXTURES: [ { id: 1 order: 1 plant: 1 quantity: 12 plantName: 'Narzisse' plantPriceInCents: 200 } { id: 2 order: 1 plant: 2 quantity: 3 plantName: 'Rose' plantPriceInCents: 320 } { id: 3 order: 2 plant: 1 quantity: 6 plantName: 'Tulpe' plantPriceInCents: 120 } { id: 4 order: 3 plant: 1 quantity: 12 plantName: 'Glücksfeder' plantPriceInCents: 2200 } { id: 5 order: 3 plant: 2 quantity: 3 plantName: 'Elefantenfuss' plantPriceInCents: 1900 } ] `export default OrderItem`
14385
`import DS from 'ember-data'` `import divideWithHundret from '../utils/divide-with-hundret'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] OrderItem = DS.Model.extend order: belongsTo 'order' plant: belongsTo 'plant' plantName: attr 'string' plantPriceInCents: attr 'number', defaultValue: 0 quantity: attr 'number', defaultValue: 0 done: attr 'boolean', defaultValue: false plantPrice: divideWithHundret 'plantPriceInCents' totalInCents: Em.computed 'plantPriceInCents', 'quantity', -> @get('plantPriceInCents') * @get('quantity') totalPrice: divideWithHundret 'totalInCents' OrderItem.reopenClass FIXTURES: [ { id: 1 order: 1 plant: 1 quantity: 12 plantName: '<NAME>' plantPriceInCents: 200 } { id: 2 order: 1 plant: 2 quantity: 3 plantName: '<NAME>' plantPriceInCents: 320 } { id: 3 order: 2 plant: 1 quantity: 6 plantName: '<NAME>' plantPriceInCents: 120 } { id: 4 order: 3 plant: 1 quantity: 12 plantName: '<NAME>ücksfeder' plantPriceInCents: 2200 } { id: 5 order: 3 plant: 2 quantity: 3 plantName: 'Elefantenfuss' plantPriceInCents: 1900 } ] `export default OrderItem`
true
`import DS from 'ember-data'` `import divideWithHundret from '../utils/divide-with-hundret'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] OrderItem = DS.Model.extend order: belongsTo 'order' plant: belongsTo 'plant' plantName: attr 'string' plantPriceInCents: attr 'number', defaultValue: 0 quantity: attr 'number', defaultValue: 0 done: attr 'boolean', defaultValue: false plantPrice: divideWithHundret 'plantPriceInCents' totalInCents: Em.computed 'plantPriceInCents', 'quantity', -> @get('plantPriceInCents') * @get('quantity') totalPrice: divideWithHundret 'totalInCents' OrderItem.reopenClass FIXTURES: [ { id: 1 order: 1 plant: 1 quantity: 12 plantName: 'PI:NAME:<NAME>END_PI' plantPriceInCents: 200 } { id: 2 order: 1 plant: 2 quantity: 3 plantName: 'PI:NAME:<NAME>END_PI' plantPriceInCents: 320 } { id: 3 order: 2 plant: 1 quantity: 6 plantName: 'PI:NAME:<NAME>END_PI' plantPriceInCents: 120 } { id: 4 order: 3 plant: 1 quantity: 12 plantName: 'PI:NAME:<NAME>END_PIücksfeder' plantPriceInCents: 2200 } { id: 5 order: 3 plant: 2 quantity: 3 plantName: 'Elefantenfuss' plantPriceInCents: 1900 } ] `export default OrderItem`
[ { "context": "{\n _id: App.server.createUUID()\n name: \"Unnamed\"\n displayNameBinding: \"name\"\n input: {\n", "end": 604, "score": 0.9737189412117004, "start": 597, "tag": "NAME", "value": "Unnamed" } ]
cmdr_web/src/scripts/views/source_configure.coffee
wesleyan/cmdr-server
2
slinky_require('../core.coffee') slinky_require('configure_list.coffee') slinky_require('bind_view.coffee') App.SourcesConfigureView = App.BindView.extend initialize: () -> App.rooms.bind "change:selection", @render, this @configure_list = new App.ConfigureListView(App.sources) App.sources.bind "change:selection", @change_selection, this @configure_list.bind "add", @add, this @configure_list.bind "remove", @remove, this App.sources.bind "change:update", @render, this @change_selection() add: () -> msg = { _id: App.server.createUUID() name: "Unnamed" displayNameBinding: "name" input: { projector: "HDMI" switcher: 0 video: 0 audio: 0 } belongs_to: App.rooms.selected.get('id') source: true } App.server.create_doc(msg) App.sources.add(msg) @render remove: () -> doc = App.sources.selected.attributes doc.belongs_to = doc.belongs_to.id App.server.remove_doc(doc) App.rooms.selected.attributes.sources.remove(App.sources.selected) App.sources.remove(App.sources.selected) @render set_up_bindings: (room) -> @unbind_all() if @source @field_bind "input[name='name']", @source, ((r) -> r.get('name')), ((r, v) -> r.set(name: v)) @field_bind "select[name='switcher input']", @source, ((r) -> if r.get('input').switcher? r.get('input').switcher else r.get('input').video), ((r, v) => r.set(input: _(r.get('input')).extend(switcher: v))) @field_bind "select[name='projector input']", @source, ((r) -> r.get('input').projector), ((r, v) -> r.set(input: _(r.get('input')).extend(projector: v))) # TODO: Abstract this more update_sources: () -> switcher = ["1".."8"] projector = ["HDMI", "RGB1", "RGB2", "Video", "SVideo"] option = (d) -> "<option value=\"#{d}\">#{d}</option>" sw = switcher.map(option).join("\n") pr = projector.map(option).join("\n") $("select[name='switcher input']", @el).html sw $("select[name='projector input']", @el).html pr change_selection: () -> @source = App.sources.selected @update_sources() @set_up_bindings() render: () -> @model = App.rooms.selected if @model $(@el).html App.templates.source_configure() $(".source-list", @el).html @configure_list.render().el @set_up_bindings(@model) $(".save-button", @el).click((e) => @save(e)) $(".cancel-button", @el).click((e) => @cancel(e)) this save: () -> App.server.save_doc(App.sources.selected) cancel: () ->
118082
slinky_require('../core.coffee') slinky_require('configure_list.coffee') slinky_require('bind_view.coffee') App.SourcesConfigureView = App.BindView.extend initialize: () -> App.rooms.bind "change:selection", @render, this @configure_list = new App.ConfigureListView(App.sources) App.sources.bind "change:selection", @change_selection, this @configure_list.bind "add", @add, this @configure_list.bind "remove", @remove, this App.sources.bind "change:update", @render, this @change_selection() add: () -> msg = { _id: App.server.createUUID() name: "<NAME>" displayNameBinding: "name" input: { projector: "HDMI" switcher: 0 video: 0 audio: 0 } belongs_to: App.rooms.selected.get('id') source: true } App.server.create_doc(msg) App.sources.add(msg) @render remove: () -> doc = App.sources.selected.attributes doc.belongs_to = doc.belongs_to.id App.server.remove_doc(doc) App.rooms.selected.attributes.sources.remove(App.sources.selected) App.sources.remove(App.sources.selected) @render set_up_bindings: (room) -> @unbind_all() if @source @field_bind "input[name='name']", @source, ((r) -> r.get('name')), ((r, v) -> r.set(name: v)) @field_bind "select[name='switcher input']", @source, ((r) -> if r.get('input').switcher? r.get('input').switcher else r.get('input').video), ((r, v) => r.set(input: _(r.get('input')).extend(switcher: v))) @field_bind "select[name='projector input']", @source, ((r) -> r.get('input').projector), ((r, v) -> r.set(input: _(r.get('input')).extend(projector: v))) # TODO: Abstract this more update_sources: () -> switcher = ["1".."8"] projector = ["HDMI", "RGB1", "RGB2", "Video", "SVideo"] option = (d) -> "<option value=\"#{d}\">#{d}</option>" sw = switcher.map(option).join("\n") pr = projector.map(option).join("\n") $("select[name='switcher input']", @el).html sw $("select[name='projector input']", @el).html pr change_selection: () -> @source = App.sources.selected @update_sources() @set_up_bindings() render: () -> @model = App.rooms.selected if @model $(@el).html App.templates.source_configure() $(".source-list", @el).html @configure_list.render().el @set_up_bindings(@model) $(".save-button", @el).click((e) => @save(e)) $(".cancel-button", @el).click((e) => @cancel(e)) this save: () -> App.server.save_doc(App.sources.selected) cancel: () ->
true
slinky_require('../core.coffee') slinky_require('configure_list.coffee') slinky_require('bind_view.coffee') App.SourcesConfigureView = App.BindView.extend initialize: () -> App.rooms.bind "change:selection", @render, this @configure_list = new App.ConfigureListView(App.sources) App.sources.bind "change:selection", @change_selection, this @configure_list.bind "add", @add, this @configure_list.bind "remove", @remove, this App.sources.bind "change:update", @render, this @change_selection() add: () -> msg = { _id: App.server.createUUID() name: "PI:NAME:<NAME>END_PI" displayNameBinding: "name" input: { projector: "HDMI" switcher: 0 video: 0 audio: 0 } belongs_to: App.rooms.selected.get('id') source: true } App.server.create_doc(msg) App.sources.add(msg) @render remove: () -> doc = App.sources.selected.attributes doc.belongs_to = doc.belongs_to.id App.server.remove_doc(doc) App.rooms.selected.attributes.sources.remove(App.sources.selected) App.sources.remove(App.sources.selected) @render set_up_bindings: (room) -> @unbind_all() if @source @field_bind "input[name='name']", @source, ((r) -> r.get('name')), ((r, v) -> r.set(name: v)) @field_bind "select[name='switcher input']", @source, ((r) -> if r.get('input').switcher? r.get('input').switcher else r.get('input').video), ((r, v) => r.set(input: _(r.get('input')).extend(switcher: v))) @field_bind "select[name='projector input']", @source, ((r) -> r.get('input').projector), ((r, v) -> r.set(input: _(r.get('input')).extend(projector: v))) # TODO: Abstract this more update_sources: () -> switcher = ["1".."8"] projector = ["HDMI", "RGB1", "RGB2", "Video", "SVideo"] option = (d) -> "<option value=\"#{d}\">#{d}</option>" sw = switcher.map(option).join("\n") pr = projector.map(option).join("\n") $("select[name='switcher input']", @el).html sw $("select[name='projector input']", @el).html pr change_selection: () -> @source = App.sources.selected @update_sources() @set_up_bindings() render: () -> @model = App.rooms.selected if @model $(@el).html App.templates.source_configure() $(".source-list", @el).html @configure_list.render().el @set_up_bindings(@model) $(".save-button", @el).click((e) => @save(e)) $(".cancel-button", @el).click((e) => @cancel(e)) this save: () -> App.server.save_doc(App.sources.selected) cancel: () ->
[ { "context": "n\n\nclass LockWorker extends BaseWorker\n @_name: 'test_worker'\n _run: (payload, cb) ->\n console.log \"runnin", "end": 1325, "score": 0.9988194108009338, "start": 1314, "tag": "USERNAME", "value": "test_worker" }, { "context": "PasswordWorker extends BaseWorker\...
test/reservation.coffee
Clever/node-redis-reservation
4
_ = require 'underscore' redis = require 'redis' assert = require 'assert' async = require 'async' domain = require 'domain' debug = require('debug') 'test/redis-reservation' ReserveResource = require "#{__dirname}/../lib/index" class BaseWorker constructor: (payload, @cb) -> worker_domain = domain.create() worker_domain.on 'error', (err) -> console.log "FAILED: Exception caught by domain:", err.stack worker_domain.dispose() worker_domain.once 'error', (err) => @_complete err # only call complete once @reservation = new ReserveResource @constructor._name, process.env.REDIS_HOST, process.env.REDIS_PORT, @_hearbeat_interval, @_lock_ttl setImmediate => worker_domain.enter() @_run payload, (args...) => worker_domain.exit() @_complete args... _complete: (args...) -> @reservation.release (err) => console.log "ENDING #{@constructor._name} WORKER with args:", args @cb args... _run: (payload, cb) -> cb new Error "must implement _run" _hearbeat_interval: 10*60*1000 # 10 minutes in milliseconds for resource reservation _lock_ttl: 30*60 # 30 minutes in seconds for resource reservation class LockWorker extends BaseWorker @_name: 'test_worker' _run: (payload, cb) -> console.log "running test_worker" console.log "RESERVE", @reserve @reservation.lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" class PasswordWorker extends BaseWorker @_name: 'redis_password_worker' _run: (payload, cb) -> console.log "running redis_password_worker" console.log "RESERVE", @reserve @reservation.password = payload.password @reservation.lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" class FreeWorker extends BaseWorker @_name: 'free_worker' _run: (payload, cb) -> cb null, "always_done" class FailWorker extends BaseWorker @_name: 'fail_worker' _run: (payload, cb) -> throw new Error(":(") class SlowWorker extends BaseWorker @_name: 'slow_worker' _hearbeat_interval: 500 _lock_ttl: 1 _run: (payload, cb) -> console.log "running slow_worker" @reservation.lock payload.resource_id, (err, state) -> setTimeout((state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" , 2000 , state) class WaitWorker extends BaseWorker @_name: 'wait_worker' _hearbeat_interval: 500 _lock_ttl: 1 _run: (payload, cb) -> console.log "running wait_worker" @reservation.wait_until_lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, 'patience_is_bitter_but_fruit_is_sweet' describe 'ReserveResource', -> it "allows you to create a bunch of reservations", -> # Reasons it might fail: # * memory leaks # * connection limits for i in [0...10000000] resource = new ReserveResource 'some worker', process.env.REDIS_HOST, process.env.REDIS_PORT resource._init_redis() describe 'redis-reservation', -> before (done) -> @redis = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST) #@redis.select 3 done() beforeEach (done) -> @redis.flushall done it 'can reserve and release a lock', (done) -> test_worker = new LockWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'can reserve and release a lock with redis password', (done) -> @redis.config 'set', 'requirepass', '12345' @redis.auth '12345' payload = resource_id: 'test_resource', password: '12345' test_worker = new PasswordWorker payload, (err, resp) => @redis.config 'set', 'requirepass', '' assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'holds a lock while running', (done) -> test_worker = new SlowWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'resource-test_resource', (err, resp) -> assert.equal resp, null done() it 'can wait for a lock', (done) -> setTimeout(=> @redis.del 'reservation-test_resource', -> return , 1000) @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new WaitWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'patience_is_bitter_but_fruit_is_sweet' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'fails silently if resource is already reserved', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new LockWorker resource_id: 'test_resource', (err, resp) => assert.equal err, 'no_reservations' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'does not interfere for workers without reservations', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new FreeWorker resource_id: 'test_resource', (err, resp) => assert.equal resp, 'always_done' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'handles failing jobs', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new FailWorker resource_id: 'test_resource', (err, resp) => assert.equal err.message, ":(" assert.equal null, resp @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'fails on no redis', (done) -> process.env.REDIS_HOST = 'localhost' process.env.REDIS_PORT = 6666 # incorrect port test_worker = new SlowWorker resource_id: 'test_resource', (err, resp) -> console.log "ERR", err assert err.message.match( /Redis connection to .+:6666 failed - connect ECONNREFUSED/ ) setTimeout done, 1000
128872
_ = require 'underscore' redis = require 'redis' assert = require 'assert' async = require 'async' domain = require 'domain' debug = require('debug') 'test/redis-reservation' ReserveResource = require "#{__dirname}/../lib/index" class BaseWorker constructor: (payload, @cb) -> worker_domain = domain.create() worker_domain.on 'error', (err) -> console.log "FAILED: Exception caught by domain:", err.stack worker_domain.dispose() worker_domain.once 'error', (err) => @_complete err # only call complete once @reservation = new ReserveResource @constructor._name, process.env.REDIS_HOST, process.env.REDIS_PORT, @_hearbeat_interval, @_lock_ttl setImmediate => worker_domain.enter() @_run payload, (args...) => worker_domain.exit() @_complete args... _complete: (args...) -> @reservation.release (err) => console.log "ENDING #{@constructor._name} WORKER with args:", args @cb args... _run: (payload, cb) -> cb new Error "must implement _run" _hearbeat_interval: 10*60*1000 # 10 minutes in milliseconds for resource reservation _lock_ttl: 30*60 # 30 minutes in seconds for resource reservation class LockWorker extends BaseWorker @_name: 'test_worker' _run: (payload, cb) -> console.log "running test_worker" console.log "RESERVE", @reserve @reservation.lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" class PasswordWorker extends BaseWorker @_name: 'redis_password_worker' _run: (payload, cb) -> console.log "running redis_password_worker" console.log "RESERVE", @reserve @reservation.password = <PASSWORD>.password @reservation.lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" class FreeWorker extends BaseWorker @_name: 'free_worker' _run: (payload, cb) -> cb null, "always_done" class FailWorker extends BaseWorker @_name: 'fail_worker' _run: (payload, cb) -> throw new Error(":(") class SlowWorker extends BaseWorker @_name: 'slow_worker' _hearbeat_interval: 500 _lock_ttl: 1 _run: (payload, cb) -> console.log "running slow_worker" @reservation.lock payload.resource_id, (err, state) -> setTimeout((state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" , 2000 , state) class WaitWorker extends BaseWorker @_name: 'wait_worker' _hearbeat_interval: 500 _lock_ttl: 1 _run: (payload, cb) -> console.log "running wait_worker" @reservation.wait_until_lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, 'patience_is_bitter_but_fruit_is_sweet' describe 'ReserveResource', -> it "allows you to create a bunch of reservations", -> # Reasons it might fail: # * memory leaks # * connection limits for i in [0...10000000] resource = new ReserveResource 'some worker', process.env.REDIS_HOST, process.env.REDIS_PORT resource._init_redis() describe 'redis-reservation', -> before (done) -> @redis = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST) #@redis.select 3 done() beforeEach (done) -> @redis.flushall done it 'can reserve and release a lock', (done) -> test_worker = new LockWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'can reserve and release a lock with redis password', (done) -> @redis.config 'set', 'requirepass', '<PASSWORD>' @redis.auth '12345' payload = resource_id: 'test_resource', password: '<PASSWORD>' test_worker = new PasswordWorker payload, (err, resp) => @redis.config 'set', 'requirepass', '' assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'holds a lock while running', (done) -> test_worker = new SlowWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'resource-test_resource', (err, resp) -> assert.equal resp, null done() it 'can wait for a lock', (done) -> setTimeout(=> @redis.del 'reservation-test_resource', -> return , 1000) @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new WaitWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'patience_is_bitter_but_fruit_is_sweet' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'fails silently if resource is already reserved', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new LockWorker resource_id: 'test_resource', (err, resp) => assert.equal err, 'no_reservations' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'does not interfere for workers without reservations', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new FreeWorker resource_id: 'test_resource', (err, resp) => assert.equal resp, 'always_done' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'handles failing jobs', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new FailWorker resource_id: 'test_resource', (err, resp) => assert.equal err.message, ":(" assert.equal null, resp @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'fails on no redis', (done) -> process.env.REDIS_HOST = 'localhost' process.env.REDIS_PORT = 6666 # incorrect port test_worker = new SlowWorker resource_id: 'test_resource', (err, resp) -> console.log "ERR", err assert err.message.match( /Redis connection to .+:6666 failed - connect ECONNREFUSED/ ) setTimeout done, 1000
true
_ = require 'underscore' redis = require 'redis' assert = require 'assert' async = require 'async' domain = require 'domain' debug = require('debug') 'test/redis-reservation' ReserveResource = require "#{__dirname}/../lib/index" class BaseWorker constructor: (payload, @cb) -> worker_domain = domain.create() worker_domain.on 'error', (err) -> console.log "FAILED: Exception caught by domain:", err.stack worker_domain.dispose() worker_domain.once 'error', (err) => @_complete err # only call complete once @reservation = new ReserveResource @constructor._name, process.env.REDIS_HOST, process.env.REDIS_PORT, @_hearbeat_interval, @_lock_ttl setImmediate => worker_domain.enter() @_run payload, (args...) => worker_domain.exit() @_complete args... _complete: (args...) -> @reservation.release (err) => console.log "ENDING #{@constructor._name} WORKER with args:", args @cb args... _run: (payload, cb) -> cb new Error "must implement _run" _hearbeat_interval: 10*60*1000 # 10 minutes in milliseconds for resource reservation _lock_ttl: 30*60 # 30 minutes in seconds for resource reservation class LockWorker extends BaseWorker @_name: 'test_worker' _run: (payload, cb) -> console.log "running test_worker" console.log "RESERVE", @reserve @reservation.lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" class PasswordWorker extends BaseWorker @_name: 'redis_password_worker' _run: (payload, cb) -> console.log "running redis_password_worker" console.log "RESERVE", @reserve @reservation.password = PI:PASSWORD:<PASSWORD>END_PI.password @reservation.lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" class FreeWorker extends BaseWorker @_name: 'free_worker' _run: (payload, cb) -> cb null, "always_done" class FailWorker extends BaseWorker @_name: 'fail_worker' _run: (payload, cb) -> throw new Error(":(") class SlowWorker extends BaseWorker @_name: 'slow_worker' _hearbeat_interval: 500 _lock_ttl: 1 _run: (payload, cb) -> console.log "running slow_worker" @reservation.lock payload.resource_id, (err, state) -> setTimeout((state) -> return cb "no_reservations" unless state return cb null, "whostheboss.iam" , 2000 , state) class WaitWorker extends BaseWorker @_name: 'wait_worker' _hearbeat_interval: 500 _lock_ttl: 1 _run: (payload, cb) -> console.log "running wait_worker" @reservation.wait_until_lock payload.resource_id, (err, state) -> return cb "no_reservations" unless state return cb null, 'patience_is_bitter_but_fruit_is_sweet' describe 'ReserveResource', -> it "allows you to create a bunch of reservations", -> # Reasons it might fail: # * memory leaks # * connection limits for i in [0...10000000] resource = new ReserveResource 'some worker', process.env.REDIS_HOST, process.env.REDIS_PORT resource._init_redis() describe 'redis-reservation', -> before (done) -> @redis = redis.createClient(process.env.REDIS_PORT, process.env.REDIS_HOST) #@redis.select 3 done() beforeEach (done) -> @redis.flushall done it 'can reserve and release a lock', (done) -> test_worker = new LockWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'can reserve and release a lock with redis password', (done) -> @redis.config 'set', 'requirepass', 'PI:PASSWORD:<PASSWORD>END_PI' @redis.auth '12345' payload = resource_id: 'test_resource', password: 'PI:PASSWORD:<PASSWORD>END_PI' test_worker = new PasswordWorker payload, (err, resp) => @redis.config 'set', 'requirepass', '' assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'holds a lock while running', (done) -> test_worker = new SlowWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'whostheboss.iam' @redis.get 'resource-test_resource', (err, resp) -> assert.equal resp, null done() it 'can wait for a lock', (done) -> setTimeout(=> @redis.del 'reservation-test_resource', -> return , 1000) @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new WaitWorker resource_id: 'test_resource', (err, resp) => assert.equal null, err assert.equal resp, 'patience_is_bitter_but_fruit_is_sweet' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, null done() it 'fails silently if resource is already reserved', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new LockWorker resource_id: 'test_resource', (err, resp) => assert.equal err, 'no_reservations' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'does not interfere for workers without reservations', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new FreeWorker resource_id: 'test_resource', (err, resp) => assert.equal resp, 'always_done' @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'handles failing jobs', (done) -> @redis.set 'reservation-test_resource', 'MOCK', (err, resp) => test_worker = new FailWorker resource_id: 'test_resource', (err, resp) => assert.equal err.message, ":(" assert.equal null, resp @redis.get 'reservation-test_resource', (err, resp) -> assert.equal resp, 'MOCK' done() it 'fails on no redis', (done) -> process.env.REDIS_HOST = 'localhost' process.env.REDIS_PORT = 6666 # incorrect port test_worker = new SlowWorker resource_id: 'test_resource', (err, resp) -> console.log "ERR", err assert err.message.match( /Redis connection to .+:6666 failed - connect ECONNREFUSED/ ) setTimeout done, 1000
[ { "context": "ken) =>\n\n key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C'\n cmd = if err\n \"<a h", "end": 636, "score": 0.9699971079826355, "start": 631, "tag": "KEY", "value": "⌘ + C" }, { "context": " key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl...
client/home/lib/utilities/components/kdcli/container.coffee
ezgikaysi/koding
1
_ = require 'lodash' kd = require 'kd' React = require 'kd-react' globals = require 'globals' whoami = require 'app/util/whoami' Tracker = require 'app/util/tracker' copyToClipboard = require 'app/util/copyToClipboard' View = require './view' KodingKontrol = require 'app/kite/kodingkontrol' module.exports = class KDCliContainer extends React.Component constructor: (props) -> super props @state= key : '' cmd : '' componentWillMount: -> whoami().fetchOtaToken (err, token) => key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C' cmd = if err "<a href='#'>Failed to generate your command, click to try again!</a>" else if globals.config.environment in ['dev', 'default', 'sandbox'] "export KONTROLURL=#{KodingKontrol.getKontrolUrl()}; curl -sL https://sandbox.kodi.ng/c/d/kd | bash -s #{token}" else "curl -sL https://kodi.ng/c/p/kd | bash -s #{token}" @setState key : key cmd : cmd onCMDClick: -> codeblock = @refs.view.refs.codeblock copyToClipboard codeblock Tracker.track Tracker.KD_INSTALLED render: -> <View ref='view' copyKey={@state.key} cmd={@state.cmd} onCMDClick={@bound 'onCMDClick'} />
62021
_ = require 'lodash' kd = require 'kd' React = require 'kd-react' globals = require 'globals' whoami = require 'app/util/whoami' Tracker = require 'app/util/tracker' copyToClipboard = require 'app/util/copyToClipboard' View = require './view' KodingKontrol = require 'app/kite/kodingkontrol' module.exports = class KDCliContainer extends React.Component constructor: (props) -> super props @state= key : '' cmd : '' componentWillMount: -> whoami().fetchOtaToken (err, token) => key = if globals.os is 'mac' then '<KEY>' else '<KEY>' cmd = if err "<a href='#'>Failed to generate your command, click to try again!</a>" else if globals.config.environment in ['dev', 'default', 'sandbox'] "export KONTROLURL=#{KodingKontrol.getKontrolUrl()}; curl -sL https://sandbox.kodi.ng/c/d/kd | bash -s #{token}" else "curl -sL https://kodi.ng/c/p/kd | bash -s #{token}" @setState key : key cmd : cmd onCMDClick: -> codeblock = @refs.view.refs.codeblock copyToClipboard codeblock Tracker.track Tracker.KD_INSTALLED render: -> <View ref='view' copyKey={@state.key} cmd={@state.cmd} onCMDClick={@bound 'onCMDClick'} />
true
_ = require 'lodash' kd = require 'kd' React = require 'kd-react' globals = require 'globals' whoami = require 'app/util/whoami' Tracker = require 'app/util/tracker' copyToClipboard = require 'app/util/copyToClipboard' View = require './view' KodingKontrol = require 'app/kite/kodingkontrol' module.exports = class KDCliContainer extends React.Component constructor: (props) -> super props @state= key : '' cmd : '' componentWillMount: -> whoami().fetchOtaToken (err, token) => key = if globals.os is 'mac' then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI' cmd = if err "<a href='#'>Failed to generate your command, click to try again!</a>" else if globals.config.environment in ['dev', 'default', 'sandbox'] "export KONTROLURL=#{KodingKontrol.getKontrolUrl()}; curl -sL https://sandbox.kodi.ng/c/d/kd | bash -s #{token}" else "curl -sL https://kodi.ng/c/p/kd | bash -s #{token}" @setState key : key cmd : cmd onCMDClick: -> codeblock = @refs.view.refs.codeblock copyToClipboard codeblock Tracker.track Tracker.KD_INSTALLED render: -> <View ref='view' copyKey={@state.key} cmd={@state.cmd} onCMDClick={@bound 'onCMDClick'} />
[ { "context": "s [{id: 0, name: \"San Francisco\"}, {id: 1, name: \"Lyon\"}, {id: 2, name: \"Barcelona\"}]\n\n loadNeighborhoo", "end": 132, "score": 0.6942501068115234, "start": 128, "tag": "NAME", "value": "Lyon" }, { "context": " if cityId[0] == \"0\"\n [{id: 0, name: ...
examples/dynamic-simple/cityService.coffee
vedantchoubey098/react-form-builder
44
module.exports = cityService = loadCities: (callback) -> callback.success [{id: 0, name: "San Francisco"}, {id: 1, name: "Lyon"}, {id: 2, name: "Barcelona"}] loadNeighborhoodsWithCityId: (cityId, callback) -> response = if cityId[0] == "0" [{id: 0, name: "SoMa"}, {id: 1, name: "Mission"}, {id: 2, name: "Fillmore"}] else if cityId[0] == "1" [{id: 0, name: "Les Pentes"}, {id: 1, name: "Presqu'ile"}, {id: 2, name: "Gerland"}] else if cityId[0] == "2" [{id: 0, name: "Barri Gotic"}, {id: 1, name: "Passeig de Gracia"}, {id: 2, name: "Barceloneta"}] callback.success response
80300
module.exports = cityService = loadCities: (callback) -> callback.success [{id: 0, name: "San Francisco"}, {id: 1, name: "<NAME>"}, {id: 2, name: "Barcelona"}] loadNeighborhoodsWithCityId: (cityId, callback) -> response = if cityId[0] == "0" [{id: 0, name: "<NAME>"}, {id: 1, name: "<NAME>"}, {id: 2, name: "<NAME>"}] else if cityId[0] == "1" [{id: 0, name: "<NAME>entes"}, {id: 1, name: "<NAME>"}, {id: 2, name: "Gerland"}] else if cityId[0] == "2" [{id: 0, name: "<NAME>"}, {id: 1, name: "<NAME> Gr<NAME>ia"}, {id: 2, name: "<NAME>on<NAME>"}] callback.success response
true
module.exports = cityService = loadCities: (callback) -> callback.success [{id: 0, name: "San Francisco"}, {id: 1, name: "PI:NAME:<NAME>END_PI"}, {id: 2, name: "Barcelona"}] loadNeighborhoodsWithCityId: (cityId, callback) -> response = if cityId[0] == "0" [{id: 0, name: "PI:NAME:<NAME>END_PI"}, {id: 1, name: "PI:NAME:<NAME>END_PI"}, {id: 2, name: "PI:NAME:<NAME>END_PI"}] else if cityId[0] == "1" [{id: 0, name: "PI:NAME:<NAME>END_PIentes"}, {id: 1, name: "PI:NAME:<NAME>END_PI"}, {id: 2, name: "Gerland"}] else if cityId[0] == "2" [{id: 0, name: "PI:NAME:<NAME>END_PI"}, {id: 1, name: "PI:NAME:<NAME>END_PI GrPI:NAME:<NAME>END_PIia"}, {id: 2, name: "PI:NAME:<NAME>END_PIonPI:NAME:<NAME>END_PI"}] callback.success response
[ { "context": "er.then ->\n expect(\"#waldo\").to.have.text(\"Simon says\")\n expect(\".math\").to.have.text(\"(1 +", "end": 5623, "score": 0.6918536424636841, "start": 5618, "tag": "NAME", "value": "Simon" }, { "context": "hen ->\n expect(\"#waldo\").to.not.have....
test/common.coffee
brianmhunt/casper-chai
33
### # Unit-tests for Casper-Chai ### # TODO: Test 'loaded' describe "Casper-Chai addons to Chai", -> before -> require("webserver").create().listen 8523, (request, response) -> response.writeHead 200, "Content-Type": "text/html" response.write "<!DOCTYPE html> <html> <head> <title>The Title</title> </head> <body> <h1 id=\"header_1\">A Header</h1> <blockquote class='tagged'> “Do what you can, with what <em>you</em> have, where you are.” <small>THEODORE ROOSEVELT.</small> </blockquote> <div id='waldo' class='says tagged' style='display: none' data-empty=''>Simon says</div> <div class='says'>Also says</div> <div class='math'>(1 + 1) = 2</div> <form action=''> <input id='afield' name='anamedfield' value='42' /> <input id='anotherfield' name='foo' type='number' /> </form> </body> </html>" response.close() casper.start "http://localhost:8523/" describe "the attr method", -> it "matches 'class' by id", -> casper.then -> expect("#waldo").to.have.attr('class') it 'does not match where attribute is empty', -> casper.then -> expect("#waldo").to.not.have.attr("data-empty") it "finds not all divs have an 'id' attribute", -> casper.then -> expect('div').to.not.have.attr('id') it "finds that all divs have a 'class' attribute", -> casper.then -> expect("div").to.have.attr('class') it 'should change the assertion subject to the attributes', -> casper.then -> expect('input').to.have.attribute('name').and.deep.equal(['anamedfield', 'foo']) describe "with element chain", -> it "matches any div with an 'id' attribute", -> casper.then -> expect('div').to.have.an.element.with.attr("id") it "finds divs with an 'class' attribute", -> casper.then -> # all divs have the class attribute expect('div').to.have.an.element.with.attr("class") it "finds no divs with an 'data-empty' attribute", -> casper.then -> expect('div').to.not.have.an.element.with.attr("data-empty") describe "the tagName method", -> it "finds that the '.says' tags are all 'divs'", -> casper.then -> expect(".says").to.have.tagName('div') it "finds that the .tagged tags are divs and blockquotes", -> casper.then -> expect(".says").to.have.tagName(['div', 'blockquote']) it "finds that the children of blockquotes are em and small tags", -> casper.then -> expect("blockquote *").to.have.tagName(['em', 'small']) describe "the inDOM property", -> it "matches a selector in the DOM", -> casper.then -> expect("#header_1").to.be.inDOM it "does not match a selector that is not in the DOM", -> casper.then -> expect("#not_in_dom").to.not.be.inDOM describe "the visible property", -> it "matches a visible property", -> casper.then -> expect("#header_1").to.be.visible it "does not match an invisible property", -> casper.then -> expect("#waldo").to.not.be.visible describe "the textInDOM property", -> it "finds text somewhere in the DOM", -> casper.then -> expect("THEODORE ROOSEVELT").to.be.textInDOM.and.be.ok it "does not find text that is not in the DOM", -> casper.then -> expect("THEODORE ROOSEVELt").to.not.be.textInDOM describe "the matchTitle property", -> it "matches a regular expression (/Title/)", -> casper.then -> expect(/Title/).to.matchTitle.and.be.ok it "does not match an given regular expression (/^Title/)", -> casper.then -> expect(/^Title/).to.not.matchTitle it "matches a given string when equal", -> casper.then -> expect("The Title").to.matchTitle it "does not match a partial title", -> casper.then -> expect("Title").to.not.matchTitle describe "BDD 'should' framework", -> it "should include the new asserts", -> "#header_1".should.be.inDOM.and.visible.and.ok "#header_X".should.not.be.inDOM.and.visible describe "the matchCurrentUrl property", -> it "matches /localhost/", -> casper.then -> expect(/localhost/).to.matchCurrentUrl.and.be.ok it "does not match /some_remote_host/", -> casper.then -> expect(/some_remote_host/).to.not.matchCurrentUrl it "matches the current url (a string) given by Casper", -> casper.then -> expect(casper.getCurrentUrl()).to.matchCurrentUrl it "does not match a string that is not the current url", -> casper.then -> expect(casper.getCurrentUrl()+"X").to.not.matchCurrentUrl describe "the fieldValue method", -> it "matches anamedfield's value of 42", -> casper.then -> expect("anamedfield").to.have.fieldValue("42") describe "the text method", -> it "matches #waldo's with a regular expression (/says/)", -> casper.then -> expect("#waldo").to.have.text(/says/) it "matches a case insensitive regex expression (/says/i)", -> casper.then -> expect("#waldo").to.have.text(/SAYS/i) it "matches multiple selectors with a regular expression", -> casper.then -> expect("div.says").to.have.text(/says/) it "does not match multiple selectors against a given selection", -> casper.then -> expect("div.says").to.not.have.text(/said/) it "matches a text string exactly", -> casper.then -> expect("#waldo").to.have.text("Simon says") expect(".math").to.have.text("(1 + 1) = 2") it "does not match a partial string", -> casper.then -> expect("#waldo").to.not.have.text("Simon says, also") expect("#waldo").to.not.have.text("Simon") it "does match a partial string with contains or include", -> casper.then -> expect("#waldo").to.contain.text("Simon") expect("#waldo").to.include.text("Simon") expect("div.says").to.contain.text("Also") it "does not falsely match a partial string with contains or include", -> casper.then -> expect("#waldo").to.not.contain.text("Simon also says") expect("#waldo").to.not.include.text("Simon is a monkey") expect("div.says").to.not.contain.text("ALSO") describe "evaluate language chain", -> it "evaluates functions", -> casper.then -> expect(-> fruits = strawberry: 'red', orange: 'orange', kiwi: 'green' for fruit, color of fruits "#{fruit}:#{color}" ).to.evaluate.to.deep.equal ['strawberry:red', 'orange:orange', 'kiwi:green'] it "evaluates function strings", -> casper.then -> expect("function () { return 'foo'; }").to.evaluate.to.equal 'foo' it "evaluates expression strings that contain 'return'", -> casper.then -> expect("return true").to.evaluate.to.be.true.and.ok it "evaluates expression strings that does not contain 'return'", -> casper.then -> expect("typeof {}").to.evaluate.to.equal('object') describe "trivial tests", -> before -> casper.start "http://localhost:10777/" it "to check for HttpStatus", -> casper.then -> expect(casper.currentHTTPStatus).to.equal(null) # we loaded from a file casper.thenOpen "http://localhost:8523/" # "remote" file casper.then -> expect(casper.currentHTTPStatus).to.equal(200) # we loaded over http it "to check remote content, created by a function remotely executed", -> casper.then -> remote_value = casper.evaluate(-> document.title + "eee") expect(remote_value).to.equal("The Titleeee") describe "test for loaded", -> it "checks for jQuery when it is not loaded", -> casper.then -> expect(-> typeof jQuery).to.evaluate.to.equal("undefined") expect('jquery-1.8.3').to.not.be.loaded.now it "checks for jQuery loaded by CDN", -> casper.then -> jQueryCDN = 'http://code.jquery.com/jquery-1.8.3.min.js' casper.waitStart() casper.page.includeJs jQueryCDN, -> console.log("\t(Loaded #{jQueryCDN})") casper.waitDone() # includeJs is basically equivalent to: # v = document.createElement("script"); # v.src = "http://code.jquery.com/jquery-1.8.3.min.js"; # document.body.appendChild(v); casper.then -> expect(-> typeof jQuery).to.not.evaluate.to.equal("undefined") expect('jquery-1.8.3.min.js').to.be.loaded
44218
### # Unit-tests for Casper-Chai ### # TODO: Test 'loaded' describe "Casper-Chai addons to Chai", -> before -> require("webserver").create().listen 8523, (request, response) -> response.writeHead 200, "Content-Type": "text/html" response.write "<!DOCTYPE html> <html> <head> <title>The Title</title> </head> <body> <h1 id=\"header_1\">A Header</h1> <blockquote class='tagged'> “Do what you can, with what <em>you</em> have, where you are.” <small>THEODORE ROOSEVELT.</small> </blockquote> <div id='waldo' class='says tagged' style='display: none' data-empty=''>Simon says</div> <div class='says'>Also says</div> <div class='math'>(1 + 1) = 2</div> <form action=''> <input id='afield' name='anamedfield' value='42' /> <input id='anotherfield' name='foo' type='number' /> </form> </body> </html>" response.close() casper.start "http://localhost:8523/" describe "the attr method", -> it "matches 'class' by id", -> casper.then -> expect("#waldo").to.have.attr('class') it 'does not match where attribute is empty', -> casper.then -> expect("#waldo").to.not.have.attr("data-empty") it "finds not all divs have an 'id' attribute", -> casper.then -> expect('div').to.not.have.attr('id') it "finds that all divs have a 'class' attribute", -> casper.then -> expect("div").to.have.attr('class') it 'should change the assertion subject to the attributes', -> casper.then -> expect('input').to.have.attribute('name').and.deep.equal(['anamedfield', 'foo']) describe "with element chain", -> it "matches any div with an 'id' attribute", -> casper.then -> expect('div').to.have.an.element.with.attr("id") it "finds divs with an 'class' attribute", -> casper.then -> # all divs have the class attribute expect('div').to.have.an.element.with.attr("class") it "finds no divs with an 'data-empty' attribute", -> casper.then -> expect('div').to.not.have.an.element.with.attr("data-empty") describe "the tagName method", -> it "finds that the '.says' tags are all 'divs'", -> casper.then -> expect(".says").to.have.tagName('div') it "finds that the .tagged tags are divs and blockquotes", -> casper.then -> expect(".says").to.have.tagName(['div', 'blockquote']) it "finds that the children of blockquotes are em and small tags", -> casper.then -> expect("blockquote *").to.have.tagName(['em', 'small']) describe "the inDOM property", -> it "matches a selector in the DOM", -> casper.then -> expect("#header_1").to.be.inDOM it "does not match a selector that is not in the DOM", -> casper.then -> expect("#not_in_dom").to.not.be.inDOM describe "the visible property", -> it "matches a visible property", -> casper.then -> expect("#header_1").to.be.visible it "does not match an invisible property", -> casper.then -> expect("#waldo").to.not.be.visible describe "the textInDOM property", -> it "finds text somewhere in the DOM", -> casper.then -> expect("THEODORE ROOSEVELT").to.be.textInDOM.and.be.ok it "does not find text that is not in the DOM", -> casper.then -> expect("THEODORE ROOSEVELt").to.not.be.textInDOM describe "the matchTitle property", -> it "matches a regular expression (/Title/)", -> casper.then -> expect(/Title/).to.matchTitle.and.be.ok it "does not match an given regular expression (/^Title/)", -> casper.then -> expect(/^Title/).to.not.matchTitle it "matches a given string when equal", -> casper.then -> expect("The Title").to.matchTitle it "does not match a partial title", -> casper.then -> expect("Title").to.not.matchTitle describe "BDD 'should' framework", -> it "should include the new asserts", -> "#header_1".should.be.inDOM.and.visible.and.ok "#header_X".should.not.be.inDOM.and.visible describe "the matchCurrentUrl property", -> it "matches /localhost/", -> casper.then -> expect(/localhost/).to.matchCurrentUrl.and.be.ok it "does not match /some_remote_host/", -> casper.then -> expect(/some_remote_host/).to.not.matchCurrentUrl it "matches the current url (a string) given by Casper", -> casper.then -> expect(casper.getCurrentUrl()).to.matchCurrentUrl it "does not match a string that is not the current url", -> casper.then -> expect(casper.getCurrentUrl()+"X").to.not.matchCurrentUrl describe "the fieldValue method", -> it "matches anamedfield's value of 42", -> casper.then -> expect("anamedfield").to.have.fieldValue("42") describe "the text method", -> it "matches #waldo's with a regular expression (/says/)", -> casper.then -> expect("#waldo").to.have.text(/says/) it "matches a case insensitive regex expression (/says/i)", -> casper.then -> expect("#waldo").to.have.text(/SAYS/i) it "matches multiple selectors with a regular expression", -> casper.then -> expect("div.says").to.have.text(/says/) it "does not match multiple selectors against a given selection", -> casper.then -> expect("div.says").to.not.have.text(/said/) it "matches a text string exactly", -> casper.then -> expect("#waldo").to.have.text("<NAME> says") expect(".math").to.have.text("(1 + 1) = 2") it "does not match a partial string", -> casper.then -> expect("#waldo").to.not.have.text("<NAME>on says, also") expect("#waldo").to.not.have.text("Simon") it "does match a partial string with contains or include", -> casper.then -> expect("#waldo").to.contain.text("<NAME>") expect("#waldo").to.include.text("<NAME>") expect("div.says").to.contain.text("Also") it "does not falsely match a partial string with contains or include", -> casper.then -> expect("#waldo").to.not.contain.text("<NAME> also says") expect("#waldo").to.not.include.text("<NAME> is a monkey") expect("div.says").to.not.contain.text("ALSO") describe "evaluate language chain", -> it "evaluates functions", -> casper.then -> expect(-> fruits = strawberry: 'red', orange: 'orange', kiwi: 'green' for fruit, color of fruits "#{fruit}:#{color}" ).to.evaluate.to.deep.equal ['strawberry:red', 'orange:orange', 'kiwi:green'] it "evaluates function strings", -> casper.then -> expect("function () { return 'foo'; }").to.evaluate.to.equal 'foo' it "evaluates expression strings that contain 'return'", -> casper.then -> expect("return true").to.evaluate.to.be.true.and.ok it "evaluates expression strings that does not contain 'return'", -> casper.then -> expect("typeof {}").to.evaluate.to.equal('object') describe "trivial tests", -> before -> casper.start "http://localhost:10777/" it "to check for HttpStatus", -> casper.then -> expect(casper.currentHTTPStatus).to.equal(null) # we loaded from a file casper.thenOpen "http://localhost:8523/" # "remote" file casper.then -> expect(casper.currentHTTPStatus).to.equal(200) # we loaded over http it "to check remote content, created by a function remotely executed", -> casper.then -> remote_value = casper.evaluate(-> document.title + "eee") expect(remote_value).to.equal("The Titleeee") describe "test for loaded", -> it "checks for jQuery when it is not loaded", -> casper.then -> expect(-> typeof jQuery).to.evaluate.to.equal("undefined") expect('jquery-1.8.3').to.not.be.loaded.now it "checks for jQuery loaded by CDN", -> casper.then -> jQueryCDN = 'http://code.jquery.com/jquery-1.8.3.min.js' casper.waitStart() casper.page.includeJs jQueryCDN, -> console.log("\t(Loaded #{jQueryCDN})") casper.waitDone() # includeJs is basically equivalent to: # v = document.createElement("script"); # v.src = "http://code.jquery.com/jquery-1.8.3.min.js"; # document.body.appendChild(v); casper.then -> expect(-> typeof jQuery).to.not.evaluate.to.equal("undefined") expect('jquery-1.8.3.min.js').to.be.loaded
true
### # Unit-tests for Casper-Chai ### # TODO: Test 'loaded' describe "Casper-Chai addons to Chai", -> before -> require("webserver").create().listen 8523, (request, response) -> response.writeHead 200, "Content-Type": "text/html" response.write "<!DOCTYPE html> <html> <head> <title>The Title</title> </head> <body> <h1 id=\"header_1\">A Header</h1> <blockquote class='tagged'> “Do what you can, with what <em>you</em> have, where you are.” <small>THEODORE ROOSEVELT.</small> </blockquote> <div id='waldo' class='says tagged' style='display: none' data-empty=''>Simon says</div> <div class='says'>Also says</div> <div class='math'>(1 + 1) = 2</div> <form action=''> <input id='afield' name='anamedfield' value='42' /> <input id='anotherfield' name='foo' type='number' /> </form> </body> </html>" response.close() casper.start "http://localhost:8523/" describe "the attr method", -> it "matches 'class' by id", -> casper.then -> expect("#waldo").to.have.attr('class') it 'does not match where attribute is empty', -> casper.then -> expect("#waldo").to.not.have.attr("data-empty") it "finds not all divs have an 'id' attribute", -> casper.then -> expect('div').to.not.have.attr('id') it "finds that all divs have a 'class' attribute", -> casper.then -> expect("div").to.have.attr('class') it 'should change the assertion subject to the attributes', -> casper.then -> expect('input').to.have.attribute('name').and.deep.equal(['anamedfield', 'foo']) describe "with element chain", -> it "matches any div with an 'id' attribute", -> casper.then -> expect('div').to.have.an.element.with.attr("id") it "finds divs with an 'class' attribute", -> casper.then -> # all divs have the class attribute expect('div').to.have.an.element.with.attr("class") it "finds no divs with an 'data-empty' attribute", -> casper.then -> expect('div').to.not.have.an.element.with.attr("data-empty") describe "the tagName method", -> it "finds that the '.says' tags are all 'divs'", -> casper.then -> expect(".says").to.have.tagName('div') it "finds that the .tagged tags are divs and blockquotes", -> casper.then -> expect(".says").to.have.tagName(['div', 'blockquote']) it "finds that the children of blockquotes are em and small tags", -> casper.then -> expect("blockquote *").to.have.tagName(['em', 'small']) describe "the inDOM property", -> it "matches a selector in the DOM", -> casper.then -> expect("#header_1").to.be.inDOM it "does not match a selector that is not in the DOM", -> casper.then -> expect("#not_in_dom").to.not.be.inDOM describe "the visible property", -> it "matches a visible property", -> casper.then -> expect("#header_1").to.be.visible it "does not match an invisible property", -> casper.then -> expect("#waldo").to.not.be.visible describe "the textInDOM property", -> it "finds text somewhere in the DOM", -> casper.then -> expect("THEODORE ROOSEVELT").to.be.textInDOM.and.be.ok it "does not find text that is not in the DOM", -> casper.then -> expect("THEODORE ROOSEVELt").to.not.be.textInDOM describe "the matchTitle property", -> it "matches a regular expression (/Title/)", -> casper.then -> expect(/Title/).to.matchTitle.and.be.ok it "does not match an given regular expression (/^Title/)", -> casper.then -> expect(/^Title/).to.not.matchTitle it "matches a given string when equal", -> casper.then -> expect("The Title").to.matchTitle it "does not match a partial title", -> casper.then -> expect("Title").to.not.matchTitle describe "BDD 'should' framework", -> it "should include the new asserts", -> "#header_1".should.be.inDOM.and.visible.and.ok "#header_X".should.not.be.inDOM.and.visible describe "the matchCurrentUrl property", -> it "matches /localhost/", -> casper.then -> expect(/localhost/).to.matchCurrentUrl.and.be.ok it "does not match /some_remote_host/", -> casper.then -> expect(/some_remote_host/).to.not.matchCurrentUrl it "matches the current url (a string) given by Casper", -> casper.then -> expect(casper.getCurrentUrl()).to.matchCurrentUrl it "does not match a string that is not the current url", -> casper.then -> expect(casper.getCurrentUrl()+"X").to.not.matchCurrentUrl describe "the fieldValue method", -> it "matches anamedfield's value of 42", -> casper.then -> expect("anamedfield").to.have.fieldValue("42") describe "the text method", -> it "matches #waldo's with a regular expression (/says/)", -> casper.then -> expect("#waldo").to.have.text(/says/) it "matches a case insensitive regex expression (/says/i)", -> casper.then -> expect("#waldo").to.have.text(/SAYS/i) it "matches multiple selectors with a regular expression", -> casper.then -> expect("div.says").to.have.text(/says/) it "does not match multiple selectors against a given selection", -> casper.then -> expect("div.says").to.not.have.text(/said/) it "matches a text string exactly", -> casper.then -> expect("#waldo").to.have.text("PI:NAME:<NAME>END_PI says") expect(".math").to.have.text("(1 + 1) = 2") it "does not match a partial string", -> casper.then -> expect("#waldo").to.not.have.text("PI:NAME:<NAME>END_PIon says, also") expect("#waldo").to.not.have.text("Simon") it "does match a partial string with contains or include", -> casper.then -> expect("#waldo").to.contain.text("PI:NAME:<NAME>END_PI") expect("#waldo").to.include.text("PI:NAME:<NAME>END_PI") expect("div.says").to.contain.text("Also") it "does not falsely match a partial string with contains or include", -> casper.then -> expect("#waldo").to.not.contain.text("PI:NAME:<NAME>END_PI also says") expect("#waldo").to.not.include.text("PI:NAME:<NAME>END_PI is a monkey") expect("div.says").to.not.contain.text("ALSO") describe "evaluate language chain", -> it "evaluates functions", -> casper.then -> expect(-> fruits = strawberry: 'red', orange: 'orange', kiwi: 'green' for fruit, color of fruits "#{fruit}:#{color}" ).to.evaluate.to.deep.equal ['strawberry:red', 'orange:orange', 'kiwi:green'] it "evaluates function strings", -> casper.then -> expect("function () { return 'foo'; }").to.evaluate.to.equal 'foo' it "evaluates expression strings that contain 'return'", -> casper.then -> expect("return true").to.evaluate.to.be.true.and.ok it "evaluates expression strings that does not contain 'return'", -> casper.then -> expect("typeof {}").to.evaluate.to.equal('object') describe "trivial tests", -> before -> casper.start "http://localhost:10777/" it "to check for HttpStatus", -> casper.then -> expect(casper.currentHTTPStatus).to.equal(null) # we loaded from a file casper.thenOpen "http://localhost:8523/" # "remote" file casper.then -> expect(casper.currentHTTPStatus).to.equal(200) # we loaded over http it "to check remote content, created by a function remotely executed", -> casper.then -> remote_value = casper.evaluate(-> document.title + "eee") expect(remote_value).to.equal("The Titleeee") describe "test for loaded", -> it "checks for jQuery when it is not loaded", -> casper.then -> expect(-> typeof jQuery).to.evaluate.to.equal("undefined") expect('jquery-1.8.3').to.not.be.loaded.now it "checks for jQuery loaded by CDN", -> casper.then -> jQueryCDN = 'http://code.jquery.com/jquery-1.8.3.min.js' casper.waitStart() casper.page.includeJs jQueryCDN, -> console.log("\t(Loaded #{jQueryCDN})") casper.waitDone() # includeJs is basically equivalent to: # v = document.createElement("script"); # v.src = "http://code.jquery.com/jquery-1.8.3.min.js"; # document.body.appendChild(v); casper.then -> expect(-> typeof jQuery).to.not.evaluate.to.equal("undefined") expect('jquery-1.8.3.min.js').to.be.loaded
[ { "context": "eds\"\nphase: \"beta\"\nphase_modifier: \"Public\"\nsro: \"Derek Hobbs\"\nservice_man: \"Zoe Gould\"\nphase_history:\n discov", "end": 256, "score": 0.9998944997787476, "start": 245, "tag": "NAME", "value": "Derek Hobbs" }, { "context": "difier: \"Public\"\nsro: \"Dere...
app/data/projects/budgeting-loans.cson
tsmorgan/dwp-ux-work
0
id: 15 name: "Apply for a Budgeting Loan" description: "Lets users apply for a short-term cash loan so that they can afford to buy essential items or services." theme: "Working Age" location: "Leeds" phase: "beta" phase_modifier: "Public" sro: "Derek Hobbs" service_man: "Zoe Gould" phase_history: discovery: [ { label: "Completed" date: "May 2015" } ] alpha: [ { label: "Completed" date: "November 2015" } ] beta: [ { label: "Started" date: "November 2015" } { label: "Private beta started" date: "February 2016" } { label: "Public beta started" date: "October 2016" } ] priority: "Low" prototype: "http://bud-loans.herokuapp.com/"
119527
id: 15 name: "Apply for a Budgeting Loan" description: "Lets users apply for a short-term cash loan so that they can afford to buy essential items or services." theme: "Working Age" location: "Leeds" phase: "beta" phase_modifier: "Public" sro: "<NAME>" service_man: "<NAME>" phase_history: discovery: [ { label: "Completed" date: "May 2015" } ] alpha: [ { label: "Completed" date: "November 2015" } ] beta: [ { label: "Started" date: "November 2015" } { label: "Private beta started" date: "February 2016" } { label: "Public beta started" date: "October 2016" } ] priority: "Low" prototype: "http://bud-loans.herokuapp.com/"
true
id: 15 name: "Apply for a Budgeting Loan" description: "Lets users apply for a short-term cash loan so that they can afford to buy essential items or services." theme: "Working Age" location: "Leeds" phase: "beta" phase_modifier: "Public" sro: "PI:NAME:<NAME>END_PI" service_man: "PI:NAME:<NAME>END_PI" phase_history: discovery: [ { label: "Completed" date: "May 2015" } ] alpha: [ { label: "Completed" date: "November 2015" } ] beta: [ { label: "Started" date: "November 2015" } { label: "Private beta started" date: "February 2016" } { label: "Public beta started" date: "October 2016" } ] priority: "Low" prototype: "http://bud-loans.herokuapp.com/"
[ { "context": "ith a chainsaw, #{req.params.name}. Do I look like Mother Teresa?\"\n subtitle = \"- #{req.params.from}\"\n o", "end": 331, "score": 0.7506927847862244, "start": 318, "tag": "NAME", "value": "Mother Teresa" } ]
lib/operations/chainsaw.coffee
BenOien/ForkOAAS
0
module.exports = name: "Chainsaw" url: '/chainsaw/:name/:from' fields: [ { name: 'Name', field: 'name'} { name: 'From', field: 'from'} ] register: (app, output) -> app.get '/chainsaw/:name/:from', (req, res) -> message = "Fork me gently with a chainsaw, #{req.params.name}. Do I look like Mother Teresa?" subtitle = "- #{req.params.from}" output(req, res, message, subtitle)
2031
module.exports = name: "Chainsaw" url: '/chainsaw/:name/:from' fields: [ { name: 'Name', field: 'name'} { name: 'From', field: 'from'} ] register: (app, output) -> app.get '/chainsaw/:name/:from', (req, res) -> message = "Fork me gently with a chainsaw, #{req.params.name}. Do I look like <NAME>?" subtitle = "- #{req.params.from}" output(req, res, message, subtitle)
true
module.exports = name: "Chainsaw" url: '/chainsaw/:name/:from' fields: [ { name: 'Name', field: 'name'} { name: 'From', field: 'from'} ] register: (app, output) -> app.get '/chainsaw/:name/:from', (req, res) -> message = "Fork me gently with a chainsaw, #{req.params.name}. Do I look like PI:NAME:<NAME>END_PI?" subtitle = "- #{req.params.from}" output(req, res, message, subtitle)
[ { "context": "email = 'support@roqua.nl'\nmessage = \"Onbekende fout. Mail naar <a href='ma", "end": 25, "score": 0.9999270439147949, "start": 9, "tag": "EMAIL", "value": "support@roqua.nl" } ]
app/assets/javascripts/error_handler.coffee
roqua/screensmart
2
email = 'support@roqua.nl' message = "Onbekende fout. Mail naar <a href='mailto:#{email}'>#{email}</a> voor hulp" applicationInitialized = -> Screensmart? && typeof Screensmart.store?.dispatch == 'function' showUnknownError = -> # Show error in a primitive way if something went wrong during initialization if applicationInitialized() Screensmart.store.dispatch Screensmart.Actions.addMessage message else document.body.innerHTML = message window.onerror = (_message, _filename, _lineno, _colno, error) -> showUnknownError() error.message += " store contents: #{prettyStoreContents()}" appsignal.sendError(error) if error && window.environment != 'development' prettyStoreContents = -> storeContents = Screensmart.store.getState() JSON.stringify(storeContents, null, 2) # Global jQuery AJAX error handler $(document).ajaxError (event, xhr, settings, error ) -> { method, url, type } = settings { status } = xhr if window.environment == 'development' || window.environment == 'test' console.log "#{type} #{url} failed: #{error}" console.log xhr: xhr, settings: settings else appsignal.sendError new Error "#{type} #{url} failed: #{error}"
190435
email = '<EMAIL>' message = "Onbekende fout. Mail naar <a href='mailto:#{email}'>#{email}</a> voor hulp" applicationInitialized = -> Screensmart? && typeof Screensmart.store?.dispatch == 'function' showUnknownError = -> # Show error in a primitive way if something went wrong during initialization if applicationInitialized() Screensmart.store.dispatch Screensmart.Actions.addMessage message else document.body.innerHTML = message window.onerror = (_message, _filename, _lineno, _colno, error) -> showUnknownError() error.message += " store contents: #{prettyStoreContents()}" appsignal.sendError(error) if error && window.environment != 'development' prettyStoreContents = -> storeContents = Screensmart.store.getState() JSON.stringify(storeContents, null, 2) # Global jQuery AJAX error handler $(document).ajaxError (event, xhr, settings, error ) -> { method, url, type } = settings { status } = xhr if window.environment == 'development' || window.environment == 'test' console.log "#{type} #{url} failed: #{error}" console.log xhr: xhr, settings: settings else appsignal.sendError new Error "#{type} #{url} failed: #{error}"
true
email = 'PI:EMAIL:<EMAIL>END_PI' message = "Onbekende fout. Mail naar <a href='mailto:#{email}'>#{email}</a> voor hulp" applicationInitialized = -> Screensmart? && typeof Screensmart.store?.dispatch == 'function' showUnknownError = -> # Show error in a primitive way if something went wrong during initialization if applicationInitialized() Screensmart.store.dispatch Screensmart.Actions.addMessage message else document.body.innerHTML = message window.onerror = (_message, _filename, _lineno, _colno, error) -> showUnknownError() error.message += " store contents: #{prettyStoreContents()}" appsignal.sendError(error) if error && window.environment != 'development' prettyStoreContents = -> storeContents = Screensmart.store.getState() JSON.stringify(storeContents, null, 2) # Global jQuery AJAX error handler $(document).ajaxError (event, xhr, settings, error ) -> { method, url, type } = settings { status } = xhr if window.environment == 'development' || window.environment == 'test' console.log "#{type} #{url} failed: #{error}" console.log xhr: xhr, settings: settings else appsignal.sendError new Error "#{type} #{url} failed: #{error}"
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9994432926177979, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-domain-exit-dispose.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. # no matter what happens, we should increment a 10 times. log = -> console.log a++, process.domain setTimeout log, 20 if a < 10 return # in 50ms we'll throw an error. err = -> err2 = -> # this timeout should never be called, since the domain gets # disposed when the error happens. setTimeout -> console.error "This should not happen." disposalFailed = true process.exit 1 return # this function doesn't exist, and throws an error as a result. err3() return handle = (e) -> # this should clean up everything properly. d.dispose() console.error e console.error "in handler", process.domain, process.domain is d return d = domain.create() d.on "error", handle d.run err2 return common = require("../common.js") assert = require("assert") domain = require("domain") disposalFailed = false a = 0 log() setTimeout err, 50 process.on "exit", -> assert.equal a, 10 assert.equal disposalFailed, false console.log "ok" return
7049
# 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. # no matter what happens, we should increment a 10 times. log = -> console.log a++, process.domain setTimeout log, 20 if a < 10 return # in 50ms we'll throw an error. err = -> err2 = -> # this timeout should never be called, since the domain gets # disposed when the error happens. setTimeout -> console.error "This should not happen." disposalFailed = true process.exit 1 return # this function doesn't exist, and throws an error as a result. err3() return handle = (e) -> # this should clean up everything properly. d.dispose() console.error e console.error "in handler", process.domain, process.domain is d return d = domain.create() d.on "error", handle d.run err2 return common = require("../common.js") assert = require("assert") domain = require("domain") disposalFailed = false a = 0 log() setTimeout err, 50 process.on "exit", -> assert.equal a, 10 assert.equal disposalFailed, false 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. # no matter what happens, we should increment a 10 times. log = -> console.log a++, process.domain setTimeout log, 20 if a < 10 return # in 50ms we'll throw an error. err = -> err2 = -> # this timeout should never be called, since the domain gets # disposed when the error happens. setTimeout -> console.error "This should not happen." disposalFailed = true process.exit 1 return # this function doesn't exist, and throws an error as a result. err3() return handle = (e) -> # this should clean up everything properly. d.dispose() console.error e console.error "in handler", process.domain, process.domain is d return d = domain.create() d.on "error", handle d.run err2 return common = require("../common.js") assert = require("assert") domain = require("domain") disposalFailed = false a = 0 log() setTimeout err, 50 process.on "exit", -> assert.equal a, 10 assert.equal disposalFailed, false console.log "ok" return
[ { "context": "regresar\"\n cancel: \"Cancelar\"\n changePassword: \"Cambiar Contraseña\"\n choosePassword: \"Eligir Contraseña\"\n clickAgr", "end": 213, "score": 0.9886507987976074, "start": 195, "tag": "PASSWORD", "value": "Cambiar Contraseña" }, { "context": "Password: \"Cambi...
t9n/es_ES.coffee
coWorkr-InSights/meteor-accounts-t9n
0
#Language: Spanish #Translators: softwarerero, maomorales, mortaldraw es_ES = t9Name: 'Español-España' add: "agregar" and: "y" back: "regresar" cancel: "Cancelar" changePassword: "Cambiar Contraseña" choosePassword: "Eligir Contraseña" clickAgree: "Si haces clic en Crear Cuenta estás de acuerdo con la" configure: "Configurar" createAccount: "Crear cuenta" currentPassword: "Contraseña actual" dontHaveAnAccount: "¿No estás registrado?" email: "Correo electrónico" emailAddress: "Correo electrónico" emailResetLink: "Restaurar dirección de correo electrónico" forgotPassword: "¿Has olvidado tu contraseña?" ifYouAlreadyHaveAnAccount: "Si ya tienes una cuenta, " newPassword: "Nueva Contraseña" newPasswordAgain: "Nueva Contraseña (repetición)" optional: "Opcional" OR: "O" password: "Contraseña" passwordAgain: "Contraseña (repetición)" privacyPolicy: "Póliza de Privacidad" remove: "remover" resetYourPassword: "Recuperar contraseña" setPassword: "Definir Contraseña" sign: "Entrar" signIn: "Entrar" signin: "entra" signOut: "Salir" signUp: "Regístrate" signupCode: "Código para registrarte" signUpWithYourEmailAddress: "Regístrate con tu correo electrónico" terms: "Términos de Uso" updateYourPassword: "Actualizar tu contraseña" username: "Usuario" usernameOrEmail: "Usuario o correo electrónico" with: "con" maxAllowedLength: "Longitud máxima permitida" minRequiredLength: "Longitud máxima requerida" resendVerificationEmail: "Mandar correo de nuevo" resendVerificationEmailLink_pre: "Correo de verificación perdido?" resendVerificationEmailLink_link: "Volver a mandar" enterPassword: "Introducir contraseña" enterNewPassword: "Introducir contraseña nueva" enterEmail: "Introducir correo electrónico" enterUsername: "Introducir nombre de usuario" enterUsernameOrEmail: "Introducir nombre de usuario o correo electrónico" orUse: "O puedes usar" "Required Field": "Compo requerido" info: emailSent: "Mensaje enviado" emailVerified: "Dirección de correo verificada" passwordChanged: "Contraseña cambiada" passwordReset: "Resetar Contraseña" alert: ok: 'Ok' type: info: 'Aviso' error: 'Error' warning: 'Advertencia' error: emailRequired: "La dirección de correo electrónico es necesaria." minChar: "7 carácteres mínimo." pwdsDontMatch: "Contraseñas no coinciden" pwOneDigit: "mínimo un dígito." pwOneLetter: "mínimo una letra." signInRequired: "Debes iniciar sesión para esta opción." signupCodeIncorrect: "Código de registro inválido." signupCodeRequired: "Se requiere un código de registro." usernameIsEmail: "El usuario no puede ser una dirección de correo." usernameRequired: "Se requiere nombre de usuario." accounts: #---- accounts-base #"@" + domain + " email required": #"A login handler should return a result or undefined": "Email already exists.": "El correo ya existe." "Email doesn't match the criteria.": "El correo no coincide." "Invalid login token": "Token de inicio de sesión inválido" "Login forbidden": "Inicio de sesión prohibido" #"Service " + options.service + " already configured": "Service unknown": "Servicio desconocido" "Unrecognized options for login request": "Opciones desconocidas para solicitud de inicio de sesión" "User validation failed": "No se ha podido validar el usuario" "Username already exists.": "El usuario ya existe." "You are not logged in.": "No estás conectado." "You've been logged out by the server. Please log in again.": "Has sido desconectado por el servidor. Por favor inicia sesión de nuevo." "Your session has expired. Please log in again.": "Tu sesión ha expirado. Por favor inicia sesión de nuevo." "Already verified": "Ya ha sido verificada" "Invalid email or username": "Dirección electrónica o nombre de usuario no validos" "Internal server error": "Error interno del servidor" "undefined": "Algo ha ido mal" #---- accounts-oauth "No matching login attempt found": "Ningún intento de inicio de sesión coincidente se encontró" #---- accounts-password-client "Password is old. Please reset your password.": "Contraseña es vieja. Por favor, resetea la contraseña." #---- accounts-password "Incorrect password": "Contraseña inválida." "Invalid email": "Correo electrónico inválido" "Must be logged in": "Debes ingresar" "Need to set a username or email": "Tienes que especificar un usuario o una dirección de correo" "old password format": "formato viejo de contraseña" "Password may not be empty": "Contraseña no debe quedar vacía" "Signups forbidden": "Registro prohibido" "Token expired": "Token expirado" "Token has invalid email address": "Token contiene una dirección electrónica inválido" "User has no password set": "Usuario no tiene contraseña" "User not found": "Usuario no encontrado" "Verify email link expired": "El enlace para verificar el correo electrónico ha expirado" "Verify email link is for unknown address": "El enlace para verificar el correo electrónico contiene una dirección desconocida" "At least 1 digit, 1 lowercase and 1 uppercase": "Al menos tiene que contener un número, una minúscula y una mayúscula" "Please verify your email first. Check the email and follow the link!": "Por favor comprueba tu correo electrónico primero. Sigue el link que te ha sido enviado." "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nuevo correo te ha sido enviado. Si no ves el correo en tu bandeja comprueba tu carpeta de spam." #---- match "Match failed": "No ha habido ninguna coincidencia" #---- Misc... "Unknown error": "Error desconocido" "Error, too many requests. Please slow down. You must wait 1 seconds before trying again.": "Error, demasiadas peticiones. Por favor no vayas tan rapido. Tienes que esperar al menos un segundo antes de probar otra vez." T9n?.map "es_ES", es_ES module?.exports = es_ES
205974
#Language: Spanish #Translators: softwarerero, maomorales, mortaldraw es_ES = t9Name: 'Español-España' add: "agregar" and: "y" back: "regresar" cancel: "Cancelar" changePassword: "<PASSWORD>" choosePassword: "<PASSWORD>" clickAgree: "Si haces clic en Crear Cuenta estás de acuerdo con la" configure: "Configurar" createAccount: "Crear cuenta" currentPassword: "<PASSWORD>" dontHaveAnAccount: "¿No estás registrado?" email: "Correo electrónico" emailAddress: "Correo electrónico" emailResetLink: "Restaurar dirección de correo electrónico" forgotPassword: "<PASSWORD> tu <PASSWORD>?" ifYouAlreadyHaveAnAccount: "Si ya tienes una cuenta, " newPassword: "<PASSWORD>" newPasswordAgain: "<PASSWORD> (<PASSWORD>)" optional: "Opcional" OR: "O" password: "<PASSWORD>" passwordAgain: "<PASSWORD>)" privacyPolicy: "Póliza de Privacidad" remove: "remover" resetYourPassword: "<PASSWORD>" setPassword: "<PASSWORD>" sign: "Entrar" signIn: "Entrar" signin: "entra" signOut: "Salir" signUp: "Regístrate" signupCode: "Código para registrarte" signUpWithYourEmailAddress: "Regístrate con tu correo electrónico" terms: "Términos de Uso" updateYourPassword: "<PASSWORD>" username: "Usuario" usernameOrEmail: "Usuario o correo electrónico" with: "con" maxAllowedLength: "Longitud máxima permitida" minRequiredLength: "Longitud máxima requerida" resendVerificationEmail: "Mandar correo de nuevo" resendVerificationEmailLink_pre: "Correo de verificación perdido?" resendVerificationEmailLink_link: "Volver a mandar" enterPassword: "<PASSWORD>" enterNewPassword: "<PASSWORD>" enterEmail: "Introducir correo electrónico" enterUsername: "Introducir nombre de usuario" enterUsernameOrEmail: "Introducir nombre de usuario o correo electrónico" orUse: "O puedes usar" "Required Field": "Compo requerido" info: emailSent: "Mensaje enviado" emailVerified: "Dirección de correo verificada" passwordChanged: "Contr<PASSWORD> cambi<PASSWORD>" passwordReset: "<PASSWORD>" alert: ok: 'Ok' type: info: 'Aviso' error: 'Error' warning: 'Advertencia' error: emailRequired: "La dirección de correo electrónico es necesaria." minChar: "7 carácteres mínimo." pwdsDontMatch: "Contraseñas no coinciden" pwOneDigit: "mínimo un dígito." pwOneLetter: "mínimo una letra." signInRequired: "Debes iniciar sesión para esta opción." signupCodeIncorrect: "Código de registro inválido." signupCodeRequired: "Se requiere un código de registro." usernameIsEmail: "El usuario no puede ser una dirección de correo." usernameRequired: "Se requiere nombre de usuario." accounts: #---- accounts-base #"@" + domain + " email required": #"A login handler should return a result or undefined": "Email already exists.": "El correo ya existe." "Email doesn't match the criteria.": "El correo no coincide." "Invalid login token": "Token de inicio de sesión inválido" "Login forbidden": "Inicio de sesión prohibido" #"Service " + options.service + " already configured": "Service unknown": "Servicio desconocido" "Unrecognized options for login request": "Opciones desconocidas para solicitud de inicio de sesión" "User validation failed": "No se ha podido validar el usuario" "Username already exists.": "El usuario ya existe." "You are not logged in.": "No estás conectado." "You've been logged out by the server. Please log in again.": "Has sido desconectado por el servidor. Por favor inicia sesión de nuevo." "Your session has expired. Please log in again.": "Tu sesión ha expirado. Por favor inicia sesión de nuevo." "Already verified": "Ya ha sido verificada" "Invalid email or username": "Dirección electrónica o nombre de usuario no validos" "Internal server error": "Error interno del servidor" "undefined": "Algo ha ido mal" #---- accounts-oauth "No matching login attempt found": "Ningún intento de inicio de sesión coincidente se encontró" #---- accounts-password-client "Password is old. Please reset your password.": "Contraseña es vieja. Por favor, resetea la contraseña." #---- accounts-password "Incorrect password": "Contraseña inválida." "Invalid email": "Correo electrónico inválido" "Must be logged in": "Debes ingresar" "Need to set a username or email": "Tienes que especificar un usuario o una dirección de correo" "old password format": "formato viejo de contraseña" "Password may not be empty": "Contraseña no debe quedar vacía" "Signups forbidden": "Registro prohibido" "Token expired": "Token expirado" "Token has invalid email address": "Token contiene una dirección electrónica inválido" "User has no password set": "Usuario no tiene contraseña" "User not found": "Usuario no encontrado" "Verify email link expired": "El enlace para verificar el correo electrónico ha expirado" "Verify email link is for unknown address": "El enlace para verificar el correo electrónico contiene una dirección desconocida" "At least 1 digit, 1 lowercase and 1 uppercase": "Al menos tiene que contener un número, una minúscula y una mayúscula" "Please verify your email first. Check the email and follow the link!": "Por favor comprueba tu correo electrónico primero. Sigue el link que te ha sido enviado." "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nuevo correo te ha sido enviado. Si no ves el correo en tu bandeja comprueba tu carpeta de spam." #---- match "Match failed": "No ha habido ninguna coincidencia" #---- Misc... "Unknown error": "Error desconocido" "Error, too many requests. Please slow down. You must wait 1 seconds before trying again.": "Error, demasiadas peticiones. Por favor no vayas tan rapido. Tienes que esperar al menos un segundo antes de probar otra vez." T9n?.map "es_ES", es_ES module?.exports = es_ES
true
#Language: Spanish #Translators: softwarerero, maomorales, mortaldraw es_ES = t9Name: 'Español-España' add: "agregar" and: "y" back: "regresar" cancel: "Cancelar" changePassword: "PI:PASSWORD:<PASSWORD>END_PI" choosePassword: "PI:PASSWORD:<PASSWORD>END_PI" clickAgree: "Si haces clic en Crear Cuenta estás de acuerdo con la" configure: "Configurar" createAccount: "Crear cuenta" currentPassword: "PI:PASSWORD:<PASSWORD>END_PI" dontHaveAnAccount: "¿No estás registrado?" email: "Correo electrónico" emailAddress: "Correo electrónico" emailResetLink: "Restaurar dirección de correo electrónico" forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI tu PI:PASSWORD:<PASSWORD>END_PI?" ifYouAlreadyHaveAnAccount: "Si ya tienes una cuenta, " newPassword: "PI:PASSWORD:<PASSWORD>END_PI" newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI (PI:PASSWORD:<PASSWORD>END_PI)" optional: "Opcional" OR: "O" password: "PI:PASSWORD:<PASSWORD>END_PI" passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI)" privacyPolicy: "Póliza de Privacidad" remove: "remover" resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI" setPassword: "PI:PASSWORD:<PASSWORD>END_PI" sign: "Entrar" signIn: "Entrar" signin: "entra" signOut: "Salir" signUp: "Regístrate" signupCode: "Código para registrarte" signUpWithYourEmailAddress: "Regístrate con tu correo electrónico" terms: "Términos de Uso" updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI" username: "Usuario" usernameOrEmail: "Usuario o correo electrónico" with: "con" maxAllowedLength: "Longitud máxima permitida" minRequiredLength: "Longitud máxima requerida" resendVerificationEmail: "Mandar correo de nuevo" resendVerificationEmailLink_pre: "Correo de verificación perdido?" resendVerificationEmailLink_link: "Volver a mandar" enterPassword: "PI:PASSWORD:<PASSWORD>END_PI" enterNewPassword: "PI:PASSWORD:<PASSWORD>END_PI" enterEmail: "Introducir correo electrónico" enterUsername: "Introducir nombre de usuario" enterUsernameOrEmail: "Introducir nombre de usuario o correo electrónico" orUse: "O puedes usar" "Required Field": "Compo requerido" info: emailSent: "Mensaje enviado" emailVerified: "Dirección de correo verificada" passwordChanged: "ContrPI:PASSWORD:<PASSWORD>END_PI cambiPI:PASSWORD:<PASSWORD>END_PI" passwordReset: "PI:PASSWORD:<PASSWORD>END_PI" alert: ok: 'Ok' type: info: 'Aviso' error: 'Error' warning: 'Advertencia' error: emailRequired: "La dirección de correo electrónico es necesaria." minChar: "7 carácteres mínimo." pwdsDontMatch: "Contraseñas no coinciden" pwOneDigit: "mínimo un dígito." pwOneLetter: "mínimo una letra." signInRequired: "Debes iniciar sesión para esta opción." signupCodeIncorrect: "Código de registro inválido." signupCodeRequired: "Se requiere un código de registro." usernameIsEmail: "El usuario no puede ser una dirección de correo." usernameRequired: "Se requiere nombre de usuario." accounts: #---- accounts-base #"@" + domain + " email required": #"A login handler should return a result or undefined": "Email already exists.": "El correo ya existe." "Email doesn't match the criteria.": "El correo no coincide." "Invalid login token": "Token de inicio de sesión inválido" "Login forbidden": "Inicio de sesión prohibido" #"Service " + options.service + " already configured": "Service unknown": "Servicio desconocido" "Unrecognized options for login request": "Opciones desconocidas para solicitud de inicio de sesión" "User validation failed": "No se ha podido validar el usuario" "Username already exists.": "El usuario ya existe." "You are not logged in.": "No estás conectado." "You've been logged out by the server. Please log in again.": "Has sido desconectado por el servidor. Por favor inicia sesión de nuevo." "Your session has expired. Please log in again.": "Tu sesión ha expirado. Por favor inicia sesión de nuevo." "Already verified": "Ya ha sido verificada" "Invalid email or username": "Dirección electrónica o nombre de usuario no validos" "Internal server error": "Error interno del servidor" "undefined": "Algo ha ido mal" #---- accounts-oauth "No matching login attempt found": "Ningún intento de inicio de sesión coincidente se encontró" #---- accounts-password-client "Password is old. Please reset your password.": "Contraseña es vieja. Por favor, resetea la contraseña." #---- accounts-password "Incorrect password": "Contraseña inválida." "Invalid email": "Correo electrónico inválido" "Must be logged in": "Debes ingresar" "Need to set a username or email": "Tienes que especificar un usuario o una dirección de correo" "old password format": "formato viejo de contraseña" "Password may not be empty": "Contraseña no debe quedar vacía" "Signups forbidden": "Registro prohibido" "Token expired": "Token expirado" "Token has invalid email address": "Token contiene una dirección electrónica inválido" "User has no password set": "Usuario no tiene contraseña" "User not found": "Usuario no encontrado" "Verify email link expired": "El enlace para verificar el correo electrónico ha expirado" "Verify email link is for unknown address": "El enlace para verificar el correo electrónico contiene una dirección desconocida" "At least 1 digit, 1 lowercase and 1 uppercase": "Al menos tiene que contener un número, una minúscula y una mayúscula" "Please verify your email first. Check the email and follow the link!": "Por favor comprueba tu correo electrónico primero. Sigue el link que te ha sido enviado." "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nuevo correo te ha sido enviado. Si no ves el correo en tu bandeja comprueba tu carpeta de spam." #---- match "Match failed": "No ha habido ninguna coincidencia" #---- Misc... "Unknown error": "Error desconocido" "Error, too many requests. Please slow down. You must wait 1 seconds before trying again.": "Error, demasiadas peticiones. Por favor no vayas tan rapido. Tienes que esperar al menos un segundo antes de probar otra vez." T9n?.map "es_ES", es_ES module?.exports = es_ES
[ { "context": "9bc\",\n \"anonymous\" : false,\n \"email\" : \"example@email.com\",\n \"name\" : \"Joe\",\n \"app_id\" : \"...\",\n ", "end": 857, "score": 0.9999065399169922, "start": 840, "tag": "EMAIL", "value": "example@email.com" }, { "context": " \"email\" ...
spec/server/functional/intercom.spec.coffee
IngJuanRuiz/codecombat
0
utils = require '../utils' request = require '../request' unsubscribe = require '../../../server/commons/unsubscribe' pingJson = { "type" : "notification_event", "app_id" : "...", "data" : { "type" : "notification_event_data", "item" : { "type" : "ping", "message" : "something something interzen" } }, "links" : { }, "id" : null, "topic" : "ping", "delivery_status" : null, "delivery_attempts" : 1, "delivered_at" : 0, "first_sent_at" : 1526489523, "created_at" : 1526489523, "self" : null } unsubscribeJson = { "type" : "notification_event", "app_id" : "...", "data" : { "type" : "notification_event_data", "item" : { "type" : "user", "id" : "5afc6213d65aaf1cc4ce855a", "user_id" : "5afc61e3dc1bd800474819bc", "anonymous" : false, "email" : "example@email.com", "name" : "Joe", "app_id" : "...", "unsubscribed_from_emails" : true, # many more attributes "custom_attributes" : { } } }, "links" : { }, "id" : "notif_e8c70b50-5929-11e8-ab2a-b3711290f1cd", "topic" : "user.unsubscribed", "delivery_status" : "pending", "delivery_attempts" : 1, "delivered_at" : 0, "first_sent_at" : 1526489716, "created_at" : 1526489716, "self" : null } url = utils.getUrl('/webhooks/intercom') describe 'POST /webhooks/intercom', -> it 'returns 200 when it receives a ping', utils.wrap -> [res] = yield request.postAsync({url, json: pingJson, headers: { 'x-hub-signature': 'sha1=d3b43375515b1efe15839e4ce84b47ab7e0346db' }}) expect(res.statusCode).toBe(200) it 'calls unsubscribe.unsubscribeEmailFromMarketingEmails for the given email for user.unsubscribed events', utils.wrap -> spyOn(unsubscribe, 'unsubscribeEmailFromMarketingEmails') [res] = yield request.postAsync({url, json: unsubscribeJson, headers: { 'x-hub-signature': 'sha1=ebdf7fb43eafbbff8927625cea221131b03b170c' }}) expect(res.statusCode).toBe(200) expect(unsubscribe.unsubscribeEmailFromMarketingEmails).toHaveBeenCalled() expect(unsubscribe.unsubscribeEmailFromMarketingEmails.calls.argsFor(0)[0]).toBe(unsubscribeJson.data.item.email)
68771
utils = require '../utils' request = require '../request' unsubscribe = require '../../../server/commons/unsubscribe' pingJson = { "type" : "notification_event", "app_id" : "...", "data" : { "type" : "notification_event_data", "item" : { "type" : "ping", "message" : "something something interzen" } }, "links" : { }, "id" : null, "topic" : "ping", "delivery_status" : null, "delivery_attempts" : 1, "delivered_at" : 0, "first_sent_at" : 1526489523, "created_at" : 1526489523, "self" : null } unsubscribeJson = { "type" : "notification_event", "app_id" : "...", "data" : { "type" : "notification_event_data", "item" : { "type" : "user", "id" : "5afc6213d65aaf1cc4ce855a", "user_id" : "5afc61e3dc1bd800474819bc", "anonymous" : false, "email" : "<EMAIL>", "name" : "<NAME>", "app_id" : "...", "unsubscribed_from_emails" : true, # many more attributes "custom_attributes" : { } } }, "links" : { }, "id" : "notif_e8c70b50-5929-11e8-ab2a-b3711290f1cd", "topic" : "user.unsubscribed", "delivery_status" : "pending", "delivery_attempts" : 1, "delivered_at" : 0, "first_sent_at" : 1526489716, "created_at" : 1526489716, "self" : null } url = utils.getUrl('/webhooks/intercom') describe 'POST /webhooks/intercom', -> it 'returns 200 when it receives a ping', utils.wrap -> [res] = yield request.postAsync({url, json: pingJson, headers: { 'x-hub-signature': 'sha1=d3b43375515b1efe15839e4ce84b47ab7e0346db' }}) expect(res.statusCode).toBe(200) it 'calls unsubscribe.unsubscribeEmailFromMarketingEmails for the given email for user.unsubscribed events', utils.wrap -> spyOn(unsubscribe, 'unsubscribeEmailFromMarketingEmails') [res] = yield request.postAsync({url, json: unsubscribeJson, headers: { 'x-hub-signature': 'sha1=ebdf7fb43eafbbff8927625cea221131b03b170c' }}) expect(res.statusCode).toBe(200) expect(unsubscribe.unsubscribeEmailFromMarketingEmails).toHaveBeenCalled() expect(unsubscribe.unsubscribeEmailFromMarketingEmails.calls.argsFor(0)[0]).toBe(unsubscribeJson.data.item.email)
true
utils = require '../utils' request = require '../request' unsubscribe = require '../../../server/commons/unsubscribe' pingJson = { "type" : "notification_event", "app_id" : "...", "data" : { "type" : "notification_event_data", "item" : { "type" : "ping", "message" : "something something interzen" } }, "links" : { }, "id" : null, "topic" : "ping", "delivery_status" : null, "delivery_attempts" : 1, "delivered_at" : 0, "first_sent_at" : 1526489523, "created_at" : 1526489523, "self" : null } unsubscribeJson = { "type" : "notification_event", "app_id" : "...", "data" : { "type" : "notification_event_data", "item" : { "type" : "user", "id" : "5afc6213d65aaf1cc4ce855a", "user_id" : "5afc61e3dc1bd800474819bc", "anonymous" : false, "email" : "PI:EMAIL:<EMAIL>END_PI", "name" : "PI:NAME:<NAME>END_PI", "app_id" : "...", "unsubscribed_from_emails" : true, # many more attributes "custom_attributes" : { } } }, "links" : { }, "id" : "notif_e8c70b50-5929-11e8-ab2a-b3711290f1cd", "topic" : "user.unsubscribed", "delivery_status" : "pending", "delivery_attempts" : 1, "delivered_at" : 0, "first_sent_at" : 1526489716, "created_at" : 1526489716, "self" : null } url = utils.getUrl('/webhooks/intercom') describe 'POST /webhooks/intercom', -> it 'returns 200 when it receives a ping', utils.wrap -> [res] = yield request.postAsync({url, json: pingJson, headers: { 'x-hub-signature': 'sha1=d3b43375515b1efe15839e4ce84b47ab7e0346db' }}) expect(res.statusCode).toBe(200) it 'calls unsubscribe.unsubscribeEmailFromMarketingEmails for the given email for user.unsubscribed events', utils.wrap -> spyOn(unsubscribe, 'unsubscribeEmailFromMarketingEmails') [res] = yield request.postAsync({url, json: unsubscribeJson, headers: { 'x-hub-signature': 'sha1=ebdf7fb43eafbbff8927625cea221131b03b170c' }}) expect(res.statusCode).toBe(200) expect(unsubscribe.unsubscribeEmailFromMarketingEmails).toHaveBeenCalled() expect(unsubscribe.unsubscribeEmailFromMarketingEmails.calls.argsFor(0)[0]).toBe(unsubscribeJson.data.item.email)
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9979743957519531, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-url.parse-https.request.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. # https options check = (request) -> # assert that I'm https assert.ok request.socket._secureEstablished return common = require("../common") assert = require("assert") https = require("https") url = require("url") fs = require("fs") clientRequest = undefined httpsOptions = key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem") cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem") testURL = url.parse("https://localhost:" + common.PORT) testURL.rejectUnauthorized = false server = https.createServer(httpsOptions, (request, response) -> # run the check function check.call this, request, response response.writeHead 200, {} response.end "ok" server.close() return ) server.listen common.PORT, -> # make the request clientRequest = https.request(testURL) # since there is a little magic with the agent # make sure that the request uses the https.Agent assert.ok clientRequest.agent instanceof https.Agent clientRequest.end() return
122379
# 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. # https options check = (request) -> # assert that I'm https assert.ok request.socket._secureEstablished return common = require("../common") assert = require("assert") https = require("https") url = require("url") fs = require("fs") clientRequest = undefined httpsOptions = key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem") cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem") testURL = url.parse("https://localhost:" + common.PORT) testURL.rejectUnauthorized = false server = https.createServer(httpsOptions, (request, response) -> # run the check function check.call this, request, response response.writeHead 200, {} response.end "ok" server.close() return ) server.listen common.PORT, -> # make the request clientRequest = https.request(testURL) # since there is a little magic with the agent # make sure that the request uses the https.Agent assert.ok clientRequest.agent instanceof https.Agent clientRequest.end() 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. # https options check = (request) -> # assert that I'm https assert.ok request.socket._secureEstablished return common = require("../common") assert = require("assert") https = require("https") url = require("url") fs = require("fs") clientRequest = undefined httpsOptions = key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem") cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem") testURL = url.parse("https://localhost:" + common.PORT) testURL.rejectUnauthorized = false server = https.createServer(httpsOptions, (request, response) -> # run the check function check.call this, request, response response.writeHead 200, {} response.end "ok" server.close() return ) server.listen common.PORT, -> # make the request clientRequest = https.request(testURL) # since there is a little magic with the agent # make sure that the request uses the https.Agent assert.ok clientRequest.agent instanceof https.Agent clientRequest.end() return
[ { "context": "# @author Gianluigi Mango\n# Handle User API\nUserModel = require './../model", "end": 25, "score": 0.9998371005058289, "start": 10, "tag": "NAME", "value": "Gianluigi Mango" } ]
dev/server/api/handler/userHandler.coffee
knickatheart/mean-api
0
# @author Gianluigi Mango # Handle User API UserModel = require './../model/userModel' PostModel = require './../model/postModel' PostHandler = require './postHandler' Notify = require './../utils/Notifier' bcrypt = require 'bcrypt-nodejs' module.exports = class userHandler # Check if there is an active session constructor: (@req) -> @userModel = new UserModel @postModel = new PostModel @postHandler = new PostHandler checkSession: (req, res) -> if not req.session.user then new Notify 'Not in session', res, 1 else new Notify req.session.user, res, false getInfo: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists @postModel.getAll exists[0]._id, (err, body) -> if not err exists.push body new Notify exists, res, false else new Notify err, res, true else new Notify 'User does not exist', res, true addUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists new Notify 'User already exists', res, 1 else bcrypt.genSalt 10, (err, salt) => if err throw err else bcrypt.hash path[1][1], salt, (err) => if err then new Notify err, res, true , (err, hash) => path[1][1] = hash @userModel.addUser path, (err, body) => unless err then new Notify body, res, false else new Notify err, res, true deleteUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if not exists new Notify 'User does not exist', res, 1 else @userModel.deleteUser exists[0]._id, (err, body) -> unless err then new Notify 'Deleted successfully', res, false else console.log new Notify err, res, true loginUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists if bcrypt.compareSync path[1][1], exists[0].password @postHandler.getAll exists[0]._id, (err, body) => if not err exists.push body console.log body @setSession exists, res else new Notify err, res, true else new Notify 'Wrong password', res, true else new Notify 'User not found', res, true logout: (path, res) -> @req.session.reset() new Notify 'User logged out', res, false setSession: (user, res) -> @req.session.user = user[0] res.locals.user = user[0] new Notify user, res, false
28791
# @author <NAME> # Handle User API UserModel = require './../model/userModel' PostModel = require './../model/postModel' PostHandler = require './postHandler' Notify = require './../utils/Notifier' bcrypt = require 'bcrypt-nodejs' module.exports = class userHandler # Check if there is an active session constructor: (@req) -> @userModel = new UserModel @postModel = new PostModel @postHandler = new PostHandler checkSession: (req, res) -> if not req.session.user then new Notify 'Not in session', res, 1 else new Notify req.session.user, res, false getInfo: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists @postModel.getAll exists[0]._id, (err, body) -> if not err exists.push body new Notify exists, res, false else new Notify err, res, true else new Notify 'User does not exist', res, true addUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists new Notify 'User already exists', res, 1 else bcrypt.genSalt 10, (err, salt) => if err throw err else bcrypt.hash path[1][1], salt, (err) => if err then new Notify err, res, true , (err, hash) => path[1][1] = hash @userModel.addUser path, (err, body) => unless err then new Notify body, res, false else new Notify err, res, true deleteUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if not exists new Notify 'User does not exist', res, 1 else @userModel.deleteUser exists[0]._id, (err, body) -> unless err then new Notify 'Deleted successfully', res, false else console.log new Notify err, res, true loginUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists if bcrypt.compareSync path[1][1], exists[0].password @postHandler.getAll exists[0]._id, (err, body) => if not err exists.push body console.log body @setSession exists, res else new Notify err, res, true else new Notify 'Wrong password', res, true else new Notify 'User not found', res, true logout: (path, res) -> @req.session.reset() new Notify 'User logged out', res, false setSession: (user, res) -> @req.session.user = user[0] res.locals.user = user[0] new Notify user, res, false
true
# @author PI:NAME:<NAME>END_PI # Handle User API UserModel = require './../model/userModel' PostModel = require './../model/postModel' PostHandler = require './postHandler' Notify = require './../utils/Notifier' bcrypt = require 'bcrypt-nodejs' module.exports = class userHandler # Check if there is an active session constructor: (@req) -> @userModel = new UserModel @postModel = new PostModel @postHandler = new PostHandler checkSession: (req, res) -> if not req.session.user then new Notify 'Not in session', res, 1 else new Notify req.session.user, res, false getInfo: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists @postModel.getAll exists[0]._id, (err, body) -> if not err exists.push body new Notify exists, res, false else new Notify err, res, true else new Notify 'User does not exist', res, true addUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists new Notify 'User already exists', res, 1 else bcrypt.genSalt 10, (err, salt) => if err throw err else bcrypt.hash path[1][1], salt, (err) => if err then new Notify err, res, true , (err, hash) => path[1][1] = hash @userModel.addUser path, (err, body) => unless err then new Notify body, res, false else new Notify err, res, true deleteUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if not exists new Notify 'User does not exist', res, 1 else @userModel.deleteUser exists[0]._id, (err, body) -> unless err then new Notify 'Deleted successfully', res, false else console.log new Notify err, res, true loginUser: (path, res) -> @userModel.findUser path[0][1], (exists) => if exists if bcrypt.compareSync path[1][1], exists[0].password @postHandler.getAll exists[0]._id, (err, body) => if not err exists.push body console.log body @setSession exists, res else new Notify err, res, true else new Notify 'Wrong password', res, true else new Notify 'User not found', res, true logout: (path, res) -> @req.session.reset() new Notify 'User logged out', res, false setSession: (user, res) -> @req.session.user = user[0] res.locals.user = user[0] new Notify user, res, false
[ { "context": ".helpers\n name: -> Meteor.user().profile.name ? \"User\"\n email: -> Meteor.user().emails?[0]?.address ? ", "end": 70, "score": 0.5020297765731812, "start": 66, "tag": "NAME", "value": "User" } ]
client/templates/profile/profile.coffee
orlade/cortex
4
Template.profile.helpers name: -> Meteor.user().profile.name ? "User" email: -> Meteor.user().emails?[0]?.address ? Meteor.user().services?.google?.email ? "None" awsSet: -> Meteor.user().profile.awsSet Template.profile.events 'click .aws.button': -> [modal, form] = [$('.aws.modal'), $('.aws.form')] modal.modal('show') get = (name) -> form.form('get value', name) form.submit (e) -> e.preventDefault() Meteor.call 'setAwsCredentials', get('accessKeyId'), get('secretAccessKey'), (err, res) -> if err then return log.error "Error setting AWS credentials", err closeForm() 'click .cancel.button': -> closeForm() closeForm = -> $('.aws.form').form('clear') $('.aws.modal').modal('hide')
88121
Template.profile.helpers name: -> Meteor.user().profile.name ? "<NAME>" email: -> Meteor.user().emails?[0]?.address ? Meteor.user().services?.google?.email ? "None" awsSet: -> Meteor.user().profile.awsSet Template.profile.events 'click .aws.button': -> [modal, form] = [$('.aws.modal'), $('.aws.form')] modal.modal('show') get = (name) -> form.form('get value', name) form.submit (e) -> e.preventDefault() Meteor.call 'setAwsCredentials', get('accessKeyId'), get('secretAccessKey'), (err, res) -> if err then return log.error "Error setting AWS credentials", err closeForm() 'click .cancel.button': -> closeForm() closeForm = -> $('.aws.form').form('clear') $('.aws.modal').modal('hide')
true
Template.profile.helpers name: -> Meteor.user().profile.name ? "PI:NAME:<NAME>END_PI" email: -> Meteor.user().emails?[0]?.address ? Meteor.user().services?.google?.email ? "None" awsSet: -> Meteor.user().profile.awsSet Template.profile.events 'click .aws.button': -> [modal, form] = [$('.aws.modal'), $('.aws.form')] modal.modal('show') get = (name) -> form.form('get value', name) form.submit (e) -> e.preventDefault() Meteor.call 'setAwsCredentials', get('accessKeyId'), get('secretAccessKey'), (err, res) -> if err then return log.error "Error setting AWS credentials", err closeForm() 'click .cancel.button': -> closeForm() closeForm = -> $('.aws.form').form('clear') $('.aws.modal').modal('hide')
[ { "context": "m() * 99999999 + 900000000)\n\n #this.username1 = 'arielyang'\n #this.username2 = 'novasman'\n #this.username3", "end": 539, "score": 0.9995627403259277, "start": 530, "tag": "USERNAME", "value": "arielyang" }, { "context": "this.username1 = 'arielyang'\n #this.user...
spec/helpers/helper.coffee
lly5401/dhcseltalkserver
1
request = require 'supertest' cookie = require 'cookie' _ = require 'underscore' app = require '../../src' config = require '../../src/conf' Utility = require('../../src/util/util').Utility # 引用数据库对象和模型 [sequelize, User] = require '../../src/db' beforeAll -> this.phoneNumber1 = '13' + Math.floor(Math.random() * 99999999 + 900000000) this.phoneNumber2 = '13' + Math.floor(Math.random() * 99999999 + 900000000) this.phoneNumber3 = '13' + Math.floor(Math.random() * 99999999 + 900000000) #this.username1 = 'arielyang' #this.username2 = 'novasman' #this.username3 = 'luckyjiang' this.nickname1 = 'Ariel Yang' this.nickname2 = 'Novas Man' this.nickname3 = 'Lucky Jiang' this.userId1 = null this.userId2 = null this.userId3 = null this.password = 'P@ssw0rd' this.passwordNew = 'P@ssw0rdNew' this.groupName1 = 'Business' this.groupName2 = 'Product' this.groupId1 = null this.groupId2 = null this.userCookie1 = null this.userCookie2 = null this.userCookie3 = null this.xssString = '<a>hello</a>' this.filteredString = '&lt;a&gt;hello&lt;/a&gt;' getAuthCookieValue = (res) -> cookieHeader = res.header['set-cookie'] if cookieHeader if Array.isArray cookieHeader cookieHeader = cookieHeader[0] return authCookieValue = cookie.parse(cookieHeader)[config.AUTH_COOKIE_NAME] return null this.testPOSTAPI = (path, cookieValue, params, statusCode, testBody, callback) -> _this = this if arguments.length is 5 callback = testBody testBody = statusCode statusCode = params params = cookieValue cookieValue = '' setTimeout -> request app .post path .set 'Cookie', config.AUTH_COOKIE_NAME + '=' + cookieValue .type 'json' .send params .end (err, res) -> _this.testHTTPResult err, res, statusCode, testBody callback res.body, getAuthCookieValue(res) if callback , 10 this.testGETAPI = (path, cookieValue, statusCode, testBody, callback) -> _this = this if arguments.length is 4 callback = testBody testBody = statusCode statusCode = cookieValue cookieValue = '' setTimeout -> request app .get path .set 'Cookie', config.AUTH_COOKIE_NAME + '=' + cookieValue .end (err, res) -> _this.testHTTPResult err, res, statusCode, testBody callback res.body if callback , 10 this.testHTTPResult = (err, res, statusCode, testBody) -> cacheControl = res.get 'Cache-Control' contentType = res.get 'Content-Type' switch res.status when 200 expect(contentType).toEqual('application/json; charset=utf-8') expect(cacheControl).toEqual('private') when 204 expect(contentType).toEqual(undefined) else expect(contentType).toEqual('text/html; charset=utf-8') if statusCode expect(res.status).toEqual(statusCode) if res.status is 500 console.log 'Server error: ', res.text console.log 'Respone status: ', res.status console.log 'Respone error: ', err return else if res.status isnt statusCode console.log 'Respone message: ', res.text console.log 'Respone status: ', res.status console.log 'Respone error: ', err return testProperty = (obj, testBody) -> for p of testBody if typeof testBody[p] is 'object' testProperty obj[p], testBody[p] else switch testBody[p] when 'INTEGER' expect(Number.isInteger obj[p]).toBeTruthy() when 'UUID' expect(obj[p]).toMatch(/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}/) when 'STRING' expect(typeof obj[p] is 'string').toBeTruthy() when 'NULL' expect(obj[p]).toBeNull() else expect(testBody[p]).toEqual(obj[p]) testProperty res.body, testBody this.createUser = (user, callback) -> passwordSalt = _.random 1000, 9999 passwordHash = Utility.hash user.password, passwordSalt User.create #username: user.username region: user.region phone: user.phone nickname: user.nickname passwordHash: passwordHash passwordSalt: passwordSalt.toString() .then (user) -> callback Utility.encodeId user.id .catch (err) -> console.log 'Create user failed: ', err this.loginUser = (phoneNumber, callback) -> request app .post '/user/login' .type 'json' .send region: '86' phone: phoneNumber password: this.password .end (err, res) -> if not err and res.status is 200 callback res.body.result.id, getAuthCookieValue(res) else console.log 'Login user failed: ', err
35323
request = require 'supertest' cookie = require 'cookie' _ = require 'underscore' app = require '../../src' config = require '../../src/conf' Utility = require('../../src/util/util').Utility # 引用数据库对象和模型 [sequelize, User] = require '../../src/db' beforeAll -> this.phoneNumber1 = '13' + Math.floor(Math.random() * 99999999 + 900000000) this.phoneNumber2 = '13' + Math.floor(Math.random() * 99999999 + 900000000) this.phoneNumber3 = '13' + Math.floor(Math.random() * 99999999 + 900000000) #this.username1 = 'arielyang' #this.username2 = 'novasman' #this.username3 = 'luckyjiang' this.nickname1 = '<NAME>' this.nickname2 = '<NAME>' this.nickname3 = '<NAME>' this.userId1 = null this.userId2 = null this.userId3 = null this.password = '<PASSWORD>' this.passwordNew = '<PASSWORD>' this.groupName1 = 'Business' this.groupName2 = 'Product' this.groupId1 = null this.groupId2 = null this.userCookie1 = null this.userCookie2 = null this.userCookie3 = null this.xssString = '<a>hello</a>' this.filteredString = '&lt;a&gt;hello&lt;/a&gt;' getAuthCookieValue = (res) -> cookieHeader = res.header['set-cookie'] if cookieHeader if Array.isArray cookieHeader cookieHeader = cookieHeader[0] return authCookieValue = cookie.parse(cookieHeader)[config.AUTH_COOKIE_NAME] return null this.testPOSTAPI = (path, cookieValue, params, statusCode, testBody, callback) -> _this = this if arguments.length is 5 callback = testBody testBody = statusCode statusCode = params params = cookieValue cookieValue = '' setTimeout -> request app .post path .set 'Cookie', config.AUTH_COOKIE_NAME + '=' + cookieValue .type 'json' .send params .end (err, res) -> _this.testHTTPResult err, res, statusCode, testBody callback res.body, getAuthCookieValue(res) if callback , 10 this.testGETAPI = (path, cookieValue, statusCode, testBody, callback) -> _this = this if arguments.length is 4 callback = testBody testBody = statusCode statusCode = cookieValue cookieValue = '' setTimeout -> request app .get path .set 'Cookie', config.AUTH_COOKIE_NAME + '=' + cookieValue .end (err, res) -> _this.testHTTPResult err, res, statusCode, testBody callback res.body if callback , 10 this.testHTTPResult = (err, res, statusCode, testBody) -> cacheControl = res.get 'Cache-Control' contentType = res.get 'Content-Type' switch res.status when 200 expect(contentType).toEqual('application/json; charset=utf-8') expect(cacheControl).toEqual('private') when 204 expect(contentType).toEqual(undefined) else expect(contentType).toEqual('text/html; charset=utf-8') if statusCode expect(res.status).toEqual(statusCode) if res.status is 500 console.log 'Server error: ', res.text console.log 'Respone status: ', res.status console.log 'Respone error: ', err return else if res.status isnt statusCode console.log 'Respone message: ', res.text console.log 'Respone status: ', res.status console.log 'Respone error: ', err return testProperty = (obj, testBody) -> for p of testBody if typeof testBody[p] is 'object' testProperty obj[p], testBody[p] else switch testBody[p] when 'INTEGER' expect(Number.isInteger obj[p]).toBeTruthy() when 'UUID' expect(obj[p]).toMatch(/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}/) when 'STRING' expect(typeof obj[p] is 'string').toBeTruthy() when 'NULL' expect(obj[p]).toBeNull() else expect(testBody[p]).toEqual(obj[p]) testProperty res.body, testBody this.createUser = (user, callback) -> passwordSalt = _.random 1000, 9999 passwordHash = Utility.hash user.password, passwordSalt User.create #username: user.username region: user.region phone: user.phone nickname: user.nickname passwordHash: <PASSWORD> passwordSalt: <PASSWORD>() .then (user) -> callback Utility.encodeId user.id .catch (err) -> console.log 'Create user failed: ', err this.loginUser = (phoneNumber, callback) -> request app .post '/user/login' .type 'json' .send region: '86' phone: phoneNumber password: <PASSWORD> .end (err, res) -> if not err and res.status is 200 callback res.body.result.id, getAuthCookieValue(res) else console.log 'Login user failed: ', err
true
request = require 'supertest' cookie = require 'cookie' _ = require 'underscore' app = require '../../src' config = require '../../src/conf' Utility = require('../../src/util/util').Utility # 引用数据库对象和模型 [sequelize, User] = require '../../src/db' beforeAll -> this.phoneNumber1 = '13' + Math.floor(Math.random() * 99999999 + 900000000) this.phoneNumber2 = '13' + Math.floor(Math.random() * 99999999 + 900000000) this.phoneNumber3 = '13' + Math.floor(Math.random() * 99999999 + 900000000) #this.username1 = 'arielyang' #this.username2 = 'novasman' #this.username3 = 'luckyjiang' this.nickname1 = 'PI:NAME:<NAME>END_PI' this.nickname2 = 'PI:NAME:<NAME>END_PI' this.nickname3 = 'PI:NAME:<NAME>END_PI' this.userId1 = null this.userId2 = null this.userId3 = null this.password = 'PI:PASSWORD:<PASSWORD>END_PI' this.passwordNew = 'PI:PASSWORD:<PASSWORD>END_PI' this.groupName1 = 'Business' this.groupName2 = 'Product' this.groupId1 = null this.groupId2 = null this.userCookie1 = null this.userCookie2 = null this.userCookie3 = null this.xssString = '<a>hello</a>' this.filteredString = '&lt;a&gt;hello&lt;/a&gt;' getAuthCookieValue = (res) -> cookieHeader = res.header['set-cookie'] if cookieHeader if Array.isArray cookieHeader cookieHeader = cookieHeader[0] return authCookieValue = cookie.parse(cookieHeader)[config.AUTH_COOKIE_NAME] return null this.testPOSTAPI = (path, cookieValue, params, statusCode, testBody, callback) -> _this = this if arguments.length is 5 callback = testBody testBody = statusCode statusCode = params params = cookieValue cookieValue = '' setTimeout -> request app .post path .set 'Cookie', config.AUTH_COOKIE_NAME + '=' + cookieValue .type 'json' .send params .end (err, res) -> _this.testHTTPResult err, res, statusCode, testBody callback res.body, getAuthCookieValue(res) if callback , 10 this.testGETAPI = (path, cookieValue, statusCode, testBody, callback) -> _this = this if arguments.length is 4 callback = testBody testBody = statusCode statusCode = cookieValue cookieValue = '' setTimeout -> request app .get path .set 'Cookie', config.AUTH_COOKIE_NAME + '=' + cookieValue .end (err, res) -> _this.testHTTPResult err, res, statusCode, testBody callback res.body if callback , 10 this.testHTTPResult = (err, res, statusCode, testBody) -> cacheControl = res.get 'Cache-Control' contentType = res.get 'Content-Type' switch res.status when 200 expect(contentType).toEqual('application/json; charset=utf-8') expect(cacheControl).toEqual('private') when 204 expect(contentType).toEqual(undefined) else expect(contentType).toEqual('text/html; charset=utf-8') if statusCode expect(res.status).toEqual(statusCode) if res.status is 500 console.log 'Server error: ', res.text console.log 'Respone status: ', res.status console.log 'Respone error: ', err return else if res.status isnt statusCode console.log 'Respone message: ', res.text console.log 'Respone status: ', res.status console.log 'Respone error: ', err return testProperty = (obj, testBody) -> for p of testBody if typeof testBody[p] is 'object' testProperty obj[p], testBody[p] else switch testBody[p] when 'INTEGER' expect(Number.isInteger obj[p]).toBeTruthy() when 'UUID' expect(obj[p]).toMatch(/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}/) when 'STRING' expect(typeof obj[p] is 'string').toBeTruthy() when 'NULL' expect(obj[p]).toBeNull() else expect(testBody[p]).toEqual(obj[p]) testProperty res.body, testBody this.createUser = (user, callback) -> passwordSalt = _.random 1000, 9999 passwordHash = Utility.hash user.password, passwordSalt User.create #username: user.username region: user.region phone: user.phone nickname: user.nickname passwordHash: PI:PASSWORD:<PASSWORD>END_PI passwordSalt: PI:PASSWORD:<PASSWORD>END_PI() .then (user) -> callback Utility.encodeId user.id .catch (err) -> console.log 'Create user failed: ', err this.loginUser = (phoneNumber, callback) -> request app .post '/user/login' .type 'json' .send region: '86' phone: phoneNumber password: PI:PASSWORD:<PASSWORD>END_PI .end (err, res) -> if not err and res.status is 200 callback res.body.result.id, getAuthCookieValue(res) else console.log 'Login user failed: ', err
[ { "context": " MONGODB_DB\n#\n# Commands:\n# None\n#\n# Author:\n# ajacksified, maxbeatty\n\nUtil = require \"util\"\nmongodb = requi", "end": 392, "score": 0.9996252059936523, "start": 381, "tag": "USERNAME", "value": "ajacksified" }, { "context": "\n# Commands:\n# None\n#\n# ...
src/scripts/mongo-brain.coffee
contolini/hubot-scripts
1,450
# Description: # Enhances hubot-brain with MongoDB. Useful for Heroku accounts that want # better persistance. Falls back to memory brain if Mongo connection fails # for local testing. # # Dependencies: # "mongodb": ">= 1.2.0" # # Configuration: # MONGODB_USERNAME # MONGODB_PASSWORD # MONGODB_HOST # MONGODB_PORT # MONGODB_DB # # Commands: # None # # Author: # ajacksified, maxbeatty Util = require "util" mongodb = require "mongodb" Server = mongodb.Server Collection = mongodb.Collection Db = mongodb.Db module.exports = (robot) -> user = process.env.MONGODB_USERNAME || "admin" pass = process.env.MONGODB_PASSWORD || "password" host = process.env.MONGODB_HOST || "localhost" port = process.env.MONGODB_PORT || "27017" dbname = process.env.MONGODB_DB || "hubot" error = (err) -> console.log "==MONGO BRAIN UNAVAILABLE==\n==SWITCHING TO MEMORY BRAIN==" console.log err server = new Server host, port, {} db = new Db dbname, server, { w: 1, native_parser: true } db.open (err, client) -> return error err if err robot.logger.debug 'Successfully opened connection to mongo' db.authenticate user, pass, (err, success) -> return error err if err robot.logger.debug 'Successfully authenticated with mongo' collection = new Collection client, 'hubot_storage' collection.find().limit(1).toArray (err, results) -> return error err if err robot.logger.debug 'Successfully queried mongo' robot.logger.debug Util.inspect(results, false, 4) if results.length > 0 robot.brain.data = results[0] robot.brain.emit 'loaded', results[0] else robot.logger.debug 'No results found' robot.brain.on 'save', (data) -> robot.logger.debug 'Save event caught by mongo' robot.logger.debug Util.inspect(robot.brain.data, false, 4) collection.save robot.brain.data, (err) -> console.warn err if err?
138291
# Description: # Enhances hubot-brain with MongoDB. Useful for Heroku accounts that want # better persistance. Falls back to memory brain if Mongo connection fails # for local testing. # # Dependencies: # "mongodb": ">= 1.2.0" # # Configuration: # MONGODB_USERNAME # MONGODB_PASSWORD # MONGODB_HOST # MONGODB_PORT # MONGODB_DB # # Commands: # None # # Author: # ajacksified, maxbeatty Util = require "util" mongodb = require "mongodb" Server = mongodb.Server Collection = mongodb.Collection Db = mongodb.Db module.exports = (robot) -> user = process.env.MONGODB_USERNAME || "admin" pass = process.env.MONGODB_PASSWORD || "<PASSWORD>" host = process.env.MONGODB_HOST || "localhost" port = process.env.MONGODB_PORT || "27017" dbname = process.env.MONGODB_DB || "hubot" error = (err) -> console.log "==MONGO BRAIN UNAVAILABLE==\n==SWITCHING TO MEMORY BRAIN==" console.log err server = new Server host, port, {} db = new Db dbname, server, { w: 1, native_parser: true } db.open (err, client) -> return error err if err robot.logger.debug 'Successfully opened connection to mongo' db.authenticate user, pass, (err, success) -> return error err if err robot.logger.debug 'Successfully authenticated with mongo' collection = new Collection client, 'hubot_storage' collection.find().limit(1).toArray (err, results) -> return error err if err robot.logger.debug 'Successfully queried mongo' robot.logger.debug Util.inspect(results, false, 4) if results.length > 0 robot.brain.data = results[0] robot.brain.emit 'loaded', results[0] else robot.logger.debug 'No results found' robot.brain.on 'save', (data) -> robot.logger.debug 'Save event caught by mongo' robot.logger.debug Util.inspect(robot.brain.data, false, 4) collection.save robot.brain.data, (err) -> console.warn err if err?
true
# Description: # Enhances hubot-brain with MongoDB. Useful for Heroku accounts that want # better persistance. Falls back to memory brain if Mongo connection fails # for local testing. # # Dependencies: # "mongodb": ">= 1.2.0" # # Configuration: # MONGODB_USERNAME # MONGODB_PASSWORD # MONGODB_HOST # MONGODB_PORT # MONGODB_DB # # Commands: # None # # Author: # ajacksified, maxbeatty Util = require "util" mongodb = require "mongodb" Server = mongodb.Server Collection = mongodb.Collection Db = mongodb.Db module.exports = (robot) -> user = process.env.MONGODB_USERNAME || "admin" pass = process.env.MONGODB_PASSWORD || "PI:PASSWORD:<PASSWORD>END_PI" host = process.env.MONGODB_HOST || "localhost" port = process.env.MONGODB_PORT || "27017" dbname = process.env.MONGODB_DB || "hubot" error = (err) -> console.log "==MONGO BRAIN UNAVAILABLE==\n==SWITCHING TO MEMORY BRAIN==" console.log err server = new Server host, port, {} db = new Db dbname, server, { w: 1, native_parser: true } db.open (err, client) -> return error err if err robot.logger.debug 'Successfully opened connection to mongo' db.authenticate user, pass, (err, success) -> return error err if err robot.logger.debug 'Successfully authenticated with mongo' collection = new Collection client, 'hubot_storage' collection.find().limit(1).toArray (err, results) -> return error err if err robot.logger.debug 'Successfully queried mongo' robot.logger.debug Util.inspect(results, false, 4) if results.length > 0 robot.brain.data = results[0] robot.brain.emit 'loaded', results[0] else robot.logger.debug 'No results found' robot.brain.on 'save', (data) -> robot.logger.debug 'Save event caught by mongo' robot.logger.debug Util.inspect(robot.brain.data, false, 4) collection.save robot.brain.data, (err) -> console.warn err if err?
[ { "context": "powerful two-card strategies there is.\n{\n name: 'ChapelWitch'\n requires: ['Chapel', 'Witch']\n gainPriority: ", "end": 142, "score": 0.9105900526046753, "start": 131, "tag": "NAME", "value": "ChapelWitch" } ]
strategies/ChapelWitch.coffee
rspeer/dominiate
65
# Gain one Chapel and one Witch, and otherwise play Big Money. One of the most # powerful two-card strategies there is. { name: 'ChapelWitch' requires: ['Chapel', 'Witch'] gainPriority: (state, my) -> [ "Colony" if my.countInDeck("Platinum") > 0 "Province" if state.countInSupply("Colony") <= 6 "Witch" if my.countInDeck("Witch") == 0 "Duchy" if 0 < state.gainsToEndGame() <= 5 "Estate" if 0 < state.gainsToEndGame() <= 2 "Platinum" "Gold" # If this bot somehow gets rid of its chapel later in the game, # it won't try to acquire another one. "Chapel" if my.coins <= 3 and my.countInDeck("Chapel") == 0 and my.turnsTaken <= 2 "Silver" "Copper" if state.gainsToEndGame() <= 3 ] trashPriority: (state, my) -> [ "Curse" "Estate" if state.gainsToEndGame() > 4 "Copper" if my.getTotalMoney() > 4\ and not (my.countInDeck("Witch") == 0 and my.getTreasureInHand() == 5) "Estate" if state.gainsToEndGame() > 2 ] }
136788
# Gain one Chapel and one Witch, and otherwise play Big Money. One of the most # powerful two-card strategies there is. { name: '<NAME>' requires: ['Chapel', 'Witch'] gainPriority: (state, my) -> [ "Colony" if my.countInDeck("Platinum") > 0 "Province" if state.countInSupply("Colony") <= 6 "Witch" if my.countInDeck("Witch") == 0 "Duchy" if 0 < state.gainsToEndGame() <= 5 "Estate" if 0 < state.gainsToEndGame() <= 2 "Platinum" "Gold" # If this bot somehow gets rid of its chapel later in the game, # it won't try to acquire another one. "Chapel" if my.coins <= 3 and my.countInDeck("Chapel") == 0 and my.turnsTaken <= 2 "Silver" "Copper" if state.gainsToEndGame() <= 3 ] trashPriority: (state, my) -> [ "Curse" "Estate" if state.gainsToEndGame() > 4 "Copper" if my.getTotalMoney() > 4\ and not (my.countInDeck("Witch") == 0 and my.getTreasureInHand() == 5) "Estate" if state.gainsToEndGame() > 2 ] }
true
# Gain one Chapel and one Witch, and otherwise play Big Money. One of the most # powerful two-card strategies there is. { name: 'PI:NAME:<NAME>END_PI' requires: ['Chapel', 'Witch'] gainPriority: (state, my) -> [ "Colony" if my.countInDeck("Platinum") > 0 "Province" if state.countInSupply("Colony") <= 6 "Witch" if my.countInDeck("Witch") == 0 "Duchy" if 0 < state.gainsToEndGame() <= 5 "Estate" if 0 < state.gainsToEndGame() <= 2 "Platinum" "Gold" # If this bot somehow gets rid of its chapel later in the game, # it won't try to acquire another one. "Chapel" if my.coins <= 3 and my.countInDeck("Chapel") == 0 and my.turnsTaken <= 2 "Silver" "Copper" if state.gainsToEndGame() <= 3 ] trashPriority: (state, my) -> [ "Curse" "Estate" if state.gainsToEndGame() > 4 "Copper" if my.getTotalMoney() > 4\ and not (my.countInDeck("Witch") == 0 and my.getTreasureInHand() == 5) "Estate" if state.gainsToEndGame() > 2 ] }