entities listlengths 1 8.61k | max_stars_repo_path stringlengths 7 172 | max_stars_repo_name stringlengths 5 89 | max_stars_count int64 0 82k | content stringlengths 14 1.05M | id stringlengths 2 6 | new_content stringlengths 15 1.05M | modified bool 1 class | references stringlengths 29 1.05M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": "###\n * quad\n * https://github.com/1egoman/quad\n *\n * Copyright (c) 2015 Ryan Gaus\n * Licens",
"end": 41,
"score": 0.9988946914672852,
"start": 34,
"tag": "USERNAME",
"value": "1egoman"
},
{
"context": "//github.com/1egoman/quad\n *\n * Copyright (c) 2015 Ryan Gaus\... | quadpi/src/quad.coffee | 1egoman/quad | 0 | ###
* quad
* https://github.com/1egoman/quad
*
* Copyright (c) 2015 Ryan Gaus
* Licensed under the MIT license.
###
'use strict'
express = require "express"
app = express()
chalk = require "chalk"
path = require "path"
bodyParser = require "body-parser"
uuid = require "uuid"
event = require "./call_event"
exports.main = ->
# set ejs as view engine
app.set "view engine", "ejs"
# include all the required middleware
exports.middleware app
# some sample routes
router = express.Router()
router.get "/", (req, res) ->
res.send
name: "device.hello"
id: uuid.v4()
data: {}
router.post "/device/event", event.onMiddleware
app.use router
# listen for requests
PORT = process.argv.port or 8000
app.listen PORT, ->
console.log chalk.blue "-> :#{PORT}"
exports.middleware = (app) ->
# json body parser
app.use bodyParser.json()
# include sass middleware to auto-compile sass stylesheets
node_sass = require "node-sass-middleware"
app.use node_sass
src: path.join(__dirname, "../public"),
dest: path.join(__dirname, "../public"),
# serve static assets
app.use require("express-static") path.join(__dirname, '../public')
exports.main()
| 43036 | ###
* quad
* https://github.com/1egoman/quad
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
###
'use strict'
express = require "express"
app = express()
chalk = require "chalk"
path = require "path"
bodyParser = require "body-parser"
uuid = require "uuid"
event = require "./call_event"
exports.main = ->
# set ejs as view engine
app.set "view engine", "ejs"
# include all the required middleware
exports.middleware app
# some sample routes
router = express.Router()
router.get "/", (req, res) ->
res.send
name: "device.hello"
id: uuid.v4()
data: {}
router.post "/device/event", event.onMiddleware
app.use router
# listen for requests
PORT = process.argv.port or 8000
app.listen PORT, ->
console.log chalk.blue "-> :#{PORT}"
exports.middleware = (app) ->
# json body parser
app.use bodyParser.json()
# include sass middleware to auto-compile sass stylesheets
node_sass = require "node-sass-middleware"
app.use node_sass
src: path.join(__dirname, "../public"),
dest: path.join(__dirname, "../public"),
# serve static assets
app.use require("express-static") path.join(__dirname, '../public')
exports.main()
| true | ###
* quad
* https://github.com/1egoman/quad
*
* Copyright (c) 2015 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
'use strict'
express = require "express"
app = express()
chalk = require "chalk"
path = require "path"
bodyParser = require "body-parser"
uuid = require "uuid"
event = require "./call_event"
exports.main = ->
# set ejs as view engine
app.set "view engine", "ejs"
# include all the required middleware
exports.middleware app
# some sample routes
router = express.Router()
router.get "/", (req, res) ->
res.send
name: "device.hello"
id: uuid.v4()
data: {}
router.post "/device/event", event.onMiddleware
app.use router
# listen for requests
PORT = process.argv.port or 8000
app.listen PORT, ->
console.log chalk.blue "-> :#{PORT}"
exports.middleware = (app) ->
# json body parser
app.use bodyParser.json()
# include sass middleware to auto-compile sass stylesheets
node_sass = require "node-sass-middleware"
app.use node_sass
src: path.join(__dirname, "../public"),
dest: path.join(__dirname, "../public"),
# serve static assets
app.use require("express-static") path.join(__dirname, '../public')
exports.main()
|
[
{
"context": "###!\nCopyright (c) 2002-2017 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 44,
"score": 0.5599489212036133,
"start": 34,
"tag": "NAME",
"value": "Technology"
}
] | src/components/D3Visualization/lib/visualization/components/style.coffee | yezonggang/zcfx-admin-master | 24 | ###!
Copyright (c) 2002-2017 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.style = do ->
_style = (storage) ->
new GraphStyle(storage)
_style.defaults =
autoColor: yes
colors: [
{ color: '#DFE1E3', 'border-color': '#D4D6D7', 'text-color-internal': '#000000' }
{ color: '#F25A29', 'border-color': '#DC4717', 'text-color-internal': '#FFFFFF' }
{ color: '#AD62CE', 'border-color': '#9453B1', 'text-color-internal': '#FFFFFF' }
{ color: '#30B6AF', 'border-color': '#46A39E', 'text-color-internal': '#FFFFFF' }
{ color: '#FF6C7C', 'border-color': '#EB5D6C', 'text-color-internal': '#FFFFFF' }
{ color: '#FCC940', 'border-color': '#F3BA25', 'text-color-internal': '#000000' }
{ color: '#4356C0', 'border-color': '#3445A2', 'text-color-internal': '#FFFFFF' }
]
style:
'node':
'diameter': '40px'
'color': '#DFE1E3'
'border-color': '#5CA8DB'
'border-width': '2px'
'text-color-internal': '#000000'
'caption': '{id}'
'font-size': '10px'
'relationship':
'color': '#D4D6D7'
'shaft-width': '1px'
'font-size': '8px'
'padding': '3px'
'text-color-external': '#5CA8DB'
'text-color-internal': '#68BDF6'
# 'node':
# 'diameter': '40px'
# 'color': '#DFE1E3'
# 'border-color': '#D4D6D7'
# 'border-width': '2px'
# 'text-color-internal': '#000000'
# 'caption': '{id}'
# 'font-size': '10px'
# 'relationship':
# 'color': '#D4D6D7'
# 'shaft-width': '1px'
# 'font-size': '8px'
# 'padding': '3px'
# 'text-color-external': '#000000'
# 'text-color-internal': '#FFFFFF'
sizes: [
{ diameter: '10px' }
{ diameter: '20px' }
{ diameter: '30px' }
{ diameter: '50px' }
{ diameter: '80px' }
]
arrayWidths: [
{ 'shaft-width': '1px' }
{ 'shaft-width': '2px' }
{ 'shaft-width': '3px' }
{ 'shaft-width': '5px' }
{ 'shaft-width': '8px' }
{ 'shaft-width': '13px' }
{ 'shaft-width': '25px' }
{ 'shaft-width': '38px' }
]
class Selector
constructor: (selector) ->
[@tag, @klass] = if selector.indexOf('.') > 0
selector.split('.')
else
[selector, undefined]
toString: ->
str = @tag
str += ".#{@klass}" if @klass?
str
class StyleRule
constructor: (@selector, @props) ->
matches: (selector) ->
if @selector.tag is selector.tag
if @selector.klass is selector.klass or not @selector.klass
return yes
return no
matchesExact: (selector) ->
@selector.tag is selector.tag and @selector.klass is selector.klass
class StyleElement
constructor: (selector, @data) ->
@selector = selector
@props = {}
applyRules: (rules) ->
# Two passes
for rule in rules when rule.matches(@selector)
neo.utils.extend(@props, rule.props)
break
for rule in rules when rule.matchesExact(@selector)
neo.utils.extend(@props, rule.props)
break
@
get: (attr) ->
@props[attr] or ''
class GraphStyle
constructor: (@storage) ->
@rules = []
@loadRules()
# Generate a selector string from an object (node or rel)
selector: (item) ->
if item.isNode
@nodeSelector(item)
else if item.isRelationship
@relationshipSelector(item)
#
# Methods for calculating applied style for elements
#
calculateStyle: (selector, data) ->
new StyleElement(selector, data).applyRules(@rules)
forEntity: (item) ->
@calculateStyle(@selector(item), item)
forNode: (node = {}) ->
selector = @nodeSelector(node)
if node.labels?.length > 0
@setDefaultStyling(selector)
@calculateStyle(selector, node)
forRelationship: (rel) ->
@calculateStyle(@relationshipSelector(rel), rel)
findAvailableDefaultColor: () ->
usedColors = {}
for rule in @rules
if rule.props.color?
usedColors[rule.props.color] = yes
for defaultColor in _style.defaults.colors
if !usedColors[defaultColor.color]?
return neo.utils.copy(defaultColor)
return neo.utils.copy(_style.defaults.colors[0])
setDefaultStyling: (selector) ->
rule = @findRule(selector)
if _style.defaults.autoColor and not rule?
rule = new StyleRule(selector, @findAvailableDefaultColor())
@rules.push(rule)
@persist()
#
# Methods for getting and modifying rules
#
change: (item, props) ->
selector = @selector(item)
rule = @findRule(selector)
if not rule?
rule = new StyleRule(selector, {})
@rules.push(rule)
neo.utils.extend(rule.props, props)
@persist()
rule
destroyRule: (rule) ->
idx = @rules.indexOf(rule)
@rules.splice(idx, 1) if idx?
@persist()
findRule: (selector) ->
rule = r for r in @rules when r.matchesExact(selector)
rule
#
# Selector helpers
#
nodeSelector: (node = {}) ->
selector = 'node'
if node.labels?.length > 0
selector += ".#{node.labels[0]}"
new Selector(selector)
relationshipSelector: (rel = {}) ->
selector = 'relationship'
selector += ".#{rel.type}" if rel.type?
new Selector(selector)
#
# Import/export
#
importGrass: (string) ->
try
rules = @parse(string)
@loadRules(rules)
@persist()
catch e
return
loadRules: (data) ->
data = _style.defaults.style unless neo.utils.isObject(data)
@rules.length = 0
for rule, props of data
@rules.push(new StyleRule(new Selector(rule), neo.utils.copy(props)))
@
parse: (string)->
chars = string.split('')
insideString = no
insideProps = no
keyword = ""
props = ""
rules = {}
for c in chars
skipThis = yes
switch c
when "{"
if not insideString
insideProps = yes
else
skipThis = no
when "}"
if not insideString
insideProps = no
rules[keyword] = props
keyword = ""
props = ""
else
skipThis = no
when "'", "\"" then insideString ^= true
else skipThis = no
continue if skipThis
if insideProps
props += c
else
keyword += c unless c.match(/[\s\n]/)
for k, v of rules
rules[k] = {}
for prop in v.split(';')
[key, val] = prop.split(':')
continue unless key and val
rules[k][key?.trim()] = val?.trim()
rules
persist: ->
@storage?.add('grass', JSON.stringify(@toSheet()))
resetToDefault: ->
@loadRules()
@persist()
toSheet: ->
sheet = {}
sheet[rule.selector.toString()] = rule.props for rule in @rules
sheet
toString: ->
str = ""
for r in @rules
str += r.selector.toString() + " {\n"
for k, v of r.props
v = "'#{v}'" if k == "caption"
str += " #{k}: #{v};\n"
str += "}\n\n"
str
#
# Misc.
#
nextDefaultColor: 0
defaultColors: -> neo.utils.copy(_style.defaults.colors)
interpolate: (str, id, properties) ->
# Supplant
# http://javascript.crockford.com/remedial.html
str.replace(
/\{([^{}]*)\}/g,
(a, b) ->
r = properties[b] or id
return if (typeof r is 'string' or typeof r is 'number') then r else a
)
_style
| 86207 | ###!
Copyright (c) 2002-2017 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.style = do ->
_style = (storage) ->
new GraphStyle(storage)
_style.defaults =
autoColor: yes
colors: [
{ color: '#DFE1E3', 'border-color': '#D4D6D7', 'text-color-internal': '#000000' }
{ color: '#F25A29', 'border-color': '#DC4717', 'text-color-internal': '#FFFFFF' }
{ color: '#AD62CE', 'border-color': '#9453B1', 'text-color-internal': '#FFFFFF' }
{ color: '#30B6AF', 'border-color': '#46A39E', 'text-color-internal': '#FFFFFF' }
{ color: '#FF6C7C', 'border-color': '#EB5D6C', 'text-color-internal': '#FFFFFF' }
{ color: '#FCC940', 'border-color': '#F3BA25', 'text-color-internal': '#000000' }
{ color: '#4356C0', 'border-color': '#3445A2', 'text-color-internal': '#FFFFFF' }
]
style:
'node':
'diameter': '40px'
'color': '#DFE1E3'
'border-color': '#5CA8DB'
'border-width': '2px'
'text-color-internal': '#000000'
'caption': '{id}'
'font-size': '10px'
'relationship':
'color': '#D4D6D7'
'shaft-width': '1px'
'font-size': '8px'
'padding': '3px'
'text-color-external': '#5CA8DB'
'text-color-internal': '#68BDF6'
# 'node':
# 'diameter': '40px'
# 'color': '#DFE1E3'
# 'border-color': '#D4D6D7'
# 'border-width': '2px'
# 'text-color-internal': '#000000'
# 'caption': '{id}'
# 'font-size': '10px'
# 'relationship':
# 'color': '#D4D6D7'
# 'shaft-width': '1px'
# 'font-size': '8px'
# 'padding': '3px'
# 'text-color-external': '#000000'
# 'text-color-internal': '#FFFFFF'
sizes: [
{ diameter: '10px' }
{ diameter: '20px' }
{ diameter: '30px' }
{ diameter: '50px' }
{ diameter: '80px' }
]
arrayWidths: [
{ 'shaft-width': '1px' }
{ 'shaft-width': '2px' }
{ 'shaft-width': '3px' }
{ 'shaft-width': '5px' }
{ 'shaft-width': '8px' }
{ 'shaft-width': '13px' }
{ 'shaft-width': '25px' }
{ 'shaft-width': '38px' }
]
class Selector
constructor: (selector) ->
[@tag, @klass] = if selector.indexOf('.') > 0
selector.split('.')
else
[selector, undefined]
toString: ->
str = @tag
str += ".#{@klass}" if @klass?
str
class StyleRule
constructor: (@selector, @props) ->
matches: (selector) ->
if @selector.tag is selector.tag
if @selector.klass is selector.klass or not @selector.klass
return yes
return no
matchesExact: (selector) ->
@selector.tag is selector.tag and @selector.klass is selector.klass
class StyleElement
constructor: (selector, @data) ->
@selector = selector
@props = {}
applyRules: (rules) ->
# Two passes
for rule in rules when rule.matches(@selector)
neo.utils.extend(@props, rule.props)
break
for rule in rules when rule.matchesExact(@selector)
neo.utils.extend(@props, rule.props)
break
@
get: (attr) ->
@props[attr] or ''
class GraphStyle
constructor: (@storage) ->
@rules = []
@loadRules()
# Generate a selector string from an object (node or rel)
selector: (item) ->
if item.isNode
@nodeSelector(item)
else if item.isRelationship
@relationshipSelector(item)
#
# Methods for calculating applied style for elements
#
calculateStyle: (selector, data) ->
new StyleElement(selector, data).applyRules(@rules)
forEntity: (item) ->
@calculateStyle(@selector(item), item)
forNode: (node = {}) ->
selector = @nodeSelector(node)
if node.labels?.length > 0
@setDefaultStyling(selector)
@calculateStyle(selector, node)
forRelationship: (rel) ->
@calculateStyle(@relationshipSelector(rel), rel)
findAvailableDefaultColor: () ->
usedColors = {}
for rule in @rules
if rule.props.color?
usedColors[rule.props.color] = yes
for defaultColor in _style.defaults.colors
if !usedColors[defaultColor.color]?
return neo.utils.copy(defaultColor)
return neo.utils.copy(_style.defaults.colors[0])
setDefaultStyling: (selector) ->
rule = @findRule(selector)
if _style.defaults.autoColor and not rule?
rule = new StyleRule(selector, @findAvailableDefaultColor())
@rules.push(rule)
@persist()
#
# Methods for getting and modifying rules
#
change: (item, props) ->
selector = @selector(item)
rule = @findRule(selector)
if not rule?
rule = new StyleRule(selector, {})
@rules.push(rule)
neo.utils.extend(rule.props, props)
@persist()
rule
destroyRule: (rule) ->
idx = @rules.indexOf(rule)
@rules.splice(idx, 1) if idx?
@persist()
findRule: (selector) ->
rule = r for r in @rules when r.matchesExact(selector)
rule
#
# Selector helpers
#
nodeSelector: (node = {}) ->
selector = 'node'
if node.labels?.length > 0
selector += ".#{node.labels[0]}"
new Selector(selector)
relationshipSelector: (rel = {}) ->
selector = 'relationship'
selector += ".#{rel.type}" if rel.type?
new Selector(selector)
#
# Import/export
#
importGrass: (string) ->
try
rules = @parse(string)
@loadRules(rules)
@persist()
catch e
return
loadRules: (data) ->
data = _style.defaults.style unless neo.utils.isObject(data)
@rules.length = 0
for rule, props of data
@rules.push(new StyleRule(new Selector(rule), neo.utils.copy(props)))
@
parse: (string)->
chars = string.split('')
insideString = no
insideProps = no
keyword = ""
props = ""
rules = {}
for c in chars
skipThis = yes
switch c
when "{"
if not insideString
insideProps = yes
else
skipThis = no
when "}"
if not insideString
insideProps = no
rules[keyword] = props
keyword = ""
props = ""
else
skipThis = no
when "'", "\"" then insideString ^= true
else skipThis = no
continue if skipThis
if insideProps
props += c
else
keyword += c unless c.match(/[\s\n]/)
for k, v of rules
rules[k] = {}
for prop in v.split(';')
[key, val] = prop.split(':')
continue unless key and val
rules[k][key?.trim()] = val?.trim()
rules
persist: ->
@storage?.add('grass', JSON.stringify(@toSheet()))
resetToDefault: ->
@loadRules()
@persist()
toSheet: ->
sheet = {}
sheet[rule.selector.toString()] = rule.props for rule in @rules
sheet
toString: ->
str = ""
for r in @rules
str += r.selector.toString() + " {\n"
for k, v of r.props
v = "'#{v}'" if k == "caption"
str += " #{k}: #{v};\n"
str += "}\n\n"
str
#
# Misc.
#
nextDefaultColor: 0
defaultColors: -> neo.utils.copy(_style.defaults.colors)
interpolate: (str, id, properties) ->
# Supplant
# http://javascript.crockford.com/remedial.html
str.replace(
/\{([^{}]*)\}/g,
(a, b) ->
r = properties[b] or id
return if (typeof r is 'string' or typeof r is 'number') then r else a
)
_style
| true | ###!
Copyright (c) 2002-2017 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.style = do ->
_style = (storage) ->
new GraphStyle(storage)
_style.defaults =
autoColor: yes
colors: [
{ color: '#DFE1E3', 'border-color': '#D4D6D7', 'text-color-internal': '#000000' }
{ color: '#F25A29', 'border-color': '#DC4717', 'text-color-internal': '#FFFFFF' }
{ color: '#AD62CE', 'border-color': '#9453B1', 'text-color-internal': '#FFFFFF' }
{ color: '#30B6AF', 'border-color': '#46A39E', 'text-color-internal': '#FFFFFF' }
{ color: '#FF6C7C', 'border-color': '#EB5D6C', 'text-color-internal': '#FFFFFF' }
{ color: '#FCC940', 'border-color': '#F3BA25', 'text-color-internal': '#000000' }
{ color: '#4356C0', 'border-color': '#3445A2', 'text-color-internal': '#FFFFFF' }
]
style:
'node':
'diameter': '40px'
'color': '#DFE1E3'
'border-color': '#5CA8DB'
'border-width': '2px'
'text-color-internal': '#000000'
'caption': '{id}'
'font-size': '10px'
'relationship':
'color': '#D4D6D7'
'shaft-width': '1px'
'font-size': '8px'
'padding': '3px'
'text-color-external': '#5CA8DB'
'text-color-internal': '#68BDF6'
# 'node':
# 'diameter': '40px'
# 'color': '#DFE1E3'
# 'border-color': '#D4D6D7'
# 'border-width': '2px'
# 'text-color-internal': '#000000'
# 'caption': '{id}'
# 'font-size': '10px'
# 'relationship':
# 'color': '#D4D6D7'
# 'shaft-width': '1px'
# 'font-size': '8px'
# 'padding': '3px'
# 'text-color-external': '#000000'
# 'text-color-internal': '#FFFFFF'
sizes: [
{ diameter: '10px' }
{ diameter: '20px' }
{ diameter: '30px' }
{ diameter: '50px' }
{ diameter: '80px' }
]
arrayWidths: [
{ 'shaft-width': '1px' }
{ 'shaft-width': '2px' }
{ 'shaft-width': '3px' }
{ 'shaft-width': '5px' }
{ 'shaft-width': '8px' }
{ 'shaft-width': '13px' }
{ 'shaft-width': '25px' }
{ 'shaft-width': '38px' }
]
class Selector
constructor: (selector) ->
[@tag, @klass] = if selector.indexOf('.') > 0
selector.split('.')
else
[selector, undefined]
toString: ->
str = @tag
str += ".#{@klass}" if @klass?
str
class StyleRule
constructor: (@selector, @props) ->
matches: (selector) ->
if @selector.tag is selector.tag
if @selector.klass is selector.klass or not @selector.klass
return yes
return no
matchesExact: (selector) ->
@selector.tag is selector.tag and @selector.klass is selector.klass
class StyleElement
constructor: (selector, @data) ->
@selector = selector
@props = {}
applyRules: (rules) ->
# Two passes
for rule in rules when rule.matches(@selector)
neo.utils.extend(@props, rule.props)
break
for rule in rules when rule.matchesExact(@selector)
neo.utils.extend(@props, rule.props)
break
@
get: (attr) ->
@props[attr] or ''
class GraphStyle
constructor: (@storage) ->
@rules = []
@loadRules()
# Generate a selector string from an object (node or rel)
selector: (item) ->
if item.isNode
@nodeSelector(item)
else if item.isRelationship
@relationshipSelector(item)
#
# Methods for calculating applied style for elements
#
calculateStyle: (selector, data) ->
new StyleElement(selector, data).applyRules(@rules)
forEntity: (item) ->
@calculateStyle(@selector(item), item)
forNode: (node = {}) ->
selector = @nodeSelector(node)
if node.labels?.length > 0
@setDefaultStyling(selector)
@calculateStyle(selector, node)
forRelationship: (rel) ->
@calculateStyle(@relationshipSelector(rel), rel)
findAvailableDefaultColor: () ->
usedColors = {}
for rule in @rules
if rule.props.color?
usedColors[rule.props.color] = yes
for defaultColor in _style.defaults.colors
if !usedColors[defaultColor.color]?
return neo.utils.copy(defaultColor)
return neo.utils.copy(_style.defaults.colors[0])
setDefaultStyling: (selector) ->
rule = @findRule(selector)
if _style.defaults.autoColor and not rule?
rule = new StyleRule(selector, @findAvailableDefaultColor())
@rules.push(rule)
@persist()
#
# Methods for getting and modifying rules
#
change: (item, props) ->
selector = @selector(item)
rule = @findRule(selector)
if not rule?
rule = new StyleRule(selector, {})
@rules.push(rule)
neo.utils.extend(rule.props, props)
@persist()
rule
destroyRule: (rule) ->
idx = @rules.indexOf(rule)
@rules.splice(idx, 1) if idx?
@persist()
findRule: (selector) ->
rule = r for r in @rules when r.matchesExact(selector)
rule
#
# Selector helpers
#
nodeSelector: (node = {}) ->
selector = 'node'
if node.labels?.length > 0
selector += ".#{node.labels[0]}"
new Selector(selector)
relationshipSelector: (rel = {}) ->
selector = 'relationship'
selector += ".#{rel.type}" if rel.type?
new Selector(selector)
#
# Import/export
#
importGrass: (string) ->
try
rules = @parse(string)
@loadRules(rules)
@persist()
catch e
return
loadRules: (data) ->
data = _style.defaults.style unless neo.utils.isObject(data)
@rules.length = 0
for rule, props of data
@rules.push(new StyleRule(new Selector(rule), neo.utils.copy(props)))
@
parse: (string)->
chars = string.split('')
insideString = no
insideProps = no
keyword = ""
props = ""
rules = {}
for c in chars
skipThis = yes
switch c
when "{"
if not insideString
insideProps = yes
else
skipThis = no
when "}"
if not insideString
insideProps = no
rules[keyword] = props
keyword = ""
props = ""
else
skipThis = no
when "'", "\"" then insideString ^= true
else skipThis = no
continue if skipThis
if insideProps
props += c
else
keyword += c unless c.match(/[\s\n]/)
for k, v of rules
rules[k] = {}
for prop in v.split(';')
[key, val] = prop.split(':')
continue unless key and val
rules[k][key?.trim()] = val?.trim()
rules
persist: ->
@storage?.add('grass', JSON.stringify(@toSheet()))
resetToDefault: ->
@loadRules()
@persist()
toSheet: ->
sheet = {}
sheet[rule.selector.toString()] = rule.props for rule in @rules
sheet
toString: ->
str = ""
for r in @rules
str += r.selector.toString() + " {\n"
for k, v of r.props
v = "'#{v}'" if k == "caption"
str += " #{k}: #{v};\n"
str += "}\n\n"
str
#
# Misc.
#
nextDefaultColor: 0
defaultColors: -> neo.utils.copy(_style.defaults.colors)
interpolate: (str, id, properties) ->
# Supplant
# http://javascript.crockford.com/remedial.html
str.replace(
/\{([^{}]*)\}/g,
(a, b) ->
r = properties[b] or id
return if (typeof r is 'string' or typeof r is 'number') then r else a
)
_style
|
[
{
"context": "### Copyright 2013 Mark Watson. All rights reserved.\n This code may be used un",
"end": 30,
"score": 0.9997200965881348,
"start": 19,
"tag": "NAME",
"value": "Mark Watson"
}
] | src/nn.coffee | mark-watson/javascript_intelligent_systems | 5 | ### Copyright 2013 Mark Watson. All rights reserved.
This code may be used under the Apache 2 license.
This notice must remain in this file and derived files. ###
learningRate = 0.3
new_neural_network = (num_input, num_hidden, num_output) ->
data =
numInputs: num_input
numHidden: num_hidden
numOutputs: num_output
inputs: []
hidden: Array(num_hidden)
outputs: Array(num_output)
w1: Array(num_input) # will be num_input * num_hidden
w2: Array(num_hidden) # will be num_hidden * num_output
output_errors: Array(num_output)
hidden_errors: Array(num_hidden)
input_training_examples: []
output_training_examples: []
for i in [0...num_input]
data.w1[i] = Array(num_hidden)
data.inputs[i] = 0
for h in [0..num_hidden]
data.w2[h] = Array(num_output)
for i in [0...num_input]
for h in [0...num_hidden]
data.w1[i][h] = 0.1 * (Math.random() - 0.5)
for h in [0...num_hidden]
for o in [0...num_output]
data.w2[h][o] = 0.1 * (Math.random() - 0.5);
data
test_data = new_neural_network(3, 3, 3)
console.log test_data
add_training_example = (nn, inputs, outputs) ->
nn.input_training_examples.push(inputs)
nn.output_training_examples.push(outputs)
add_training_example(test_data, [0.1, 0.1, 0.9], [0.9, 0.1, 0.1])
console.log test_data
sigmoid = (x) ->
(1.0 / (1.0 + Math.exp(-x)))
sigmoidP = (x) ->
z = sigmoid(x)
z * (1.0 - z)
forward_pass = (nn) ->
for h in [0...nn.numHidden]
nn.hidden[h] = 0
for i in [0...nn.numInputs]
for h in [0...nn.numHidden]
nn.hidden[h] += nn.inputs[i] * nn.w1[i][h]
for o in [0...nn.numOutputs]
nn.outputs[o] = 0
for h in [0...nn.numHidden]
for o in [0...nn.numOutputs]
nn.outputs[o] += sigmoid(nn.hidden[h]) * nn.w2[h][o]
for o in [0...nn.numOutput]
nn.outputs[o] = sigmoid(nn.outputs[o])
train = (nn) ->
error = 0
num_cases = nn.input_training_examples.length
for ncase in [0...num_cases]
# zero out the errors: at the hidden and output layers:
for i in [0...nn.numHidden]
nn.hidden_errors[h] = 0
for o in [0...nn.numOutputs]
nn.output_errors[o] = 0
for i in [0...nn.numInputs]
nn.inputs[i] = nn.input_training_examples[ncase][i]
outs = nn.output_training_examples[ncase]
forward_pass(nn)
for o in [0..nn.numOutputs]
nn.output_errors[o] = (outs[o] - nn.outputs[o]) * sigmoidP(nn.outputs[o])
for h in [0...nn.numHidden]
nn.hidden_errors[h] = 0.0
for o in [0...nn.numOutputs]
nn.hidden_errors[h] += nn.output_errors[o] * nn.w2[h][o]
for h in [0...nn.numHidden]
nn.hidden_errors[h] = nn.hidden_errors[h] * sigmoidP(nn.hidden[h])
# update the hidden to output weights:
for o in [0...nn.numOutputs]
for h in [0...nn.numHidden]
nn.w2[h][o] += learningRate * nn.output_errors[o] * nn.hidden[h]
# update the input to hidden weights:
for h in [0...nn.numHidden]
for i in [0...nn.numInputs]
nn.w1[i][h] += learningRate * nn.hidden_errors[h] * nn.inputs[i]
for o in [0...nn.numOutputs]
error += Math.abs(outs[o] - nn.outputs[o])
error
for iter in [0...500]
console.log(train(test_data))
| 9095 | ### Copyright 2013 <NAME>. All rights reserved.
This code may be used under the Apache 2 license.
This notice must remain in this file and derived files. ###
learningRate = 0.3
new_neural_network = (num_input, num_hidden, num_output) ->
data =
numInputs: num_input
numHidden: num_hidden
numOutputs: num_output
inputs: []
hidden: Array(num_hidden)
outputs: Array(num_output)
w1: Array(num_input) # will be num_input * num_hidden
w2: Array(num_hidden) # will be num_hidden * num_output
output_errors: Array(num_output)
hidden_errors: Array(num_hidden)
input_training_examples: []
output_training_examples: []
for i in [0...num_input]
data.w1[i] = Array(num_hidden)
data.inputs[i] = 0
for h in [0..num_hidden]
data.w2[h] = Array(num_output)
for i in [0...num_input]
for h in [0...num_hidden]
data.w1[i][h] = 0.1 * (Math.random() - 0.5)
for h in [0...num_hidden]
for o in [0...num_output]
data.w2[h][o] = 0.1 * (Math.random() - 0.5);
data
test_data = new_neural_network(3, 3, 3)
console.log test_data
add_training_example = (nn, inputs, outputs) ->
nn.input_training_examples.push(inputs)
nn.output_training_examples.push(outputs)
add_training_example(test_data, [0.1, 0.1, 0.9], [0.9, 0.1, 0.1])
console.log test_data
sigmoid = (x) ->
(1.0 / (1.0 + Math.exp(-x)))
sigmoidP = (x) ->
z = sigmoid(x)
z * (1.0 - z)
forward_pass = (nn) ->
for h in [0...nn.numHidden]
nn.hidden[h] = 0
for i in [0...nn.numInputs]
for h in [0...nn.numHidden]
nn.hidden[h] += nn.inputs[i] * nn.w1[i][h]
for o in [0...nn.numOutputs]
nn.outputs[o] = 0
for h in [0...nn.numHidden]
for o in [0...nn.numOutputs]
nn.outputs[o] += sigmoid(nn.hidden[h]) * nn.w2[h][o]
for o in [0...nn.numOutput]
nn.outputs[o] = sigmoid(nn.outputs[o])
train = (nn) ->
error = 0
num_cases = nn.input_training_examples.length
for ncase in [0...num_cases]
# zero out the errors: at the hidden and output layers:
for i in [0...nn.numHidden]
nn.hidden_errors[h] = 0
for o in [0...nn.numOutputs]
nn.output_errors[o] = 0
for i in [0...nn.numInputs]
nn.inputs[i] = nn.input_training_examples[ncase][i]
outs = nn.output_training_examples[ncase]
forward_pass(nn)
for o in [0..nn.numOutputs]
nn.output_errors[o] = (outs[o] - nn.outputs[o]) * sigmoidP(nn.outputs[o])
for h in [0...nn.numHidden]
nn.hidden_errors[h] = 0.0
for o in [0...nn.numOutputs]
nn.hidden_errors[h] += nn.output_errors[o] * nn.w2[h][o]
for h in [0...nn.numHidden]
nn.hidden_errors[h] = nn.hidden_errors[h] * sigmoidP(nn.hidden[h])
# update the hidden to output weights:
for o in [0...nn.numOutputs]
for h in [0...nn.numHidden]
nn.w2[h][o] += learningRate * nn.output_errors[o] * nn.hidden[h]
# update the input to hidden weights:
for h in [0...nn.numHidden]
for i in [0...nn.numInputs]
nn.w1[i][h] += learningRate * nn.hidden_errors[h] * nn.inputs[i]
for o in [0...nn.numOutputs]
error += Math.abs(outs[o] - nn.outputs[o])
error
for iter in [0...500]
console.log(train(test_data))
| true | ### Copyright 2013 PI:NAME:<NAME>END_PI. All rights reserved.
This code may be used under the Apache 2 license.
This notice must remain in this file and derived files. ###
learningRate = 0.3
new_neural_network = (num_input, num_hidden, num_output) ->
data =
numInputs: num_input
numHidden: num_hidden
numOutputs: num_output
inputs: []
hidden: Array(num_hidden)
outputs: Array(num_output)
w1: Array(num_input) # will be num_input * num_hidden
w2: Array(num_hidden) # will be num_hidden * num_output
output_errors: Array(num_output)
hidden_errors: Array(num_hidden)
input_training_examples: []
output_training_examples: []
for i in [0...num_input]
data.w1[i] = Array(num_hidden)
data.inputs[i] = 0
for h in [0..num_hidden]
data.w2[h] = Array(num_output)
for i in [0...num_input]
for h in [0...num_hidden]
data.w1[i][h] = 0.1 * (Math.random() - 0.5)
for h in [0...num_hidden]
for o in [0...num_output]
data.w2[h][o] = 0.1 * (Math.random() - 0.5);
data
test_data = new_neural_network(3, 3, 3)
console.log test_data
add_training_example = (nn, inputs, outputs) ->
nn.input_training_examples.push(inputs)
nn.output_training_examples.push(outputs)
add_training_example(test_data, [0.1, 0.1, 0.9], [0.9, 0.1, 0.1])
console.log test_data
sigmoid = (x) ->
(1.0 / (1.0 + Math.exp(-x)))
sigmoidP = (x) ->
z = sigmoid(x)
z * (1.0 - z)
forward_pass = (nn) ->
for h in [0...nn.numHidden]
nn.hidden[h] = 0
for i in [0...nn.numInputs]
for h in [0...nn.numHidden]
nn.hidden[h] += nn.inputs[i] * nn.w1[i][h]
for o in [0...nn.numOutputs]
nn.outputs[o] = 0
for h in [0...nn.numHidden]
for o in [0...nn.numOutputs]
nn.outputs[o] += sigmoid(nn.hidden[h]) * nn.w2[h][o]
for o in [0...nn.numOutput]
nn.outputs[o] = sigmoid(nn.outputs[o])
train = (nn) ->
error = 0
num_cases = nn.input_training_examples.length
for ncase in [0...num_cases]
# zero out the errors: at the hidden and output layers:
for i in [0...nn.numHidden]
nn.hidden_errors[h] = 0
for o in [0...nn.numOutputs]
nn.output_errors[o] = 0
for i in [0...nn.numInputs]
nn.inputs[i] = nn.input_training_examples[ncase][i]
outs = nn.output_training_examples[ncase]
forward_pass(nn)
for o in [0..nn.numOutputs]
nn.output_errors[o] = (outs[o] - nn.outputs[o]) * sigmoidP(nn.outputs[o])
for h in [0...nn.numHidden]
nn.hidden_errors[h] = 0.0
for o in [0...nn.numOutputs]
nn.hidden_errors[h] += nn.output_errors[o] * nn.w2[h][o]
for h in [0...nn.numHidden]
nn.hidden_errors[h] = nn.hidden_errors[h] * sigmoidP(nn.hidden[h])
# update the hidden to output weights:
for o in [0...nn.numOutputs]
for h in [0...nn.numHidden]
nn.w2[h][o] += learningRate * nn.output_errors[o] * nn.hidden[h]
# update the input to hidden weights:
for h in [0...nn.numHidden]
for i in [0...nn.numInputs]
nn.w1[i][h] += learningRate * nn.hidden_errors[h] * nn.inputs[i]
for o in [0...nn.numOutputs]
error += Math.abs(outs[o] - nn.outputs[o])
error
for iter in [0...500]
console.log(train(test_data))
|
[
{
"context": "___________\n# Architecture and Code Handcrafted by Prabhat Kumar.\n# Architectuur en Code handgemaakt door Prabhat ",
"end": 352,
"score": 0.7903473973274231,
"start": 339,
"tag": "NAME",
"value": "Prabhat Kumar"
},
{
"context": "hat Kumar.\n# Architectuur en Code hand... | source/core/coffee/main.coffee | CB2L/CB2L.github.io | 1 | #
# CBBL®
# Computational Biology and Bioinformatics Laboratory.
# _______________________________________________________________
# CoffeeScript, http://coffeescript.org/.
# The AMD JavaScript - for defining "common" configurations.
# _______________________________________________________________
# Architecture and Code Handcrafted by Prabhat Kumar.
# Architectuur en Code handgemaakt door Prabhat Kumar.
# @author : Prabhat Kumar [http://prabhatkumar.org/]
# @copyright : Sequømics Corporation [http://sequomics.com/]
# _______________________________________________________________
# @date : 10-May-2016
# @license : Apache, version 2.0
# @require : Node.js®
# @require : NPM
# @require : Grunt
# _______________________________________________________________
| 183400 | #
# CBBL®
# Computational Biology and Bioinformatics Laboratory.
# _______________________________________________________________
# CoffeeScript, http://coffeescript.org/.
# The AMD JavaScript - for defining "common" configurations.
# _______________________________________________________________
# Architecture and Code Handcrafted by <NAME>.
# Architectuur en Code handgemaakt door <NAME>.
# @author : <NAME> [http://prabhatkumar.org/]
# @copyright : Sequømics Corporation [http://sequomics.com/]
# _______________________________________________________________
# @date : 10-May-2016
# @license : Apache, version 2.0
# @require : Node.js®
# @require : NPM
# @require : Grunt
# _______________________________________________________________
| true | #
# CBBL®
# Computational Biology and Bioinformatics Laboratory.
# _______________________________________________________________
# CoffeeScript, http://coffeescript.org/.
# The AMD JavaScript - for defining "common" configurations.
# _______________________________________________________________
# Architecture and Code Handcrafted by PI:NAME:<NAME>END_PI.
# Architectuur en Code handgemaakt door PI:NAME:<NAME>END_PI.
# @author : PI:NAME:<NAME>END_PI [http://prabhatkumar.org/]
# @copyright : Sequømics Corporation [http://sequomics.com/]
# _______________________________________________________________
# @date : 10-May-2016
# @license : Apache, version 2.0
# @require : Node.js®
# @require : NPM
# @require : Grunt
# _______________________________________________________________
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993962645530701,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-event-emitter-subclass.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.
MyEE = (cb) ->
@once 1, cb
@emit 1
@removeAllListeners()
EventEmitter.call this
return
ErrorEE = ->
@emit "error", new Error("blerg")
return
MyEE2 = ->
EventEmitter.call this
return
common = require("../common")
assert = require("assert")
EventEmitter = require("events").EventEmitter
util = require("util")
util.inherits MyEE, EventEmitter
called = false
myee = new MyEE(->
called = true
return
)
util.inherits ErrorEE, EventEmitter
assert.throws (->
new ErrorEE()
return
), /blerg/
process.on "exit", ->
assert called
assert.deepEqual myee._events, {}
console.log "ok"
return
MyEE2:: = new EventEmitter()
ee1 = new MyEE2()
ee2 = new MyEE2()
ee1.on "x", ->
assert.equal EventEmitter.listenerCount(ee2, "x"), 0
| 26571 | # 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.
MyEE = (cb) ->
@once 1, cb
@emit 1
@removeAllListeners()
EventEmitter.call this
return
ErrorEE = ->
@emit "error", new Error("blerg")
return
MyEE2 = ->
EventEmitter.call this
return
common = require("../common")
assert = require("assert")
EventEmitter = require("events").EventEmitter
util = require("util")
util.inherits MyEE, EventEmitter
called = false
myee = new MyEE(->
called = true
return
)
util.inherits ErrorEE, EventEmitter
assert.throws (->
new ErrorEE()
return
), /blerg/
process.on "exit", ->
assert called
assert.deepEqual myee._events, {}
console.log "ok"
return
MyEE2:: = new EventEmitter()
ee1 = new MyEE2()
ee2 = new MyEE2()
ee1.on "x", ->
assert.equal EventEmitter.listenerCount(ee2, "x"), 0
| 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.
MyEE = (cb) ->
@once 1, cb
@emit 1
@removeAllListeners()
EventEmitter.call this
return
ErrorEE = ->
@emit "error", new Error("blerg")
return
MyEE2 = ->
EventEmitter.call this
return
common = require("../common")
assert = require("assert")
EventEmitter = require("events").EventEmitter
util = require("util")
util.inherits MyEE, EventEmitter
called = false
myee = new MyEE(->
called = true
return
)
util.inherits ErrorEE, EventEmitter
assert.throws (->
new ErrorEE()
return
), /blerg/
process.on "exit", ->
assert called
assert.deepEqual myee._events, {}
console.log "ok"
return
MyEE2:: = new EventEmitter()
ee1 = new MyEE2()
ee2 = new MyEE2()
ee1.on "x", ->
assert.equal EventEmitter.listenerCount(ee2, "x"), 0
|
[
{
"context": "\n beforeEach ->\n @sut.forgotPassword(\"peter@bacon.com\")\n @rootScope.$digest()\n\n it 'should ",
"end": 526,
"score": 0.9998916983604431,
"start": 511,
"tag": "EMAIL",
"value": "peter@bacon.com"
},
{
"context": "ould call AuthenticatorService... | test/app/forgot-password-controller-spec.coffee | octoblu/email-password-site | 1 | describe 'ForgotPasswordController', ->
beforeEach ->
module 'email-password'
inject ($controller, $q, $rootScope) ->
@q = $q
@rootScope = $rootScope
@AuthenticatorService = forgotPassword: sinon.stub().returns(@q.when())
@sut = $controller 'ForgotPasswordController',
AuthenticatorService: @AuthenticatorService
$routeParams: {}
describe '->forgotPassword', ->
describe 'when called with an email', ->
beforeEach ->
@sut.forgotPassword("peter@bacon.com")
@rootScope.$digest()
it 'should call AuthenticatorService.forgotPassword with peter@bacon.com', ->
expect(@AuthenticatorService.forgotPassword).to.have.been.calledWith 'peter@bacon.com'
describe 'when called with a different email', ->
beforeEach ->
@sut.forgotPassword("aaron@isnt-cool-enough-for-bacon.com")
@rootScope.$digest()
it 'should call AuthenticatorService.forgotPassword with aaron@isnt-cool-enough-for-bacon.com', ->
expect(@AuthenticatorService.forgotPassword).to.have.been.calledWith 'aaron@isnt-cool-enough-for-bacon.com'
describe "when AuthenticatorService.forgotPassword resolves it's promise", ->
beforeEach ->
@AuthenticatorService.forgotPassword.returns @q.when()
@sut.forgotPassword "yes@aaron-totally-is.com"
@rootScope.$digest()
it "should add a message", ->
expect(@sut.message).to.equal 'An email has been sent.'
it "should not add an error message", ->
expect(@sut.errorMessage).to.not.exist
describe "when AuthenticatorService.forgotPassword rejects it's promise", ->
beforeEach ->
@AuthenticatorService.forgotPassword.returns @q.reject()
@sut.forgotPassword "yes@aaron-totally-is.com"
@rootScope.$digest()
it "should not add a message", ->
expect(@sut.message).to.not.exist
it "should add an errorMessage", ->
expect(@sut.errorMessage).to.equal 'Error resetting your password'
| 211316 | describe 'ForgotPasswordController', ->
beforeEach ->
module 'email-password'
inject ($controller, $q, $rootScope) ->
@q = $q
@rootScope = $rootScope
@AuthenticatorService = forgotPassword: sinon.stub().returns(@q.when())
@sut = $controller 'ForgotPasswordController',
AuthenticatorService: @AuthenticatorService
$routeParams: {}
describe '->forgotPassword', ->
describe 'when called with an email', ->
beforeEach ->
@sut.forgotPassword("<EMAIL>")
@rootScope.$digest()
it 'should call AuthenticatorService.forgotPassword with <EMAIL>', ->
expect(@AuthenticatorService.forgotPassword).to.have.been.calledWith '<EMAIL>'
describe 'when called with a different email', ->
beforeEach ->
@sut.forgotPassword("<EMAIL>")
@rootScope.$digest()
it 'should call AuthenticatorService.forgotPassword with <EMAIL>', ->
expect(@AuthenticatorService.forgotPassword).to.have.been.calledWith '<EMAIL>'
describe "when AuthenticatorService.forgotPassword resolves it's promise", ->
beforeEach ->
@AuthenticatorService.forgotPassword.returns @q.when()
@sut.forgotPassword "<EMAIL>"
@rootScope.$digest()
it "should add a message", ->
expect(@sut.message).to.equal 'An email has been sent.'
it "should not add an error message", ->
expect(@sut.errorMessage).to.not.exist
describe "when AuthenticatorService.forgotPassword rejects it's promise", ->
beforeEach ->
@AuthenticatorService.forgotPassword.returns @q.reject()
@sut.forgotPassword "<EMAIL>"
@rootScope.$digest()
it "should not add a message", ->
expect(@sut.message).to.not.exist
it "should add an errorMessage", ->
expect(@sut.errorMessage).to.equal 'Error resetting your password'
| true | describe 'ForgotPasswordController', ->
beforeEach ->
module 'email-password'
inject ($controller, $q, $rootScope) ->
@q = $q
@rootScope = $rootScope
@AuthenticatorService = forgotPassword: sinon.stub().returns(@q.when())
@sut = $controller 'ForgotPasswordController',
AuthenticatorService: @AuthenticatorService
$routeParams: {}
describe '->forgotPassword', ->
describe 'when called with an email', ->
beforeEach ->
@sut.forgotPassword("PI:EMAIL:<EMAIL>END_PI")
@rootScope.$digest()
it 'should call AuthenticatorService.forgotPassword with PI:EMAIL:<EMAIL>END_PI', ->
expect(@AuthenticatorService.forgotPassword).to.have.been.calledWith 'PI:EMAIL:<EMAIL>END_PI'
describe 'when called with a different email', ->
beforeEach ->
@sut.forgotPassword("PI:EMAIL:<EMAIL>END_PI")
@rootScope.$digest()
it 'should call AuthenticatorService.forgotPassword with PI:EMAIL:<EMAIL>END_PI', ->
expect(@AuthenticatorService.forgotPassword).to.have.been.calledWith 'PI:EMAIL:<EMAIL>END_PI'
describe "when AuthenticatorService.forgotPassword resolves it's promise", ->
beforeEach ->
@AuthenticatorService.forgotPassword.returns @q.when()
@sut.forgotPassword "PI:EMAIL:<EMAIL>END_PI"
@rootScope.$digest()
it "should add a message", ->
expect(@sut.message).to.equal 'An email has been sent.'
it "should not add an error message", ->
expect(@sut.errorMessage).to.not.exist
describe "when AuthenticatorService.forgotPassword rejects it's promise", ->
beforeEach ->
@AuthenticatorService.forgotPassword.returns @q.reject()
@sut.forgotPassword "PI:EMAIL:<EMAIL>END_PI"
@rootScope.$digest()
it "should not add a message", ->
expect(@sut.message).to.not.exist
it "should add an errorMessage", ->
expect(@sut.errorMessage).to.equal 'Error resetting your password'
|
[
{
"context": "mail('foo@bar'))\n\n aok(utils.is_email('foo@bar.baz'))\n\n test_luhn_check: ->\n aok(u",
"end": 5533,
"score": 0.9769812822341919,
"start": 5522,
"tag": "EMAIL",
"value": "foo@bar.baz"
}
] | clients/test/jstest_utils_any.coffee | jacob22/accounting | 0 | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Tests = new Deferred()
require(['utils'], (utils) ->
Tests.callback(
test_formatCurrency: ->
res = utils.formatCurrency(1000)
ais(res, '10,00')
res = utils.formatCurrency(1000, '.')
ais(res, '10.00')
res = utils.formatCurrency(0)
ais(res, '0,00')
res = utils.formatCurrency(-12345)
ais(res, '-123,45')
res = utils.formatCurrency(1.1)
ais(res, '0,01')
test_parseCurrency: ->
res = utils.parseCurrency('1234')
ais(res, 123400)
res = utils.parseCurrency('12.34')
ais(res, 1234)
res = utils.parseCurrency('12.')
ais(res, 1200)
res = utils.parseCurrency('1,212.')
ais(res, 121200)
res = utils.parseCurrency('1.212.00')
ais(res, 121200)
res = utils.parseCurrency('1.212.00 ')
ais(res, 121200)
res = utils.parseCurrency('.45')
ais(res, 45)
res = utils.parseCurrency('')
ais(res, null)
res = utils.parseCurrency("-12")
ais(res, -1200)
res = utils.parseCurrency("-12.34")
ais(res, -1234)
res = utils.parseCurrency("-1.234.56")
ais(res, -123456)
res = utils.parseCurrency("1,000")
ais(res, 100000)
res = utils.parseCurrency("-.45")
ais(res, -45)
res = utils.parseCurrency('12,34,56,78')
ais(res, 12345678)
res = utils.parseCurrency('1,23,45,678') # Indians...
ais(res, 1234567800)
res = utils.parseCurrency('12 34 56:78')
ais(res, 12345678)
test_parseDecimal: ->
res = utils.parseDecimal('0')
ais(res, 0)
res = utils.parseDecimal('1234')
ais(res, 123400)
res = utils.parseDecimal('1234.0')
ais(res, 123400)
res = utils.parseDecimal('1234.00')
ais(res, 123400)
res = utils.parseDecimal('1234.000')
ais(res, 123400)
res = utils.parseDecimal('1234.0000')
ais(res, 123400)
res = utils.parseDecimal('1234.1')
ais(res, 123410)
res = utils.parseDecimal('1234.10')
ais(res, 123410)
res = utils.parseDecimal('1234.100')
ais(res, 123410)
res = utils.parseDecimal('1234.1000')
ais(res, 123410)
res = utils.parseDecimal('12.34')
ais(res, 1234)
res = utils.parseDecimal('12.340000')
ais(res, 1234)
araises(utils.parseDecimal, '12.')
araises(utils.parseDecimal, '12.345678') # too many decimals
araises(utils.parseDecimal, '12,000')
araises(utils.parseDecimal, '12,000.00')
araises(utils.parseDecimal, 'random gorp')
test_clear: ->
obj =
foo: 1
bar: 2
baz: 3
result = utils.clear(obj)
aok(result == obj) # result and obj is the same object
# All keys should have been removed
aok(not obj.foo?)
aok(not obj.bar?)
aok(not obj.baz?)
test_sum: ->
ais(utils.sum([]), 0)
ais(utils.sum([1]), 1)
ais(utils.sum([1, 2, 3]), 6)
test_update: ->
first = foo: 1
second = bar: 2
result = utils.update(first, second)
aok(result == first) # result and first is the same object
ais(result.foo, 1)
ais(result.bar, 2)
# second should be unaffected
ais(second.bar, 2)
aok(not second.foo?)
test_array_equal: ->
aok(utils.array_equal([1], [1]))
aok(utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]))
aok(not utils.array_equal([1], [2]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 4]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, '4', 5]))
# Nested arrays
a = [[1, 2]]
b = [[1, 2]]
aok(utils.array_equal(a, b, true))
a = [null]
b = [null]
aok(utils.array_equal(a, b, true))
a = [[1, 2]]
b = [[1]]
aok(not utils.array_equal(a, b, true))
a = [[1, 2]]
b = [1]
aok(not utils.array_equal(a, b, true))
test_is_email: ->
aok(not utils.is_email(null))
aok(not utils.is_email(''))
aok(not utils.is_email('foo@bar'))
aok(utils.is_email('foo@bar.baz'))
test_luhn_check: ->
aok(utils.luhn_check('4539869986356160'))
aok(utils.luhn_check('5440269983606292'))
aok(utils.luhn_check('345779552730759'))
aok(utils.luhn_check('6011826568969481'))
aok(utils.luhn_check('3589289678861297'))
aok(utils.luhn_check('5512860722117394'))
aok(utils.luhn_check('30002946744307'))
aok(utils.luhn_check('36084156383632'))
aok(utils.luhn_check('6763994125062388'))
aok(utils.luhn_check('6771326207691877'))
aok(utils.luhn_check('4844738655516265'))
aok(utils.luhn_check('6374721799752858'))
aok(!utils.luhn_check('5539869986356160'))
aok(!utils.luhn_check('5540269983606292'))
aok(!utils.luhn_check('346779552730759'))
aok(!utils.luhn_check('6012826568969481'))
aok(!utils.luhn_check('3589389678861297'))
aok(!utils.luhn_check('5512870722117394'))
aok(!utils.luhn_check('30002956744307'))
aok(!utils.luhn_check('36084157383632'))
aok(!utils.luhn_check('6763994135062388'))
aok(!utils.luhn_check('6771326208691877'))
aok(!utils.luhn_check('4844738655616265'))
aok(!utils.luhn_check('6374721799762858'))
test_date_re: ->
ok = [
'2017-05-01'
'2017-02-28'
'2017-02-31' # Oh well
]
not_ok = [
''
'not a date'
'2017-13-01' # Invalid month
]
for v in ok
aok(v.match(utils.date.regex)?)
aok(v.match(utils.date.pattern)?)
for v in not_ok
aok(!v.match(utils.date.regex)?)
aok(!v.match(utils.date.pattern)?)
test_get_error_message: ->
error1 =
__class__: 'BlmError'
args: ['foo']
error2 =
__class__: 'BlmError'
args: ['Permission denied: <TO 5b30dc50a735c30327ade3a3>, on_create']
error3 =
__class__: 'PermissionError'
ais(utils.get_error_message(error1), 'foo')
ais(utils.get_error_message(error2), 'Permission denied')
ais(utils.get_error_message(error3), 'Permission denied')
ais(utils.get_error_message(null), null)
ais(utils.get_error_message('whatever'), null)
test_is_permission_error: ->
permerror =
__class__: 'PermissionError'
wrappedpermerror =
__class__: 'BlmError'
args: ['Permission denied: <TO 5b30dc50a735c30327ade3a3>, on_create']
othererror =
__class__: 'BlmError'
args: ['foo']
aok(utils.is_permission_error(permerror))
aok(utils.is_permission_error(wrappedpermerror))
aok(!utils.is_permission_error(othererror))
)
)
| 97086 | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Tests = new Deferred()
require(['utils'], (utils) ->
Tests.callback(
test_formatCurrency: ->
res = utils.formatCurrency(1000)
ais(res, '10,00')
res = utils.formatCurrency(1000, '.')
ais(res, '10.00')
res = utils.formatCurrency(0)
ais(res, '0,00')
res = utils.formatCurrency(-12345)
ais(res, '-123,45')
res = utils.formatCurrency(1.1)
ais(res, '0,01')
test_parseCurrency: ->
res = utils.parseCurrency('1234')
ais(res, 123400)
res = utils.parseCurrency('12.34')
ais(res, 1234)
res = utils.parseCurrency('12.')
ais(res, 1200)
res = utils.parseCurrency('1,212.')
ais(res, 121200)
res = utils.parseCurrency('1.212.00')
ais(res, 121200)
res = utils.parseCurrency('1.212.00 ')
ais(res, 121200)
res = utils.parseCurrency('.45')
ais(res, 45)
res = utils.parseCurrency('')
ais(res, null)
res = utils.parseCurrency("-12")
ais(res, -1200)
res = utils.parseCurrency("-12.34")
ais(res, -1234)
res = utils.parseCurrency("-1.234.56")
ais(res, -123456)
res = utils.parseCurrency("1,000")
ais(res, 100000)
res = utils.parseCurrency("-.45")
ais(res, -45)
res = utils.parseCurrency('12,34,56,78')
ais(res, 12345678)
res = utils.parseCurrency('1,23,45,678') # Indians...
ais(res, 1234567800)
res = utils.parseCurrency('12 34 56:78')
ais(res, 12345678)
test_parseDecimal: ->
res = utils.parseDecimal('0')
ais(res, 0)
res = utils.parseDecimal('1234')
ais(res, 123400)
res = utils.parseDecimal('1234.0')
ais(res, 123400)
res = utils.parseDecimal('1234.00')
ais(res, 123400)
res = utils.parseDecimal('1234.000')
ais(res, 123400)
res = utils.parseDecimal('1234.0000')
ais(res, 123400)
res = utils.parseDecimal('1234.1')
ais(res, 123410)
res = utils.parseDecimal('1234.10')
ais(res, 123410)
res = utils.parseDecimal('1234.100')
ais(res, 123410)
res = utils.parseDecimal('1234.1000')
ais(res, 123410)
res = utils.parseDecimal('12.34')
ais(res, 1234)
res = utils.parseDecimal('12.340000')
ais(res, 1234)
araises(utils.parseDecimal, '12.')
araises(utils.parseDecimal, '12.345678') # too many decimals
araises(utils.parseDecimal, '12,000')
araises(utils.parseDecimal, '12,000.00')
araises(utils.parseDecimal, 'random gorp')
test_clear: ->
obj =
foo: 1
bar: 2
baz: 3
result = utils.clear(obj)
aok(result == obj) # result and obj is the same object
# All keys should have been removed
aok(not obj.foo?)
aok(not obj.bar?)
aok(not obj.baz?)
test_sum: ->
ais(utils.sum([]), 0)
ais(utils.sum([1]), 1)
ais(utils.sum([1, 2, 3]), 6)
test_update: ->
first = foo: 1
second = bar: 2
result = utils.update(first, second)
aok(result == first) # result and first is the same object
ais(result.foo, 1)
ais(result.bar, 2)
# second should be unaffected
ais(second.bar, 2)
aok(not second.foo?)
test_array_equal: ->
aok(utils.array_equal([1], [1]))
aok(utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]))
aok(not utils.array_equal([1], [2]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 4]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, '4', 5]))
# Nested arrays
a = [[1, 2]]
b = [[1, 2]]
aok(utils.array_equal(a, b, true))
a = [null]
b = [null]
aok(utils.array_equal(a, b, true))
a = [[1, 2]]
b = [[1]]
aok(not utils.array_equal(a, b, true))
a = [[1, 2]]
b = [1]
aok(not utils.array_equal(a, b, true))
test_is_email: ->
aok(not utils.is_email(null))
aok(not utils.is_email(''))
aok(not utils.is_email('foo@bar'))
aok(utils.is_email('<EMAIL>'))
test_luhn_check: ->
aok(utils.luhn_check('4539869986356160'))
aok(utils.luhn_check('5440269983606292'))
aok(utils.luhn_check('345779552730759'))
aok(utils.luhn_check('6011826568969481'))
aok(utils.luhn_check('3589289678861297'))
aok(utils.luhn_check('5512860722117394'))
aok(utils.luhn_check('30002946744307'))
aok(utils.luhn_check('36084156383632'))
aok(utils.luhn_check('6763994125062388'))
aok(utils.luhn_check('6771326207691877'))
aok(utils.luhn_check('4844738655516265'))
aok(utils.luhn_check('6374721799752858'))
aok(!utils.luhn_check('5539869986356160'))
aok(!utils.luhn_check('5540269983606292'))
aok(!utils.luhn_check('346779552730759'))
aok(!utils.luhn_check('6012826568969481'))
aok(!utils.luhn_check('3589389678861297'))
aok(!utils.luhn_check('5512870722117394'))
aok(!utils.luhn_check('30002956744307'))
aok(!utils.luhn_check('36084157383632'))
aok(!utils.luhn_check('6763994135062388'))
aok(!utils.luhn_check('6771326208691877'))
aok(!utils.luhn_check('4844738655616265'))
aok(!utils.luhn_check('6374721799762858'))
test_date_re: ->
ok = [
'2017-05-01'
'2017-02-28'
'2017-02-31' # Oh well
]
not_ok = [
''
'not a date'
'2017-13-01' # Invalid month
]
for v in ok
aok(v.match(utils.date.regex)?)
aok(v.match(utils.date.pattern)?)
for v in not_ok
aok(!v.match(utils.date.regex)?)
aok(!v.match(utils.date.pattern)?)
test_get_error_message: ->
error1 =
__class__: 'BlmError'
args: ['foo']
error2 =
__class__: 'BlmError'
args: ['Permission denied: <TO 5b30dc50a735c30327ade3a3>, on_create']
error3 =
__class__: 'PermissionError'
ais(utils.get_error_message(error1), 'foo')
ais(utils.get_error_message(error2), 'Permission denied')
ais(utils.get_error_message(error3), 'Permission denied')
ais(utils.get_error_message(null), null)
ais(utils.get_error_message('whatever'), null)
test_is_permission_error: ->
permerror =
__class__: 'PermissionError'
wrappedpermerror =
__class__: 'BlmError'
args: ['Permission denied: <TO 5b30dc50a735c30327ade3a3>, on_create']
othererror =
__class__: 'BlmError'
args: ['foo']
aok(utils.is_permission_error(permerror))
aok(utils.is_permission_error(wrappedpermerror))
aok(!utils.is_permission_error(othererror))
)
)
| true | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Tests = new Deferred()
require(['utils'], (utils) ->
Tests.callback(
test_formatCurrency: ->
res = utils.formatCurrency(1000)
ais(res, '10,00')
res = utils.formatCurrency(1000, '.')
ais(res, '10.00')
res = utils.formatCurrency(0)
ais(res, '0,00')
res = utils.formatCurrency(-12345)
ais(res, '-123,45')
res = utils.formatCurrency(1.1)
ais(res, '0,01')
test_parseCurrency: ->
res = utils.parseCurrency('1234')
ais(res, 123400)
res = utils.parseCurrency('12.34')
ais(res, 1234)
res = utils.parseCurrency('12.')
ais(res, 1200)
res = utils.parseCurrency('1,212.')
ais(res, 121200)
res = utils.parseCurrency('1.212.00')
ais(res, 121200)
res = utils.parseCurrency('1.212.00 ')
ais(res, 121200)
res = utils.parseCurrency('.45')
ais(res, 45)
res = utils.parseCurrency('')
ais(res, null)
res = utils.parseCurrency("-12")
ais(res, -1200)
res = utils.parseCurrency("-12.34")
ais(res, -1234)
res = utils.parseCurrency("-1.234.56")
ais(res, -123456)
res = utils.parseCurrency("1,000")
ais(res, 100000)
res = utils.parseCurrency("-.45")
ais(res, -45)
res = utils.parseCurrency('12,34,56,78')
ais(res, 12345678)
res = utils.parseCurrency('1,23,45,678') # Indians...
ais(res, 1234567800)
res = utils.parseCurrency('12 34 56:78')
ais(res, 12345678)
test_parseDecimal: ->
res = utils.parseDecimal('0')
ais(res, 0)
res = utils.parseDecimal('1234')
ais(res, 123400)
res = utils.parseDecimal('1234.0')
ais(res, 123400)
res = utils.parseDecimal('1234.00')
ais(res, 123400)
res = utils.parseDecimal('1234.000')
ais(res, 123400)
res = utils.parseDecimal('1234.0000')
ais(res, 123400)
res = utils.parseDecimal('1234.1')
ais(res, 123410)
res = utils.parseDecimal('1234.10')
ais(res, 123410)
res = utils.parseDecimal('1234.100')
ais(res, 123410)
res = utils.parseDecimal('1234.1000')
ais(res, 123410)
res = utils.parseDecimal('12.34')
ais(res, 1234)
res = utils.parseDecimal('12.340000')
ais(res, 1234)
araises(utils.parseDecimal, '12.')
araises(utils.parseDecimal, '12.345678') # too many decimals
araises(utils.parseDecimal, '12,000')
araises(utils.parseDecimal, '12,000.00')
araises(utils.parseDecimal, 'random gorp')
test_clear: ->
obj =
foo: 1
bar: 2
baz: 3
result = utils.clear(obj)
aok(result == obj) # result and obj is the same object
# All keys should have been removed
aok(not obj.foo?)
aok(not obj.bar?)
aok(not obj.baz?)
test_sum: ->
ais(utils.sum([]), 0)
ais(utils.sum([1]), 1)
ais(utils.sum([1, 2, 3]), 6)
test_update: ->
first = foo: 1
second = bar: 2
result = utils.update(first, second)
aok(result == first) # result and first is the same object
ais(result.foo, 1)
ais(result.bar, 2)
# second should be unaffected
ais(second.bar, 2)
aok(not second.foo?)
test_array_equal: ->
aok(utils.array_equal([1], [1]))
aok(utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]))
aok(not utils.array_equal([1], [2]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 4]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]))
aok(not utils.array_equal([1, 2, 3, 4, 5], [1, 2, 3, '4', 5]))
# Nested arrays
a = [[1, 2]]
b = [[1, 2]]
aok(utils.array_equal(a, b, true))
a = [null]
b = [null]
aok(utils.array_equal(a, b, true))
a = [[1, 2]]
b = [[1]]
aok(not utils.array_equal(a, b, true))
a = [[1, 2]]
b = [1]
aok(not utils.array_equal(a, b, true))
test_is_email: ->
aok(not utils.is_email(null))
aok(not utils.is_email(''))
aok(not utils.is_email('foo@bar'))
aok(utils.is_email('PI:EMAIL:<EMAIL>END_PI'))
test_luhn_check: ->
aok(utils.luhn_check('4539869986356160'))
aok(utils.luhn_check('5440269983606292'))
aok(utils.luhn_check('345779552730759'))
aok(utils.luhn_check('6011826568969481'))
aok(utils.luhn_check('3589289678861297'))
aok(utils.luhn_check('5512860722117394'))
aok(utils.luhn_check('30002946744307'))
aok(utils.luhn_check('36084156383632'))
aok(utils.luhn_check('6763994125062388'))
aok(utils.luhn_check('6771326207691877'))
aok(utils.luhn_check('4844738655516265'))
aok(utils.luhn_check('6374721799752858'))
aok(!utils.luhn_check('5539869986356160'))
aok(!utils.luhn_check('5540269983606292'))
aok(!utils.luhn_check('346779552730759'))
aok(!utils.luhn_check('6012826568969481'))
aok(!utils.luhn_check('3589389678861297'))
aok(!utils.luhn_check('5512870722117394'))
aok(!utils.luhn_check('30002956744307'))
aok(!utils.luhn_check('36084157383632'))
aok(!utils.luhn_check('6763994135062388'))
aok(!utils.luhn_check('6771326208691877'))
aok(!utils.luhn_check('4844738655616265'))
aok(!utils.luhn_check('6374721799762858'))
test_date_re: ->
ok = [
'2017-05-01'
'2017-02-28'
'2017-02-31' # Oh well
]
not_ok = [
''
'not a date'
'2017-13-01' # Invalid month
]
for v in ok
aok(v.match(utils.date.regex)?)
aok(v.match(utils.date.pattern)?)
for v in not_ok
aok(!v.match(utils.date.regex)?)
aok(!v.match(utils.date.pattern)?)
test_get_error_message: ->
error1 =
__class__: 'BlmError'
args: ['foo']
error2 =
__class__: 'BlmError'
args: ['Permission denied: <TO 5b30dc50a735c30327ade3a3>, on_create']
error3 =
__class__: 'PermissionError'
ais(utils.get_error_message(error1), 'foo')
ais(utils.get_error_message(error2), 'Permission denied')
ais(utils.get_error_message(error3), 'Permission denied')
ais(utils.get_error_message(null), null)
ais(utils.get_error_message('whatever'), null)
test_is_permission_error: ->
permerror =
__class__: 'PermissionError'
wrappedpermerror =
__class__: 'BlmError'
args: ['Permission denied: <TO 5b30dc50a735c30327ade3a3>, on_create']
othererror =
__class__: 'BlmError'
args: ['foo']
aok(utils.is_permission_error(permerror))
aok(utils.is_permission_error(wrappedpermerror))
aok(!utils.is_permission_error(othererror))
)
)
|
[
{
"context": "text_manipulate.dict_append_proc(dict_aa,'t2539','彦根',26857,'1954-11-18')\n\t\n\treturn\tdict_aa\n\n# -------",
"end": 1183,
"score": 0.9991827011108398,
"start": 1181,
"tag": "NAME",
"value": "彦根"
}
] | pdf/coffee/create/pdf_create.coffee | ekzemplaro/data_base_language | 3 | #! /usr/bin/coffee
# ---------------------------------------------------------------
# pdf_create.coffee
#
# Jan/10/2017
#
# ---------------------------------------------------------------
PDFDocument = require('pdfkit')
fs = require('fs')
text_manipulate=require ("/var/www/data_base/common/coffee_common/text_manipulate")
#
# ---------------------------------------------------------------
data_prepare_proc = () ->
dict_aa = new Object
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2531','大津',85614,'1954-9-12')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2532','草津',69157,'1954-3-15')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2533','守山',29371,'1954-10-2')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2534','栗東',82664,'1954-6-22')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2535','野洲',13658,'1954-8-14')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2536','甲賀',65792,'1954-9-12')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2537','湖南',38251,'1954-3-21')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2538','近江八幡',52486,'1954-7-26')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2539','彦根',26857,'1954-11-18')
return dict_aa
# ---------------------------------------------------------------
console.error "*** 開始 ***"
doc = new PDFDocument
file_pdf=process.argv[2]
dict_aa = data_prepare_proc()
doc.pipe(fs.createWriteStream (file_pdf))
doc.font ('/var/www/data_base/common/node_common/IPAexfont00301/ipaexm.ttf')
array_aa = text_manipulate.sort_key_proc(dict_aa)
yy = 10
for unit in array_aa
key = unit.key
value = unit.value
doc.save()
.fontSize(25)
.text(key, 50, yy)
.text(value.name, 150, yy)
.text(value.population, 300, yy)
.text(value.date_mod, 400, yy)
yy += 50
doc.end()
console.error "*** 終了 ***"
# ---------------------------------------------------------------
| 3580 | #! /usr/bin/coffee
# ---------------------------------------------------------------
# pdf_create.coffee
#
# Jan/10/2017
#
# ---------------------------------------------------------------
PDFDocument = require('pdfkit')
fs = require('fs')
text_manipulate=require ("/var/www/data_base/common/coffee_common/text_manipulate")
#
# ---------------------------------------------------------------
data_prepare_proc = () ->
dict_aa = new Object
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2531','大津',85614,'1954-9-12')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2532','草津',69157,'1954-3-15')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2533','守山',29371,'1954-10-2')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2534','栗東',82664,'1954-6-22')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2535','野洲',13658,'1954-8-14')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2536','甲賀',65792,'1954-9-12')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2537','湖南',38251,'1954-3-21')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2538','近江八幡',52486,'1954-7-26')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2539','<NAME>',26857,'1954-11-18')
return dict_aa
# ---------------------------------------------------------------
console.error "*** 開始 ***"
doc = new PDFDocument
file_pdf=process.argv[2]
dict_aa = data_prepare_proc()
doc.pipe(fs.createWriteStream (file_pdf))
doc.font ('/var/www/data_base/common/node_common/IPAexfont00301/ipaexm.ttf')
array_aa = text_manipulate.sort_key_proc(dict_aa)
yy = 10
for unit in array_aa
key = unit.key
value = unit.value
doc.save()
.fontSize(25)
.text(key, 50, yy)
.text(value.name, 150, yy)
.text(value.population, 300, yy)
.text(value.date_mod, 400, yy)
yy += 50
doc.end()
console.error "*** 終了 ***"
# ---------------------------------------------------------------
| true | #! /usr/bin/coffee
# ---------------------------------------------------------------
# pdf_create.coffee
#
# Jan/10/2017
#
# ---------------------------------------------------------------
PDFDocument = require('pdfkit')
fs = require('fs')
text_manipulate=require ("/var/www/data_base/common/coffee_common/text_manipulate")
#
# ---------------------------------------------------------------
data_prepare_proc = () ->
dict_aa = new Object
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2531','大津',85614,'1954-9-12')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2532','草津',69157,'1954-3-15')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2533','守山',29371,'1954-10-2')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2534','栗東',82664,'1954-6-22')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2535','野洲',13658,'1954-8-14')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2536','甲賀',65792,'1954-9-12')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2537','湖南',38251,'1954-3-21')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2538','近江八幡',52486,'1954-7-26')
dict_aa = text_manipulate.dict_append_proc(dict_aa,'t2539','PI:NAME:<NAME>END_PI',26857,'1954-11-18')
return dict_aa
# ---------------------------------------------------------------
console.error "*** 開始 ***"
doc = new PDFDocument
file_pdf=process.argv[2]
dict_aa = data_prepare_proc()
doc.pipe(fs.createWriteStream (file_pdf))
doc.font ('/var/www/data_base/common/node_common/IPAexfont00301/ipaexm.ttf')
array_aa = text_manipulate.sort_key_proc(dict_aa)
yy = 10
for unit in array_aa
key = unit.key
value = unit.value
doc.save()
.fontSize(25)
.text(key, 50, yy)
.text(value.name, 150, yy)
.text(value.population, 300, yy)
.text(value.date_mod, 400, yy)
yy += 50
doc.end()
console.error "*** 終了 ***"
# ---------------------------------------------------------------
|
[
{
"context": " port: 3306,\n password: '',\n database: 'test'\n onEr",
"end": 6647,
"score": 0.7763354182243347,
"start": 6647,
"tag": "PASSWORD",
"value": ""
}
] | src/index.coffee | yangsibai/mysql-dbhelper | 1 | mysql = require("mysql")
Connection = require("mysql/lib/Connection")
_ = require("underscore")
Connection.prototype.execute = ->
this.query.apply(this, arguments)
###
查询并在完成后立即关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$execute = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
查询第一行第一列的内容
@param {String} sql
@param {Array} paras parameters array
@param {Function} cb callback function
###
Connection.prototype.executeScalar = (sql, paras, cb) ->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction cb
if err
cb err
else if result.length > 0
for name, value of result[0]
cb null, value
return
else
cb null, null
###
查询第一行第一列的内容,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeScalar = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeScalar sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end =>
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
更新
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.update = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.changedRows > 0
cb null, true, result.changedRows
else
cb null, false
###
更新并且自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$update = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@update sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
插入
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.insert = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.affectedRows > 0
cb null, true, result.insertId
else
cb null, false
###
插入数据并且自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$insert = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@insert sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
执行sql,返回受影响的行数
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.executeNonQuery = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.affectedRows > 0
cb null, true, result.affectedRows
else
cb null, false
###
执行sql,返回受影响的行数,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeNonQuery = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeNonQuery sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
获取第一行数据
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.executeFirstRow = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.length > 0
cb null, result[0]
else
cb null, null
###
获取第一行的数据,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeFirstRow = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeFirstRow sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
判断是否存在
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.exist = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, results)->
if _.isFunction(cb)
if err
cb err
else if results.length > 0
cb null, true, results
else
cb null, false, results
###
判断是否存在,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$exist = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, results)=>
@end ->
if _.isFunction(cb)
if err
cb err
else if results.length > 0
cb null, true, results
else
cb null, false, results
class DbHelper
constructor: (_cfg)->
@cfg =
dbConfig:
host: 'localhost',
user: 'root',
port: 3306,
password: '',
database: 'test'
onError: (err)->
console.dir err
customError: null
timeout: 30
debug: false
for key, value of _cfg
@cfg[key] = value
createConnection: ->
_options = @cfg
conn = mysql.createConnection(@cfg.dbConfig)
endConnectionProxy = conn.end
#auto close connection when timeout
timeoutObj = setTimeout ->
try
unless conn._socket._readableState.ended
endConnectionProxy.apply conn
if conn.busy
console.warn("query `#{conn.lastQuery}` cause timeout")
else
console.error("connection has been closed, last query:#{conn.lastQuery}")
catch e
console.log e.message, conn.lastQuery
, @cfg.timeout * 1000
conn.end = (cb)->
clearTimeout(timeoutObj)
unless conn._socket._readableState.ended
return endConnectionProxy.apply(this, arguments)
else
console.error("connection has been closed, last query:#{conn.lastQuery}")
cb(new Error("connection has been closed, last query:#{conn.lastQuery}"))
queryProxy = conn.query
###
执行 sql
@param {String} sql
@param {Array} paras parameters array
@param {Function} cb callback function
###
conn.query = (sql, paras, cb)->
conn.lastQuery = sql
conn.busy = true
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
queryProxy.call this, sql, paras, (err, result)->
this.busy = false
if err
console.dir err if _options.debug
_options.onError err
err = _options.customError if _options.customError
cb err, result if _.isFunction(cb)
return conn
module.exports = exports = (options)->
return new DbHelper(options)
| 45245 | mysql = require("mysql")
Connection = require("mysql/lib/Connection")
_ = require("underscore")
Connection.prototype.execute = ->
this.query.apply(this, arguments)
###
查询并在完成后立即关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$execute = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
查询第一行第一列的内容
@param {String} sql
@param {Array} paras parameters array
@param {Function} cb callback function
###
Connection.prototype.executeScalar = (sql, paras, cb) ->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction cb
if err
cb err
else if result.length > 0
for name, value of result[0]
cb null, value
return
else
cb null, null
###
查询第一行第一列的内容,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeScalar = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeScalar sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end =>
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
更新
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.update = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.changedRows > 0
cb null, true, result.changedRows
else
cb null, false
###
更新并且自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$update = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@update sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
插入
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.insert = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.affectedRows > 0
cb null, true, result.insertId
else
cb null, false
###
插入数据并且自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$insert = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@insert sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
执行sql,返回受影响的行数
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.executeNonQuery = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.affectedRows > 0
cb null, true, result.affectedRows
else
cb null, false
###
执行sql,返回受影响的行数,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeNonQuery = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeNonQuery sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
获取第一行数据
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.executeFirstRow = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.length > 0
cb null, result[0]
else
cb null, null
###
获取第一行的数据,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeFirstRow = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeFirstRow sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
判断是否存在
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.exist = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, results)->
if _.isFunction(cb)
if err
cb err
else if results.length > 0
cb null, true, results
else
cb null, false, results
###
判断是否存在,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$exist = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, results)=>
@end ->
if _.isFunction(cb)
if err
cb err
else if results.length > 0
cb null, true, results
else
cb null, false, results
class DbHelper
constructor: (_cfg)->
@cfg =
dbConfig:
host: 'localhost',
user: 'root',
port: 3306,
password:<PASSWORD> '',
database: 'test'
onError: (err)->
console.dir err
customError: null
timeout: 30
debug: false
for key, value of _cfg
@cfg[key] = value
createConnection: ->
_options = @cfg
conn = mysql.createConnection(@cfg.dbConfig)
endConnectionProxy = conn.end
#auto close connection when timeout
timeoutObj = setTimeout ->
try
unless conn._socket._readableState.ended
endConnectionProxy.apply conn
if conn.busy
console.warn("query `#{conn.lastQuery}` cause timeout")
else
console.error("connection has been closed, last query:#{conn.lastQuery}")
catch e
console.log e.message, conn.lastQuery
, @cfg.timeout * 1000
conn.end = (cb)->
clearTimeout(timeoutObj)
unless conn._socket._readableState.ended
return endConnectionProxy.apply(this, arguments)
else
console.error("connection has been closed, last query:#{conn.lastQuery}")
cb(new Error("connection has been closed, last query:#{conn.lastQuery}"))
queryProxy = conn.query
###
执行 sql
@param {String} sql
@param {Array} paras parameters array
@param {Function} cb callback function
###
conn.query = (sql, paras, cb)->
conn.lastQuery = sql
conn.busy = true
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
queryProxy.call this, sql, paras, (err, result)->
this.busy = false
if err
console.dir err if _options.debug
_options.onError err
err = _options.customError if _options.customError
cb err, result if _.isFunction(cb)
return conn
module.exports = exports = (options)->
return new DbHelper(options)
| true | mysql = require("mysql")
Connection = require("mysql/lib/Connection")
_ = require("underscore")
Connection.prototype.execute = ->
this.query.apply(this, arguments)
###
查询并在完成后立即关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$execute = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
查询第一行第一列的内容
@param {String} sql
@param {Array} paras parameters array
@param {Function} cb callback function
###
Connection.prototype.executeScalar = (sql, paras, cb) ->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction cb
if err
cb err
else if result.length > 0
for name, value of result[0]
cb null, value
return
else
cb null, null
###
查询第一行第一列的内容,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeScalar = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeScalar sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end =>
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
更新
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.update = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.changedRows > 0
cb null, true, result.changedRows
else
cb null, false
###
更新并且自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$update = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@update sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
插入
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.insert = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.affectedRows > 0
cb null, true, result.insertId
else
cb null, false
###
插入数据并且自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$insert = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@insert sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
执行sql,返回受影响的行数
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.executeNonQuery = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.affectedRows > 0
cb null, true, result.affectedRows
else
cb null, false
###
执行sql,返回受影响的行数,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeNonQuery = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeNonQuery sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
获取第一行数据
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.executeFirstRow = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, result)->
if _.isFunction(cb)
if err
cb err
else if result.length > 0
cb null, result[0]
else
cb null, null
###
获取第一行的数据,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$executeFirstRow = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@executeFirstRow sql, paras, ()=>
thisCache = this
argumentsCache = arguments
@end ->
cb.apply thisCache, argumentsCache if _.isFunction(cb)
###
判断是否存在
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.exist = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, results)->
if _.isFunction(cb)
if err
cb err
else if results.length > 0
cb null, true, results
else
cb null, false, results
###
判断是否存在,然后自动关闭连接
@param {String} sql
@param {Array} [paras]
@param {Function} cb callback function
###
Connection.prototype.$exist = (sql, paras, cb)->
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
@execute sql, paras, (err, results)=>
@end ->
if _.isFunction(cb)
if err
cb err
else if results.length > 0
cb null, true, results
else
cb null, false, results
class DbHelper
constructor: (_cfg)->
@cfg =
dbConfig:
host: 'localhost',
user: 'root',
port: 3306,
password:PI:PASSWORD:<PASSWORD>END_PI '',
database: 'test'
onError: (err)->
console.dir err
customError: null
timeout: 30
debug: false
for key, value of _cfg
@cfg[key] = value
createConnection: ->
_options = @cfg
conn = mysql.createConnection(@cfg.dbConfig)
endConnectionProxy = conn.end
#auto close connection when timeout
timeoutObj = setTimeout ->
try
unless conn._socket._readableState.ended
endConnectionProxy.apply conn
if conn.busy
console.warn("query `#{conn.lastQuery}` cause timeout")
else
console.error("connection has been closed, last query:#{conn.lastQuery}")
catch e
console.log e.message, conn.lastQuery
, @cfg.timeout * 1000
conn.end = (cb)->
clearTimeout(timeoutObj)
unless conn._socket._readableState.ended
return endConnectionProxy.apply(this, arguments)
else
console.error("connection has been closed, last query:#{conn.lastQuery}")
cb(new Error("connection has been closed, last query:#{conn.lastQuery}"))
queryProxy = conn.query
###
执行 sql
@param {String} sql
@param {Array} paras parameters array
@param {Function} cb callback function
###
conn.query = (sql, paras, cb)->
conn.lastQuery = sql
conn.busy = true
if _.isFunction(paras) and _.isUndefined(cb)
cb = paras
paras = []
queryProxy.call this, sql, paras, (err, result)->
this.busy = false
if err
console.dir err if _options.debug
_options.onError err
err = _options.customError if _options.customError
cb err, result if _.isFunction(cb)
return conn
module.exports = exports = (options)->
return new DbHelper(options)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993565678596497,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-process-argv-0.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.
util = require("util")
path = require("path")
assert = require("assert")
spawn = require("child_process").spawn
common = require("../common")
console.error "argv=%j", process.argv
console.error "exec=%j", process.execPath
if process.argv[2] isnt "child"
child = spawn("./node", [
__filename
"child"
],
cwd: path.dirname(process.execPath)
)
childArgv0 = ""
childErr = ""
child.stdout.on "data", (chunk) ->
childArgv0 += chunk
return
child.stderr.on "data", (chunk) ->
childErr += chunk
return
child.on "exit", ->
console.error "CHILD: %s", childErr.trim().split("\n").join("\nCHILD: ")
if process.platform is "win32"
# On Windows argv[0] is not expanded into full path
assert.equal childArgv0, "./node"
else
assert.equal childArgv0, process.execPath
return
else
process.stdout.write process.argv[0]
| 180026 | # 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.
util = require("util")
path = require("path")
assert = require("assert")
spawn = require("child_process").spawn
common = require("../common")
console.error "argv=%j", process.argv
console.error "exec=%j", process.execPath
if process.argv[2] isnt "child"
child = spawn("./node", [
__filename
"child"
],
cwd: path.dirname(process.execPath)
)
childArgv0 = ""
childErr = ""
child.stdout.on "data", (chunk) ->
childArgv0 += chunk
return
child.stderr.on "data", (chunk) ->
childErr += chunk
return
child.on "exit", ->
console.error "CHILD: %s", childErr.trim().split("\n").join("\nCHILD: ")
if process.platform is "win32"
# On Windows argv[0] is not expanded into full path
assert.equal childArgv0, "./node"
else
assert.equal childArgv0, process.execPath
return
else
process.stdout.write process.argv[0]
| 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.
util = require("util")
path = require("path")
assert = require("assert")
spawn = require("child_process").spawn
common = require("../common")
console.error "argv=%j", process.argv
console.error "exec=%j", process.execPath
if process.argv[2] isnt "child"
child = spawn("./node", [
__filename
"child"
],
cwd: path.dirname(process.execPath)
)
childArgv0 = ""
childErr = ""
child.stdout.on "data", (chunk) ->
childArgv0 += chunk
return
child.stderr.on "data", (chunk) ->
childErr += chunk
return
child.on "exit", ->
console.error "CHILD: %s", childErr.trim().split("\n").join("\nCHILD: ")
if process.platform is "win32"
# On Windows argv[0] is not expanded into full path
assert.equal childArgv0, "./node"
else
assert.equal childArgv0, process.execPath
return
else
process.stdout.write process.argv[0]
|
[
{
"context": "essfully accepted invitation'\n FORGOT_PASSWORD: 'User forgot password'\n RESET_PASSWORD: 'User successfully reset passw",
"end": 3655,
"score": 0.9993632435798645,
"start": 3635,
"tag": "PASSWORD",
"value": "User forgot password"
},
{
"context": "SSWORD: 'User forgot... | lib/analytics.coffee | 1aurabrown/ervell | 118 | { extend, reduce, map, wrap } = require 'underscore'
{ capitalize } = require 'underscore.string'
{ NODE_ENV, CURRENT_USER, GOOGLE_ANALYTICS_ID, DO_NOT_TRACK } = require('sharify').data
module.exports = (options) =>
return if module.exports.getUserAgent()?.indexOf?('PhantomJS') > -1
return if DO_NOT_TRACK
{ @ga, @location } = options
@location ?= window?.location
if GOOGLE_ANALYTICS_ID
googleAnalyticsParams = cookieDomain: 'are.na'
if CURRENT_USER?.id
googleAnalyticsParams.userId = CURRENT_USER?.id
@ga? 'create', GOOGLE_ANALYTICS_ID, googleAnalyticsParams
module.exports.getUserAgent = ->
window?.navigator?.userAgent
module.exports.trackPageview = (args = {}) =>
opts = extend { hitType: 'pageview' }, args
ga? 'send', opts
module.exports.trackOutboundLink = (url, cb = $.noop) =>
ga? 'send', 'event', 'Outbound link', 'click', url,
'transport': 'beacon'
'hitCallback': cb
module.exports.registerCurrentUser = ->
userType = if CURRENT_USER then "Logged In" else "Logged Out"
ga?('set', 'dimension1', userType)
ga?('set', 'dimension2', CURRENT_USER?.registered) if CURRENT_USER
module.exports.modelNameAndIdToLabel = (modelName, id) ->
throw new Error('Requires modelName and id') unless modelName? and id?
"#{capitalize modelName}:#{id}"
#
# Just the GA call.
#
module.exports.fireGa = fireGa = (kind, description, options = {}) ->
if NODE_ENV is 'development'
console.info "analytics.#{kind}: #{description}", options
else
ga? 'send',
hitType: 'event'
eventCategory: options.category or 'UI Interactions'
eventAction: description
eventLabel: options.label
eventValue: options.value
nonInteraction: if options.category in ['Funnel Progressions', 'Impressions', 'Timing'] then 1 else 0
categories =
impression: 'Impressions'
hover: 'UI Interactions'
click: 'UI Interactions'
submit: 'UI Interactions'
funnel: 'Funnel Progressions'
segment: 'UI A/B Test Segments'
error: 'UI Errors'
multi: 'Multi-object Events'
timing: 'Timing'
other: 'Other Events'
module.exports.track = track =
reduce Object.keys(categories), (memo, kind) ->
memo[kind] = (description, options = {}) ->
fireGa(kind, description, options)
memo
, {}
#
# Obviously there is no way of knowing if this is going to return,
# so we resolve after a reasonable amount of time.
#
module.exports.trackWithPromise =
reduce Object.keys(categories), (memo, kind) ->
memo[kind] = (description, options = {}) ->
new Promise (resolve, reject) ->
fireGa(kind, description, options)
setTimeout((-> resolve()), 300)
memo
, {}
module.exports.exception = (errorObj) ->
@ga? 'send', 'exception', errorObj
# These need to be set up individually before using. Read this non-sense:
# https://developers.google.com/analytics/devguides/platform/customdimsmets
module.exports.setDimension = (index, value) ->
@ga? 'set', index, value
# Event labels
module.exports.en =
CREATE_CHANNEL: 'New Channel created'
CREATE_CONNECTION: 'Connection created'
DESTROY_CONNECTION: 'Connection removed'
STARTED_CHANNEL_TRANSFER: 'Initiated channel transfer'
ACCEPTED_CHANNEL_TRANSFER: 'Accepted channel transfer'
REJECTED_CHANNEL_TRANSFER: 'Rejected channel transfer'
PREMIUM_CHARGE_INITIATED: 'User clicked to submit charge for premium'
PREMIUM_PAID: 'User paid for pro account'
LOGIN: 'User logged in'
REGISTER: 'User successfully registered'
SKIPPED_ONBOARDING: 'User skipped onboarding'
ACCEPTED_INVITATION: 'User successfully accepted invitation'
FORGOT_PASSWORD: 'User forgot password'
RESET_PASSWORD: 'User successfully reset password'
| 144444 | { extend, reduce, map, wrap } = require 'underscore'
{ capitalize } = require 'underscore.string'
{ NODE_ENV, CURRENT_USER, GOOGLE_ANALYTICS_ID, DO_NOT_TRACK } = require('sharify').data
module.exports = (options) =>
return if module.exports.getUserAgent()?.indexOf?('PhantomJS') > -1
return if DO_NOT_TRACK
{ @ga, @location } = options
@location ?= window?.location
if GOOGLE_ANALYTICS_ID
googleAnalyticsParams = cookieDomain: 'are.na'
if CURRENT_USER?.id
googleAnalyticsParams.userId = CURRENT_USER?.id
@ga? 'create', GOOGLE_ANALYTICS_ID, googleAnalyticsParams
module.exports.getUserAgent = ->
window?.navigator?.userAgent
module.exports.trackPageview = (args = {}) =>
opts = extend { hitType: 'pageview' }, args
ga? 'send', opts
module.exports.trackOutboundLink = (url, cb = $.noop) =>
ga? 'send', 'event', 'Outbound link', 'click', url,
'transport': 'beacon'
'hitCallback': cb
module.exports.registerCurrentUser = ->
userType = if CURRENT_USER then "Logged In" else "Logged Out"
ga?('set', 'dimension1', userType)
ga?('set', 'dimension2', CURRENT_USER?.registered) if CURRENT_USER
module.exports.modelNameAndIdToLabel = (modelName, id) ->
throw new Error('Requires modelName and id') unless modelName? and id?
"#{capitalize modelName}:#{id}"
#
# Just the GA call.
#
module.exports.fireGa = fireGa = (kind, description, options = {}) ->
if NODE_ENV is 'development'
console.info "analytics.#{kind}: #{description}", options
else
ga? 'send',
hitType: 'event'
eventCategory: options.category or 'UI Interactions'
eventAction: description
eventLabel: options.label
eventValue: options.value
nonInteraction: if options.category in ['Funnel Progressions', 'Impressions', 'Timing'] then 1 else 0
categories =
impression: 'Impressions'
hover: 'UI Interactions'
click: 'UI Interactions'
submit: 'UI Interactions'
funnel: 'Funnel Progressions'
segment: 'UI A/B Test Segments'
error: 'UI Errors'
multi: 'Multi-object Events'
timing: 'Timing'
other: 'Other Events'
module.exports.track = track =
reduce Object.keys(categories), (memo, kind) ->
memo[kind] = (description, options = {}) ->
fireGa(kind, description, options)
memo
, {}
#
# Obviously there is no way of knowing if this is going to return,
# so we resolve after a reasonable amount of time.
#
module.exports.trackWithPromise =
reduce Object.keys(categories), (memo, kind) ->
memo[kind] = (description, options = {}) ->
new Promise (resolve, reject) ->
fireGa(kind, description, options)
setTimeout((-> resolve()), 300)
memo
, {}
module.exports.exception = (errorObj) ->
@ga? 'send', 'exception', errorObj
# These need to be set up individually before using. Read this non-sense:
# https://developers.google.com/analytics/devguides/platform/customdimsmets
module.exports.setDimension = (index, value) ->
@ga? 'set', index, value
# Event labels
module.exports.en =
CREATE_CHANNEL: 'New Channel created'
CREATE_CONNECTION: 'Connection created'
DESTROY_CONNECTION: 'Connection removed'
STARTED_CHANNEL_TRANSFER: 'Initiated channel transfer'
ACCEPTED_CHANNEL_TRANSFER: 'Accepted channel transfer'
REJECTED_CHANNEL_TRANSFER: 'Rejected channel transfer'
PREMIUM_CHARGE_INITIATED: 'User clicked to submit charge for premium'
PREMIUM_PAID: 'User paid for pro account'
LOGIN: 'User logged in'
REGISTER: 'User successfully registered'
SKIPPED_ONBOARDING: 'User skipped onboarding'
ACCEPTED_INVITATION: 'User successfully accepted invitation'
FORGOT_PASSWORD: '<PASSWORD>'
RESET_PASSWORD: '<PASSWORD>'
| true | { extend, reduce, map, wrap } = require 'underscore'
{ capitalize } = require 'underscore.string'
{ NODE_ENV, CURRENT_USER, GOOGLE_ANALYTICS_ID, DO_NOT_TRACK } = require('sharify').data
module.exports = (options) =>
return if module.exports.getUserAgent()?.indexOf?('PhantomJS') > -1
return if DO_NOT_TRACK
{ @ga, @location } = options
@location ?= window?.location
if GOOGLE_ANALYTICS_ID
googleAnalyticsParams = cookieDomain: 'are.na'
if CURRENT_USER?.id
googleAnalyticsParams.userId = CURRENT_USER?.id
@ga? 'create', GOOGLE_ANALYTICS_ID, googleAnalyticsParams
module.exports.getUserAgent = ->
window?.navigator?.userAgent
module.exports.trackPageview = (args = {}) =>
opts = extend { hitType: 'pageview' }, args
ga? 'send', opts
module.exports.trackOutboundLink = (url, cb = $.noop) =>
ga? 'send', 'event', 'Outbound link', 'click', url,
'transport': 'beacon'
'hitCallback': cb
module.exports.registerCurrentUser = ->
userType = if CURRENT_USER then "Logged In" else "Logged Out"
ga?('set', 'dimension1', userType)
ga?('set', 'dimension2', CURRENT_USER?.registered) if CURRENT_USER
module.exports.modelNameAndIdToLabel = (modelName, id) ->
throw new Error('Requires modelName and id') unless modelName? and id?
"#{capitalize modelName}:#{id}"
#
# Just the GA call.
#
module.exports.fireGa = fireGa = (kind, description, options = {}) ->
if NODE_ENV is 'development'
console.info "analytics.#{kind}: #{description}", options
else
ga? 'send',
hitType: 'event'
eventCategory: options.category or 'UI Interactions'
eventAction: description
eventLabel: options.label
eventValue: options.value
nonInteraction: if options.category in ['Funnel Progressions', 'Impressions', 'Timing'] then 1 else 0
categories =
impression: 'Impressions'
hover: 'UI Interactions'
click: 'UI Interactions'
submit: 'UI Interactions'
funnel: 'Funnel Progressions'
segment: 'UI A/B Test Segments'
error: 'UI Errors'
multi: 'Multi-object Events'
timing: 'Timing'
other: 'Other Events'
module.exports.track = track =
reduce Object.keys(categories), (memo, kind) ->
memo[kind] = (description, options = {}) ->
fireGa(kind, description, options)
memo
, {}
#
# Obviously there is no way of knowing if this is going to return,
# so we resolve after a reasonable amount of time.
#
module.exports.trackWithPromise =
reduce Object.keys(categories), (memo, kind) ->
memo[kind] = (description, options = {}) ->
new Promise (resolve, reject) ->
fireGa(kind, description, options)
setTimeout((-> resolve()), 300)
memo
, {}
module.exports.exception = (errorObj) ->
@ga? 'send', 'exception', errorObj
# These need to be set up individually before using. Read this non-sense:
# https://developers.google.com/analytics/devguides/platform/customdimsmets
module.exports.setDimension = (index, value) ->
@ga? 'set', index, value
# Event labels
module.exports.en =
CREATE_CHANNEL: 'New Channel created'
CREATE_CONNECTION: 'Connection created'
DESTROY_CONNECTION: 'Connection removed'
STARTED_CHANNEL_TRANSFER: 'Initiated channel transfer'
ACCEPTED_CHANNEL_TRANSFER: 'Accepted channel transfer'
REJECTED_CHANNEL_TRANSFER: 'Rejected channel transfer'
PREMIUM_CHARGE_INITIATED: 'User clicked to submit charge for premium'
PREMIUM_PAID: 'User paid for pro account'
LOGIN: 'User logged in'
REGISTER: 'User successfully registered'
SKIPPED_ONBOARDING: 'User skipped onboarding'
ACCEPTED_INVITATION: 'User successfully accepted invitation'
FORGOT_PASSWORD: 'PI:PASSWORD:<PASSWORD>END_PI'
RESET_PASSWORD: 'PI:PASSWORD:<PASSWORD>END_PI'
|
[
{
"context": "uisiera CodeCombat en su escuela?\"\n educator: \"Maestro\"\n student: \"Estudiante\"\n go_to_my_dashboard",
"end": 27821,
"score": 0.8413981795310974,
"start": 27814,
"tag": "NAME",
"value": "Maestro"
},
{
"context": "ashboard: \"Ir a mi panel\"\n\n nav:\n ... | app/locale/es-419.ozar.coffee | goranoberg/codecombat | 0 | module.exports = nativeDescription: "Español (América Latina)", englishDescription: "Spanish (Latin America)", translation:
ozaria_home:
subtitle: "Informática que fascina"
heading_subtitle: "Una aventura de programación para estudiantes y una solución inmediata para enseñar Ciencias de la Computación."
item_list_p: "¡Prueba hoy mismo el capítulo 1 sin costo!"
engaging_heading_corner: "Una solución para involucrar a los estudiantes y apoyar a los maestros"
engaging_row1_h2: "Implementación sencilla"
engaging_row1_p: "Incluso sin experiencia en programación, con Ozaria puedes enseñar un plan de estudios de Ciencias de la Computación completo. Nuestros planes de estudios predefinidos y el intuitivo panel te darán las herramientas necesarias para empezar a enseñar desde el primer día."
engaging_row2_h2: "Jugabilidad inmersiva"
engaging_row2_p: "Los estudiantes se sumergirán en un juego de aventura en el cual sus conocimientos sobre Ciencias de la Computación avanzarán junto con la trama. En este entorno de aprendizaje divertido, los estudiantes desarrollarán habilidades del mundo real jugando."
engaging_row3_h2: "Planes de estudio que cumplen con las normas educativas"
engaging_row3_p: "Ozaria cumple con las normas ISTE y CSTA, por lo que enseñarás contenido de calidad a tus estudiantes, quienes dominarán conceptos esenciales de Ciencias de la Computación, desarrollarán habilidades de pensamiento computacional y aprenderán sobre la importancia de estos temas en la vida cotidiana."
pd_blurb: "Aprende las habilidades necesarias para enseñar Ciencias de la Computación de manera efectiva con nuestro curso de autoaprendizaje __pd__ acreditado por la CSTA. Obtén hasta 40 horas de crédito en cualquier momento y desde cualquier dispositivo."
back_cta_1_a: "Probar el capítulo 1 sin costo"
speech_bubble_testimonial_1_blockquote: "Una vez más, el equipo creó una reliquia del entretenimiento educativo. En mi opinión, como maestro veterano de secundaria con 26 años de experiencia, no existe mejor recurso para enseñar programación."
core_curriculum_header: "Asignaturas principales de Ciencias de la Computación"
core_curriculum_p: "Hemos desarrollado nuestro modelo de enseñanza a partir de teorías comprobadas y pruebas exhaustivas sobre la mejor forma de aprender."
core_curriculum_carousel_item1_header: "Hacer conexiones"
core_curriculum_carousel_item1_p: "Al principio de cada módulo, usa las diapositivas preexistentes de la lección para que los estudiantes hagan conexiones entre los nuevos conceptos de Ciencias de la Computación y ejemplos pertinentes de la vida diaria."
core_curriculum_carousel_item2_header: "Formar un significado propio"
core_curriculum_carousel_item2_p: "Luego, guía a los estudiantes para que comprendan mejor los nuevos conceptos completando las actividades de extensión que incluyen nuestros planes de estudios."
core_curriculum_carousel_item3_header: "Aprender nuevos conceptos"
core_curriculum_carousel_item3_p: "En la tercera etapa del ciclo de aprendizaje, los estudiantes aprenderán nuevos conceptos a través de diálogos expositivos entre los personajes de la historia de Ozaria. Las voces, los gráficos y las animaciones hacen que incorporar nueva información sea aún más accesible y divertido."
core_curriculum_carousel_item4_header: "Aplicar nuevos conocimientos"
core_curriculum_carousel_item4_p: "Luego, los estudiantes pondrán en práctica lo aprendido escribiendo código real de Python y JavaScript para resolver distintos desafíos presentados en niveles escalonados. Las pistas el juego ayudan a los estudiantes a identificar y corregir errores para que desarrollen una mayor confianza a la hora de programar."
core_curriculum_carousel_item5_header: "Proyecto sumativo"
core_curriculum_carousel_item5_p: "Al final de cada capítulo, los estudiantes se enfrentarán al desafío de exhibir sus nuevas habilidades y expresar su creatividad en proyectos sumativos en los que deberán construir sus propios juegos, historias y más."
core_curriculum_scope_sequence: "Ver alcance y secuencia"
core_curriculum_sample_lesson_slides: "Ver ejemplo de diapositivas de lección"
global_community_header: "Únete a nuestra comunidad global"
global_community_row1_p: "de estudiantes"
global_community_row2_p: "de líneas de código"
global_community_row3_p: "de maestros"
global_community_row4_p: "países"
admin_dashboard_header: "Paneles completos para administradores y maestros"
admin_dashboard_p: "Ozaria está diseñado sobre la base de opiniones de nuestra comunidad de más de 140.000 educadores y brinda las herramientas y los recursos necesarios para abordar los desafíos que conlleva enseñar Ciencias de la Computación."
admin_dashboard_row1_p: "El panel para maestros es intuitivo y permite acceder a los planes de estudio que ven los estudiantes, guías didácticas, estrategias de aprendizaje a distancia y otros recursos que seguramente te servirán."
admin_dashboard_row2_p: "La página de seguimiento del progreso te permite monitorear los avances de los estudiantes en tiempo real, obtener información valiosa sobre su desempeño e identificar de inmediato si es necesario intervenir de alguna forma."
admin_dashboard_row3_a: "Solicitar una cotización"
acodus_awards_a: "Probar el capítulo 1 sin costo"
speech_bubble_testimonial_2_blockquote: "Es el sitio de programación más accesible que conozco hasta el momento. Me gusta la historia que se plantea en Ozaria porque es una misión con la que los estudiantes pueden empatizar. La verdad, me encanta. De hecho, ¡yo también lo juego más de lo que me gustaría admitir!"
shareable_resources_header: "Recursos para compartir"
shareable_resources_p: "Comparte los siguientes recursos con maestros y administradores, o con los responsables de introducir o expandir las Ciencias de la Computación en tu escuela."
shareable_resources_a: "Descargar folleto"
back_cta_2_a: "Probar el capítulo 1 sin costo"
faq_header: "Preguntas frecuentes"
faq_row1_header: "¿Cómo se relaciona Ozaria con CodeCombat?"
faq_row1_p: "Ozaria se centra en el estudiante y es la evolución de CodeCombat, uno de los juegos de programación más populares de la historia. Desarrollamos Ozaria sobre la base de los aprendizajes obtenidos por enseñar Python y JavaScript a más de 20 millones de estudiantes. Ozaria incorpora nuevos modelos pedagógicos y una narrativa con una historia inmersiva, y está diseñado para implementarse en aulas tanto presenciales como virtuales."
faq_row2_header: "¿Qué edades o grados son los más adecuados para Ozaria?"
faq_row2_p: "Ozaria cumple con las normas ISTE y CSTA para enseñar Ciencias de la Computación en escuelas secundarias, pero estudiantes tanto mayores como menores lo han disfrutado y aprovechado."
faq_row3_header: "¿Cuánto cuesta acceder a todas las unidades y recursos disponibles?"
faq_row3_p_part1: "Personalizamos soluciones para escuelas y distritos. Podemos ayudarte a entender tus necesidades, contexto y presupuesto. "
faq_row3_p_part2: " para más detalles. También ofrecemos una "
faq_row3_p_part3: "guía de recursos de financiación"
faq_row3_p_part4: " para programas de Ciencias de la Computación en escuelas y distritos."
faq_row4_header: "En Ozaria, ¿el aprendizaje está basado en proyectos?"
faq_row4_p: "Sí. Ozaria incluye proyectos al final de cada capítulo para que los estudiantes creen sus propios juegos y puedan compartirlos. Estos proyectos son evaluaciones sumativas y una buena manera de que los estudiantes se expresen y les muestren a sus compañeros, amigos y familiares todo lo aprendido."
faq_row5_header: "¿Puedo usar Ozaria como plan de estudios principal para mi clase?"
faq_row5_p: "¡Claro que sí! Ozaria tiene todo lo que necesitas para dictar una asignatura completa de Ciencias de la Computación, incluso si vienes de otro campo: desde planificaciones de clases hasta guías de soluciones, guías de evaluación y alineaciones con normas."
faq_row6_p_part1: "Si tienes más preguntas, "
# see_faq_prefix: "See more"
# see_faq_link: "frequently asked questions in our help center"
# see_faq_suffix: "."
summary: "Ozaria es un programa de ciencias de la computación, un juego de aventura y una historia de fantasía en la que los estudiantes deben dominar la magia perdida de la programación para salvar al mundo."
value_prop1_h1: "Una historia épica. Jugabilidad inmersiva."
value_prop1_h2: "Inspira una conexión más profunda con el aprendizaje"
value_prop1_p: "En Ozaria, los estudiantes se encuentran inmersos en un nuevo mundo donde deben dominar conceptos esenciales de las ciencias de la computación para avanzar en el juego. La narrativa que se desarrolla crea una gran experiencia de aprendizaje centrada en los estudiantes, en la cual el tiempo que cada alumno invierte en la historia de Ozaria equivale al tiempo que invierten en su propio camino de aprendizaje."
value_prop2_h1: "Descubre el héroe que hay en cada estudiante"
value_prop2_h2: "Desarrolla habilidades reales jugando"
value_prop2_p: "Los conceptos y las habilidades se presentan a través de contenidos diseñados cuidadosamente que incluyen niveles de juego, diálogos de enseñanza entre personajes, escenas de video y más. Los estudiantes aprenderán a programar en Python o JavaScript, a resolver problemas usando pensamiento computacional, a demostrar su comprensión mediante evaluaciones formativas y a aplicar lo que aprendieron en sus propios proyectos."
value_prop3_h1: "Empieza tu camino de manera gratuita"
value_prop3_p: "Enseña a través de la aventura con contenido gratuito que cubre conceptos introductorios de ciencias de la computación, así como acceso a guías de aplicación y planes de estudios."
projects_inspire_heading: "Proyectos que inspiran. Recursos que empoderan."
student_creativity: "Desata la creatividad de tus estudiantes"
student_creativity_paragraph: "Al final de cada unidad, para aplicar lo que han aprendido, los estudiantes crean proyectos que van desde videojuegos hasta historias con distintos desenlaces y más. Con objetivos de andamiaje que permiten desarrollar ideas sin límites, los estudiantes arman una cartera de trabajo que pueden compartir y jugar para exhibir su identidad creativa."
teach_with_support: "Enseña con apoyo"
teach_with_support_paragraph: "Ozaria está diseñado para educadores. Cada unidad del currículo incluye un plan de estudios que detalla los objetivos de aprendizaje, las confusiones más comunes, los términos clave y las normas CSTA. Además, existe un tablero de maestros muy completo para ayudarlos a supervisar el progreso de los estudiantes y corroborar el código de cada uno de ellos."
request_demo: "Solicita una demo"
im_an_educator: "Soy educador"
im_a_student: "Soy estudiante"
global_title: "Únete a nuestra comunidad mundial de estudiantes y educadores"
global_subtitle1: "Estudiantes"
global_subtitle2: "Líneas de código"
global_subtitle3: "Maestros"
global_subtitle4: "Países"
sign_up: "Registrarse"
learner_number: "12 millones"
code_line_number: "1000 millones"
new_home:
title: "CodeCombat - Juegos de Programación para aprender Python y JavaScript" # {change}
meta_keywords: "CodeCombat, Python, JavaScript, juegos de programación, programa de Ciencias de la Computación, aventura, historia épica"
meta_description: "Aprende a esciribir código a través de un juego de programación. Aprende Python, JavaScript y HTML mientras resuelves rompecabezas y aprendes a hacer tus propios juegos de código y páginas web." # {change}
become_investor: "para invertir en CodeCombat"
built_for_teachers_title: "Un Juego de programación construido teniendo en cuenta a los maestros."
built_for_teachers_blurb: "Enseñar a los niños a programar puede ser abrumador. CodeCombat ayuda a todos los educadores a enseñar a los estudiantes cómo programar en JavaScript o Python, dos de los lenguajes de programación más populares. Con un plan de estudios comprensivo que incluye seis unidades de Ciencias de la Computación, y refuerza el aprendizaje a través de unidades en el desarrollo de juegos y desarrollo web basados en proyectos, los niños progresarán en un viaje desde la sintaxis básica hasta la recursión!"
built_for_teachers_subtitle1: "Ciencias de la Computación"
built_for_teachers_subblurb1: "Comenzando con nuestro curso gratuito de Introducción a las Ciencias de la Computación, los estudiantes dominan los conceptos básicos de programación, tales como bucles de while / for, funciones y algoritmos."
built_for_teachers_subtitle2: "Desarrollo de Juegos"
built_for_teachers_subblurb2: "Los alumnos construyen laberintos y utilizan el manejo de entrada básico para programar sus propios juegos que pueden compartir con amigos y familiares."
built_for_teachers_subtitle3: "Desarrollo Web"
built_for_teachers_subblurb3: "Usando HTML, CSS y jQuery, los estudiantes ejercitan sus músculos creativos para programar sus propias páginas web con una URL personalizada para compartir con sus compañeros de clase."
century_skills_title: "Habilidades del siglo 21"
century_skills_blurb1: "Los Estudiantes No Solo Suben de Nivel a su Héroe, Sino que se Suben de Nivel Ellos Mismos"
century_skills_quote1: "Te equivocas ... entonces piensas en todas las formas posibles de solucionarlo y luego lo intentas de nuevo. No sería capaz llegar hasta aquí sin esforzarme."
century_skills_subtitle1: "Pensamiento Crítico"
century_skills_subblurb1: "Con los rompecabezas de programación que se naturalmente se organizan en niveles cada vez más desafiantes, el juego de programación de CodeCombat asegura que los niños siempre estén practicando el pensamiento crítico."
century_skills_quote2: "Todos los demás estaban haciendo laberintos, así que pensé, 'capturar la bandera' y eso es lo que hice."
century_skills_subtitle2: "Creatividad"
century_skills_subblurb2: "CodeCombat anima a los estudiantes a mostrar su creatividad construyendo y compartiendo sus propios juegos y páginas web."
century_skills_quote3: "Si me quedo atascado en un nivel. Trabajaría con la gente a mi alrededor hasta que todos pudiéramos resolverlo."
century_skills_subtitle3: "Colaboración"
century_skills_subblurb3: "A lo largo del juego hay oportunidades para que los estudiantes colaboren cuando se atasquen y trabajen juntos utilizando nuestra guía de programación en pareja."
century_skills_quote4: "Siempre he tenido aspiraciones de diseñar videojuegos y aprender a programar ... esto me está dando un gran punto de partida."
century_skills_subtitle4: "Comunicación"
century_skills_subblurb4: "La programación requiere que los niños practiquen nuevas formas de comunicación, incluida la comunicación con la computadora y la transmisión de sus ideas utilizando el código más eficiente."
classroom_in_box_title: "Nos esforzamos por:"
classroom_in_box_blurb1: "Involucre a todos los estudiantes para que confíen que la programación es para ellos."
classroom_in_box_blurb2: "Apoderar a cualquier educador para que se sienta seguro al enseñar programación."
classroom_in_box_blurb3: "Inspirar a todos los líderes escolares para crear un programa de Ciencias de la Computación de clase mundial."
click_here: "Haz clic aquí"
creativity_rigor_title: "Donde la creatividad alcanza el rigor"
creativity_rigor_subtitle1: "Haga que la programación sea divertida y enseñe habilidades del mundo real"
creativity_rigor_blurb1: "Los estudiantes escriben Python y JavaScript real mientras juegan juegos que fomentan el ensayo y error, el pensamiento crítico y la creatividad. Luego, los estudiantes aplican las habilidades de programación que han aprendido al desarrollar sus propios juegos y sitios web en cursos basados en proyectos."
creativity_rigor_subtitle2: "Alcanza a los alumnos a sus niveles"
creativity_rigor_blurb2: "Cada nivel de CodeCombat está basado en millones de puntos de datos y optimizado para adaptarse a cada alumno. Los niveles de práctica y las sugerencias ayudan a los estudiantes cuando se atascan, y los niveles de desafío evalúan el aprendizaje de los estudiantes a lo largo del juego."
creativity_rigor_subtitle3: "Construido para todos los maestros, independientemente de la experiencia"
creativity_rigor_blurb3: "El plan de estudios de CodeCombat, a ritmo propio y alineado con los estándares, hace posible la enseñanza de Ciencias de la Computación para todos. CodeCombat equipa a los maestros con capacitación, recursos de instrucción y apoyo dedicado para sentirse seguros y exitosos en el aula."
featured_partners_title1: "Presentado en"
featured_partners_title2: "Premios y socios"
featured_partners_blurb1: "Proveedor respaldado por CollegeBoard"
featured_partners_blurb2: "Mejor herramienta de creatividad para estudiantes"
featured_partners_blurb3: "La mejor opción para aprender"
featured_partners_blurb4: "Socio oficial de Code.org"
featured_partners_blurb5: "Miembro oficial de CSforAll"
featured_partners_blurb6: "Socio de Hour of Code Activity"
for_leaders_title: "Para los líderes de la escuela"
for_leaders_blurb: "Un programa de Ciencias de la Computación, comprensible y alineado con los estándares"
for_leaders_subtitle1: "Fácil implementación"
for_leaders_subblurb1: "Un programa basado en la web que no requiere soporte de TI. Comience en menos de 5 minutos con Google o el inicio de sesión único inteligente (SSO)."
for_leaders_subtitle2: "Completo plan de estudio de programación"
for_leaders_subblurb2: "Un currículo alineado con los estándares con recursos de instrucción y desarrollo profesional para permitir que cualquier maestro enseñe Ciencias de la Computación."
for_leaders_subtitle3: "Casos de uso flexibles"
for_leaders_subblurb3: "Ya sea que desee crear una clase electiva de programación de escuela intermedia, una ruta CTE o una clase de Principios de Ciencias de la Computación, CodeCombat se adapta a sus necesidades."
for_leaders_subtitle4: "Habilidades del mundo real"
for_leaders_subblurb4: "Los estudiantes construyen y desarrollan una mentalidad de crecimiento a través de los desafíos de programación que los preparan para los más de 500k trabajos informáticos abiertos."
for_teachers_title: "Para maestros"
for_teachers_blurb: "Herramientas para abrir el potencial del estudiante"
for_teachers_subtitle1: "Aprendizaje basado en proyectos"
for_teachers_subblurb1: "Promueva la creatividad, la resolución de problemas y la confianza en los cursos basados en proyectos donde los estudiantes desarrollan sus propios juegos y páginas web."
for_teachers_subtitle2: "Tablero de maestros"
for_teachers_subblurb2: "Vea datos sobre el progreso de los alumnos, descubra recursos curriculares y acceda a soporte en tiempo real para potenciar el aprendizaje."
for_teachers_subtitle3: "Evaluaciones incorporadas"
for_teachers_subblurb3: "Personalice la instrucción y asegúrese de que los alumnos comprendan los conceptos básicos con evaluaciones formativas y aditivas."
for_teachers_subtitle4: "Diferenciación automática"
for_teachers_subblurb4: "Involucre a todos los alumnos en un aula diversa con niveles de práctica que se adapten a las necesidades de aprendizaje de cada alumno."
game_based_blurb: "CodeCombat es un programa de Ciencias de la Computación basado en juegos en los que los estudiantes escriben código real y ven a sus personajes reaccionar en tiempo real."
get_started: "Empieza ahora"
global_title: "Únete a nuestra comunidad global de estudiantes y educadores"
global_subtitle1: "Alumnos"
global_subtitle2: "Líneas de código"
global_subtitle3: "Maestros"
global_subtitle4: "Países"
go_to_my_classes: "Ir a mis clases"
go_to_my_courses: "Ir a mis cursos"
quotes_quote1: "Nombra cualquier programa en línea, ya lo he intentado. Ninguno de ellos coincide con CodeCombat. Cualquier maestro que quiera que sus estudiantes aprendan a programar ... ¡comience aquí!"
quotes_quote2: " Me sorprendió lo fácil e intuitivo que CodeCombat hace que aprendan Ciencias de la Computación. Las calificaciones en el examen AP fueron mucho más altas de lo que esperaba y creo que CodeCombat es la razón por la que este fue el caso."
quotes_quote3: "CodeCombat ha sido lo más beneficioso para enseñar a mis alumnos las capacidades de programación de la vida real. Mi esposo es ingeniero de software y ha probado todos mis programas. Puso esto como su mejor opción."
quotes_quote4: "Los comentarios ... han sido tan positivos que estamos estructurando una clase de informática en torno a CodeCombat. El programa realmente involucra a los estudiantes con una plataforma estilo juego que es entretenida e instructiva al mismo tiempo. ¡Sigan con el buen trabajo, CodeCombat!"
see_example: "Ver ejemplo"
slogan: "El juego más interesante para aprender programación." # {change}
teach_cs1_free: "Enseña programación gratis"
teachers_love_codecombat_title: "A los maestros les encanta CodeCombat"
teachers_love_codecombat_blurb1: "Informan que sus estudiantes disfrutan usando CodeCombat para aprender a programar"
teachers_love_codecombat_blurb2: "Recomendarían CodeCombat a otros maestros de Ciencias de la Computación"
teachers_love_codecombat_blurb3: "Dicen que CodeCombat los ayuda a mejorar las habilidades de resolución de problemas de sus estudiantes"
teachers_love_codecombat_subblurb: "En asociación con McREL International, líder en orientación basada en investigación y evaluaciones de tecnología educativa."
top_banner_blurb: "Nuevo: ¡Únete a nuestra misión!" # {change}
top_banner_blurb_pd: "Ahora ofrecemos opciones de desarrollo profesional para educadores."
top_banner_blurb_funding: "Nuevo: Ley CARES: guía de recursos de financiación para conseguir fondos ESSER y GEER para programas de Ciencias de la Computación."
try_the_game: "Prueba el juego"
classroom_edition: "Versión para el aula:"
learn_to_code: "Aprende a programar:"
play_now: "Jugar Ahora"
im_an_educator: "Soy un Educador"
im_a_teacher: "Soy un Maestro"
im_a_student: "Soy un Estudiante"
learn_more: "Aprender más"
classroom_in_a_box: "Un aula prediseñada para enseñar Ciencias de la Computación."
codecombat_is: "CodeCombat es una plataforma para que los estudiantes aprendan Ciencias de la Computación mientras están jugando un juego de verdad." # {change}
our_courses: "Nuestros cursos fueron probados especificamente para destacarse en el aula, incluso con maestros con poca o ninguna experiencia previa en programación." # {change}
watch_how: "Observa como CodeCombat está transformando la manera en que la gente aprende Ciencias de la Computación."
top_screenshots_hint: "Los estudiantes escriben código y ven sus cambios actualizarse en tiempo real"
designed_with: "Diseñado teniendo en cuenta a los maestros"
real_code: "Escritura de código real"
from_the_first_level: "desde el primer nivel"
getting_students: "Conseguir que los estudiantes escriban código lo más pronto posible es fundamental para que aprendan la sintaxis y la estructura apropiada."
educator_resources: "Recursos para el educador"
course_guides: "y guías de curso"
teaching_computer_science: "Enseñar Ciencias de la Computación no requiere un título costoso, porque proporcionamos herramientas para ayudar a educadores con cualquier conocimiento previo."
accessible_to: "Comprensible para"
everyone: "todos"
democratizing: "Democratizar el proceso de aprender a programar es la esencia de nuestra filosofía. Todos deberían poder aprender a programar"
forgot_learning: "Creo que ellos en realidad olvidaron de que estaban aprendiendo algo." # {change}
wanted_to_do: "Programar es algo que siempre quise hacer, y que nunca pensé que sería capaz de aprenderlo en la escuela ."
builds_concepts_up: "Me gusta cómo CodeCombat construye los conceptos. Es muy fácil de entender y es divertido averiguarlo."
why_games: "¿Por qué el aprendizaje mediante juegos es importante?"
games_reward: "Los juegos recompensan el esfuerzo productivo."
encourage: "El juego es un medio que incentiva la interacción, el descubrimiento, y la prueba-error. Un buen juego desafía al jugador a dominar habilidades con el paso del tiempo, que es un proceso crítico similar al que los estudiantes atraviesan mientran aprenden"
excel: "Los juegos se destacan en recompensar el"
struggle: "esfuerzo productivo"
kind_of_struggle: "el tipo de esfuerzo que se traduce en aprendizaje que interesa y "
motivating: "que motiva"
not_tedious: "no tedioso."
gaming_is_good: "Los estudios sugieren que jugar es bueno para el cerebro de los niños (¡es verdad!)"
game_based: "Cuando los sistemas de aprendizaje basados en juegos son"
compared: "comparados"
conventional: "con los métodos de evaluación convencionales, la diferencia es clara: los juegos son mejores al ayudar a los estudiantes a retener el conocimiento, a concentrarse y"
perform_at_higher_level: "a desempeñarse con un mayor nivel de éxito"
feedback: "Los juegos también proveen retroalimentación en tiempo real que permite a los estudiantes ajustar su camino a la solución y entender conceptos de forma más holística, en lugar de estar limitados solamente a respuestas 'correctas' e 'incorrectas'"
real_game: "Un juego de verdad, jugado con código auténtico."
great_game: "Un gran juego es más que solo medallas y logros - se trata sobre una travesía del jugador, acertijos bien diseñados, y la habilidad de abordar desafios con voluntad y confianza."
agency: "CodeCombat es un juego que ofrece a los jugadores esa voluntad y confianza mediante nuestro motor de código robusto, que ayuda tanto a principiantes como a estudiantes avanzados por igual a escribir código correcto y válido."
request_demo_title: "Invita a tus estudiantes hoy!"
request_demo_subtitle: "Solicitar una demostración y empieza a jugar con tus estudiantes en menos de una hora."
get_started_title: "Configure su clase hoy"
get_started_subtitle: "Prepare su clase, agregue cuentas de estudiantes y siga su progreso a medida que aprenden a programar."
request_demo: "Solicitar un Demo"
request_quote: "Solicitar una cotización"
setup_a_class: "Configurar una Clase"
have_an_account: "¿Ya tienes una cuenta?" # {change}
logged_in_as: "Estás actualmente conectado como"
computer_science: "Cursos de Ciencias de la Computación para todas las edades" # {change}
ffa: "Gratis para todos los estudiantes"
coming_soon: "¡Proximamente!"
courses_available_in: "Los cursos están disponibles en JavaScript, Python, y Java (¡proximamente!)" # {change}
boast: "Cuenta con acertijos lo suficiente complejos como para fascinar a jugadores y programadores por igual."
winning: "Una combinación ganadora entre un juego de rol y una tarea sobre programación que consigue hacer de la educación amigable y disfrutable para los niños."
run_class: "Todo lo que necesitas para organizar una clase de Ciencias de la Computación en tu escuela hoy mismo, sin necesidad de ningún conocimiento previo de Ciencias de la Computación."
goto_classes: "Ir a mis clases" # {change}
view_profile: "Ver mi perfíl"
view_progress: "Ver mi progreso"
go_to_courses: "Ir a mis cursos"
want_coco: "¿Quisiera CodeCombat en su escuela?"
educator: "Maestro"
student: "Estudiante"
go_to_my_dashboard: "Ir a mi panel"
nav:
educators: "Maestros"
follow_us: "Síguenos"
general: "General"
map: "Mapa"
play: "Jugar" # The top nav bar entry where players choose which levels to play
community: "Comunidad"
units: "Unidades"
blog: "Blog"
forum: "Foro"
account: "Cuenta"
my_account: "Mi Cuenta"
profile: "Perfil"
home: "Inicio"
contribute: "Contribuir"
legal: "Legal"
privacy: "Privacidad"
about: "Acerca"
contact: "Contacto"
press: "Prensa"
twitter_follow: "Seguir"
my_classrooms: "Mis clases"
my_courses: "Mis cursos"
my_units: "Mis unidades"
my_teachers: "Mis maestros"
careers: "Carreras"
facebook: "Facebook"
twitter: "Twitter"
create_a_class: "Crear una Clase"
other: "Otro"
learn_to_code: "¡Aprender a programar!"
toggle_nav: "Cambia la navigación"
schools: "Escuelas"
get_involved: "Participa"
open_source: "Código Libre (GitHub)"
support: "Soporte"
faqs: "FAQs"
copyright_prefix: "Copyright"
copyright_suffix: "Todos los derechos reservados."
help_pref: "¿Necesitas ayuda? Envianos un correó electronico!"
help_suff: "y te contactaremos pronto"
resource_hub: "Centro de recursos"
apcsp: "Principios AP CS"
parent: "Padres"
faq: "Preguntas frecuentes"
return_coco: "Volver a CodeCombat"
classes: "Clases"
term_of_service: "Términos de Servicio"
esports: "Esports"
browser_recommendation: "Para una mejor experiencia, recomendamos usar la última versión de Chrome. ¡Descarga el navegador aquí!"
ozaria_classroom: "Aula de Ozaria"
codecombat_classroom: "Aula de CodeCombat"
ozaria_dashboard: "Panel de Ozaria"
codecombat_dashboard: "Panel de CodeCombat"
professional_development: "Desarrollo profesional"
new: "¡Nuevo!"
admin: "Admin"
funding_resources_guide: "Guía de recursos de financiación"
modal:
close: "Cerrar"
okay: "OK"
cancel: "Cancelar"
try_again: "Volver a intentarlo"
not_found:
page_not_found: "Página no encontrada"
diplomat_suggestion:
title: "¡Ayuda a traducir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector.
sub_heading: "Necesitamos tus habilidades de idioma."
pitch_body: "Desarrollamos CodeCombat en inglés, pero ya tenemos jugadores de todo el mundo. Muchos de ellos quieren jugar en español pero no hablan inglés, así que si puedes hablar ambos, por favor considera registrarte pare ser un Diplomático y ayudar a traducir tanto el sitio de CodeCombat como todos los niveles al español."
missing_translations: "Hasta que podamos traducir todo al español, verás inglés cuando el español no esté disponible."
learn_more: "Aprende más sobre ser un Diplomático"
subscribe_as_diplomat: "Suscríbete como un Diplomático"
play:
title: "Juega los niveles de CodeCombat - Aprende Python, JavaScript y HTML"
meta_description: "Aprende a programar con un juego para principiantes. Aprende Python o JavaScript mientras resuelves acertijos, crea tus propios videojuegos y sube de nivel. ¡Desafía a tus amigos en niveles de arena multijugador!"
level_title: "__level__ - Aprende a programar en Python, JavaScript y HTML"
video_title: "__video__ | Nivel de video"
game_development_title: "__level__ | Desarrollo de juegos"
web_development_title: "__level__ | Desarrollo web"
anon_signup_title_1: "CodeCombat tiene un"
anon_signup_title_2: "¡Versión de aula!"
anon_signup_enter_code: "Ingresa el código de la clase:"
anon_signup_ask_teacher: "¿No tienes uno? pregunta a tu maestro"
anon_signup_create_class: "¿Quieres crear una clase?"
anon_signup_setup_class: "¡Configura una clase, agrega a tus estudiantes, y monitorea el progreso!"
anon_signup_create_teacher: "Crea una cuenta de maestro gratuita"
play_as: "Jugar Como " # Ladder page
get_course_for_class: "¡Asigna desarrollo de juegos y más a tus clases!"
request_licenses: "Contacta a nuestros especialistas escolares para más detalles."
compete: "¡Competir!" # Course details page
spectate: "Observar" # Ladder page
players: "Jugadores" # Hover over a level on /play
hours_played: "horas jugadas" # Hover over a level on /play
items: "Objetos" # Tooltip on item shop button from /play
unlock: "Desbloquear" # For purchasing items and heroes
confirm: "Confirmar"
owned: "Adquirido" # For items you own
locked: "Bloqueado"
available: "Disponible"
skills_granted: "Habilidades concedidas" # Property documentation details
heroes: "Héroes" # Tooltip on hero shop button from /play
achievements: "Logros" # Tooltip on achievement list button from /play
settings: "Configuración" # Tooltip on settings button from /play
poll: "Encuestas" # Tooltip on poll button from /play
next: "Próximo" # Go from choose hero to choose inventory before playing a level
change_hero: "Cambiar héroe" # Go back from choose inventory to choose hero
change_hero_or_language: "Cambiar héroe o lenguaje"
buy_gems: "Comprar gemas"
subscribers_only: "¡Solo para suscriptores!"
subscribe_unlock: "¡Suscríbete para desbloquear!"
subscriber_heroes: "¡Suscríbete ahora para debloquear inmediatamente a Amara, Hushbaum y Hattori!"
subscriber_gems: "¡Suscríbete ahora para comprar este héroe con gemas!"
anonymous: "Jugador Anónimo"
level_difficulty: "Dificultad: "
awaiting_levels_adventurer_prefix: "Nosotros liberamos nuevos niveles cada semana"
awaiting_levels_adventurer: "Registrate como un aventurero"
awaiting_levels_adventurer_suffix: "para ser el primero en jugar nuevos niveles."
adjust_volume: "Ajustar el volúmen"
campaign_multiplayer: "Arenas Multijugador"
campaign_multiplayer_description: "... en las que programas cara a cara contra otros jugadores."
brain_pop_done: "!Has derrotado a los Ogros programando! ¡Ganaste!"
brain_pop_challenge: "¡Desafiate a jugar de nuevo usando otro lenguaje de programación!"
replay: "Repetir"
back_to_classroom: "Volver al aula"
teacher_button: "Para maestros"
get_more_codecombat: "Consigue más CodeCombat"
back_to_dashboard: "Volver al panel"
back_to_ozaria: "Volver a ozaria.com"
customize_hero: "Personalizar héroe"
account_settings: "Configuración de cuenta"
back_to_tutorial: "Volver al tutorial"
teacher_vega_message: "Estos mensajes de tutorial guían a los estudiantes. Para ver estos mensajes y guardar tu progreso en el juego, crea una cuenta de estudiante y accede a ella para jugar Ozaria."
code:
if: "si" # 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: "de lo contrario"
elif: "o si"
while: "mientras"
loop: "ciclo"
for: "para"
break: "interrumpir"
continue: "continuar"
pass: "pasar"
return: "regresar"
then: "entonces"
do: "hacer"
end: "fin"
function: "función"
def: "define"
var: "variable"
self: "sí mismo"
hero: "héroe"
this: "este"
or: "o"
"||": "o"
and: "y"
"&&": "y"
not: "no"
"!": "no"
"=": "asignar"
"==": "igual a"
"===": "estrictamente igual a"
"!=": "distinto a"
"!==": "estrictamente distinto a"
">": "mayor que"
">=": "mayor o igual que"
"<": "menor que"
"<=": "menor o igual que"
"*": "multiplicado por"
"/": "dividido por"
"+": "más"
"-": "menos"
"+=": "añade y asigna"
"-=": "substrae y asigna"
True: "Verdadero"
true: "verdadero"
False: "Falso"
false: "falso"
undefined: "indefinido"
null: "nulo"
nil: "nada"
None: "Ninguno"
share_progress_modal:
blurb: "¡Estás haciendo un gran progreso! Cuéntale a tus padres cuánto has aprendido con CodeCombat."
email_invalid: "Dirección de Email inválida."
form_blurb: "¡Escribe su email debajo y les enseñaremos!"
form_label: "Dirección de Email"
placeholder: "dirección de email"
title: "Excelente Trabajo, Aprendiz"
login:
auth_sign_up: "¿Primera vez en Ozaria? Crea una cuenta"
sign_up: "Crear Cuenta"
email_or_username: "Email o Nombre de usuario" # {change}
or: "o"
log_in: "Entrar"
sign_in: "Regístrate"
logging_in: "Entrando"
log_out: "Salir"
forgot_password: "¿Olvidaste la contraseña?"
finishing: "Finalizando"
sign_in_with_facebook: "Registrarse con Facebook" # {change}
sign_in_with_gplus: "Registrarse con G+" # {change}
signup_switch: "¿Quieres crear una cuenta?"
already_have_account1: "¿Ya tienes una cuenta de maestro o estudiante de CodeCombat?"
already_have_account2: "Puedes ingresar a Ozaria.com con esa cuenta."
sign_into_ozaria: "Ingresa a Ozaria.com"
individual_users_not_supported: "¡Ozaria es solo para aulas! ¡Visita CodeCombat para seguir jugando!"
accounts_merge_confirmation: "Hay una cuenta asociada al correo electrónico de esta cuenta de Google. ¿Quieres combinar las cuentas?"
signup:
complete_subscription: "Completa Suscripción"
create_student_header: "Crear Cuenta de Estudiante"
create_teacher_header: "Crear Cuenta de Maestro"
create_individual_header: "Crear Cuenta Individual"
email_announcements: "Recibe noticias por email" # {change}
sign_in_to_continue: "Inicia sesión o crea una cuenta para continuar"
teacher_email_announcements: "Mantenme actualizado sobre nuevos recursos para maestros, currículo y cursos!"
creating: "Creando Cuenta..."
sign_up: "Registrarse"
log_in: "Inicia sesión con tu contraseña"
login: "Iniciar sesión"
required: "Necesitas entrar a tu cuenta antes de continuar."
login_switch: "¿Ya tienes una cuenta?"
optional: "opcional"
connected_gplus_header: "Te has conectado exitosamente a travez de Google+!"
connected_gplus_p: "Termina el registro para que inicies sesión con tu cuenta de Google+."
connected_facebook_header: "Te has conectado exitosamente a travez de Facebook!"
connected_facebook_p: "Termina el registro para que inicies sesión con tu cuenta de Facebook."
hey_students: "Estudiante, ingresa el coódigo de clase de tu maestro."
birthday: "Cumpleaños"
parent_email_blurb: "Nosotros sabemos que tu no puedes esperar para aprender programación — nosotros tambien estamos emocionados! Tus padres recibirán un correo electrónico con más instrucciones sobre cómo crear una cuenta para ti. Envíe un correo electrónico a {{email_link}} si tienes alguna pregunta"
classroom_not_found: "Ninguna clase existe con este código de clase. Revisa tu ortografía o pidele ayuda a tu maestro."
checking: "Comprobando..."
account_exists: "Este email ya esta en uso:"
sign_in: "Iniciar Sesión"
email_good: "Tu email se ve bien!"
name_taken: "Ese nombre de usuario ya esta en uso! Intenta {{suggestedName}}?"
name_available: "Nombre de usuario disponible!"
name_is_email: "Tu email no puede ser tu nombre de usuario"
choose_type: "Elige el tipo de cuenta:"
teacher_type_1: "Enseña como programar con CodeCombat!"
teacher_type_2: "Configura tu clase"
teacher_type_3: "Accede a guías de cursos"
teacher_type_4: "Ve el progreso del estudiante"
signup_as_teacher: "Iniciar sesión como Maestro" # {change}
student_type_1: "Aprende a programar mientras que juegas"
student_type_2: "Jugar con tu clase"
student_type_3: "Compite en arenas"
student_type_4: "Escoge tu héroe!"
student_type_5: "Ten tu código de clase listo!"
signup_as_student: "Iniciar sesión como Estudiante" # {change}
individuals_or_parents: "Independientes y Padres"
individual_type: "Para jugadores que aprenden a programar fuera de clase. Los padres deben registrar una cuenta aquí."
signup_as_individual: "Registrarse como Independiente"
enter_class_code: "Ingresa el código de tu clase"
enter_birthdate: "Ingresa tu fecha de nacimiento:"
parent_use_birthdate: "Padres, usen su propia fecha de nacimiento."
ask_teacher_1: "Pregúntale a tu maestro por el código de tu clase."
ask_teacher_2: "¿No eres parte de una clase? Crea una"
ask_teacher_3: "Cuenta Independiente"
ask_teacher_4: " en cambio."
about_to_join: "Te vas a unir a:"
enter_parent_email: "Ingresa el correo eletrónico de tus padres:"
parent_email_error: "Ha ocurrido un error al tratar de enviar el correo. Verifica la dirección de correo electrónico e intenta de nuevo."
parent_email_sent: "Hemos enviado un correo electrónico con más instrucciones sobre cómo crear una cuenta. Pide a tus padres que revisen su bandeja de entrada."
account_created: "¡Cuenta Creada!"
confirm_student_blurb: "Escribe tu información para que no la olvides. Tu maestro también puede ayudarte a restablecer tu contraseña en cualquier momento."
confirm_individual_blurb: "Escribe tu información de inicio de sesión en caso de que la necesites más adelante. Verifica tu correo electrónico para que puedas recuperar tu cuenta si alguna vez olvidas la contraseña. ¡Revisa tu bandeja de entrada!"
write_this_down: "Escribe esto:" # {change}
start_playing: "¡Empieza a jugar!"
sso_connected: "Conectado exitosamente con:"
select_your_starting_hero: "Selecciona tu héroe inicial:"
you_can_always_change_your_hero_later: "Podrás cambiar tu héroe luego."
finish: "Finalizar"
teacher_ready_to_create_class: "¡Estás listo para crear tu primera clase!"
teacher_students_can_start_now: "Sus alumnos podrán comenzar a jugar el primer curso, Introducción a las Ciencias de la Computación, inmediatamente." # {change}
teacher_list_create_class: "En la siguiente pantalla podrás crear una nueva clase."
teacher_list_add_students: "Agregue alumnos a la clase haciendo clic en el enlace Ver clase y luego envíe a sus alumnos el Código de clase o la URL. También puedes invitarlos por correo electrónico si tienen."
teacher_list_resource_hub_1: "Revisar la "
teacher_list_resource_hub_2: "Guías de curso" # {change}
teacher_list_resource_hub_3: "para soluciones a todos los niveles, y la"
teacher_list_resource_hub_4: "Centro de recursos"
teacher_list_resource_hub_5: "para guías curriculares, actividades, y más."
teacher_additional_questions: "¡Eso es todo! Si necesita ayuda adicional o tiene preguntas, comuníquese con __supportEmail__."
dont_use_our_email_silly: "¡No pongas nuestro email aquí! Pon el correo de tus padres."
want_codecombat_in_school: "¿Quieres jugar CodeCombat todo el tiempo?"
eu_confirmation: "Acepto permitir que CodeCombat almacene mis datos en servidores de los Estados Unidos."
eu_confirmation_place_of_processing: "Aprender más sobre los posibles riesgos"
eu_confirmation_student: "Si no estás seguro, pregúntale a tu maestro."
eu_confirmation_individual: "Si no deseas que almacenemos tus datos en servidores de EE. UU., Siempre puedes seguir jugando de forma anónima sin guardar tu código."
request_class_code: "¡Estudiantes, pídanle un código de clase a su docente para crear una cuenta!"
educators_create_account: "¡Docentes, creen una cuenta de maestro para acceder a la primera unidad de manera gratuita!"
looking_for_classroom: "Buscando aulas..."
create_your_educator_account: "Crea una cuenta de educador"
educator_signup_list_1_title: "Ve lo mismo que tus estudiantes:"
educator_signup_list_1_desc: "Prueba cada nivel del juego en la primera unidad"
educator_signup_list_2_title: "Ve los recursos para maestros:"
educator_signup_list_2_desc: "Accede al alcance y el orden, las lecciones y más"
educator_signup_list_3_title: "Observa el progreso de tus estudiantes:"
educator_signup_list_3_desc: "Prueba gratis la primera unidad con tu clase"
signup_with_email: "Regístrate con tu correo electrónico"
already_have_account: "Ya tienes una cuenta de Ozaria o CodeCombat"
select_your_role: "Selecciona tu rol"
select_your_state: "Selecciona tu estado"
password_requirements: "Entre 8 y 64 caracteres no repetidos"
invalid: "No válido"
invalid_password: "Contraseña no válida"
form_validation_errors:
required: "El campo es obligatorio"
invalidEmail: "Correo no válido"
invalidPhone: "Número de teléfono no válido"
emailExists: "El correo electrónico ya existe"
numberGreaterThanZero: "Debe ser un número mayor que 0"
recover:
recover_account_title: "recuperar cuenta"
send_password: "Enviar contraseña de recuperación"
recovery_sent: "Correo de recuperación enviado."
items:
primary: "Primario"
secondary: "Secundario"
armor: "Armadura"
accessories: "Accesorios"
misc: "Misceláneo"
books: "Libros"
common:
default_title: "Ozaria - Informática que fascina"
ozaria: "Ozaria"
default_meta_description: "Ozaria es un programa de ciencias de la computación, un juego de aventura y una historia de fantasía en la que los estudiantes deben dominar la magia perdida de la programación para salvar al mundo."
back: "Atrás" # When used as an action verb, like "Navigate backward"
coming_soon: "¡Próximamente!"
continue: "Continuar" # When used as an action verb, like "Continue forward"
next: "Siguiente"
default_code: "Código predeterminado"
loading: "Cargando..."
LOADING: "CARGANDO"
overview: "Vista global"
processing: "Procesando..."
solution: "Solución"
table_of_contents: "Tabla de contenidos"
intro: "Intro"
saving: "Guardando..."
sending: "Enviando..."
send: "Enviar"
sent: "Enviado"
cancel: "Cancelar"
save: "Guardar"
publish: "Publicar"
create: "Crear"
fork: "Bifurcar"
play: "Jugar" # When used as an action verb, like "Play next level"
retry: "Reintentar"
actions: "Acciones"
info: "Info"
help: "Ayuda"
watch: "Seguir"
unwatch: "No seguir"
submit_patch: "Enviar Parche"
submit_changes: "Enviar cambios"
save_changes: "Guardar cambios"
required_field: "Requisito necesario" # {change}
submit: "Enviar"
replay: "Volver a jugar"
complete: "Completado"
continue_editing: "Continuar editando"
logout: "Cerrar sesión"
empty: "Vacío"
done: "Listo"
remove: "Quitar"
locked: "Bloqueado"
general:
and: "y"
name: "Nombre"
date: "Fecha"
body: "Cuerpo"
version: "Versión"
pending: "Pendiente"
accepted: "Aceptado"
rejected: "Rechazado"
withdrawn: "Retirado"
accept: "Aceptar"
accept_and_save: "Aceptar y Guardar"
reject: "Rechazar"
withdraw: "Retirar"
submitter: "Emisor"
submitted: "Enviado"
commit_msg: "Enviar mensaje"
version_history: "Historial de Versiones"
version_history_for: "Historial de Versiones para: "
select_changes: "Selcciona dos cambios abajo para ver la diferencia"
undo_prefix: "Deshacer"
undo_shortcut: "(Ctrl+Z)"
redo_prefix: "Rehacer"
redo_shortcut: "(Ctrl+Shift+Z)"
play_preview: "Mira el avance del nivel"
result: "Resultado"
results: "Resultados"
description: "Descripción"
or: "o"
subject: "Asunto"
email: "Email"
password: "Contraseña"
confirm_password: "Confirme Contraseña"
message: "Mensaje"
code: "Código"
ladder: "Escalera"
when: "Cuando"
opponent: "Oponente"
rank: "Posición"
score: "Puntuación"
win: "Ganada"
loss: "Perdida"
tie: "Empate"
easy: "Fácil"
medium: "Medio"
hard: "Difícil"
player: "Jugador"
player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard
warrior: "Guerrero"
ranger: "Guardabosques"
wizard: "Mago"
first_name: " Nombre de pila"
last_name: "Apellido"
last_initial: "Última inicial"
username: "Nombre de usuario"
contact_us: "Contáctenos"
close_window: "Cerrar ventana"
learn_more: "Aprende Más"
more: "Más"
fewer: "Menos"
with: "con"
archived: "Archivado"
chat: "Chat"
chat_with_us: "Chatea con nosotros"
email_us: "Envíanos un correo electrónico"
sales: "Ventas"
support: "Ayuda"
units:
second: "segundo"
seconds: "segundos"
sec: "seg"
minute: "minuto"
minutes: "minutos"
hour: "hora"
hours: "horas"
day: "día"
days: "días"
week: "semana"
weeks: "semanas"
month: "mes"
months: "meses"
year: "año"
years: "años"
play_level:
back_to_map: "Volver al Mapa"
directions: "Instrucciones"
edit_level: "Editar Nivel"
keep_learning: "Sigue aprendiendo"
explore_codecombat: "Explorar CodeCombat"
finished_hoc: "He terminado con mi Hora of Código"
get_certificate: "¡Obtén tu certificado!"
level_complete: "Nivel completo"
completed_level: "Nivel Completado:"
course: "Curso:"
done: "Listo"
next_level: "Siguiente Nivel"
combo_challenge: "Desafío Combo"
concept_challenge: "Desafío de Concepto"
challenge: "Desafío"
challenge_unlocked: "Desafío Desbloqueado"
combo_challenge_unlocked: "Desafío Combo Desbloqueado"
concept_challenge_unlocked: "Desafío de Concepto Desbloqueado"
concept_challenge_complete: "Desafío de Concepto Completado!"
combo_challenge_complete: "Deasfío Combo Completado!"
combo_challenge_complete_body: "Buen trabajo, parece que te va bien entendiendo __concept__!"
replay_level: "Reiniciar nivel"
combo_concepts_used: "__complete__/__total__ Conceptos usados"
combo_all_concepts_used: "Usaste todos los conceptos posibles para resolver el desafío. ¡Buen trabajo!"
combo_not_all_concepts_used: "Usaste __complete__ de __total__ conceptos posibles para resolver el desafío. ¡Intenta obtener todos los __total__ conceptos la próxima vez!"
start_challenge: "Empezar Desafío"
next_game: "Siguiente juego"
languages: "Lenguajes"
programming_language: "Lenguajes de programación"
show_menu: "Mostrar menú de juego"
home: "Inicio" # Not used any more, will be removed soon.
level: "Nivel" # Like "Level: Dungeons of Kithgard"
skip: "Omitir"
game_menu: "Menú del Juego"
restart: "Reiniciar"
goals: "Objetivos"
goal: "Objetivo"
challenge_level_goals: "Metas del Nivel de Desafío"
challenge_level_goal: "Meta del Nivel de Desafío"
concept_challenge_goals: "Metas del Desafío de Concepto"
combo_challenge_goals: "Metas del Nivel de Desafío"
concept_challenge_goal: "Metas del Desafío de Concepto"
combo_challenge_goal: "Meta del Nivel de Desafío"
running: "Andando..."
success: "¡Éxito!"
incomplete: "Incompleto"
timed_out: "Acabó el tiempo"
failing: "Fallando"
reload: "Recargar"
reload_title: "¿Recargar Todo el Código?"
reload_really: "¿Estás seguro de que quieres empezar este nivel desde el principio?"
reload_confirm: "Recargar Todo"
restart_really: "¿Seguro que quieres reiniciar el nivel? Perderás todo el código que has escrito."
restart_confirm: "Sí, reiniciar"
test_level: "Probar Nivel"
victory: "Victoria"
victory_title_prefix: "¡"
victory_title_suffix: "¡Completo!"
victory_sign_up: "Regístrate para recibir actualizaciones"
victory_sign_up_poke: "¿Quieres recibir las últimas noticias por correo? ¡Crea una cuenta gratuita y te mantendremos informado!"
victory_rate_the_level: "¿Cómo de divertido estuvo este nivel?"
victory_return_to_ladder: "Volver a la escalera"
victory_saving_progress: "Guardando Progreso"
victory_go_home: "Ir al Inicio"
victory_review: "¡Cuéntanos más!"
victory_review_placeholder: "¿Cómo estuvo el nivel?"
victory_hour_of_code_done: "¿Has acabado?"
victory_hour_of_code_done_yes: "¡Si, he terminado con mi Hora de Código!"
victory_experience_gained: "XP Ganada"
victory_gems_gained: "Gemas Ganadas"
victory_new_item: "Objeto Nuevo"
victory_new_hero: "Nuevo Héroe"
victory_viking_code_school: "¡Changos macacos!, ¡el nivel que acabas de pasar era dificil! Si todavía no eres un desarrollador de software, deberías serlo. Acabas de conseguir una aceptación por vía rápida con la Escuela Vikinga de Có, donde tú puedes llevar tus habilidades al siguiente nivel y convertirte en un desarrollador web profesional en 14 semanas."
victory_become_a_viking: "Conviértete en un Vikingo"
victory_no_progress_for_teachers: "El progreso no es guardado para maestros. Pero puede añadir cuenta de estudiante a su aula, por su mismo."
tome_cast_button_run: "Ejecutar"
tome_cast_button_running: "Ejecutando"
tome_cast_button_ran: "Ejecutado"
tome_cast_button_update: "Actualizar"
tome_submit_button: "Enviar"
tome_reload_method: "Recargar código original para este método" # {change}
tome_available_spells: "Hechizos Disponibles"
tome_your_skills: "Tus habilidades"
hints: "Pistas"
videos: "Videos"
hints_title: "Pistas {{number}}"
code_saved: "Código Guardado"
skip_tutorial: "Saltar (esc)"
keyboard_shortcuts: "Atajos de teclado"
loading_start: "Iniciar nivel"
loading_start_combo: "Iniciar Desafío Combo"
loading_start_concept: "Iniciar Desafío de Concepto"
problem_alert_title: "Revisa tu código"
time_current: "Ahora:"
time_total: "Max:"
time_goto: "Ir a:"
non_user_code_problem_title: "No se puede cargar el nivel"
infinite_loop_title: "Ciclo infinito detectado"
infinite_loop_description: "El código inicial para construir el mundo no terminó de ejecutarse. Probablemente es muy lento o tiene un loop infinito. O puede ser un bug. Puedes tratar ejecutando este código nuevamente o reiniciar el código a su estado por defecto. Si eso no lo arregla, haznos saber."
check_dev_console: "Tú puedes también abrir la consola de desarrollo para ver que puede salir mal."
check_dev_console_link: "(instrucciones)"
infinite_loop_try_again: "Intentar nuevamente"
infinite_loop_reset_level: "Reiniciar Nivel"
infinite_loop_comment_out: "Comenta Mi Código"
tip_toggle_play: "Activa jugar/pausa con Ctrl+P."
tip_scrub_shortcut: "Ctrl+[ y Ctrl+] para rebobinar y avanzar rápido."
tip_guide_exists: "Haga click en la guía en la parte superior de la página para obtener información útil"
tip_open_source: "¡CodeCombat es 100% código abierto!" # {change}
tip_tell_friends: "¿Disfrutando de CodeCombat? ¡Cuéntale a tus amigos acerca de nosotros!"
tip_beta_launch: "CodeCombat lanzó su beta en Octubre del 2013."
tip_think_solution: "Piensa en la solución, no en el problema."
tip_theory_practice: "En teoría, no hay diferencia entre la teoría y la práctica. Pero en la práctica, si la hay. - Yogi Berra"
tip_error_free: "Hay dos formas de escribir programas libres de errores; sólo la tercera funciona. - Alan Perlis"
tip_debugging_program: "Si depurar es el proceso de remover errores, entonces programar debe ser el proceso de colocarlos. - Edsger W. Dijkstra"
tip_forums: "¡Dirígite a los foros y dinos lo que piensas!"
tip_baby_coders: "En el futuro, incluso los bebés serán Archimagos."
tip_morale_improves: "La carga continuará hasta que la moral mejore."
tip_all_species: "Creemos en la igualdad de oportunidades para aprender a programar para todas las especies."
tip_reticulating: "Espinas reticulantes."
tip_harry: "Eres un Hechicero, "
tip_great_responsibility: "Con una gran habilidad de hacer código viene una gran responsabilidad de depuración."
tip_munchkin: "Si no comes tus verduras, un enano vendrá por ti mientras estés dormido."
tip_binary: "Sólo hay 10 tipos de personas en el mundo: aquellas que entienden binario y las que no."
tip_commitment_yoda: "Un programador debe tener el compromiso más profundo, la mente más seria. ~ Yoda"
tip_no_try: "Haz. O no hagas. No hay intento. - Yoda"
tip_patience: "Paciencia debes tener, joven Padawan. - Yoda"
tip_documented_bug: "Un error documentado no es un error; es una característica."
tip_impossible: "Siempre parece imposible hasta que se hace. - Nelson Mandela"
tip_talk_is_cheap: "Hablar es barato. Muéstrame el código. - Linus Torvalds"
tip_first_language: "La cosa más desastrosa que puedes aprender es tu primer lenguaje de programación. - Alan Kay"
tip_hardware_problem: "P: ¿Cuántos programadores son necesarios para cambiar una bombilla eléctrica? R: Ninguno, es un problema de hardware."
tip_hofstadters_law: "Ley de Hofstadter: Siempre toma más tiempo del que esperas, incluso cuando tienes en cuenta la ley de Hofstadter."
tip_premature_optimization: "La optimización prematura es la raíz de la maldad. - Donald Knuth"
tip_brute_force: "Cuando tengas duda, usa la fuerza bruta. - Ken Thompson"
tip_extrapolation: "Solo hay dos tipos de personas: Esas que pueden extrapolar desde información incompleta..."
tip_superpower: "Programar es lo más cercano que tenemos a superpoderes."
tip_control_destiny: "En el Open Source real, tú tienes el derecho de controlar tu propio destino. - Linus Torvalds"
tip_no_code: "Ningún código es más rápido que nada de código."
tip_code_never_lies: "El código nunca miente, los comentarios a veces sí. — Ron Jeffries"
tip_reusable_software: "Antes de que el software sea reusable, primero tiene que ser usable."
tip_optimization_operator: "Cada lenguaje tiene un operador de optimización. En la mayoría de ellos, ese operador es ‘//’"
tip_lines_of_code: "Medir el progreso en la programación en líneas de código es como medir el progreso de construcción de una aeronave por su peso. — Bill Gates"
tip_source_code: "Quisiera cambiar el mundo, pero no me dan el código fuente."
tip_javascript_java: "Java es a Javascript lo mismo que Comer es a Comercial. - Chris Heilmann"
tip_move_forward: "Hagas lo que hagas, siempre sigue hacia delante. - Martin Luther King Jr."
tip_google: "¿Tienes un problema que no puedes resolver? ¡Googléalo!"
tip_adding_evil: "Agregando una pizca de maldad."
tip_hate_computers: "Esa es la razón por la cual la gente piensa que odia las computadoras. Lo que ellos odian de verdad, es los pesimos programadores. - Larry Niven"
tip_open_source_contribute: "¡Tú puedes ayudar a CodeCombat a mejorar!"
tip_recurse: "Iterar es humano, recursar es divino. - L. Peter Deutsch"
tip_free_your_mind: "Tienes que dejar ir todo, Neo. Miedo, duda, e incredulidad. Libera tu mente. - Morpheus"
tip_strong_opponents: "Hasta los oponentes mas fuertes siempre tienen una debilidad. - Itachi Uchiha"
tip_paper_and_pen: "Antes de comenzar a programar, siempre puedes planear con una hoja de papel y un lapicero."
tip_solve_then_write: "Primero, resuelve el problema. Entonces, escribe el código. - John Johnson"
tip_compiler_ignores_comments: "A veces pienso que el compilador ignora mis comentarios."
tip_understand_recursion: "La única manera de entender la recursividad es entender la recursividad."
tip_life_and_polymorphism: "El Open Source es como una estructura heterogénea totalmente polimórfica: Todos los tipos son bienvenidos."
tip_mistakes_proof_of_trying: "Errores en tu código son solo evidencia de que estas intentando."
tip_adding_orgres: "Redondendo ogres."
tip_sharpening_swords: "Afilando las espadas."
tip_ratatouille: "No debes dejar que nadie defina tus límites a causa de donde venas. Tu único límite es tu alma. - Gusteau, Ratatouille"
tip_nemo: "¿Cuando huye la suerte, sabes que hay que hacer? Sigue nadando, sigue nadando. - Dory, Finding Nemo"
tip_internet_weather: "Debes moverte al intenet, es genial aquí. Tenemos la oportunidad de vivir dentro donde el clima es siempre sorprendente. - John Green"
tip_nerds: "A los Nerds se les permite amor cosas, como saltar-arriba-y-abajo-en-la-silla-no-te-puedes-controlar-tu-mismo quiérelo. - John Green"
tip_self_taught: "Me enseñé a mí mismo el 90% de lo que he aprendido. ¡Y eso es normal! - Hank Green"
tip_luna_lovegood: "No te preocupes, estas tan cuerdo como yo. - Luna Lovegood"
tip_good_idea: "La mejor forma de tener una buena idea es tener un montón de ideas. - Linus Pauling"
tip_programming_not_about_computers: "Las Ciencias de la Computación está tan alejada de computadoras como la astronomía de telescopios. - Edsger Dijkstra"
tip_mulan: "Si crees que puedes, entonces lo harás. - Mulan"
project_complete: "¡Proyecto completo!"
share_this_project: "Comparte este proyecto con familia y amigos:"
ready_to_share: "¿Listo para publicar tu proyecto?"
click_publish: "Haz click en \"Publicar\" para que aparezca en la galería de la clase, a continuación ¡echa un vistazo a lo que construyeron tus compañeros! Puedes volver y seguir trabajando en este proyecto. Cualquier cambio adicional se guardará automáticamente y se compartirá con tus compañeros."
already_published_prefix: "Tus cambios se han publicado en la galería de la clase."
already_published_suffix: "¡Sigue experimentando y haciendo este proyecto aún mejor, o mira lo que el resto de la clase ha construido! Tus cambios se guardarán automáticamente y se compartirán con tus compañeros."
view_gallery: "Ver Galería"
project_published_noty: "¡Tu nivel ha sido publicado!"
keep_editing: "Continuar editando"
learn_new_concepts: "Aprende nuevos conceptos"
watch_a_video: "Mira un video de __concept_name__"
concept_unlocked: "Concepto desbloqueado"
use_at_least_one_concept: "Usa al menos un concepto: "
command_bank: "Banco de códigos"
learning_goals: "Metas de aprendizaje"
start: "Empezar"
vega_character: "Personaje Vega"
capella_character: "Personaje Capella"
octans_character: "Personaje Octans"
click_to_continue: "Haz clic para continuar"
share_your_project: "Comparte tu proyecto"
keep_editing_your_project: "Siempre puedes seguir editando tu proyecto, incluso después compartirlo."
copy_url: "Copiar URL"
level_status: "Estado"
level_status_locked: "Bloqueado"
level_status_in_progress: "En curso"
level_status_complete: "Completado"
level_type_practice: "Práctica"
level_type_challenge: "Desafío"
level_type_cutscene: "Escena"
level_type_capstone: "Final"
level_type_intro: "Introducción"
level_type_practice_level: "Nivel de práctica"
level_type_challenge_level: "Nivel de desafío"
level_type_cutscene_level: "Nivel de escena"
level_type_capstone_level: "Nivel final"
level_type_capstone_project: "Proyecto final"
level_type_intro_level: "Nivel introductorio"
content_type_avatar: "Selección de avatar"
content_type_cinematic: "Cinemática"
content_type_interactive: "Comprobación de conceptos"
feedback: "Comentarios"
apis:
methods: "Métodos"
events: "Eventos"
handlers: "Manipuladores"
properties: "Propiedades"
snippets: "Fragmentos"
spawnable: "Generable"
html: "HTML"
math: "Cálculos"
array: "Arreglo"
object: "Objeto"
string: "Cadena de texto"
function: "Función"
vector: "Vector"
date: "Fecha"
jquery: "jQuery"
json: "JSON"
number: "Número"
webjavascript: "JavaScript"
amazon_hoc:
title: "¡Sigue aprendiendo con Amazon!"
congrats: "¡Felicitaciones por conquistar esa desafiante Hora de Código!"
educate_1: "Ahora, continúa aprendiendo sobre programación y computación en la nube con AWS Educate, un programa emocionante y gratuito de Amazon para estudiantes y maestros. Con AWS Educate, puedes obtener insignias geniales a medida que aprendes sobre los conceptos básicos de la nube y las tecnologías de vanguardia, como los juegos, la realidad virtual y Alexa."
educate_2: "Aprende más y regístrate aquí"
future_eng_1: "También puedes intentar construir tu propia habilidad de datos escolares para Alexa."
future_eng_2: "aquí"
future_eng_3: "(No se requiere dispositivo). Esta actividad de Alexa es traída a ti por el"
future_eng_4: "Amazon Future Engineer"
future_eng_5: "programa que crea oportunidades de aprendizaje y trabajo para todos los estudiantes de K-12 en los Estados Unidos que desean dedicarse a Ciencias de la Computación."
play_game_dev_level:
created_by: "Creado por {{name}}"
created_during_hoc: "Creado durante Hora de Código"
restart: "Reiniciar Nivel"
play: "Iniciar Nivel"
learn_about_ozaria: "Learn About Ozaria"
default_student_instructions: "¡Haz clic para controlar a tu héroe y ganar tu juego!"
goal_survive: "Sobrevive."
goal_survive_time: "Sobrevive por __seconds__ segundos."
goal_defeat: "Derrota a todos los enemigos."
goal_defeat_amount: "Derrota __amount__ enemigos."
goal_move: "Muévete a todas las marcas X rojas."
goal_collect: "Recoge todos los objetos."
goal_collect_amount: "Recoge __amount__ objetos."
game_menu:
inventory_tab: "Inventario"
save_load_tab: "Guardar/Cargar"
options_tab: "Opciones"
guide_tab: "Guía"
guide_video_tutorial: "Guía en video"
guide_tips: "Pistas"
multiplayer_tab: "Multijugador"
auth_tab: "Entrar"
inventory_caption: "Equipar a tu héroe"
choose_hero_caption: "Elegir héroe, lenguaje"
options_caption: "Hacer ajustes"
guide_caption: "Documentos y consejos"
multiplayer_caption: "¡Jugar con amigos!"
auth_caption: "Guarda tu progreso."
leaderboard:
view_other_solutions: "Ver la Tabla de Posiciones"
scores: "Puntajes"
top_players: "Mejores jugadores"
day: "Hoy"
week: "Esta Semana"
all: "Siempre"
latest: "Mas reciente"
time: "Tiempo"
damage_taken: "Daño Recibido"
damage_dealt: "Daño Infligido"
difficulty: "Dificultad"
gold_collected: "Oro Recolectado"
survival_time: "Sobrevivido"
defeated: "Enemigos Derrotados"
code_length: "Líneas de código"
score_display: "__scoreType__: __score__"
inventory:
equipped_item: "Equipado"
required_purchase_title: "Requerido"
available_item: "Disponible"
restricted_title: "Restringido"
should_equip: "(doble-click para equipar)"
equipped: "(equipado)"
locked: "(bloqueado)"
restricted: "(restringido en este nivel)"
equip: "Equipar"
unequip: "Sacar"
warrior_only: "Sólo para Gerrero"
ranger_only: "Sólo para Arquero"
wizard_only: "Sólo para Mago"
buy_gems:
few_gems: "Pocas gemas"
pile_gems: "Pila de gemas"
chest_gems: "Cofre de gemas"
purchasing: "Comprando..."
declined: "Su tarjeta fue rechazada"
retrying: "Error del servidor, recargando."
prompt_title: "Gemas insuficientes"
prompt_body: "¿Quieres obtener más?"
prompt_button: "Entrar al mercado"
recovered: "Se recuperaron las anteriores compras de gemas. Por favor recarga la página"
price: "x{{gems}} / mes"
buy_premium: "Comprar Premium"
purchase: "Compra"
purchased: "Comprado"
subscribe_for_gems:
prompt_title: "¡Gemas suficientes!"
prompt_body: "¡Suscríbete a Premium para obtener gemas y acceso a más niveles!"
earn_gems:
prompt_title: "Gemas Insuficientes"
prompt_body: "¡Sigue jugando para ganar más!"
subscribe:
best_deal: "¡La mejor ofera!"
confirmation: "¡Felicitaciones! Ahora tienes una suscripción Premium de CodeCombat!"
premium_already_subscribed: "¡Ya tienes una suscripción Premium!"
subscribe_modal_title: "CodeCombat Premium"
comparison_blurb: "Agudiza tus habilidades con la suscripción a CodeCombat!" # {change}
must_be_logged: "Debes iniciar sesión primero. Por favor crea una cuenta o inicia sesión desde el menú superior."
subscribe_title: "Suscribirse" # Actually used in subscribe buttons, too
unsubscribe: "Cancelar suscripción"
confirm_unsubscribe: "Confirmar cancelación de suscripción"
never_mind: "Olvidalo, Te sigo queriendo"
thank_you_months_prefix: "Gracias por tu apoyo en estos últimos"
thank_you_months_suffix: "meses."
thank_you: "Gracias por apoyar CodeCombat."
sorry_to_see_you_go: "¡Sentimos que te vayas! Por favor, haznos saber lo que podríamos haber hecho mejor."
unsubscribe_feedback_placeholder: "¿Pero qué hemos hecho?"
stripe_description: "Suscripción Mensual"
buy_now: "Comprar ahora"
subscription_required_to_play: "Necesitas una suscripción para jugar este nivel."
unlock_help_videos: "Suscríbete para desbloquear todos los video tutoriales."
personal_sub: "Suscripción Personal" # Accounts Subscription View below
loading_info: "Cargando información de suscripción..."
managed_by: "Administrado por"
will_be_cancelled: "Será cancelado en"
currently_free: "Actualmente tienes una suscripción gratuita"
currently_free_until: "Actualmente tienes una suscripción gratuita hasta"
free_subscription: "Suscripción gratuita"
was_free_until: "Tuviste una suscripción gratuita hasta"
managed_subs: "Suscripciones administradas"
subscribing: "Suscribiendo..."
current_recipients: "Recipientes actuales"
unsubscribing: "Dando de baja..."
subscribe_prepaid: "Click en suscribirse para utlizar un código prepago"
using_prepaid: "Usar código prepago para una suscribción mensual"
feature_level_access: "Accede a 300+ niveles disponibles"
feature_heroes: "Desbloquea héroes y mascotas exclusivas"
feature_learn: "Aprende a crear juegos y páginas web"
month_price: "$__price__"
first_month_price: "¡Sólo $__price__ en tu primer mes!"
lifetime: "Acceso de por vida"
lifetime_price: "$__price__"
year_subscription: "Suscripción anual"
year_price: "$__price__/por año"
support_part1: "¿Necesitas ayuda con el pago o prefieres Paypal? Correo electrónico"
support_part2: "support@codecombat.com"
announcement:
now_available: "¡Ahora disponible para suscriptores!"
subscriber: "suscriptor"
cuddly_companions: "¡Compañeros de peluche!" # Pet Announcement Modal
kindling_name: "Elemental de Leña"
kindling_description: "Los Elemental de Leña sólo quieren mantenerte tibio durante la noche. Y durante el día. Todo el tiempo, realmente."
griffin_name: "Grifo Bebé"
griffin_description: "Los Grifos son mitad ágila, mitad león, son adorables."
raven_name: "Cuervo"
raven_description: "Los Cuervos son excelentes para recolectar botellas brillantes llenas de salud para ti."
mimic_name: "Mimo"
mimic_description: "Los Mimos pueden recoger monedas por tí. Colócalos sobre las monedas para aumentar tu suministro de oro."
cougar_name: "Puma"
cougar_description: "Los Pumas deberían ganar un doctorado por el ronroneo feliz de todos los días."
fox_name: "Zorro azul"
fox_description: "¡Los zorros azules son muy inteligentes y les encanta cavar en la tierra y la nieve!"
pugicorn_name: "Pugicornio"
pugicorn_description: "¡Los pugicornios son unas de las criaturas más raras y pueden lanzar hechizos!"
wolf_name: "Lobito"
wolf_description: "¡Los Lobitos son excelentes en la caza, la recolección y jugando el escondite!"
ball_name: "Bola Roja Chirriante"
ball_description: "ball.squeak()"
collect_pets: "¡Consigue mascotas para tus héroes!"
each_pet: "¡Cada mascota tiene una habilidad de ayuda única!"
upgrade_to_premium: "Vuélvete un {{subscriber}} para usar mascotas."
play_second_kithmaze: "Juega {{the_second_kithmaze}} para desbloquear al Lobito!"
the_second_kithmaze: "El segundo Kithmaze"
keep_playing: "¡Sigue jugando para descubrir la primera mascota!"
coming_soon: "Muy pronto"
ritic: "Ritic el frío" # Ritic Announcement Modal
ritic_description: "Ritic elfrío. Atrapado en el glaciar Kelvintaph durante incontables edades, finalmente libre y listo para atender a los ogros que lo encarcelaron."
ice_block: "Un bloque de hielo"
ice_description: "Parece que hay algo atrapado adentro..."
blink_name: "Parpadeo"
blink_description: "Ritic desaparece y aparece en un abrir y cerrar de ojos, dejando nada más que una sombra."
shadowStep_name: "Pasombra"
shadowStep_description: "Un asesino maestro sabe como caminar entre las sombras."
tornado_name: "Tornado"
tornado_description: "Es bueno tener un botón de reinicio cuando la tapa está quemada."
wallOfDarkness_name: "Pared de la Oscuridad"
wallOfDarkness_description: "Se oculta detrás de un muro de sombras para evitar las miradas indiscretas."
avatar_selection:
pick_an_avatar: "Elige un avatar que te representará como jugador"
select_avatar_title: "Elige un avatar de jugador"
premium_features:
get_premium: "Obtén<br>CodeCombat<br>Premium" # Fit into the banner on the /features page
master_coder: "¡Conviértete en un programador experto suscribiéndote hoy!"
paypal_redirect: "Serás redirigido a PayPal para completar el proceso de suscripción."
subscribe_now: "Suscríbete ahora"
hero_blurb_1: "Accede a __premiumHeroesCount__ héroes super cargados sólo para suscriptores! Aprovecha el poder imparable de Okar Stompfoot, la precisión mortal de Naria of the Leaf, o invoca esqueletos \"adorables\" con Nalfar Cryptor."
hero_blurb_2: "Los Guerreros Premium desbloquean impresionantes habilidades marciales como Llanto de guerra, Paso firme y Lanzar enemigo. O, ¡juega como un arquero, usando sigilo y arcos, lanzando cuchillos y trampas! ¡Prueba tu habilidad como un verdadero mago programador, y ¡libera una poderosa variedad de magia Primordial, Nigromántica o Elemental!"
hero_caption: "¡Nuevos héroes emocionantes!"
pet_blurb_1: "Las mascotas no son solo compañeros adorables, sino que también proporcionan una funcionalidad y métodos únicos. El Grifo Bebé puede transportar unidades por el aire, el Lobito juega con las flechas del enemigo, al Puma le gusta perseguir a los ogros, ¡y el Mimo atrae monedas como un imán!"
pet_blurb_2: "¡Consigue todas las mascotas para descubrir sus habilidades únicas!"
pet_caption: "¡Adopta mascotas para que acompañen a tu héroe!"
game_dev_blurb: "¡Aprende scripts de juegos y crea nuevos niveles para compartir con tus amigos! Coloca los elementos que desees, escribe el código para la lógica y el comportamiento de la unidad, ¡y mira si tus amigos pueden superar el nivel!"
game_dev_caption: "¡Diseña tus propios juegos para desafiar a tus amigos!"
everything_in_premium: "Todo lo que obtienes en CodeCombat Premium:"
list_gems: "Recibe gemas de bonificación para comprar equipo, mascotas y héroes."
list_levels: "Obtén acceso a otros __premiumLevelsCount__ niveles"
list_heroes: "Desbloquea héroes exclusivos, incluye las clases Arquero y Mago"
list_game_dev: "Crea y comparte juegos con tus amigos"
list_web_dev: "Crea páginas web y aplicaciones interactivas"
list_items: "Equipa elementos únicos para Premium, como mascotas"
list_support: "Obtén soporte Premium para ayudarte a depurar código complicado"
list_clans: "Crea clanes privados para invitar a tus amigos y competir en una tabla de clasificación de grupo."
choose_hero:
choose_hero: "Elige tu héroe"
programming_language: "Lenguaje de programación"
programming_language_description: "¿Qué lenguaje de programación vas a elegir?"
default: "por Defecto"
experimental: "Experimental"
python_blurb: "Simple pero poderoso."
javascript_blurb: "El lenguaje de la web (no es Java)."
coffeescript_blurb: "JavaScript pero más bonito."
lua_blurb: "Lenguaje para Juegos."
java_blurb: "(Sólo para Suscriptiores) Android y Empresarial."
status: "Estado"
weapons: "Armas"
weapons_warrior: "Espada - Corto Alcance, Sin Magia"
weapons_ranger: "Ballestas, Armas - Largo Alcance, Sin Magia"
weapons_wizard: "Barita, - Largo Alcance, Mágico"
attack: "Daño" # Can also translate as "Attack"
health: "Salud"
speed: "Velocidad"
regeneration: "Regeneración"
range: "Rango" # As in "attack or visual range"
blocks: "Bloqueo" # As in "this shield blocks this much damage"
backstab: "Apuñala" # As in "this dagger does this much backstab damage"
skills: "Habilidades"
attack_1: "Ofertas"
attack_2: "de la lista"
attack_3: "daño de arma."
health_1: "Gana"
health_2: "de la lista"
health_3: "salud de la armadura."
speed_1: "Se mueve a"
speed_2: "metros por segundo."
available_for_purchase: "Disponible para Comprar" # Shows up when you have unlocked, but not purchased, a hero in the hero store
level_to_unlock: "Nivel para desbloquear:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see)
restricted_to_certain_heroes: "Sólo ciertos héroes pueden jugar este nivel."
char_customization_modal:
heading: "Personaliza a tu héroe"
body: "Cuerpo"
name_label: "Nombre del héroe"
hair_label: "Color de pelo"
skin_label: "Color de piel"
skill_docs:
function: "función" # skill types
method: "método"
snippet: "fragmento"
number: "número"
array: "arreglo"
object: "objeto"
string: "cadena"
writable: "escribible" # Hover over "attack" in Your Skills while playing a level to see most of this
read_only: "Sólo Lectura"
action: "Acción"
spell: "Conjuro"
action_name: "nombre"
action_cooldown: "Toma"
action_specific_cooldown: "Enfriamiento"
action_damage: "Daño"
action_range: "Rango"
action_radius: "Radio"
action_duration: "Duración"
example: "Ejemplo"
ex: "ej" # Abbreviation of "example"
current_value: "Valor actual"
default_value: "Valor por defecto"
parameters: "Parámetros"
required_parameters: "Parámetros Requeridos"
optional_parameters: "Parámetros Opcionales"
returns: "Devoluciones"
granted_by: "Concedido por"
description_coming_soon: "Descripción próximamente"
save_load:
granularity_saved_games: "Guardado"
granularity_change_history: "Historia"
options:
general_options: "Opciones Generales" # Check out the Options tab in the Game Menu while playing a level
volume_label: "Volúmen"
music_label: "Música"
music_description: "Música encendida/apagada."
editor_config_title: "Configuración del Editor" # {change}
editor_config_livecompletion_label: "Autocompletado automático" # {change}
editor_config_livecompletion_description: "Despliega sugerencias de autocompletado mientras escribes."
editor_config_invisibles_label: "Mostrar Invisibles"
editor_config_invisibles_description: "Visualiza invisibles tales como espacios o tabulaciones."
editor_config_indentguides_label: "Mostrar guías de indentación"
editor_config_indentguides_description: "Visualiza líneas verticales para ver mejor la indentación."
editor_config_behaviors_label: "Comportamientos Inteligentes" # {change}
editor_config_behaviors_description: "Autocompleta corchetes, llaves y comillas."
# editor_config_screen_reader_mode_label: "Enable Screen Reader Mode"
# editor_config_screen_reader_mode_description: "Display levels in text rather than visually."
about:
title: "Acerca de CodeCombat - Involucrar a estudiantes, empoderar a docentes, inspirar la creación"
meta_description: "Nuestra misión es equilibrar los niveles de informática mediante el aprendizaje basado en juego y hacer que la programación sea accesible para todo el que quiera aprender. Creemos que la programación es magia y queremos que los estudiantes tengan la capacidad de crear lo que quieran con solo imaginarlo."
learn_more: "Aprende más"
main_title: "Si queres aprender a programar, necesitas escribir (un montón de) código."
main_description: "En CodeCombat, nuestro trabajo es asegurarnos que estás haciendo eso con una sonrisa en tu cara."
mission_link: "Misión"
team_link: "Equipo"
story_link: "Historia"
press_link: "Prensa"
mission_title: "Nuestra misión: hacer accesible la programación para cada estudiante en la Tierra." # {change}
mission_teach: "Enseña a través de la aventura"
mission_desc_1: "En el mundo de hoy, los niños están bombardeados con entretenimiento que cada año se vuelve más atrapante. Cada aplicación, video, juego y publicidad se crea con el objetivo de captar y retener su atención. Para competir con esa situación, la educación debe encontrar maneras de retener la atención de los estudiantes y capturar su imaginación."
mission_desc_2: "Creemos que aprender ciencias de la computación puede ser fascinante. Debe parecer mágico. Después de todo, la programación le da a cualquiera la posibilidad de explorar nuevas ideas, construir algo a partir de la imaginación e interactuar con otros de nuevas maneras. Nuestra meta es inspirar una conexión con la creatividad y la imaginación inherentes de las ciencias de la computación creando videojuegos educativos que sean creativos e imaginativos."
mission_desc_3: "A lo largo de los últimos cinco años, más de doce millones de personas han aprendido a programar en Python y JavaScript con CodeCombat, lo que lo convirtió en uno de los juegos de programación más populares de la historia. Ahora nos complace anunciar Ozaria y ampliar nuestro compromiso de inspirar a una nueva generación de estudiantes a aprender ciencias de la computación. Ozaria es un juego de aventura que pone a cada estudiante en el centro de una historia legendaria en la que, para salvar al planeta Ozaria de la oscuridad inminente, deben dominar la magia perdida de la programación. A medida que la narrativa se desarrolla, se crea una gran experiencia de aprendizaje centrada en los estudiantes, en la cual el tiempo que cada alumno invierte en la historia de Ozaria equivale al tiempo que invierten en su propio camino de aprendizaje." # {change}
team_title: "Conoce al equipo de CodeCombat"
team_values: "Valoramos el diálogo abierto y respetuoso, donde gana la mejor idea. Nuestras decisiones se basan en la investigación del cliente y nuestro método se centra en obtener resultados tangibles para ellas. Todos están echando una mano, desde nuestro CEO hasta nuestros contribuidores en GitHub, porque en nuestro equipo valoramos el crecimiento y el aprendizaje. " # {change}
nick_title: "Cofundador, CEO"
csm_title: "Gerente de relaciones comerciales"
scsm_title: "Gerente de relaciones comerciales senior"
ae_title: "Ejecutivo de cuentas"
sae_title: "Ejecutivo de cuentas senior"
sism_title: "Gerente de ventas internas senior"
shan_title: "Encargada principal de establecimiento de asociaciones, China"
run_title: "Jefe de operaciones, China"
lance_title: "Pasante de ingeniería de software, China"
zhiran_title: "Jefa de planes de estudio, China"
yuqiang_title: "Jefe de innovación, China"
swe_title: "Ingeniero de software"
sswe_title: "Ingeniero de software senior"
css_title: "Especialista en atención al cliente"
css_qa_title: "Especialista en atención al cliente / control de calidad"
maya_title: "Desarrolladora de planes de estudio senior"
bill_title: "Gerente general, China"
pvd_title: "Diseñador visual y de productos"
spvd_title: "Diseñador visual y de productos senior"
daniela_title: "Gerente de marketing"
bobby_title: "Diseñador de juegos"
brian_title: "Diseñador de juegos principal" # {change}
stephanie_title: "Especialista en atención al cliente"
sdr_title: "Representante de desarrollo de ventas"
retrostyle_title: "Ilustración"
retrostyle_blurb: "Juegos con estilo Retro"
community_title: "...y nuestra comunidad open-source"
bryukh_title: "Desarrollador de jugabilidad senior"
oa_title: "Asistente de operaciones"
ac_title: "Coordinador administrativo"
ea_title: "Asistente ejecutivo"
om_title: "Gerente de operaciones"
mo_title: "Gerente de operaciones"
smo_title: "Gerente de operaciones senior"
scd_title: "Desarrollador de planes de estudio senior"
lcd_title: "Desarrollador de planes de estudio principal"
vpm_title: "Vicepresidente de marketing"
community_subtitle: "¡Más de 450 contribuidores que ayudaron a contruir CodeCombat, y más uniendose cada semana!" # {change}
community_description_3: "CodeCombat es un"
community_description_link_2: "proyecto comunitario"
community_description_1: "CodeCombat es un proyecto comunitario, con cientos de jugadores haciendo trabajo voluntario al crear niveles, contribuir a nuestro código para añadir características, arreglar bugs, testear, e incluso traducir el juego a 50 idiomas hasta ahora. Empleados, contribuidores y la página ganan al compartir las ideas Echa un vistazo a nuestra" # {change}
community_description_link: "página de contribución"
community_description_2: "para más información."
number_contributors: "Más de 450 contribuidores dieron su apoyo y tiempo a este proyecto."
story_title: "Nuestra historia hasta ahora"
story_subtitle: "Desde 2013, CodeCombat creció desde un mero conjunto de bocetos hasta un juego próspero, vivo."
story_statistic_1a: "+5,000,000" # {change}
story_statistic_1b: "jugadores totales"
story_statistic_1c: "comenzaron su viaje en la programación mediante CodeCombat" # {change}
story_statistic_2a: "We’ve been translated into over 50 languages — nuestros jugadores son de"
story_statistic_2b: "+200 países" # {change}
story_statistic_3a: "Juntos, escribieron"
story_statistic_3b: "1 mil millones de líneas de código, y contando"
story_statistic_3c: "en seis lenguajes de programación distintos" # {change}
story_long_way_1: "Aunque hemos recorrido un largo camino..."
story_sketch_caption: "El primer boceto de Nick representando un juego de programación en acción."
story_long_way_2: "todavía nos queda mucho por hacer antes de que completemos nuestra misión, asi que..."
jobs_title: "¡Ven a trabajar con nosotros y ayuda a escribir la historia de CodeCombat!" # {change}
jobs_subtitle: "¿No encontras una buena opción pero estás interesado en mantener el contacto? Mirá nuestra entrada \"Crear Tu Propio\"."
jobs_benefits: "Beneficios del empleado"
jobs_benefit_4: "Días personales/enfermo ilimitados" # {change}
jobs_benefit_5: "Desarrollo profesional y soporte de formación continua" # {change}
jobs_benefit_6: "Seguro médico/dental/vista" # {change}
jobs_benefit_9: "Ventana opcional de ejercicio por 10 años"
jobs_benefit_10: "Permiso de maternidad: 12 semanas pagadas, luego 6 @ 55% del salario"
jobs_benefit_11: "Permiso de paternidad: 12 semanas pagadas"
jobs_custom_title: "Crear Tu Propio"
jobs_custom_description: "¿Te apasiona CodeCombat pero nos ves un puesto de trabajo que coincida con tus cualificaciones? Escríbenos y muestrenos como cree que puede contribuir a nuestro equipo. ¡Nos encantaría saber de vos!"
jobs_custom_contact_1: "¡Envíanos una nota a"
jobs_custom_contact_2: "presentándote y ¡podremos estar en contacto en el futuro!"
contact_title: "Prensa & Contacto"
contact_subtitle: "¿Necesitas más información? Contáctanos en"
press_subtitle: "o visita nuestro sitio de prensa en"
screenshots_title: "Capturas de pantalla del Juego"
screenshots_hint: "(click para ver en tamaño completo)"
downloads_title: "Descargar Recursos & Información"
about_codecombat: "Acerca de CodeCombat"
logo: "Logo"
screenshots: "Capturas de pantalla"
character_art: "Arte de Personajes"
download_all: "Descargar Todo"
previous: "Anterior"
location_title: "Nos encontramos en el centro de SF:"
teachers:
licenses_needed: "Licencias necesarias"
google_classroom_disabled_text: "Para vincular Google Classroom, inicia sesión con el SSO de Google"
select_class: "Selecciona una clase"
programming_language: "Lenguaje de programación"
programming_language_edit_desc: "No es posible cambiar el lenguaje una vez que ya hay estudiantes en la clase. Recomendamos crear una nueva clase para los mismos estudiantes."
add_a_class: "Agregar una clase nueva"
select_desired_lang: "Seleccionar el idioma de la clase"
elementary: "Primaria (elementary school)"
middle: "Intermedia (middle school)"
high_school: "Secundaria (high school)"
class_name: "Nombre de la clase"
grades: "Grados"
select_all_that_apply: "Selecciona las opciones que correspondan"
class_info_modal_sub_title: "Para invitar a los estudiantes a que se unan a tu clase, envíales lo siguiente:"
class_url: "Enlace de la clase"
class_url_desc: "Comparte el enlace para que los estudiantes se unan a tu clase tras registrarse"
class_code: "Código de la clase"
class_code_desc: "Los estudiantes pueden ingresar este código al registrarse en www.ozaria.com"
invite_by_email: "Invitación por correo electrónico"
# regenerate_class_code: "Regenerate"
invite_modal_sub_title: "Separa cada dirección de correo con un salto de línea o una coma"
no_new_students_imported: "No se importó ningún estudiante nuevo"
error_in_importing_classrooms: "Error al importar aulas"
error_in_importing_students: "Error al importar estudiantes"
no_licenses_page:
are_your_students_ready: "¿Tus estudiantes están entusiasmados por aprender más?"
once_students_have_completed: "Una vez que los estudiantes hayan completado el capítulo 1, necesitarán licencias para continuar aprendiendo con los próximos capítulos."
get_licenses: "Conseguir licencias"
get_full_access_to_ozaria: "Obtener acceso completo a Ozaria"
unlock_all: "Desbloquea todo lo anterior y recibe apoyo para maestros"
unlock_all_dsa: "Desbloquea todo lo anterior y todo el apoyo que necesitan los maestros"
comprehensive_dashboards: "Paneles muy completos para maestros y administradores"
lesson_plans_rubrics_guides: "Planes de estudios, guías de evaluación, guías de soluciones y más"
dedicated_customer_success_manager: "Un gerente exclusivo de satisfacción del cliente"
automatic_access: "Acceso automático a nuevas funciones y contenido"
license_quote: "\"En mi opinión, como maestro veterano de secundaria con 26 años de experiencia, no existe mejor recurso para enseñar programación\"."
join_our_community: "Únete a nuestra comunidad"
join_our_community_desc: "Más de 12 millones de personas han aprendido a escribir en Python y JavaScript con CodeCombat. Ahora te invitamos a unirte a nuestra comunidad de más de 82 000 educadores y 25 000 escuelas que usan Ozaria, un programa diseñado para docentes que quieren inspirar a la nueva generación de estudiantes a aprender Ciencias de la Computación."
teach_real_typed_code: "Enseña código real y práctico"
teach_real_typed_code_desc: "Los estudiantes aprenden Python y JavaScript, los dos lenguajes de programación más populares, y desarrollan habilidades del siglo XXI que les servirán para cualquier carrera."
support_student_progress: "Ayuda a los estudiantes a progresar"
support_student_progress_desc: "Obtén datos de evaluaciones formativas y sumativas a partir de comprobaciones de conceptos, niveles y proyectos finales para ayudar a los estudiantes a progresar."
creative_projects: "Proyectos creativos"
creative_projects_desc: "Despierta la imaginación y desata la creatividad de tus estudiantes con los proyectos finales. Por ejemplo, en el capítulo 2, deben diseñar su propio juego narrativo, que luego pueden compartir con quien quieran. "
looking_for_engaging: "¿Estás buscando un plan de estudios de Ciencias de la Computación interesante?"
licenses_are_required: "Para que los estudiantes continúen su camino después del capítulo 1, necesitarán licencias."
real_world_skills: "Habilidades del mundo real"
real_world_skills_desc: "Los estudiantes aprenden a escribir Python y JavaScript, los dos lenguajes de programación más populares, y perfeccionan sus habilidades de pensamiento crítico, su creatividad y su resiliencia, lo que les servirá para cualquier carrera."
personalized_learning: "Aprendizaje personalizado y enseñanza escalonada"
personalized_learning_desc: "Los estudiantes aprenden conceptos a su propio ritmo. Los niveles aumentan de dificultad a la vez que dan pistas predefinidas para fomentar la persistencia y la determinación."
flexible_curriculum: "Planes de estudio flexibles y alineados con estándares"
flexible_curriculum_desc: "Planes de estudio 100% alineados con la norma CSTA que se pueden adaptar con facilidad a cualquier cronograma, situación o entorno."
resources_to_support: "Recursos para ayudar a los maestros"
resources_to_support_desc: "Planificaciones de clases, actividades de extensión, guías curriculares y más recursos educativos diseñados para funcionar en entornos remotos e híbridos."
actionable_insights: "Información útil para maestros"
actionable_insights_desc: "Empodera a los educadores con datos intuitivos sobre el progreso y las evaluaciones de los estudiantes que posibilitan la enseñanza diferenciada."
special_offer:
special_offer: "Oferta Especial"
project_based_title: "Cursos basados en proyectos"
project_based_description: "Los cursos de desarrollo web y de juegos presentan proyectos finales compartibles."
great_for_clubs_title: "Ideal para clubes y clases electivas"
great_for_clubs_description: "Los maestros pueden comprar hasta __maxQuantityStarterLicenses__ Licencias de Principiante."
low_price_title: "Sólo __starterLicensePrice__ por estudiante"
low_price_description: "Las Licencias de Principiante se mantienen activas por for __starterLicenseLengthMonths__ meses desde la compra."
three_great_courses: "Tres grandes cursos incluidos en la Licencia de Principiante:"
license_limit_description: "Los maestros pueden comprar hasta __maxQuantityStarterLicenses__ Licencias de Principiante. Ya has comprado __quantityAlreadyPurchased__. Si necesitas más, contacta a __supportEmail__. Las Licencias de Principiante son válidas por __starterLicenseLengthMonths__ meses."
student_starter_license: "Licencia de Estudiante Principiante"
purchase_starter_licenses: "Comprar Licencias de Principiante"
purchase_starter_licenses_to_grant: "Compra Licencias de Principiante para acceder a __starterLicenseCourseList__"
starter_licenses_can_be_used: "Licencias de Principiante pueden usarse para agregar cursos adicionales inmediatamente luego de la compra."
pay_now: "Paga Ahora"
we_accept_all_major_credit_cards: "Aceptamos las principales tarjetas de crédito."
cs2_description: "se basa en la base de Introducción a las Ciencias de la Computación, adentrándose en declaraciones if, funciones, eventos y más."
wd1_description: "presenta los conceptos básicos de HTML y CSS al tiempo que enseña las habilidades necesarias para que los estudiantes construyan su primera página web."
gd1_description: "usa la sintaxis con la que los estudiantes ya están familiarizados para mostrarles cómo construir y compartir sus propios niveles de juego."
see_an_example_project: "mira un proyecto de ejemplo"
get_started_today: "¡Comienza Hoy!"
want_all_the_courses: "¿Quieres todos los cursos? Solicita información de nuestras Licencias Completas."
compare_license_types: "Compara los Typos de Licencia:"
cs: "Ciencias de la Computación"
wd: "Desarrollo Web"
wd1: "Desarrollo Web 1"
gd: "Desarrollo de Videojuegos"
gd1: "Desarrollo de Videojuegos 1"
maximum_students: "# Máximo de Estudiantes"
unlimited: "Ilimitado"
priority_support: "Apoyo prioritario"
yes: "Si"
price_per_student: "__price__ por estudiante "
pricing: "Precios"
free: "Gratis"
purchase: "Comprar"
courses_prefix: "Cursos"
courses_suffix: ""
course_prefix: "Curso"
course_suffix: ""
teachers_quote:
subtitle: "¡Obtén CodeCombat en tu clase, club, escuela o distrito!" # {change}
email_exists: "Existe un usuario con este email."
phone_number: "Teléfono"
phone_number_help: "¿Dónde podemos contactarte durante el horario de trabajo ?"
primary_role_label: "Tu Rol Primario"
role_default: "Seleccione Rol"
primary_role_default: "Seleccione Rol Primario"
purchaser_role_default: "Seleccione Rol de Comprador"
teacher: "Maestro"
tech_coordinator: "Coordinador de tecnología"
advisor: "Tutor" # {change}
principal: "Director"
superintendent: "Supervisor"
parent: "Padre"
purchaser_role_label: "Tu Rol de Comprador"
influence_advocate: "Influencia/Partidario"
evaluate_recommend: "Evaluar/Recomendar"
approve_funds: "Aprobar Fondos"
no_purchaser_role: "Ningún papel en las decisiones de compra"
district_label: "Distrito"
district_name: "Nombre del Distrito"
district_na: "Ingresa N/A si no aplica"
organization_label: "Escuela / Distrito" # {change}
school_name: "Nombre de la Escuela"
city: "Ciudad"
state: "Estado" # {change}
country: "País"
num_students_help: "¿Cuántos prevees inscribir en CodeCombat?" # {change}
num_students_default: "Seleccionar Rango"
education_level_label: "Nivel Educativo de los Estudiantes"
education_level_help: "Elegí todas las que correspondan."
elementary_school: "Escuela Primaria"
high_school: "Escuela Secundaria"
please_explain: "(describa, por favor)"
middle_school: "Escuela Intermedia"
college_plus: "Universidad o superior"
referrer: "¿Cómo supiste de nosotros?"
referrer_help: "Por ejemplo: por otro maestro, una conferencia, tus estudiantes, Code.org, etc."
referrer_default: "Selecciona Una"
referrer_conference: "Conferencia (p. ej. ISTE)"
referrer_hoc: "Code.org/Hour of Code"
referrer_teacher: "Un Maestro"
referrer_admin: "Un Administrador"
referrer_student: "Un Estudiante"
referrer_pd: "Capacitaciones/Talleres Profesionales"
referrer_web: "Google"
referrer_other: "Otro"
anything_else: "¿Algo más que deberíamos saber?" # {change}
thanks_header: "¡Gracias por solicitar un presupuesto!" # {change}
thanks_sub_header: "Gracias por el interés de su institución en CodeCombat" # {change}
thanks_p: "Estaremos en contacto pronto. ¿Preguntas? Escríbenos:" # {change}
back_to_classes: "Volver a las clases"
finish_signup: "Termine la creación de su cuenta de maestro:"
finish_signup_p: "Crear una cuenta para configurar la clase, agregar estudiante y monitorear su progreso a medida que aprenden programacioón"
signup_with: "Registrarse con:"
connect_with: "Conectar con:"
conversion_warning: "ADVERTENCIA: Su cuenta actual es de tipo <em>Estudiante</em>. Una vez que envie este formulario, su cuenta será actualizada como cuenta de maestro."
learn_more_modal: "Cuentas de maestro en CodeCombat tienen la ventaja de monitorear el progreso del estudiante, asignar inscripciónes y administrar salones de clases. Cuentas de maestro no pueden ser parte de los salones de clases. Si usted está registrado en una clase utilizando una cuenta de estudiante, no podrá acceder hasta que tenga una Cuenta de maestro." # {change}
create_account: "Crear una Cuenta de maestro"
create_account_subtitle: "Obtenga acceso a herramientas exclusivas para maestros de CodeCombat. <strong>Configurar una clase</strong>, agregar estudiantes, y <strong>monitorear su progreso</strong>!"
convert_account_title: "Actualizar mi perfil a Cuenta de maestro"
not: "No"
full_name_required: "Nombre y apellido requeridos"
versions:
save_version_title: "Guardar nueva versión"
new_major_version: "Nueva Gran Versión"
submitting_patch: "Publicando Parche..."
cla_prefix: "Para guardar los cambios, primero debes estar de acuerdo con nuestro"
cla_url: "CLA"
cla_suffix: "."
cla_agree: "ACEPTO"
owner_approve: "Necesita la aprobación de un propietario para que los cambios sean visibles."
contact:
contact_us: "Contacta a CodeCombat"
welcome: "¡Qué bueno es escuchar algo de ti! Usa este formulario para enviarnos un mensaje"
forum_prefix: "Para cualquier cosa pública, por favor prueba "
forum_page: "nuestro foro "
forum_suffix: "en su lugar."
faq_prefix: "También hay un"
faq: "FAQ"
subscribe_prefix: "Si necesitas ayuda para resolver un nivel, por favor"
subscribe: "compra una suscripción de CodeCombat"
subscribe_suffix: "y nosotros estaremos felices de ayudarte con tu código."
subscriber_support: "Como estás suscrito a CodeCombat, tu email tendrá prioridad."
screenshot_included: "Captura de pantalla incluida."
where_reply: "¿A dónde deberíamos responder?"
send: "Enviar Comentario"
account_settings:
title: "Configuración de la Cuenta"
not_logged_in: "Inicia sesión o crea una cuenta para cambiar tu configuración."
me_tab: "Yo"
picture_tab: "Imagen"
delete_account_tab: "Borra tu cuenta"
wrong_email: "Mail Incorrecto"
wrong_password: "Contraseña incorrecta"
delete_this_account: "Borrar esta cuenta permanentemente"
reset_progress_tab: "Reiniciar Todo Progreso"
reset_your_progress: "Limpiar todo tu progreso y comenzar de nuevo"
god_mode: "Modo Dios"
emails_tab: "Correos"
admin: "Admin"
manage_subscription: "Click aquí para administrar tu subscripción"
new_password: "Nueva Contraseña"
new_password_verify: "Verificar"
type_in_email: "Ingrese su correo electrónico para confirmar la eliminación de su cuenta." # {change}
type_in_email_progress: "Ingrese su correo para confirmar la eliminación de su progreso."
type_in_password: "Asimismo, ingrese su contraseña."
email_subscriptions: "Suscripciones de Email"
email_subscriptions_none: "No tienes suscripciones."
email_announcements: "Noticias"
email_announcements_description: "Recibe correos electrónicos con las últimas noticias y desarrollos de CodeCombat."
email_notifications: "Notificaciones"
email_notifications_summary: "Controles para tus notificaciones por correo electrónico automáticas y personalizadas relativas a tu actividad en CodeCombat."
email_any_notes: "Algunas notificaciones"
email_any_notes_description: "Desactiva para detener toda la actividad de correos de notificaciones."
email_news: "Noticias"
email_recruit_notes: "Oportunidades Laborales"
email_recruit_notes_description: "Si juegas realmente bien podríamos contactarte para ofrecerte un (mejor) trabajo."
contributor_emails: "Emails Clase Contribuyente"
contribute_prefix: "¡Estamos buscando gente que se una a nuestro grupo! Echa un vistazo a la "
contribute_page: "página de contribución"
contribute_suffix: "para averiguar más."
email_toggle: "Activar Todo"
error_saving: "Error al Guardar"
saved: "Cambios Guardados"
password_mismatch: "La contraseña no coincide."
password_repeat: "Por favor repita su contraseña."
keyboard_shortcuts:
keyboard_shortcuts: "Atajos de teclado"
space: "Barra espaciadora"
enter: "Enter"
press_enter: "Toca enter"
escape: "Escape"
shift: "Shift"
run_code: "Ejecutar el código."
run_real_time: "Ejecutar en tiempo real."
continue_script: "Continuar hasta finalizado el script."
skip_scripts: "Omitir todos los scripts omitibles."
toggle_playback: "Aplicar ejecutar/pausar."
scrub_playback: "Devolverse y avanzar en el tiempo."
single_scrub_playback: "Devolverse y avanzar en el tiempo de a un cuadro."
scrub_execution: "Scrub through la ejecución del hechizo actual."
toggle_debug: "Mostrar/ocultar depuración."
toggle_grid: "Mostrar/ocultar rejilla."
toggle_pathfinding: "Mostrar/ocultar buscador de rutas."
beautify: "Hacer bello tu código estandarizando formato."
maximize_editor: "Maximizar/minimizar editor de código."
cinematic:
click_anywhere_continue: "haz clic en cualquier lado para continuar" # {change}
instructional_tooltip: "Haz clic en los botones de flechas para avanzar o retroceder. También puedes usar las teclas de dirección del teclado."
community:
main_title: "Comunidad CodeCombat"
introduction: "Mira las maneras en las que puedes involucrarte adelante y decide qué es más divertido. ¡Queremos trabajar contigo!"
level_editor_prefix: "Usar CodeCombat"
level_editor_suffix: "para crear y editar niveles. Los han creado niveles para sus clases, amigos, hackatones, estudiantes, familiares. Si crear un nuevo juego luce intimidante puedes ¡comenzar con base en uno nuestro!"
thang_editor_prefix: "Nosotros llamamos a las unidades del juego 'Tiliches'. Usa el"
thang_editor_suffix: "para modificar el arte de CodeCombat. Permite a las unidades lanzar proyectiles, altera la dirección de una animación, cambia los puntos de vida de una unidad o sube tu propio sprite de vectores."
article_editor_prefix: "¿Ves algún error en nuestros documentos? ¿Quieres hacer algunas instrucciones para tus propias creaciones? Revisa el"
article_editor_suffix: "y ayuda a los jugadores de CodeCombat conseguir lo más posible de su tiempo jugando."
find_us: "Encuentranos en etsos sitios"
social_github: "Revisa todo nuestro código en GitHub"
social_blog: "Lee el blog de CodeCombat en Sett"
social_discource: "Únete a la discusión en nuestro foro"
social_facebook: "Me Gusta CodeCombat en Facebook"
social_twitter: "Sigue a CodeCombat en Twitter"
social_gplus: "Únete a CodeCombat con Google+"
social_slack: "Conversa con nosotros en nuestro canal de Slack"
contribute_to_the_project: "Contribuir al proyecto"
clans:
title: "Únete a los clanes de CodeCombat - Aprende a programar en Python, JavaScript y HTML"
clan_title: "__clan__ - Únete a los clanes de CodeCombat y aprende a programar"
meta_description: "Únete a un clan o crea tu propia comunidad de programadores. Juega en niveles de arena multijugador y mejora tu héroe y tus habilidades de programación."
clan: "Clan"
clans: "Clanes"
new_name: "Nuevo nombre de clan"
new_description: "descripción del clan"
make_private: "Hacer clan privado"
subs_only: "solo suscriptores"
create_clan: "Crear nuevo clan"
private_preview: "Vista previa"
private_clans: "Clanes Privados"
public_clans: "Clanes publicos"
my_clans: "Mis Clanes"
clan_name: "Nombre del clan"
name: "Nombre"
chieftain: "Líder del Clan"
edit_clan_name: "Editar el nombre del Clan"
edit_clan_description: "Editar descripción del clan"
edit_name: "editar nombre"
edit_description: "editar descripción"
private: "(privado)"
summary: "Resumen"
average_level: "Nivel Promedio"
average_achievements: "Logros Promedio"
delete_clan: "Borrar Clan"
leave_clan: "Abandonar Clan"
join_clan: "Ingresar Clan"
invite_1: "Invitar:"
invite_2: "*Invitar jugadores al clan, mandandoles este link."
members: "Miembros"
progress: "Progreso"
not_started_1: "no iniciado"
started_1: "iniciado"
complete_1: "completo"
exp_levels: "Expand levels"
rem_hero: "Remover Heróe"
status: "Estado"
complete_2: "Completo"
started_2: "Iniciado"
not_started_2: "No iniciado"
view_solution: "Click para ver la solución."
view_attempt: "Click para ver intento."
latest_achievement: "último logro"
playtime: "Tiempo de juego"
last_played: "Último jugado"
leagues_explanation: "Juega en una liga contra otros miembros del clan en estas instancias de arena multijugador."
track_concepts1: "Haga un seguimiento de los conceptos"
track_concepts2a: "aprendidos por cada estudiante"
track_concepts2b: "aprendidos por cada miembro"
track_concepts3a: "Haga un seguimiento de los niveles completados por cada estudiante"
track_concepts3b: "Haga un seguimiento de los niveles completados por cada miembro"
track_concepts4a: "Ve a tus estudiantes'"
track_concepts4b: "Ve a tus miembros'"
track_concepts5: "soluciones"
track_concepts6a: "Ordene a sus estudiantes por nombre o progreso"
track_concepts6b: "Ordene a sus miembros por nombre o progreso"
track_concepts7: "Requiere invitación"
track_concepts8: "para unirse"
private_require_sub: "Los clanes privados requieren una suscripción para crearlos o unírseles."
courses:
create_new_class: "Crear Nueva Clase"
hoc_blurb1: "Intenta"
hoc_blurb2: "Programa, Juega, Comparte"
hoc_blurb3: "¡actividad! Construye cuatro minijuegos diferentes para aprender los conceptos básicos del desarrollo de juegos, ¡luego crea los tuyos!"
solutions_require_licenses: "Las soluciones de nivel están disponibles para los maestros que tienen licencias."
unnamed_class: "Grupo Anónimo"
edit_settings1: "Editar Configuraciónes de Grupos"
add_students: "Agregar Estudiantes"
stats: "Estadísticas"
student_email_invite_blurb: "Sus estudiantes también pueden usar el código de clase <strong> __classCode__ </strong> al crear una Cuenta de Estudiante, no se requiere correo electrónico."
total_students: "Total de Estudiantes:"
average_time: "Tiempo Promedio de juego por nivel:"
total_time: "Tiempo total de juego:"
average_levels: "Niveles Promedio completados:"
total_levels: "Total de niveles completados:"
students: "Estudiantes"
concepts: "Con ceptos"
play_time: "Tiempo de Juego:"
completed: "Completados:"
enter_emails: "Introducir los emails de los estudiantes a invitar, uno por línea" # {change}
send_invites: "¿Mandar Invitaciones?" # {change}
number_programming_students: "Número de Estudiantes"
number_total_students: "Total de Estudiantes en Escuela/Distrito/Facultad"
enroll: "Inscribirse"
enroll_paid: "Anotar estudiantes en cursos pagos."
get_enrollments: "Obtener Más Matrículas"
change_language: "Cambiar idioma del curso"
keep_using: "Seguir Usando"
switch_to: "Cambiar a"
greetings: "Saludos!"
back_classrooms: "Volver a mis aulas"
back_classroom: "Volver a mi aula" # {change}
back_courses: "Volver a mis cursos" # {change}
edit_details: "Editar detalles de clase"
purchase_enrollments: "Comprar Matrículas" # {change}
remove_student: "Eliminar alumno"
assign: "Asignar"
to_assign: "para asignar cursos pagos."
student: "Estudiante"
teacher: "Maestro"
arena: "Arena"
available_levels: "Niveles Disponibles"
started: "iniciado"
complete: "completado"
practice: "práctica"
required: "obligatorio"
welcome_to_courses: "Aventureros, Bienvenidos a los Cursos!"
ready_to_play: "¿Estás listo?"
start_new_game: "Iniciar un Nuevo Juego"
play_now_learn_header: "Juega y Aprende"
play_now_learn_1: "Sintaxis básica para controlar a tu personaje"
play_now_learn_2: "bucles while para resolver rompecabezas molestos"
play_now_learn_3: "cadenas y variables para personalizar acciones"
play_now_learn_4: "como vencer a un ogro (¡habilidades importantes en la vida!)"
welcome_to_page: "¡Bienvenido a tu página de cursos!" # {change}
my_classes: "Mis Clases" # {change}
class_added: "¡Clase añadida satisfactoriamente!"
view_map: "ver mapa"
view_videos: "ver videos"
view_project_gallery: "ver proyectos de mis compañeros"
join_class: "Unirse a clase" # {change}
join_class_2: "Unirse a clase"
ask_teacher_for_code: "Preguntalé a tu maestro si tu tienes un código de CodeCombat! Si lo tiene, ingresalo debajo:" # {change}
enter_c_code: "<Ingresar Código de la Clase>" # {change}
join: "Unirse"
joining: "Uniéndose a clase __claseJoining__ "
unit_complete: "Unidad completada"
play_arena: "Jugar Arena"
view_project: "Ver Proyecto"
start: "Iniciar"
last_level: "Último nivel" # {change}
not_you: "¿No eres tú?"
continue_playing: "Seguir jugando"
option1_header: "Opción 1: Invitar estudiantes vía email" # {change}
remove_student1: "Quitar alumno"
are_you_sure: "¿Estás seguro que quieres eliminar a este alumno de tu clase?"
remove_description1: "El estudiante perderá acceso a esta aula y a sus clases asignadas. El progreso y la experiencia del juego NO se pierde, y el estudiante puede ser agregado de vuelta al aula en cualquier momento."
remove_description2: "La matrícula paga activada no será devuelta."
license_will_revoke: "La licencia paga de este estudiante será revocada y estará disponible para asignarla a otro estudiante."
keep_student: "Mantener alumno"
removing_user: "Eliminando usuario"
subtitle: "Revisar guías del curso, soluciones y niveles." # {change}
changelog: "Ver los últimos cambios en los niveles del curso."
select_language: "Seleccionar lenguaje"
select_level: "Seleccionar nivel"
play_level: "Jugar Nivel"
concepts_covered: "Conceptos Cubiertos"
view_guide_online: "Ver Guía En Línea(PDF)" # {change}
grants_lifetime_access: "Otorgar derecho de acceso a todos los cursos."
enrollment_credits_available: "Créditos de Inscripción Disponibles :" # {change}
language_select: "Seleccionar Lenguaje" # ClassroomSettingsModal
language_cannot_change: "El lenguaje no puede ser cambiado una vez que el estudiante ingreso a la clase."
avg_student_exp_label: "Promedio de la experiencia en programación del estudiante"
avg_student_exp_desc: "Esto nos ayudará a entender como llevar el ritmo de los cursos."
avg_student_exp_select: "Selecciona la mejor opción"
avg_student_exp_none: "Sin experiencia - poca o ninguna experiencia"
avg_student_exp_beginner: "Principiante - cierto grado de exposición o basado en bloque"
avg_student_exp_intermediate: "Intermedio - un poco de experiencia con código escrito"
avg_student_exp_advanced: "Avanzado - amplia experiencia con código escrito"
avg_student_exp_varied: "Niveles Variados de Experiencia"
student_age_range_label: "Rango de Edad del Estudiante"
student_age_range_younger: "Menor que 6"
student_age_range_older: "Mayor que 18"
student_age_range_to: "a"
estimated_class_dates_label: "Fechas Estimadas de Clase"
estimated_class_frequency_label: "Frecuencia Estimada de Clase"
classes_per_week: "clases por semana"
minutes_per_class: "minutos por clase"
create_class: "Crear Grupo"
class_name: "Nombre de clase"
teacher_account_restricted: "Tu cuenta es una cuenta de maestro, y no puedes acceder al contenido del estudiante." # {change}
account_restricted: "Necesitas una cuenta de Estudiante para acceder a esta pagina."
update_account_login_title: "Inicia sesión para actualizar tu cuenta"
update_account_title: "¡Tu cuenta necesita atención!"
update_account_blurb: "Antes de acceder a tus clases, selecciona como quieres usar esta cuenta."
update_account_current_type: "Tipo de Cuenta Actual:"
update_account_account_email: "Nombre/Correo electrónico de la Cuenta:"
update_account_am_teacher: "Soy un Maestro"
update_account_keep_access: "Mantener el acceso a las clases que he creado"
update_account_teachers_can: "Las cuentas de maestro pueden:"
update_account_teachers_can1: "Crear/administrar/agregar clases"
update_account_teachers_can2: "Asignar/inscribir estudiantes en cursos"
update_account_teachers_can3: "Desbloquea todos los niveles del curso para probar"
update_account_teachers_can4: "Accede a las nuevas funciones solo para maestros a medida que las lanzamos"
update_account_teachers_warning: "Advertencia: se lo eliminará de todas las clases a las que se haya unido anteriormente y no podrá jugar como estudiante."
update_account_remain_teacher: "Mantener Maestro"
update_account_update_teacher: "Actualizar Maestro"
update_account_am_student: "Soy un estudiante"
update_account_remove_access: "Eliminar acceso a las clases que he creado"
update_account_students_can: "Las cuentas de Estudiante pueden:"
update_account_students_can1: "Unirse a classes"
update_account_students_can2: "Juega a través de cursos como estudiante y sigue tu propio progreso"
update_account_students_can3: "Compite contra otros compañeros en arenas"
update_account_students_can4: "Accede a nuevas funciones solo para estudiantes a medida que las lanzamos"
update_account_students_warning: "Advertencia: No podrá administrar ninguna clase que haya creado anteriormente o crear nuevas clases."
unsubscribe_warning: "Advertencia: Se le dará de baja de su suscripción mensual."
update_account_remain_student: "Manener Estudiante"
update_account_update_student: "Actualizar Estudiante"
need_a_class_code: "Necesitarás un Código de Clase para la clase a la que te estás uniendo:"
update_account_not_sure: "¿No sabes cuál elegir? Correo electrónico"
update_account_confirm_update_student: "¿Estás seguro de que deseas actualizar tu cuenta a una experiencia de estudiante?"
update_account_confirm_update_student2: "No podrás administrar ninguna clase que hayas creado anteriormente o crear nuevas clases. Las clases creadas anteriormente se eliminarán de CodeCombat y no se podrán restaurar."
instructor: "Instructor: "
youve_been_invited_1: "Has sido invitado para unirte "
youve_been_invited_2: ", donde aprenderás "
youve_been_invited_3: " con tus compañeros en CodeCombat."
by_joining_1: "Uniéndote "
by_joining_2: "podrás ayudar a restablecer tu contraseña si la olvidas o la pierdes. También puedes verificar tu dirección de correo electrónico para que puedas restablecer la contraseña tu mismo."
sent_verification: "Hemos enviado un correo electrónico de verificación a:"
you_can_edit: "Puedes editar tu dirección de correo electrónico en "
account_settings: "Configuración de Cuenta"
select_your_hero: "Selecciona tu Héroe"
select_your_hero_description: "Siempre puedes cambiar tu héroe entrando en tu página de Cursos y haciendo click en \"Cambiar Héroe\""
select_this_hero: "Seleccionar este Héroe"
current_hero: "Héroe Actual:"
current_hero_female: "Heroína Actual:"
web_dev_language_transition: "Todas las clases programan en HTML / JavaScript para este curso. Las clases que han estado usando Python comenzarán con niveles de introducción de JavaScript adicionales para facilitar la transición. Las clases que ya están usando JavaScript omitirán los niveles de introducción."
course_membership_required_to_play: "Deberás unirte a un curso para jugar a este nivel."
license_required_to_play: "¡Pídele a tu maestro que te asigne una licencia para que puedas continuar jugando CodeCombat!" # {change}
update_old_classroom: "¡Nuevo año escolar, nuevos niveles!"
update_old_classroom_detail: "Para asegurarte de que estás obteniendo los niveles más actualizados, asegúrate de crear una nueva clase para este semestre haciendo clic en Crear una Nueva Clase en su"
teacher_dashboard: "tablero de maestros"
update_old_classroom_detail_2: "y entregando a los estudiantes el nuevo Código de Clase que aparecerá."
view_assessments: "Ver evaluaciones"
view_challenges: "ver niveles de desafío"
challenge: "Desafío:"
challenge_level: "Nivel de Desafío:"
status: "Estado:"
assessments: "Evaluaciones"
challenges: "Desafíos"
level_name: "Nombre del Nivel:"
keep_trying: "Sigue Intentando"
start_challenge: "Iniciar Desafío"
locked: "Bloqueado"
concepts_used: "Conceptos Usados:"
show_change_log: "Mostrar cambios a los niveles de este curso"
hide_change_log: "Ocultar cambios a los niveles de este curso"
concept_videos: "Videos de Concepto"
concept: "Concepto:"
basic_syntax: "Sintaxis Básica"
while_loops: "Bucles While"
variables: "Variables"
basic_syntax_desc: "La sintaxis es cómo escribimos código. Al igual que la ortografía y la gramática son importantes para escribir narraciones y ensayos, la sintaxis es importante al escribir código. Los humanos son buenos para entender lo que significa algo, incluso si no es exactamente correcto, pero las computadoras no son tan inteligentes, y necesitan que escribas con mucha precisión."
while_loops_desc: "Un bucle es una forma de repetir acciones en un programa. Puedes usarlos para no tener que seguir escribiendo códigos repetitivos, y cuando no sepas exactamente cuántas veces tendrá que ocurrir una acción para completar una tarea."
variables_desc: "Trabajar con variables es como organizar cosas en cajas de zapatos. Le das un nombre a la caja de zapatos, como \"Útiles escolares \", y luego pones las cosas dentro. El contenido exacto de la caja puede cambiar con el tiempo, pero todo lo que haya dentro siempre se llamará \"Útiles escolares \". En la programación, las variables son símbolos utilizados para almacenar datos que cambiarán a lo largo del programa. Las variables pueden contener una variedad de tipos de datos, incluidos números y cadenas de texto."
locked_videos_desc: "Sigue jugando para desbloquear el video del concepto __concept_name__."
unlocked_videos_desc: "Revisa el video del concepto __concept_name__."
video_shown_before: "mostrado antes de __level__"
link_google_classroom: "Enlace a Google Classroom"
select_your_classroom: "Selecciona tu Aula"
no_classrooms_found: "No se encontraron sulas"
create_classroom_manually: "Crear un aula manualmente"
classes: "Clases"
certificate_btn_print: "Imprimir"
certificate_btn_toggle: "Alternar"
module_coming_soon: "¡Próximamente, se vienen los módulos 4 a 6 del capítulo 1!"
error_in_creating_data: "Error al crear datos para el nivel introductorio."
project_gallery:
no_projects_published: "¡Sé el primero en publicar un proyecto en este curso!"
view_project: "Ver Proyecto"
edit_project: "Editar Proyecto"
teacher:
assigning_course: "Asignando curso"
back_to_top: "Volver arriba"
click_student_code: "Haz clic en cualquier nivel que el estudiante haya comenzado o completado para ver el código que escribió."
code: "Código de __name__"
complete_solution: "Solución completa"
course_not_started: "El estudiante todavía no ha completado este curso."
appreciation_week_blurb1: "¡Por la <strong>semana de apreciación al maestro de 2019</strong>, ofrecemos licencias gratuitas de una semana!<br />Debes escribirle a Rob Arevalo (<a href=\"mailto:robarev@codecombat.com?subject=Teacher Appreciation Week\">robarev@codecombat.com</a>) con el asunto \"<strong>Semana de apreciación al maestro</strong>\" e incluir:"
appreciation_week_blurb2: "la cantidad de licencias de una semana que quieres (una por estudiante)"
appreciation_week_blurb3: "la dirección de correo electrónico de tu cuenta de maestro de CodeCombat"
appreciation_week_blurb4: "si quieres licencias para la semana 1 (6 a 10 de mayo) o para la semana 2 (13 a 17 de mayo)"
hoc_happy_ed_week: "¡Feliz semana de la educación en ciencias de la computación!"
hoc_blurb1: "¡Entérate de la actividad gratuita"
hoc_blurb2: "Programa, juega y comparte,"
hoc_blurb3: "descarga un nuevo plan de estudios para maestros y dile a tus estudiantes que ingresen a jugar!"
hoc_button_text: "Ver actividad"
no_code_yet: "El estudiante aún no ha escrito nada de código para este nivel."
open_ended_level: "Nivel abierto"
partial_solution: "Solución parcial"
capstone_solution: "Solución final"
removing_course: "Quitando curso"
solution_arena_blurb: "Se alienta a los estudiantes a solucionar los niveles de arena con creatividad. La siguiente solución cumple con los requisitos del nivel."
solution_challenge_blurb: "Se alienta a los estudiantes a resolver los niveles abiertos con creatividad. La siguiente es una solución posible."
solution_project_blurb: "Se alienta a los estudiantes a crear un proyecto creativo en este nivel. Consulta las guías curriculares del centro de recursos para más información sobre cómo evaluar estos proyectos."
feedback_capstone: "El estudiante creará un proyecto básico en la parte 1 y hará actualizaciones creativas a partir de los comentarios de sus compañeros en la parte 2. Puedes compartir esta <a target=\"_blank\" rel=\"noopener\" href=\"https://docs.google.com/document/d/1u8LtMHlWnpEgLZQtZomPfe82s-Swden7iIacCzdYYxk\">plantilla de comentarios</a> con tus estudiantes."
students_code_blurb: "Cuando corresponde, se ofrece una solución correcta para el nivel. En algunos casos, es posible que el estudiante lo resuelva con un código distinto. No se muestran las soluciones de los niveles que el estudiante no ha comenzado."
course_solution: "Solución del curso"
level_overview_solutions: "Resumen del nivel y soluciones"
no_student_assigned: "No hay ningún estudiante asignado a este curso."
paren_new: "(nuevo)"
student_code: "Código del estudiante __name__"
teacher_dashboard: "Tablero del maestro" # Navbar
my_classes: "Mis Clases" # {change}
courses: "Cursos" # {change}
enrollments: "Recursos"
resources: "Resources"
help: "Ayuda"
language: "Lenguaje"
edit_class_settings: "editar configuración de la clase"
access_restricted: "Se requiere Actualización de la Cuenta"
teacher_account_required: "Una cuenta de Maestro es requerida para acceder a este contenido."
create_teacher_account: "Crear Cuenta de Maestro" # {change}
what_is_a_teacher_account: "Qué es una Cuenta de Maestro?"
teacher_account_explanation: "Una Cuenta de Maestro en CodeCombat da permiso a crear salones de clases, monitorear el progreso de los estudiantes mientras ellos trabajan a través de los cursos, manejar inscripciones y acceder a recursos para la creación de su plan de estudio." # {change}
current_classes: "Clases Recientes"
archived_classes: "Clases Archivadas"
# shared_classes: "Shared Classes"
archived_classes_blurb: "Las Clases pueden ser archivadas para futuras referencias. Desarchiva una Clase para verla en la lista de Clases Recientes de nuevo."
view_class: "ver clase"
archive_class: "almacenar clase"
unarchive_class: "desarchivar clase"
unarchive_this_class: "desarchivar esta clase"
no_students_yet: "Esta clase no tienes estudiantes todavía."
no_students_yet_view_class: "Ver clase para agregar estudiantes."
try_refreshing: "(Necesitarás recargar la página)"
create_new_class: "Crear una Nueva Clase"
class_overview: "Resumen de la Clase" # View Class page
avg_playtime: "Nivel medio de tiempo de juego"
total_playtime: "Tiempo Total de juego"
avg_completed: "Promedio de niveles completados"
total_completed: "Total de niveles completados"
created: "Creado"
concepts_covered: "Conceptos cubiertos"
earliest_incomplete: "Nivel incompleto más Reciente"
latest_complete: "Último nivel completado"
enroll_student: "Inscribir estudiante"
apply_modal_subtitle: "Se te redirigirá a la página Mis clases, donde podrás aplicar licencias a tus estudiantes de las siguientes formas:"
apply_modal_list_item_1: "Seleccionando o creando una clase"
apply_modal_list_item_2: "Seleccionando a los estudiantes a los que quieres aplicar licencias"
apply_modal_list_item_3: "Haciendo clic en el botón “Aplicar licencias”"
apply_license: "Aplicar Licencia"
revoke_license: "Eliminar Licencia"
revoke_licenses: "ELiminar Todas las Licencias"
course_progress: "Progreso del curso"
unit_progress: "Progreso de la unidad"
not_applicable: "N/A"
edit: "editar"
edit_2: "Editar"
remove: "eliminar"
latest_completed: "Último Completado" # {change}
sort_by: "Ordenado por"
progress: "Progreso"
concepts_used: "Conceptos usados por el Estudiante:"
concept_checked: "Concepto verificado:"
completed: "Completado"
practice: "Práctica"
started: "Iniciado"
no_progress: "Sin progreso"
not_required: "No requerido"
view_student_code: "Haz clic para ver el código de estudiante"
select_course: "Selecciona el curso a ver" # {change}
progress_color_key: "Color clave de Progreso:"
level_in_progress: "Nivel en Progreso"
level_not_started: "Nivel no Iniciado"
project_or_arena: "Proyecto o Arena"
students_not_assigned: "Estudiantes que no han sido asignados {{courseName}}"
course_overview: "Resumen del Curso"
copy_class_code: "Copiar código de la Clase"
class_code_blurb: "Nuevos estudiantes pueden entrar a este código de la clase en su tablero o visitar codecombat.com/courses para unirse a la clase." # {change}
copy_class_url: "Copia la URL de la Clase"
class_join_url_blurb: "Nuevos estudiantes pueden visitar esta URL mientras esten logeados para unirse a la clase." # {change}
add_students_manually: "Agregar Estudiantes Manualmente" # {change}
bulk_assign: "Mayor a asignar" # {change}
assigned_msg_1: "Se asignaron {{numberAssigned}} estudiantes a {{courseName}}."
assigned_msg_2: "Se aplicaron {{numberEnrolled}} licencias."
assigned_msg_3: "Tienes {{remainingSpots}} licencias disponibles restantes."
assign_course: "Asignar unidad"
removed_course_msg: "Se quitaron {{numberRemoved}} estudiantes de {{courseName}}."
remove_course: "Quitar unidad"
not_assigned_modal_title: "No se asignaron unidades"
not_assigned_modal_starter_body_1: "Este curso requiere una licencia de principiante. No tienes suficientes licencias de ese tipo para asignar este curso a los __selected__ estudiantes seleccionados."
not_assigned_modal_starter_body_2: "Compra licencias de principiante para brindar acceso a este curso."
not_assigned_modal_full_body_1: "Esta unidad requiere una licencia completa. No tienes suficientes licencias de ese tipo para asignar este curso a los __selected__ estudiantes seleccionados."
not_assigned_modal_full_body_2: "Solo tienes __numFullLicensesAvailable__ licencias completas disponibles (hay __numStudentsWithoutFullLicenses__ estudiantes que actualmente no tienen una licencia completa activa)."
not_assigned_modal_full_body_3: "Selecciona a menos estudiantes o escribe a __supportEmail__ para recibir asistencia."
assigned: "Asignado"
enroll_selected_students: "Inscribir Estudiantes Seleccionados"
no_students_selected: "No fueron seleccionados estudiantes."
show_students_from: "Muestra estudiantes de" # Enroll students modal
apply_licenses_to_the_following_students: "Aplicar licencias a los siguientes estudiantes"
students_have_licenses: "Los siguientes estudiantes ya tienen licencias aplicadas:"
all_students: "Todos los estudiantes"
apply_licenses: "Aplicar licencias"
not_enough_enrollments: "No tienes suficientes Inscripciones disponibles." # {change}
enrollments_blurb: "Los estudiantes deben tener una licencia para acceder al contenido luego de la primera unidad."
how_to_apply_licenses: "Cómo aplicar licencias"
export_student_progress: "Exportar el Progreso del Estudiante(CSV)"
send_email_to: "Enviar correo de recuperación de contraseña a:"
email_sent: "Correo enviado"
send_recovery_email: "Enviar correo de recuperación"
enter_new_password_below: "Ingresa la nueva contraseña:"
change_password: "Modificar contraseña"
changed: "Modificada"
available_credits: "Licencias disponibles"
pending_credits: "Licencias pendientes"
empty_credits: "Licencias vencidas"
license_remaining: "licencia restante"
licenses_remaining: "licencias restantes"
one_license_used: "Se ha utilizado 1 licencia de __totalLicenses__"
num_licenses_used: "Se han utilizado __numLicensesUsed__ licencias de __totalLicenses__"
starter_licenses: "licencias de principiante"
start_date: "fecha de inicio:"
end_date: "fecha de finalización:"
get_enrollments_blurb: " Te ayudaremos a crear una solución que satisfaga las necesidades de tu clase, escuela o distrito."
how_to_apply_licenses_blurb_1: "Cuando un maestro le asigna una unidad a un estudiante por primera vez, aplicaremos la licencia automáticamente. Utiliza la lista desplegable Seleccionar unidad en tu aula para asignar una unidad a los estudiantes seleccionados:"
how_to_apply_licenses_blurb_2: "¿Puedo aplicar una licencia sin asignar una unidad?"
how_to_apply_licenses_blurb_3: "Sí. Ve a la pestaña Estado de licencia en tu aula y haz clic en \"Aplicar licencia\" sobre todo estudiante que no tenga una licencia activa."
request_sent: "¡Solicitud enviada!"
assessments: "Evaluaciones"
license_status: "Estado de licencia"
status_expired: "Vencida el {{date}}"
status_not_enrolled: "No inscripto"
status_enrolled: "Vence el {{date}}"
select_all: "Seleccionar todo"
project: "Proyecto"
project_gallery: "Galería de proyectos"
view_project: "Ver proyecto"
unpublished: "(sin publicar)"
view_arena_ladder: "Ver clasificación de arena"
resource_hub: "Centro de recursos"
pacing_guides: "Guías didácticas de aula virtual"
pacing_guides_desc: "¡Aprende a incorporar todos los recursos de CodeCombat para planificar tu año académico!"
pacing_guides_elem: "Guía didáctica para primaria (Elementary School)"
pacing_guides_middle: "Guía didáctica para secundaria (Middle School)"
pacing_guides_high: "Guía didáctica para preparatoria (High School)"
getting_started: "Primeros pasos"
# student_resources: "Student Resources"
# lesson_slides: "Lesson Slides"
# section: "Section"
educator_faq: "Preguntas frecuentes de educadores"
educator_faq_desc: "Preguntas frecuentes sobre el uso de Ozaria en el aula o la escuela."
teacher_getting_started: "Guía introductoria para maestros"
teacher_getting_started_desc: "¿Primera vez en Ozaria? Descarga la guía introductoria para maestros para configurar tu cuenta, crear tu primera clase e invitar a tus estudiantes a trabajar en la primera unidad."
student_getting_started: "Guía de inicio rápido para estudiantes"
student_getting_started_desc: "Puedes compartir esta guía con tus estudiantes antes de empezar a jugar CodeCombat para que se familiaricen con el editor de código. Esta guía sirve para aulas de Python y JavaScript."
ap_cs_principles: "Fundamentos de Ciencias de la Computación AP"
ap_cs_principles_desc: "Con Fundamentos de Ciencias de la Computación AP, los estudiantes reciben una amplia introducción sobre la potencia, el impacto y las posibilidades de la informática. Este curso hace énfasis en el pensamiento computacional y la resolución de problemas a la vez que enseña conceptos básicos de programación."
cs1: "Introducción a las Ciencias de la Computación"
cs2: "Ciencias de la Computación 2"
cs3: "Ciencias de la Computación 3"
cs4: "Ciencias de la Computación 4"
cs5: "Ciencias de la Computación 5"
cs1_syntax_python: "Guía de sintaxis para el curso 1 de Python"
cs1_syntax_python_desc: "Apunte con referencias a la sintaxis habitual de Python que los estudiantes aprenderán en Introducción a las Ciencias de la Computación."
cs1_syntax_javascript: "Guía de sintaxis para el curso 1 de JavaScript"
cs1_syntax_javascript_desc: "Apunte con referencias a la sintaxis habitual de JavaScript que los estudiantes aprenderán en Introducción a las Ciencias de la Computación."
coming_soon: "¡Próximamente más guías!"
engineering_cycle_worksheet: "Hoja de ejercicios sobre el ciclo de ingeniería"
engineering_cycle_worksheet_desc: "Usa esta hoja de ejercicios para enseñarles a los estudiantes las bases del ciclo de ingeniería: análisis, diseño, implementación y depuración. Consulta la hoja de ejemplo completada como guía."
engineering_cycle_worksheet_link: "Ver ejemplo"
progress_journal: "Diario de progreso"
progress_journal_desc: "Alienta a los estudiantes a mantener un registro de sus avances en su diario de progreso."
cs1_curriculum: "Introducción a las Ciencias de la Computación - Guía curricular"
cs1_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 1."
arenas_curriculum: "Niveles de arena - Guía para maestros"
arenas_curriculum_desc: "Instrucciones sobre cómo jugar las arenas multijugador Batalla de Wakka, Huesos cruzados y Pico de poder con tu clase."
assessments_curriculum: "Niveles de evaluación - Guía para maestros"
assessments_curriculum_desc: "Aprende a usar los niveles de desafío y los niveles de desafío combo para evaluar el aprendizaje de los estudiantes."
cs2_curriculum: "Ciencias de la Computación 2 - Guía curricular"
cs2_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 2."
cs3_curriculum: "Ciencias de la Computación 3 - Guía curricular"
cs3_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 3."
cs4_curriculum: "Ciencias de la Computación 4 - Guía curricular"
cs4_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 4."
cs5_curriculum_js: "Ciencias de la Computación 5 - Guía curricular (JavaScript)"
cs5_curriculum_desc_js: "Alcance y orden, planes de estudio, actividades y más para las clases del curso 5 sobre JavaScript."
cs5_curriculum_py: "Ciencias de la Computación 5 - Guía curricular (Python)"
cs5_curriculum_desc_py: "Alcance y orden, planes de estudio, actividades y más para las clases del curso 5 sobre Python."
cs1_pairprogramming: "Actividad de programación en pareja"
cs1_pairprogramming_desc: "Enfrenta a los estudiantes a un ejercicio de programación en pareja que los ayudará a escuchar y comunicar mejor."
gd1: "Desarrollo de Juegos 1"
gd1_guide: "Desarrollo de Juegos 1 - Guía de proyecto"
gd1_guide_desc: "Usa esta guía para orientar a tus estudiantes mientras crean su primer proyecto de videojuego para compartir en cinco días."
gd1_rubric: "Desarrollo de Juegos 1 - Guía de evaluación del proyecto"
gd1_rubric_desc: "Usa esta guía de evaluación al finalizar Desarrollo de Juegos 1."
gd2: "Desarrollo de Juegos 2"
gd2_curriculum: "Desarrollo de Juegos 2 - Guía curricular"
gd2_curriculum_desc: "Planes de estudio para Desarrollo de Juegos 2."
gd3: "Desarrollo de Juegos 3"
gd3_curriculum: "Desarrollo de Juegos 3 - Guía curricular"
gd3_curriculum_desc: "Planes de estudio para Desarrollo de Juegos 3."
wd1: "Desarrollo Web 1"
wd1_curriculum: "Desarrollo Web 1 - Guía curricular"
wd1_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para Desarrollo Web 1."
wd1_headlines: "Actividad sobre títulos y encabezados"
wd1_headlines_example: "Ver ejemplo de solución"
wd1_headlines_desc: "¿Por qué son importantes las etiquetas de párrafo y encabezado? Usa esta actividad para demostrar que elegir bien los encabezados facilita la lectura de un sitio web. ¡Existen muchas soluciones correctas!"
wd1_html_syntax: "Guía de sintaxis HTML"
wd1_html_syntax_desc: "Hoja de referencia sobre los estilos de HTML que los estudiantes aprenderán en Desarrollo Web 1."
wd1_css_syntax: "Guía de sintaxis CSS"
wd1_css_syntax_desc: "Hoja de referencia sobre la sintaxis de CSS y de estilos que los estudiantes aprenderán en Desarrollo Web 1."
wd2: "Desarrollo Web 2"
wd2_jquery_syntax: "Guía de sintaxis para las funciones jQuery"
wd2_jquery_syntax_desc: "Hoja de referencia sobre las funciones jQuery que los estudiantes aprenderán en Desarrollo Web 2."
wd2_quizlet_worksheet: "Hoja de ejercicios para planificar el cuestionario"
wd2_quizlet_worksheet_instructions: "Ver instrucciones y ejemplos"
wd2_quizlet_worksheet_desc: "Antes de que tus estudiantes armen su proyecto de cuestionario de personalidad al finalizar Desarrollo Web 2, deben planificar las preguntas, los resultados y las respuestas con esta hoja de trabajo. Los maestros pueden distribuir las instrucciones y los ejemplos para consulta de los estudiantes."
student_overview: "Resumen"
student_details: "Detalles del estudiante"
student_name: "Nombre del estudiante"
no_name: "No ingresó nombre."
no_username: "No ingresó nombre de usuario."
no_email: "El estudiante no asignó ningún correo electrónico."
student_profile: "Perfil del estudiante"
playtime_detail: "Tiempo de juego detallado"
student_completed: "Completado por estudiante"
student_in_progress: "Estudiante en curso"
class_average: "Promedio de la clase"
not_assigned: "no cuenta con los siguientes cursos asignados"
playtime_axis: "Tiempo de juego en segundos"
levels_axis: "Niveles en"
student_state: "¿Cómo viene"
student_state_2: "en sus cursos?"
student_good: "viene bien en"
student_good_detail: "Este estudiante está a la par de la clase."
student_warn: "tal vez necesite ayuda con"
student_warn_detail: "Este estudiante tal vez necesite ayuda con nuevos conceptos que se han presentado en este curso."
student_great: "viene muy bien en"
student_great_detail: "Este estudiante tal vez pueda ayudar a otros alumnos de este curso."
full_license: "Licencia full"
starter_license: "Licencia de principiante"
trial: "Prueba"
hoc_welcome: "Feliz semana de la educación en ciencias de la computación"
hoc_title: "Juegos de la Hora del Código - Actividades gratuitas para aprender lenguajes de programación reales"
hoc_meta_description: "¡Crea tu propio juego o escapa de la mazmorra programando! CodeCombat tiene cuatro actividades de la Hora del Código y más de 60 niveles para jugar, crear y aprender a programar."
hoc_intro: "Hay tres maneras en las que tu clase puede participar de la Hora del Código con CodeCombat"
hoc_self_led: "Juego individual"
hoc_self_led_desc: "Los estudiantes pueden jugar dos tutoriales de la Hora del Código de CodeCombat por sí solos"
hoc_game_dev: "Desarrollo de juegos"
hoc_and: "y"
hoc_programming: "programación en JavaScript/Python"
hoc_teacher_led: "Lecciones dirigidas por el docente"
hoc_teacher_led_desc1: "Descarga nuestros"
hoc_teacher_led_link: "planes de estudio de Introducción a las Ciencias de la Computación"
hoc_teacher_led_desc2: "para que tus estudiantes aprendan conceptos de programación con actividades sin conexión"
hoc_group: "Juego grupal"
hoc_group_desc_1: "Los maestros pueden combinar las lecciones con nuestro curso de Introducción a las Ciencias de la Computación para supervisar el progreso de los estudiantes. Consulta nuestra"
hoc_group_link: "guía de inicio"
hoc_group_desc_2: "para más detalles"
hoc_additional_desc1: "Para acceder a más recursos y actividades de CodeCombat, consulta nuestras"
hoc_additional_desc2: "Preguntas"
hoc_additional_contact: "Contáctanos"
revoke_confirm: "¿Seguro quieres anular la licencia completa de {{student_name}}? La licencia estará disponible para asignársela a otro estudiante."
revoke_all_confirm: "¿Seguro quieres anular las licencias completas de todos los estudiantes de esta clase?"
revoking: "Anulando..."
unused_licenses: "¡Tienes licencias sin usar que te permiten asignar cursos pagos a estudiantes cuando estén listos para seguir aprendiendo!"
remember_new_courses: "¡Recuerda asignar cursos nuevos!"
more_info: "Más información"
how_to_assign_courses: "Cómo asignar cursos"
select_students: "Seleccionar Estudiantes"
select_instructions: "Haz clic en la casilla de verificación junto a cada estudiante para asignarle un curso."
choose_course: "Elegir curso"
choose_instructions: "Selecciona de la lista desplegable el curso que quieres asignar y luego haz clic en Asignar a los estudiantes seleccionados."
push_projects: "Recomendamos asignar Desarrollo Web 1 o Desarrollo de Juegos 1 una vez que los estudiantes hayan completado Introducción a las Ciencias de la Computación. Consulta nuestro {{resource_hub}} para más información sobre esos cursos."
teacher_quest: "El camino del maestro hacia el éxito"
quests_complete: "Misiones completadas"
teacher_quest_create_classroom: "Crear aula"
teacher_quest_add_students: "Agregar estudiantes"
teacher_quest_teach_methods: "Ayuda a tus estudiantes a aprender a `llamar métodos`."
teacher_quest_teach_methods_step1: "Consigue que el 75% de al menos una clase supere el primer nivel, __Mazmorras de Kithgard__"
teacher_quest_teach_methods_step2: "Imprime la [guía de inicio rápido para estudiantes](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) del centro de recursos."
teacher_quest_teach_strings: "Suéltales la cadena a tus estudiantes. Enséñales qué son las `cadenas`."
teacher_quest_teach_strings_step1: "Consigue que el 75% de al menos una clase supere __Nombres verdaderos__"
teacher_quest_teach_strings_step2: "Usa el selector de niveles para maestros que hay en la página [Guías de curso](/teachers/units) para previsualizar __Nombres verdaderos__."
teacher_quest_teach_loops: "Repíteles a tus estudiantes una y otra vez el concepto de `bucle`."
teacher_quest_teach_loops_step1: "Consigue que el 75% de al menos una clase supere __Danza con fuego__."
teacher_quest_teach_loops_step2: "Usa la __actividad sobre bucles__ de la [Guía curricular CS1](/teachers/resources/cs1) para reforzar este concepto."
teacher_quest_teach_variables: "Varía los conceptos con las `variables`."
teacher_quest_teach_variables_step1: "Consigue que el 75% de al menos una clase supere __Enemigo reconocido__."
teacher_quest_teach_variables_step2: "Fomenta la colaboración usando la [actividad de programación en pareja](/teachers/resources/pair-programming)."
teacher_quest_kithgard_gates_100: "Escapa por las Puertas de Kithgard con tu clase."
teacher_quest_kithgard_gates_100_step1: "Consigue el 75% de al menos una clase supere __Puertas de Kithgard__."
teacher_quest_kithgard_gates_100_step2: "Orienta a los estudiantes para que resuelvan problemas difíciles usando la [hoja de ejercicios sobre el ciclo de ingeniería](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)."
teacher_quest_wakka_maul_100: "Prepárate para un duelo en la Batalla de Wakka."
teacher_quest_wakka_maul_100_step1: "Consigue que el 75% de al menos una clase supere __Batalla de Wakka__."
teacher_quest_wakka_maul_100_step2: "Consulta la [guía de arenas](/teachers/resources/arenas) del [centro de recursos](/teachers/resources) para recibir sugerencias sobre cómo organizar un día de arena."
teacher_quest_reach_gamedev: "¡Explora nuevos mundos!"
teacher_quest_reach_gamedev_step1: "¡[Consigue licencias](/teachers/licenses) para que tus estudiantes exploren nuevos mundos, como el desarrollo web o de videojuegos!"
teacher_quest_done: "¿Quieres que tus estudiantes aprendan aún más sobre programación? ¡Ponte en contacto con nuestros [especialistas escolares](mailto:schools@codecombat.com) de inmediato!"
teacher_quest_keep_going: "¡Sigue avanzando! Esto es lo que puedes hacer ahora:"
teacher_quest_more: "Ver todas las misiones"
teacher_quest_less: "Ver menos misiones"
refresh_to_update: "(actualiza la página para ver actualizaciones)"
view_project_gallery: "Ver galería de proyectos" # {change}
office_hours: "Seminarios web para maestros"
office_hours_detail: "Aprende a seguir el ritmo de tus estudiantes mientras crean juegos y transitan el camino de la programación. Asiste a nuestros"
office_hours_link: "seminarios web"
office_hours_detail_2: "para maestros."
success: "Éxito"
in_progress: "En curso"
not_started: "Sin comenzar"
mid_course: "Mitad de curso"
end_course: "Fin de curso"
none: "Aún sin detectar"
explain_open_ended: "Nota: Se alienta a los estudiantes a resolver este nivel con creatividad. La siguiente es una solución posible."
level_label: "Nivel:"
time_played_label: "Tiempo jugado:" # {change}
back_to_resource_hub: "Volver al centro de recursos"
back_to_course_guides: "Volver a las guías de curso"
print_guide: "Imprimir esta guía"
combo: "Combo"
combo_explanation: "Los estudiantes superan los niveles de desafío combo si utilizan al menos uno de los conceptos enumerados. Puedes revisar el código de los estudiantes haciendo clic en el punto de progreso."
concept: "Concepto"
sync_google_classroom: "Sincronizar Google Classroom"
unit_overview: "Resumen de la unidad"
module_overview: "Resumen del módulo"
chapter1_unit_overview_desc: "Resumen de la experiencia del estudiante que incluye escenas de video, niveles de práctica, introducciones y el proyecto final del capítulo 1."
lesson_plan: "Plan de estudios"
chapter1_lesson_plan_desc: "Guía detallada que incluye objetivos de aprendizaje, normas CSTA, actividades de reflexión, sugerencias de facilitación y más."
capstone_rubric: "Guía de evaluación del proyecto final"
chapter1_capstone_rubric_desc: "Guía para evaluar los proyectos finales y las actividades de reflexión de los estudiantes al final de la unidad."
chapter1: "Capítulo 1: Bailarines de la luna" # {change}
chapter2: "Capítulo 2: Bailarines de la luna"
chapter3: "Capítulo 3: Tierras de Phoenix"
module1: "Módulo 1" # {change}
module2: "Módulo 2" # {change}
module3: "Módulo 3" # {change}
module4: "Módulo 4" # {change}
module5: "Módulo 5" # {change}
module6: "Módulo 6" # {change}
algorithms_and_syntax: "Algoritmos y sintaxis"
debugging: "Depuración"
variables: "Variables"
conditionals: "Condicionales"
capstone_intro: "Inicio del proyecto final"
capstone_project: "Proyecto final"
level_code: "Código de nivel"
review_needed: "Repaso necesario"
review_tooltip_heading: "¿Qué significa esto?"
review_tooltip_text: "Aparecerán señales de advertencia junto a las comprobaciones de conceptos en caso de que al menos un estudiante haya intentando responder la pregunta tres veces o más. En la sección <strong>Resumen del curso</strong>, aparecerán señales de advertencia junto a las comprobaciones de conceptos si al menos el 50% de los estudiantes que han comenzado o completado la comprobación lo intentaron tres veces o más."
scroll_to_see_more: "Desplázate para más información"
click_to_view_concept_check: "Haz clic para ver la comprobación de conceptos"
click_to_view_project_gallery: "Haz clic para ver la galería de proyectos"
review_learning_goal: "Repasar \"Meta de aprendizaje: __learningGoal__\" con los estudiantes."
view_capstone_project: "Ver proyecto final"
ozaria_dashboard_guide: "Guía de panel para maestros"
dashboard_guide_desc: "Un recorrido por las funciones del panel para maestros de Ozaria que te ayudará a supervisar el progreso y el trabajo de los estudiantes."
review: "Repaso"
for_loops: "Bucles for"
peer_feedback: "Formulario de comentarios"
presentation_checklist: "Lista de verificación para presentaciones"
teacher_licenses:
active_licenses: "Licencias activas"
expired_licenses: "Licencias vencidas"
share_licenses:
share_licenses: "Compartir licencias"
shared_by: "Compartido por:"
add_teacher_label: "Ingresar el correo electrónico del maestro:"
add_teacher_button: "Agregar maestro"
modal_subtitle: "Puedes compartir tus licencias con otros maestros de tu conjunto compartido."
modal_list_item_1: "Cada licencia puede utilizarse solamente para un estudiante a la vez."
modal_list_item_2: "Cuando los maestros anulan la licencia de algún estudiante, esa licencia regresa al conjunto compartido para que puedan usarla otros maestros del grupo."
subheader: "Puedes compartir tus licencias con otros maestros de tu institución. Cada licencia puede utilizarse solamente para un estudiante a la vez."
teacher_not_found: "Maestro no encontrado. Asegúrate de que el maestro ya tenga creada una cuenta de maestro."
teacher_not_valid: "Esta no es una cuenta de maestro válida. Solo los maestros pueden compartir licencias desde sus cuentas."
already_shared: "Ya has compartido estas licencias con ese maestro."
teachers_using_these: "Maestros que pueden acceder a estas licencias:"
footer: "Cuando los maestros anulan la licencia de algún estudiante, esa licencia regresa al conjunto compartido para que puedan usarla otros maestros del grupo."
you: "(tú)"
one_license_used: "(1 licencia utilizada)"
licenses_used: "(__licensesUsed__ licencias utilizadas)"
licenses_used_no_braces: "__licensesUsed__ licencias utilizadas"
more_info: "Más información"
shared_pool_label: "Maestros en tu conjunto compartido:"
sharing:
game: "Juego"
webpage: "Sitio web"
your_students_preview: "Tus estudiantes harán clic aquí para ver sus proyectos finalizados. No disponible en la vista previa del maestro."
unavailable: "No es posible compartir enlaces en la vista previa del maestro."
share_game: "Compartir este juego"
share_web: "Compartir este sitio web"
victory_share_prefix: "Comparte este enlace para invitar a tus amigos y familia a"
victory_share_prefix_short: "Invita a otras personas a"
victory_share_game: "jugar tu nivel del juego"
victory_share_web: "ver tu página web"
victory_share_suffix: "."
victory_course_share_prefix: "Este enlace les permitirá a tus amigos y familia"
victory_course_share_game: "jugar el videojuego"
victory_course_share_web: "ver la página web"
victory_course_share_suffix: "que has creado."
copy_url: "Copiar URL"
share_with_teacher_email: "Enviar a tu maestro"
game_dev:
creator: "Creador"
web_dev:
image_gallery_title: "Galería de imágenes"
select_an_image: "Selecciona la imagen que quieres usar"
scroll_down_for_more_images: "(Desplazar hacia abajo para ver más imágenes)"
copy_the_url: "Copiar la URL de abajo"
copy_the_url_description: "Útil si quieres reemplazar una imagen existente."
copy_the_img_tag: "Copiar la etiqueta <img>"
copy_the_img_tag_description: "Útil si quieres insertar una nueva imagen."
copy_url: "Copiar URL"
copy_img: "Copiar <img>"
how_to_copy_paste: "Cómo copiar y pegar"
copy: "Copiar"
paste: "Pegar"
back_to_editing: "Volver a editar"
classes:
archmage_title: "Archimago"
archmage_title_description: "(Desarrollador)"
archmage_summary: "Si eres un programador interesado en juegos educativos, conviértete en un archimago y ayúdanos a construir CodeCombat!"
artisan_title: "Artesano"
artisan_title_description: "(Constructor de Niveles)"
artisan_summary: "Construye y comparte niveles para que tú y tus amigos jueguen. Conviértete en un Artesano y aprende el arte the enseñar a los demás a programar."
adventurer_title: "Aventurero"
adventurer_title_description: "(Probador de Niveles)"
adventurer_summary: "Consigue nuestros nuevos niveles| (even our subscriber content) for free one week early and help us work out bugs before our public release."
scribe_title: "Escriba"
scribe_title_description: "(Editor de Artículos)"
scribe_summary: "Buen código necesita buena documentación. Escribe, edita y mejora los documentos leídos por millones de jugadores en el mundo."
diplomat_title: "Diplomático"
diplomat_title_description: "(Traductor)"
diplomat_summary: "CodeCombat está traducido a más de 45 idiomas por nuestros diplomáticos. Ayúdanos y contribuye con las traducciones."
ambassador_title: "Embajador"
ambassador_title_description: "(Soporte)"
ambassador_summary: "Ayuda a responder las preguntas de los usuarios del foro. Nuestros Embajadores representan CodeCombat en todo el mundo."
teacher_title: "Maestro"
editor:
main_title: "Editor de CodeCombat"
article_title: "Editor de Artículo"
thang_title: "Editor de Tiliches"
level_title: "Editor de Nivel"
course_title: "Editor de Curso"
achievement_title: "Editor de logros"
poll_title: "Editor de Encuesta"
# resource_title: "Resource Editor"
back: "Atrás"
revert: "Revertir"
revert_models: "Revertir Modelos"
pick_a_terrain: "Elije un Terreno"
dungeon: "Calabozo"
indoor: "Interior"
desert: "Desierto"
grassy: "Herboso"
mountain: "Montaña"
glacier: "Glaciar"
small: "Pequeño"
large: "Grande"
fork_title: "Fork de Nueva Versión"
fork_creating: "Creando Fork..."
generate_terrain: "Generar terreno"
more: "Más"
wiki: "Wiki"
live_chat: "Chat en vivo"
thang_main: "Principal"
thang_spritesheets: "Hojas de figuras( para animaciones )"
thang_colors: "Colores"
level_some_options: "¿Algunas opciones?"
level_tab_thangs: "Tiliches"
level_tab_scripts: "Scripts"
level_tab_components: "Componentes"
level_tab_systems: "Sistemas"
level_tab_docs: "Documentación"
level_tab_thangs_title: "Tiliches Actuales"
level_tab_thangs_all: "Todo"
level_tab_thangs_conditions: "Condiciones Iniciales"
level_tab_thangs_add: "Agregar Thangs"
level_tab_thangs_search: "Buscar Thangs"
add_components: "Agregar Componentes"
component_configs: "Configuraciones del Componente"
config_thang: "Doble clic para configurar un Tiliche"
delete: "Borrar"
duplicate: "Duplicar"
stop_duplicate: "Parar de Duplicar"
rotate: "Rotar"
level_component_tab_title: "Componentes Actuales"
level_component_btn_new: "Crear Nuevo Componente"
level_systems_tab_title: "Sistemas Actuales"
level_systems_btn_new: "Crear Nuevo Sistema"
level_systems_btn_add: "Agregar Sistema"
level_components_title: "Regresar a todos los Tiliches"
level_components_type: "Tipo"
level_component_edit_title: "Editar Componente"
level_component_config_schema: "Config Schema"
level_system_edit_title: "Editar Sistema"
# course_edit_title: "Edit Course"
# resource_edit_title: "Edit Resource"
create_system_title: "Crear Nuevo Sistema"
new_component_title: "Crear Nuevo Componente"
new_component_field_system: "Sistema"
new_article_title: "Crear un Nuevo Artículo"
new_thang_title: "Crear un Nuevo tipo de Tiliche"
new_level_title: "Crear un Nuevo Nivel"
new_article_title_login: "Ingresa para Crear un Nuevo Artículo"
new_thang_title_login: "Ingresa para crear un nuevo tipo de Tiliche"
new_level_title_login: "Ingresa para Crear un Nuevo Nivel"
new_achievement_title: "Crear un Nuevo Logro"
new_achievement_title_login: "Ingresa para Crear un Nuevo Logro"
new_poll_title: "Crear una nueva encuesta"
new_poll_title_login: "Ingresa para crear una nueva encuesta"
# new_course_title: "Create a New Course"
# new_course_title_login: "Log In to Create a New Course"
# new_resource_title: "Create a New Resource"
# new_resource_title_login: "Log In to Create a New Resource"
article_search_title: "Buscar Artículos aquí"
thang_search_title: "Buscar tipos de Tiliche aquí"
level_search_title: "Buscar Niveles aquí"
achievement_search_title: "Buscar logros"
poll_search_title: "Buscar Encuesta"
# course_search_title: "Search Courses"
# resource_search_title: "Search Resources"
read_only_warning2: "Nota: no puedes guardar ediciones aquí, porque no estas logueado."
no_achievements: "No hay logros agregados en este nivel por ahora."
achievement_query_misc: "Objetivo clave de misceláneo"
achievement_query_goals: "Objetivo clave de los objetivos de nivel"
level_completion: "Nivel Completado"
pop_i18n: "Poblar I18N"
tasks: "Tareas"
clear_storage: "Borrar tus cambios locales"
add_system_title: "Agregar Sistemas al Nivel"
done_adding: "Finalizar"
# product: "Product"
# link: "Link"
article:
edit_btn_preview: "Vista previa"
edit_article_title: "Editar Artículo"
polls:
priority: "Prioridad"
contribute:
page_title: "Contribuyendo"
intro_blurb: "CodeCombat es 100% open source! Cientos de jugadores dedicados nos han ayudado a contruir el juego. Únete y escribe el siguiente capítulo de la misión de CodeCombat de enseñar al mundo a programar!" # {change}
alert_account_message_intro: "¡Hola!"
alert_account_message: "Para suscribirte para los correos, necesitas ingresar primero."
archmage_introduction: "Una de las mejores partes de hacer juegos es que sintetizan muchas cosas diferentes. Gráficas, sonido, redes, redes sociales y muchos aspectos comunes de programación, desde manejo de bases de datos y administración de servidores, hasta trabajar en el diseño y construcción de interfaces. Hay mucho para hacer, y si eres un programador con experiencia con el deseo de ingresar en el meollo del asunto de CodeCombat, esta clase puede ser para ti. Nos encantaría contar con tu ayuda para construir el mejor juego de programación."
class_attributes: "Atributos de Clase"
archmage_attribute_1_pref: "Conocimiento en "
archmage_attribute_1_suf: ", o un deseo de aprender. La mayor parte de nuestro código está en este lenguaje. Si eres un fan de Python o Ruby, te sentirás en casa. Es Javascript, pero con un mejor syntax."
archmage_attribute_2: "Alguna experiencia programando e iniciativa personal. Te ayudaremos a orientarte, pero no podemos perder mucho tiempo entrenando."
how_to_join: "Unirse:"
join_desc_1: "¡Cualquiera puede unirse! Sólo checa nuestro "
join_desc_2: "para comenzar, y pon un check abajo para marcarte como un valiente Archimago y conseguir las últimas noticias por email. ¿Quieres chatear sobre qué hacer o cómo involucrarte más? "
join_desc_3: ", o encuéntranos en "
join_desc_4: "y ahí empezaremos!"
join_url_email: "Escríbenos"
join_url_slack: "Canal de Slack"
archmage_subscribe_desc: "Obten correos de nuevas oportunidades y anuncios."
artisan_introduction_pref: "¡Debemos construir niveles adicionales! La gente ruega por más contenido, y podemos hacer tanto por nosotros mismos. De momento tu estación de trabajo es nivel 1 ; Nuestro editor de niveles es apenas útil incluso para sus creadores, así que sea cauteloso. Si tuviera visiones de campañas apareciendo para ciclos for"
artisan_introduction_suf: ", entonces esta lase es ideal para ti."
artisan_attribute_1: "Cualquier experiencia creando contenido similar estaría bien, como por ejemplo el editor de niveles de Blizzard. ¡Aunque no es necesaria!"
artisan_attribute_2: "Un anhelo de hacer un montón de pruebas e iteraciones. Para hacer buenos niveles necesitas mostrárselos a otros y mirar como juegan, además de estar preparado para encontrar los fallos a reparar."
artisan_attribute_3: "Por el momento, la resistencia va a la par con el Aventurero. Nuestro editor de niveles está a un nivel de desarrollo temprano y puede ser muy frustrante usarlo. ¡Estás advertido!"
artisan_join_desc: "Sigue las siguientes indicaciones para usar el editor de niveles. Tómalo o déjalo:"
artisan_join_step1: "Lee la documentación."
artisan_join_step2: "Crea un nuevo nivel y explora los niveles existentes."
artisan_join_step3: "Busca nuestra sala pública de Slack en busca de ayuda."
artisan_join_step4: "Publica tus niveles en el foro para recibir comentarios críticos."
artisan_subscribe_desc: "Recibe correos sobre actualizaciones del editor de niveles y anuncios."
adventurer_introduction: "Hablemos claro sobre tu papel: eres el tanque. Vas a recibir fuertes daños. Necesitamos gente para probar nuestros flamantes niveles y ayudar a mejorarlos. El dolor será enorme; hacer buenos juegos es un proceso largo y nadie lo consigue a la primera. Si puedes resistir y tener una puntuación alta en resistencia, entonces esta clase es para ti."
adventurer_attribute_1: "Estar sediento de conocimientos. Quieres aprender a programar y nosotros queremos enseñarte a hacerlo. Aunque en este caso es más probable que seas tú el que esté haciendo la mayor parte de la enseñanza."
adventurer_attribute_2: "Carismático. Se amable pero claro a la hora de desglosar qué necesita ser mejorado y sugiere de qué formas podría hacerse."
adventurer_join_pref: "Reúnete con (¡o recluta!) un Artesano y trabaja con ellos, o marca la casilla de abajo para recibir un correo cuando haya nuevos niveles para probar. También publicaremos en nuestras redes nuevos niveles para revisar"
adventurer_forum_url: "nuestro foro"
adventurer_join_suf: "así que si prefieres estar informado en esa forma, ¡crea una cuenta allí!"
adventurer_subscribe_desc: "Recibe correos cuando haya nuevos niveles para testar."
scribe_introduction_pref: "CodeCombat no será solo un montón de niveles. También será una fuente de conocimientos, una wiki de conceptos de programación a la que los niveles se engancharan. De esa forma, en lugar de que cada Artesano tenga que describir en detalle qué es un operador de comparación, podrá simplemente enlazar el nivel al Artículo que los describe y que ya ha sido escrito para edificación del jugador. Algo en la línea de lo que la "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: " ha construido. Si tu idea de diversión es articular los conceptos de la programación de una forma sencilla, entonces esta clase es para ti."
scribe_attribute_1: "Habilidad a la hora de escribir es casi todo lo que necesitas. No solo dominar la gramática y la ortografía sino también expresar ideas complicadas a los demás de forma sencilla."
contact_us_url: "Escribenos un correo electrónico" # {change}
scribe_join_description: "cuéntanos más sobre ti, tu experiencia en el mundo de la programación y sobre qué cosas te gustaría escribir. ¡Y continuaremos a partir de ahí!"
scribe_subscribe_desc: "Recibe correos sobre anuncios de redacción de Artículos."
diplomat_introduction_pref: "Hemos aprendido algo gracias a la "
diplomat_introduction_url: "comunidad de código abierto:"
diplomat_introduction_suf: "hay un interés considerable en CodeCombat en otros paises, ¡especialmente Brasil! Estamos formando un cuerpo de traductores con ganas de traducir un grupo de palabras tras otro para hacer CodeCombat tan accesible para todo el mundo como sea posible. Si quieres recibir avances de próximos contenidos y quieres poner esos niveles a disposición de los que comparten tu idioma tan pronto como sea posible, entonces esta Clase es para ti."
diplomat_attribute_1: "Fluidez con el ingles y el lenguaje al que quieras traducir. Cuando de transmitir ideas complejas se trata, ¡es importante tener grandes conocimientos de ambas!"
diplomat_i18n_page_prefix: "Puedes traducir nuestros niveles yendo a nuestra"
diplomat_i18n_page: "página de traducciones"
diplomat_i18n_page_suffix: ", o en nuestra interfaz y sitio web en GitHub."
diplomat_join_pref_github: "Encuentra el fichero local de tu idioma "
diplomat_github_url: "en GitHub"
diplomat_join_suf_github: ", edítalo online, y solicita que sea revisado. Además, marca la casilla de abajo para mantenerte informado en nuevos progresos en Internacionalización."
diplomat_subscribe_desc: "Recibe correos sobre nuevos niveles y desarrollos para traducir."
ambassador_introduction: "Esta es una comunidad en construcción y tú eres parte de las conexiones. Tenemos chat Olark, correos electrónicos y las redes sociales con una gran cantidad de personas con quienes hablar, ayudar a familiarizarse con el juego y aprender. Si quieres ayudar a la gente a que se involucre, se divierta, y tenga buenas sensaciones sobre CodeCombat y hacia dónde vamos, entonces esta clase es para ti."
ambassador_attribute_1: "Habilidades de comunicación. Ser capaz de identificar los problemas que los jugadores están teniendo y ayudarles a resolverlos. Además, mantener al resto de nosotros informados sobre lo que los jugadores están diciendo, lo que les gusta, lo que no ¡y de lo que quieren más!"
ambassador_join_desc: "cuéntanos más sobre ti, que has hecho y qué estarías interesado en hacer. ¡Y continuaremos a partir de ahí!"
ambassador_subscribe_desc: "Recibe correos sobre actualizaciones de soporte y desarrollo del multijugador."
teacher_subscribe_desc: "Obtener actulizaciones y anuncios para maestros en su correo electrónico."
changes_auto_save: "Los cambios son guardados automáticamente cuando marcas las casillas de verificación."
diligent_scribes: "Nuestros diligentes Escribas:"
powerful_archmages: "Nuestros poderosos Archimagos:"
creative_artisans: "Nuestros creativos Artesanos:"
brave_adventurers: "Nuestros bravos Aventureros:"
translating_diplomats: "Nuestros políglotas Diplomáticos:"
helpful_ambassadors: "Nuestros amables Embajadores:"
ladder:
title: "Arenas multijugador"
arena_title: "__arena__ | Arenas multijugador"
my_matches: "Mis Partidas"
simulate: "Simular"
simulation_explanation: "¡Simulando tus juegos puedes mejorar tu posición más rápido!"
simulation_explanation_leagues: "Principalmente ayudarás a simular juegos para jugadores aliados en tus clanes y cursos."
simulate_games: "¡Simular Juegos!"
games_simulated_by: "Juegos simulados por ti:"
games_simulated_for: "Juegos simulados para ti:"
games_in_queue: "Juegos actualmente en cola:"
games_simulated: "Juegos simulados"
games_played: "Juegos jugados"
ratio: "Proporción"
leaderboard: "Tabla de Posiciones"
battle_as: "Combate como "
summary_your: "Tus "
summary_matches: "Partidas - "
summary_wins: " Ganadas, "
summary_losses: " Perdidas"
rank_no_code: "Sin Código Nuevo para Clasificar"
rank_my_game: "¡Clasifica Mi Juego!"
rank_submitting: "Enviando..."
rank_submitted: "Enviado para Clasificación"
rank_failed: "Fallo al Clasificar"
rank_being_ranked: "Juego Siendo Clasificado"
rank_last_submitted: "Presentado"
help_simulate: "¿Ayudar simulando juego?"
code_being_simulated: "Tu nuevo código está siendo simulado por otros jugadores para clasificación. Esto se refrescará a medida que vengan nuevas partidas."
no_ranked_matches_pre: "Sin partidas clasificadas para el "
no_ranked_matches_post: " equipo! Juega en contra de algunos competidores y luego vuelve aquí para ver tu juego clasificado."
choose_opponent: "Escoge un Oponente"
select_your_language: "Selecciona tu idioma"
tutorial_play: "Juega el Tutorial"
tutorial_recommended: "Recomendado si nunca has jugado antes"
tutorial_skip: "Saltar Tutorial"
tutorial_not_sure: "¿No estás seguro de que sucede?"
tutorial_play_first: "Juega el Tutorial primero."
simple_ai: "IA Simple"
warmup: "Calentamiento"
friends_playing: "Amigos Jugando"
log_in_for_friends: "Ingresa para jugar con tus amigos!"
social_connect_blurb: "Conectate y juega contra tus amigos!"
invite_friends_to_battle: "Invita a tus amigos para que se unan a la Batalla!"
fight: "Pelea!"
watch_victory: "Observa tu Victoria"
defeat_the: "Derrota a"
watch_battle: "Mirar la batalla"
tournament_started: ", iniciado"
tournament_ends: "Final de Torneo"
tournament_ended: "Finalizó el Torneo"
tournament_rules: "Reglas del Torneo"
tournament_blurb: "Escribe código, recolecta oro, arma ejercitos, aplasta adversarios, gana premios, y asciende en tu carrera por $40,000 en el Torneo Codicia! Echa un vistazo a los detalles"
tournament_blurb_criss_cross: "Gana apuestas, construye caminos, burla tus oponentes, agarra gemas, y asciende tu perfil en nuestro torneo Cruzado! Echa un vistazo a los detalles"
tournament_blurb_zero_sum: "Suelta tus habilidades de código en recolección de oro y tácticas de batalla en este partido espejo alpino entre el hechicero rojo y el hechicero azul. El torneo comenzó el Viernes, 27 de Marzo y se extenderá hasta el Lunes, 6 de Abril a las 5PM PDT. Compite por la diversión y la gloria ! Echa un vistazo a los detalles:"
tournament_blurb_ace_of_coders: "¡Lucha en el glaciar congelado en este encuentro con estilo dominación en espejo! El torneo comienza el Miércoles 16 de Septiembre, y se ejecutará hasta el Miércoles 14 de Octubre hasta las 5PM PDT. Revisa los detalles"
tournament_blurb_blog: "en nuestro blog"
rules: "Reglas"
winners: "Ganadores"
league: "Liga"
red_ai: "IA Roja" # "Red AI Wins", at end of multiplayer match playback
blue_ai: "IA Azul"
wins: "Gana" # At end of multiplayer match playback
humans: "Rojo" # Ladder page display team name
ogres: "Azul"
live_tournament: "Torneo en vivo"
awaiting_tournament_title: "Torneo inactivo"
awaiting_tournament_blurb: "La arena de torneos no se encuentra activa en este momento."
tournament_end_desc: "El torneo ha terminado. ¡Gracias por jugar!"
age: "Edad"
bracket_0_11: "0-11"
bracket_11_14: "11-14"
bracket_14_18: "14-18"
# bracket_11_18: "11-18"
bracket_open: "Abierto"
user:
user_title: "__name__ - Aprende a programar con CodeCombat"
stats: "Estados"
singleplayer_title: "Nivel un jugador"
multiplayer_title: "Niveles multijugador"
achievements_title: "Logros"
last_played: "Último jugado"
status: "Estado"
status_completed: "Completo"
status_unfinished: "Incompleto"
no_singleplayer: "No hay juegos para un jugador todavía."
no_multiplayer: "No hay juegos multijugador todavía."
no_achievements: "Sin Logros todavía."
favorite_prefix: "Idioma favorito "
favorite_postfix: "."
not_member_of_clans: "No eres miembro de ningún clan todavía."
certificate_view: "ver certificado"
certificate_click_to_view: "haz clic para ver certificado"
certificate_course_incomplete: "curso incompleto"
certificate_of_completion: "Certificado de Aprobación"
certificate_endorsed_by: "Avalado por"
certificate_stats: "Estadísticas de Curso"
certificate_lines_of: "líneas de"
certificate_levels_completed: "niveles completados"
certificate_for: "Por"
certificate_number: "No."
achievements:
last_earned: "Último Ganado"
amount_achieved: "Cantidad"
achievement: "Logros"
current_xp_prefix: ""
current_xp_postfix: " en total"
new_xp_prefix: ""
new_xp_postfix: " ganado"
left_xp_prefix: ""
left_xp_infix: " hasta el nivel "
left_xp_postfix: ""
account:
title: "Cuenta"
settings_title: "Configuración de cuenta"
unsubscribe_title: "Cancelar suscripción"
payments_title: "Pagos"
subscription_title: "Suscripción"
invoices_title: "Facturas"
prepaids_title: "Prepagados"
payments: "Pagos"
prepaid_codes: "Códigos Prepagados"
purchased: "Comprado"
subscribe_for_gems: "Suscríbete para obtener gemas"
subscription: "Suscripción"
invoices: "Facturas"
service_apple: "Apple"
service_web: "Web"
paid_on: "Pagado en"
service: "Servicio"
price: "Precio"
gems: "Gemas"
active: "Activo"
subscribed: "Suscrito"
unsubscribed: "Desuscrito"
active_until: "Activo Hasta"
cost: "Costo"
next_payment: "Próximo Pago"
card: "Tarjeta"
status_unsubscribed_active: "No estas suscrito y no se te cobrará, pero tu cuenta está activa por ahora."
status_unsubscribed: "¡Obtén acceso a nuevos niveles, héroes, items y gemas extras con la suscripción a CodeCombat!"
not_yet_verified: "No verificado todavía."
resend_email: "Reenviar email"
email_sent: "¡Email enviado! Revisa tu casilla."
verifying_email: "Verificando tu email..."
successfully_verified: "¡Has verificado tu email con exito!"
verify_error: "Algo salio mal al verificar tu email :("
unsubscribe_from_marketing: "¿Cancelar suscripción de __email__ de todos los correos de marketing de CodeCombat?"
unsubscribe_button: "Si, cancelar suscripción"
unsubscribe_failed: "Error"
unsubscribe_success: "¡Éxito!"
account_invoices:
amount: "Cantidad en dólares."
declined: "La tarjeta fue rechazada."
invalid_amount: "Por favor ingrese cantidad en dólares."
not_logged_in: "Ingresate o crea una cuenta para acceder a las facturas."
pay: "Pagar Factura"
purchasing: "Comprando..."
retrying: "Error de Servidor, reintentando..."
success: "Listo, fue cobrado. Gracias!"
account_prepaid:
purchase_code: "Adquirir un Código de Suscripción"
purchase_code1: "Los códigos de suscripción pueden ser canjeados para agregar tiempo de suscripción premium para una o más cuentas CodeCombat." # {change}
purchase_code2: "Cada cuenta CodeCombat puede canjear una sola vez un Código de Suscripción en particular."
purchase_code3: "Los meses del Código de Suscripción serán agregados al final de la suscripción existente de la cuenta."
purchase_code4: "Los códigos de suscripción son para las cuentas que juegan la versión doméstica de CodeCombat, no se pueden usar en lugar de las licencias de estudiante para la versión de aula."
purchase_code5: "Para obtener más información sobre licencias de estudiantes, comunícate con"
users: "Usuarios"
months: "Meses"
purchase_total: "Total"
purchase_button: "Enviar Adquisición"
your_codes: "Tus Códigos:"
redeem_codes: "Reclamar un Código de Suscripción"
prepaid_code: "Código Prepagado"
lookup_code: "Buscar código prepagado"
apply_account: "Aplicara tu cuenta"
copy_link: "Puedes copiarl el enlace del código y enviarlo a alguien."
quantity: "Cantidad"
redeemed: "Reclamado"
no_codes: "¡Aún sin códigos!"
you_can1: "Puedes"
you_can2: "comprar un código prepagado"
you_can3: "que puede ser aplicado a tu propia cuenta o regalado a otros."
ozaria_chrome:
sound_off: "Sonido apagado"
sound_on: "Sonido encendido"
back_to_map: "Volver al mapa"
level_options: "Opciones de nivel"
restart_level: "Reiniciar nivel"
max_browser: "Maximizar navegador"
loading_error:
could_not_load: "Error cargando del servidor" # {change}
connection_failure: "Fallo de conexión."
connection_failure_desc: "Al parecer no estás conectado a internet! Revisa tu conección de red y actualiza la página."
login_required: "Login Requerido"
login_required_desc: "Necesitas iniciar sesión para acceder a esta página."
unauthorized: "Necesitas acceder. ¿Tienes desabilitadas las cookies?"
forbidden: "No tienes los permisos."
forbidden_desc: "Oh no, no hay nada que podemos mostrarte aquí! Asegurate que has iniciado sesión en la cuenta correcta, o visita uno de los siguientes enlaces para regresar a programar!"
not_found: "No encontrado."
not_found_desc: "Mmm, no hay nada aquí. Visita uno de los siguientes enlaces para regresar a programar!"
not_allowed: "Método no permitido."
timeout: "Expiró el tiempo del servidor." # {change}
conflict: "Conflicto de recurso."
bad_input: "Mala entrada."
server_error: "Error de servidor."
unknown: "Error desconocido." # {change}
error: "ERROR"
general_desc: "Ocurrió un errór, probablemente es tu culpa. Espera un poco y luego refresca la página, o visíta uno de los siguientes enlaces para regresar a programar!"
too_many_login_failures: "Hubo demasiados intentos de acceso fallidos. Vuelve a intentarlo más tarde."
something_went_wrong: "¡Ups! Hubo un error."
resources:
level: "Nivel"
patch: "Parche"
patches: "Parches"
system: "Sistema"
systems: "Sistemas"
component: "Componente"
components: "Componentes"
hero: "Heróe"
campaigns: "Campañas"
concepts:
advanced_css_rules: "Reglas CSS Avanzadas"
advanced_css_selectors: "Selectores CSS Avanzados"
advanced_html_attributes: "Atributos HTML Avanzados"
advanced_html_tags: "Etiquetas HTML Avanzados"
algorithm_average: "Algoritmo Promedio"
algorithm_find_minmax: "Algoritmo Buscar Min/Max"
algorithm_search_binary: "Algoritmo Búsqueda Binaria"
algorithm_search_graph: "Algoritmo Búsqueda Grafica"
algorithm_sort: "Algoritmo Ordenar"
algorithm_sum: "Algoritmo Suma"
arguments: "Argumentos"
arithmetic: "Aritmética"
array_2d: "Matrices Bidimencionales"
array_index: "Indexando Matrices"
array_iterating: "Iterando Sobre Matrices"
array_literals: "Matrices Literales"
array_searching: "Buscando en Matrices"
array_sorting: "Array Sorting"
arrays: "Arreglos"
basic_css_rules: "Reglas CSS Básicas"
basic_css_selectors: "Selectores CSS Básicos"
basic_html_attributes: "Atributos HTML Básicos"
basic_html_tags: "Etiquetas HTML Básicas"
basic_syntax: "Sintaxis Básica"
binary: "Binario"
boolean_and: "Booleanos Y"
boolean_inequality: "Desigualdad Booleana"
boolean_equality: "Booleano Equidad"
boolean_greater_less: "Booleano Mayor/Menor que"
boolean_logic_shortcircuit: "Booleano Cortocircuito Lógico"
boolean_not: "Booleano Negación"
boolean_operator_precedence: "Booleano Precedencia de Operadores"
boolean_or: "Booleano O"
boolean_with_xycoordinates: "Comparación de Coordenadas"
bootstrap: "Bootstrap"
break_statements: "Declaraciones Break"
classes: "Clases"
conditionals: "Condicionales"
continue_statements: "Declaraciones Continue"
debugging: "Depuración"
dom_events: "Eventos de DOM"
dynamic_styling: "Estilos Dinámicos"
events: "Eventos"
event_concurrency: "Concurrencia de Eventos"
event_data: "Datos de Evento"
event_handlers: "Manejadores de Evento"
event_spawn: "Generador de Eventos"
for_loops: "Bucle For"
for_loops_nested: "Bucles For Anidados"
for_loops_range: "Bucle For en Rangos"
functions: "Funciones"
functions_parameters: "Parámetros"
functions_multiple_parameters: "Múltiples Parámetros"
game_ai: "IA de Juego"
game_design: "Diseño de juegos"
game_goals: "Objetivos del Juego"
game_spawn: "Generador del Juego"
graphics: "Gráficos"
graphs: "Gráfico"
heaps: "Montículos"
if_condition: "Declaraciones Condicionales If"
if_else_if: "Declaraciones If/Else If"
if_else_statements: "Declaraciones If/Else"
if_statements: "Declaraciones If"
if_statements_nested: "Declaraciones If Anidadas" # {change}
indexing: "Indexado de Arreglos"
input_handling_flags: "Manejo de Entradas - Flags"
input_handling_keyboard: "Manejo de Entradas - Keyboard"
input_handling_mouse: "Manejo de Entradas - Mouse"
intermediate_css_rules: "Reglas CSS Intermedias"
intermediate_css_selectors: "Selectores CSS Intermedios"
intermediate_html_attributes: "Atributos HTML Intermedios"
intermediate_html_tags: "Etiquetas HTML Intermedias"
jquery: "jQuery"
jquery_animations: "Animaciones jQuery"
jquery_filtering: "Filtrado de Elementos jQuery"
jquery_selectors: "Selectores jQuery"
length: "Longitud de Matrices"
math_coordinates: "Coordenadas Matemáticas"
math_geometry: "Geometría"
math_operations: "Operaciones Matemáticas"
math_proportions: "Proporciones Matemáticas"
math_trigonometry: "Trigonometría"
object_literals: "Objetos Literales"
parameters: "Parámetros"
problem_solving: "Solución de problemas"
programs: "Programas"
properties: "Propiedades"
property_access: "Acceso a Propiedades"
property_assignment: "Asignación de Propiedades"
property_coordinate: "Coordinación de Propiedades"
queues: "Estructuras de Datos - Colas"
reading_docs: "Leyendo Documentos"
recursion: "Recursividad"
return_statements: "declaraciones de Return"
sequences_algorithms: "Secuencias y algoritmos"
stacks: "Estructuras de Datos - Pilas"
strings: "Cadenas"
strings_concatenation: "Concatenación de Cadenas"
strings_substrings: "Subcadenas"
student_code: "Código de estudiante"
syntax: "Sintaxis"
trees: "Estructuras de Datos - Arboles"
variables: "Variables"
vectors: "Vectores"
while_condition_loops: "Bucles While con Condicionales"
while_loops_simple: "Bucles While"
while_loops_nested: "Bucles While Anidados"
xy_coordinates: "Coordenadas Cartesianas"
advanced_strings: "Cadenas - Avanzado" # Rest of concepts are deprecated
algorithms: "Algoritmos"
boolean_logic: "Lógica Booleana"
basic_html: "HTML Básico"
basic_css: "CSS Básico"
basic_web_scripting: "Web Scripting Básico"
intermediate_html: "HTML Intermedio"
intermediate_css: "CSS Intermedio"
intermediate_web_scripting: "Web Scripting Intermedio"
advanced_html: "HTML Avanzado"
advanced_css: "CSS Avanzado"
advanced_web_scripting: "Web Scripting Avanzado"
input_handling: "Manejo de Entradas"
while_loops: "Bucles"
place_game_objects: "Poner objetos en el juego"
construct_mazes: "Construir laberintos"
create_playable_game: "Crear un proyecto de juego jugable y compartible"
alter_existing_web_pages: "Editar página web existente"
create_sharable_web_page: "Crear página web compartible"
basic_input_handling: "Manejo de Entradas Básico"
basic_game_ai: "IA de Juego Básico"
basic_javascript: "JavaScript Básico"
basic_event_handling: "Manejo de Eventos Básico"
create_sharable_interactive_web_page: "Crear página web interactiva compartible"
iteration: "Iteración"
nesting: "Anidamiento"
data_types: "Tipos de datos"
objects: "Objetos"
methods: "Métodos"
compound_conditionals: "Condicionales compuestos"
comparators: "Comparadores"
data_and_analysis: "Datos y análisis"
anonymous_teacher:
notify_teacher: "Notificar al Maestro"
create_teacher_account: "Crear una cuenta de maestro gratuita"
enter_student_name: "Tu nombre:"
enter_teacher_email: "Correo electrónico de tu maestro:"
teacher_email_placeholder: "maestro.email@ejemplo.com"
student_name_placeholder: "escribe tu nombre aquí"
teachers_section: "Maestros:"
students_section: "Estudiantes:"
teacher_notified: "¡Hemos notificado a tu maestro que quieres jugar más CodeCombat en tu clase!"
delta:
added: "Agregado"
modified: "Modificado"
not_modified: "No Modificado"
deleted: "Borrado"
moved_index: "Índice movido"
text_diff: "Diferir Texto"
merge_conflict_with: "UNIR CONFLICTO CON"
no_changes: "Sin cambios"
legal:
page_title: "Información legal"
opensource_introduction: "CodeCombat es parte de la comunidad open source."
opensource_description_prefix: "Echa un vistazo a "
github_url: "nuestro GitHub"
opensource_description_center: "y ayudanos si quieres! CodeCombat esta construido por docenas de proyectos open source, y los amamos. Mira "
archmage_wiki_url: "nuestra wiki de Archimago"
opensource_description_suffix: "Para la lista de softwares que hacen al juego posible."
practices_title: "Mejores prácticas respetuosas"
practices_description: "Estas son nuestras promesas hacia ti, el jugador, en términos menos legales."
privacy_title: "Privacidad"
privacy_description: "No vederemos nada sobre tu información personalWe will not sell any of your personal information."
security_title: "Seguridad"
security_description: "Queremos mantener tu información personal privada. Como un proyecto open source, cualquiera puede revisar y mejorar nuestros sistemas de seguridad."
email_title: "Mail"
email_description_prefix: "No te vamos a inundar de Spam. Mediante"
email_settings_url: "tus opciones de mail"
email_description_suffix: "o mediante links en los mails que mandamos, tu puedas cambiar tus preferencias y fácilmente desuscribirte en cualquier momento."
cost_title: "Costo"
cost_description: "CodeCombat es gratuito para todos sus niveles principales, con una suscripción de ${{price}} USD/mes con acceso a niveles adicionales y un bonus de {{gems}} gemas cada mes. Puedes cancelar con un click y ofrecemos una garantía del 100%."
copyrights_title: "Derechos y Licencias"
contributor_title: "Contributor License Agreement"
contributor_description_prefix: "Todas las Contribuciones, tanto en el website como en nuestro Repositorio GitHub, estan sujetos a nuestra aprobación."
cla_url: "CLA"
contributor_description_suffix: "A lo que debes de estar de acuerdo antes de contribuir."
code_title: "Código - MIT" # {change}
client_code_description_prefix: "Todo el código del lado del cliente para codecombat.com en el repositorio público de GitHub y en la base de datos de codecombat.com, está bajo la "
mit_license_url: "Licencia MIT"
code_description_suffix: "Esto incluye todo el código en Systems and Components that are made available by CodeCombat for the purpose of creating levels."
art_title: "Arte/Música - Comunas Creativas "
art_description_prefix: "Todo el Contenido Comunal está disponible bajo la"
cc_license_url: "Licencia Internacional de Atribución Comunas Creativas (CC) 4.0"
art_description_suffix: "Contenido Comunal es cualquiera hecho por CodeCombat y disponile con el propósito de crear niveles. Esto incluye:"
art_music: "Música"
art_sound: "Sonido"
art_artwork: "Trabajo Artístico"
art_sprites: "Sprites"
art_other: "Cualquier otro trabajo creativo (no necesariamente código) que están disponibles cuando se crean niveles."
art_access: "Actualmente no hay un sistema fácil y universal para obtener estos activos. En general, obtenlos de los URLs tal y como son usados por el sitio, contáctanos si necesitas ayuda, o ayúdanos extendiendo el sitio para hacer estos activos accesibles más fácilmente."
art_paragraph_1: "Para atribución, por favor nombre y enlace a codecombat.com cerca de donde esta fuente sea usada o donde sea apropiado en el medio usado. Por ejemplo:"
use_list_1: "Si es usado en una película o en otro juego, incluya codecombat.com en los créditos."
use_list_2: "Si es usado en un website, incluya un link cerca donde es usado, por ejemplo debajo de una imagen, o en las atribuciones generales de la página, donde pueda mencionar también otros trabajos bajo Creative Commons o de código abierto que sean usados en el sitio web. Cualquier otro website que haga clara referencia a CodeCombat, tal como un blog post mencionando a CodeCombat, no necesita una atribución separada."
art_paragraph_2: "Si el contenido usado no fue creado por CodeCombat, sino por un usuario de codecombat.com, atribuya al usuario y siga las directivas de atribución provistas en la descripción del recurso, en caso las haya."
rights_title: "Derechos Reservados"
rights_desc: "Todos los derechos estan reservados para los niveles mismos. Esto incluye."
rights_scripts: "Scripts"
rights_unit: "Configuración de la unidad"
rights_writings: "Escritos"
rights_media: "Media (sonidos, música) y cualquier otro contenido creativo hecho específicamente para un nivel y que no haya sido hecho disponible al público cuando se crearon los niveles."
rights_clarification: "Aclarando, todo contenido puesto a disposición en el Editor de Niveles con el propósito de hacer más niveles se encuentra bajo licencia CC, mientras todo contenido creado con el Editor de Niveles o cargado durante la creación de Niveles no lo está."
nutshell_title: "En una palabra"
nutshell_description: "Cualquier recurso que te proveamos en el Editor de Niveles es gratis de usar como te plazca para la creación de Niveles. Sin embargo, nos reservamos el derecho de restringir la distribución de los niveles por sí mismos (aquellos creados en codecombat.com) para así poder cobrar por ellos en el futuro, si es que eso es lo que termina pasando."
nutshell_see_also: "Mira También:"
canonical: "La versión en inglés de este documento es la versión canónica y definitiva. Si hay alguna discrepancia entre las traducciones, la versión en inglés toma precedencia."
third_party_title: "Servicios de Terceros"
third_party_description: "CodeCombat utiliza los siguientes servicios de terceros (entre otros):"
cookies_message: "CodeCombat utiliza algunas cookies esenciales y no esenciales."
cookies_deny: "Rechazar las cookies no esenciales"
cookies_allow: "Permitir cookies"
ladder_prizes:
title: "Premios de Torneos" # This section was for an old tournament and doesn't need new translations now.
blurb_1: "Estos premios seran dados de acuerdo a "
blurb_2: "las reglas del torneo"
blurb_3: "a los mejores jugadores humanos y ogros."
blurb_4: "Dos equipos significan el doble de premios!"
blurb_5: "(Habrán dos ganadores en el primer puesto, dos en el segundo puesto, etc.)"
rank: "Ranking"
prizes: "Premios"
total_value: "Valor Total"
in_cash: "en dinero"
custom_wizard: "CodeCombat Mago Personalizado"
custom_avatar: " CodeCombat Avatar Personalizado"
heap: "Por seis meses acceso \"Startup\"."
credits: "creditos"
one_month_coupon: "Cupón: elige entre Rails o HTML."
one_month_discount: "descuento del 30%: elige entre Rails o HTML"
license: "licencia"
oreilly: "ebook de su elección"
calendar:
year: "Año"
day: "Día"
month: "Mes"
january: "Enero"
february: "Febrero"
march: "Marzo"
april: "Abril"
may: "Mayo"
june: "Junio"
july: "Julio"
august: "Agosto"
september: "Septiembre"
october: "Octubre"
november: "Noviembre"
december: "Diciembre"
code_play_create_account_modal:
title: "¡LO LOGRASTE!" # This section is only needed in US, UK, Mexico, India, and Germany
body: "Pronto serás un programador experto. Regístrate para recibir <strong>100 GEMAS</strong> adicionales y participar en un sorteo donde podrás <strong>GANAR $50,000 Y OTROS PREMIOS DE LENOVO</strong>."
sign_up: "REGÍSTRATE Y SIGUE PROGRAMANDO ▶"
victory_sign_up_poke: "¡ABRE UNA CUENTA GRATUITA PARA GUARDAR TU CÓDIGO Y PARTICIPAR EN UN SORTEO DONDE PODRÁS GANAR PREAMIOS!"
victory_sign_up: "REGÍSTRATE PARA PODER <strong>GANAR $50,000</strong>"
server_error:
email_taken: "Email ya utilizado"
username_taken: "El nombre de usuario ya existe"
esper:
line_no: "Linea $1: "
uncaught: "$1 no detectado" # $1 will be an error type, eg "Uncaught SyntaxError"
reference_error: "Referencia Errónea: "
argument_error: "Argumento Erróneo: "
type_error: "Tipo Erróneo: "
syntax_error: "Sintaxis Errónea: "
error: "Error: "
x_not_a_function: "$1 no es una función"
x_not_defined: "$1 no está definido"
spelling_issues: "Corrige la ortografía: ¿quisiste decir `$1` en lugar de `$2`?"
capitalization_issues: "Cuidado con las mayúsculas: `$1` debe ser `$2`."
py_empty_block: "$1 vacío. Adelanta 4 espacios las declaraciones dentro del bloque $2."
fx_missing_paren: "Si deseas llamar `$1` como función, pon paréntesis `()` al final"
unmatched_token: "`$1` no coincide. Cada apertura de `$2` necesita un cierre de `$3` para coincidir."
unterminated_string: "Cadena sin terminar. Agrega `\"` al final de la cadena."
missing_semicolon: "Falta punto y coma."
missing_quotes: "Faltan comillas. Intenta `$1`"
argument_type: "El argumento `$2` de `$1` debe tener un tipo `$3`, pero tiene `$4`: `$5`."
argument_type2: "El argumento `$2` de `$1` debe tener un tipo `$3`, pero tiene `$4`."
target_a_unit: "Apuntar a una unidad."
attack_capitalization: "Ataca a $1, no a $2. (Mayúsculas son importantes.)"
empty_while: "Sentencia while vacía. Adelanta 4 espacios las declaraciones dentro del bloque while."
line_of_site: "El argumento `$2` de `$1` tiene un problema. ¿Hay algún enemigo en la línea de visión?"
need_a_after_while: "Necesitas un `$1` después de `$2`."
too_much_indentation: "Demasiada indentación al inicio de esta línea."
missing_hero: "Falta la palabra clave `$1`; debe ser `$2`."
takes_no_arguments: "`$1` no acepta argumentos."
no_one_named: "No se puede apuntar a \"$1\" porque nadie se llama así."
separated_by_comma: "Al llamar una función los parámetros deben estar separados con `,`"
protected_property: "No se puede leer propiedad protegida: $1"
need_parens_to_call: "Si deseas llamar `$1` como función, pon paréntesis `()` al final"
expected_an_identifier: "Se esperaba un identificador y en su lugar se recibió '$1'."
unexpected_identifier: "Identificador inesperado"
unexpected_end_of: "Fin de entrada inesperado"
unnecessary_semicolon: "Punto y coma innecesario."
unexpected_token_expected: "Símbolo inesperado: se esperaba $1 pero se encontró $2 mientras se analizaba $3"
unexpected_token: "Símbolo $1 inesperado"
unexpected_token2: "Símbolo inesperado"
unexpected_number: "Número inesperado"
unexpected: "No se esperaba '$1'."
escape_pressed_code: "Escape presionado; código anulado."
target_an_enemy: "Apunta a un enemigo por su nombre, como `$1`, no la cadena `$2`."
target_an_enemy_2: "Apunta a un enemigo por su nombre, como $1."
cannot_read_property: "No se puede leer la propiedad '$1' de indefinido"
attempted_to_assign: "Se intentó asignar una propiedad de solo lectura."
unexpected_early_end: "Fin del programa antes de lo esperado."
you_need_a_string: "Necesitas una cadena para construir; una de $1"
unable_to_get_property: "No se puede obtener la propiedad '$1' de una referencia nula o indefinida" # TODO: Do we translate undefined/null?
code_never_finished_its: "El código no finalizo. Es demasiado lento o tiene un bucle infinito."
unclosed_string: "Cadena sin cerrar."
unmatched: "No coincide '$1'."
error_you_said_achoo: "Dijiste: $1, pero la contraseña es: $2. (Mayúsculas y minúsculas son importantes.)"
indentation_error_unindent_does: "Error de Indentación: no coincide con ningun nivel de indentación"
indentation_error: "Error de Indentación."
need_a_on_the: "Necesitas un `:` al final de la linea seguido de `$1`."
attempt_to_call_undefined: "se intento llamar '$1' (un valor nulo)"
unterminated: "`$1` sin terminar"
target_an_enemy_variable: "Apunta a la variable $1, y no al string $2. (Intenta usar $3.)"
error_use_the_variable: "Usa el nombre de la variable como `$1` en lugar de la cadena como `$2`"
indentation_unindent_does_not: "Desindentación no coincide con ningún nivel de indentación"
unclosed_paren_in_function_arguments: "No se cerró $1 en los argumentos de la función."
unexpected_end_of_input: "Fin de entrada inesperado"
there_is_no_enemy: "No hay `$1`. Primero utiliza `$2`." # Hints start here
try_herofindnearestenemy: "Intenta `$1`"
there_is_no_function: "No hay ninguna función `$1`, pero `$2` tiene el método `$3`."
attacks_argument_enemy_has: "El argumento `$2` de `$1` tiene un problema."
is_there_an_enemy: "¿Aún hay algún enemigo en tu linea de visión?"
target_is_null_is: "El objetivo es $1. ¿Siempre hay un blanco para atacar? (Usa $2?)"
hero_has_no_method: "`$1` no tiene el método `$2`."
there_is_a_problem: "Hay un problema con tu código."
did_you_mean: "¿Quisiste decir $1? No tienes equipado un item con esa habilidad."
missing_a_quotation_mark: "Falta una commilla. "
missing_var_use_var: "Falta `$1`. Utiliza `$2` para hacer una nueva variable."
you_do_not_have: "No tienes equipado un item con la habilidad $1."
put_each_command_on: "Pon cada comando en lineas separadas"
are_you_missing_a: "¿Te falta un '$1' despues de '$2'? "
your_parentheses_must_match: "Los paréntesis deben coincidir."
apcsp:
title: "Fundamentos de Ciencias de la Computación AP | Con el respaldo del College Board"
meta_description: "El amplio plan de estudios y el programa de desarrollo profesional de CodeCombat es todo lo que necesitas para ofrecer el curso de ciencias de la computación más reciente de College Board a tus estudiantes."
syllabus: "Programa de Fundamentos de Ciencias de la Computación AP"
syllabus_description: "Usa este recurso para planificar el plan de estudios de CodeCombat para tus clases de Fundamentos de Ciencias de la Computación AP."
computational_thinking_practices: "Prácticas del Pensamiento Computacional"
learning_objectives: "Objetivos de aprendizaje"
curricular_requirements: "Requisitos curriculares"
unit_1: "Unidad 1: Tecnología creativa"
unit_1_activity_1: "Actividad de la unidad 1: Prueba de usabilidad de la tecnología"
unit_2: "Unidad 2: Pensamiento computacional"
unit_2_activity_1: "Actividad de la unidad 2: Secuencias binarias"
unit_2_activity_2: "Actividad de la unidad 2: Proyecto de lección sobre informática"
unit_3: "Unidad 3: Algoritmos"
unit_3_activity_1: "Actividad de la unidad 3: Algoritmos - Guía del viajero"
unit_3_activity_2: "Actividad de la unidad 3: Simulación - Depredador y presa"
unit_3_activity_3: "Actividad de la unidad 3: Algoritmos - Diseño y programación en pareja"
unit_4: "Unidad 4: Programación"
unit_4_activity_1: "Actividad de la unidad 4: Abstracciones"
unit_4_activity_2: "Actividad de la unidad 4: Búsqueda y ordenamiento"
unit_4_activity_3: "Actividad de la unidad 4: Refactorización"
unit_5: "Unidad 5: La Internet"
unit_5_activity_1: "Actividad de la unidad 5: Cómo funciona la Internet"
unit_5_activity_2: "Actividad de la unidad 5: Simulador de la Internet"
unit_5_activity_3: "Actividad de la unidad 5: Simulación de una sala de chat"
unit_5_activity_4: "Actividad de la unidad 5: Ciberseguridad"
unit_6: "Unidad 6: Datos"
unit_6_activity_1: "Actividad de la unidad 6: Introducción a los datos"
unit_6_activity_2: "Actividad de la unidad 6: Big data"
unit_6_activity_3: "Actividad de la unidad 6: Compresión con y sin pérdida"
unit_7: "Unidad 7: Impacto personal y global"
unit_7_activity_1: "Actividad de la unidad 7: Impacto personal y global"
unit_7_activity_2: "Actividad de la unidad 7: Crowdsourcing"
unit_8: "Unidad 8: Tareas de desempeño"
unit_8_description: "Ayuda a los estudiantes a prepararse para la tarea de creación mediante el diseño de sus propios videojuegos y el repaso de conceptos clave."
unit_8_activity_1: "Práctica 1 para la tarea de creación: Desarrollo de Juegos 1"
unit_8_activity_2: "Práctica 2 para la tarea de creación: Desarrollo de Juegos 2"
unit_8_activity_3: "Práctica 3 para la tarea de creación: Desarrollo de Juegos 3"
unit_9: "Unidad 9: Reseña de Advanced Placement (AP)"
unit_10: "Unidad 10: Después de AP"
unit_10_activity_1: "Actividad de la unidad 10: Cuestionario web"
parent_landing:
slogan_quote: "\"CodeCombat es muy vertido y te enseña muchas cosas.\""
quote_attr: "Estudiante de quinto grado, Oakland, California"
refer_teacher: "Invitar a un maestro"
focus_quote: "Desbloquea el futuro de tu hijo"
value_head1: "La forma más divertida de aprender código escrito"
value_copy1: "CodeCombat es el tutor personal del estudiante. El material de estudio, que cumple con las pautas curriculares nacionales, ayudará a tu hijo a programar algoritmos, crear sitios web e incluso diseñar sus propios videojuegos."
value_head2: "Desarrollo de habilidades esenciales para el siglo 21"
value_copy2: "Tus hijos aprenderán a navegar por el mundo digital y se convertirán en sus verdaderos ciudadanos. CodeCombat es una solución que mejora el pensamiento crítico y la capacidad de adaptación de su hijo."
value_head3: "Héroes que le encantarán a tu hijo"
value_copy3: "Sabemos lo importante que son la diversión y el interés para un cerebro en desarrollo, así que incluimos todo el aprendizaje posible en un juego que los niños amarán."
dive_head1: "No solo ingenieros de software"
dive_intro: "Las habilidades de informática tienen una amplia gama de aplicaciones. ¡Estos son solo algunos ejemplos!"
medical_flag: "Aplicaciones médicas"
medical_flag_copy: "Desde la cartografía del genoma humano hasta una máquina para hacer resonancias magnéticas, la programación nos permite entender el cuerpo de maneras nunca antes conocidas."
explore_flag: "Exploración espacial"
explore_flag_copy: "Apollo llegó a la luna gracias a computadoras humanas que trabajaron arduamente, y los científicos usan programas de computación para analizar la gravedad de los planetas y encontrar estrellas nuevas."
filmaking_flag: "Cine y animación"
filmaking_flag_copy: "Desde los robots de Parque Jurásico hasta las animaciones increíbles de Dreamworks y Pixar, las películas no serían lo que son sin los creativos digitales detrás de escena."
dive_head2: "Los videojuegos son importante para el aprendizaje"
dive_par1: "Muchos estudios descubrieron que el aprendizaje basado en juego promueve"
dive_link1: "el desarrollo cognitivo"
dive_par2: "en niños, a la vez que es"
dive_link2: "más efectivo"
dive_par3: "a la hora de ayudar a los estudiantes"
dive_link3: "a aprender y retener conocimiento"
dive_par4: ","
dive_link4: "concentrarse"
dive_par5: "y alcanzar un mayor nivel de consecución de logros."
dive_par6: "El aprendizaje basado en juego también es bueno para desarrollar"
dive_link5: "capacidad de adaptación"
dive_par7: ", razonamiento cognitivo y"
dive_par8: ". La ciencia solo nos dice lo que ya saben los estudiantes. Los niños aprenden mejor jugando."
dive_link6: "funciones ejecutivas"
dive_head3: "Trabaja en equipo con maestros"
dive_3_par1: "En el futuro, "
dive_3_link1: "programar será tan fundamental como aprender a leer y escribir"
dive_3_par2: ". Trabajamos en conjunto con docentes para diseñar y desarrollar nuestro contenido, y estamos ansiosos por que tus hijos empiecen a aprender. Los programas de tecnología educativa como CodeCombat funcionan mejor cuando los docentes los implementan con regularidad. ¡Ayúdanos a lograrlo presentándonos a los maestros de tu hijo!"
mission: "Nuestra misión: enseñar y entretener"
mission1_heading: "Código para la generación de hoy"
mission2_heading: "Prepararse para el futuro"
mission3_heading: "Con el apoyo de padres como tú"
mission1_copy: "Nuestros especialistas en educación trabajan en colaboración con docentes para adaptar el contenido al panorama educativo de los estudiantes. Los niños adquieren habilidades que pueden aplicarse fuera del juego porque aprenden a resolver problemas más allá de su estilo de aprendizaje."
mission2_copy: "Una encuesta de 2016 demostró que el 64% de las niñas de tercer a quinto grado quieren aprender a programar. En 2015, hubo siete millones de búsquedas laborales que requerían habilidades de programación. Creamos CodeCombat porque todos los niños deberían tener la oportunidad de crear su mejor futuro."
mission3_copy: "En CodeCombat somos padres. Somos programadores. Somos educadores. Pero, sobre todo, somos personas que creemos en darles a nuestros hijos la mejor oportunidad para triunfar en lo que sea que decidan hacer en el futuro."
parent_modal:
refer_teacher: "Invitar a un maestro"
name: "Tu nombre"
parent_email: "Tu correo electrónico"
teacher_email: "Correo electrónico del maestro"
message: "Mensaje"
custom_message: "Acabo de enterarme de CodeCombat y creo que sería un gran programa para tu asignatura. Es una plataforma para aprender ciencias de la computación que tiene un plan de estudios que cumple con las normas educativas.\n\nLa alfabetización digital es muy importante, y creo que esta sería una gran forma de hacer que los estudiantes se interesen en aprender a programar."
send: "Enviar correo"
hoc_2019:
heading: "Hora del Código 2019"
start: "Empieza tu camino"
create_a_class: "¡Crea una clase para monitorear el progreso de los estudiantes y garantizar el guardado de sus juegos de la Hora del Código!"
choose_language: "1. ELEGIR IDIOMA"
programming_language: "Idioma"
sign_up: "2. REGISTRARSE"
already_have_account: "¿Ya tienes una cuenta de CodeCombat o de Ozaria? Inicia sesión."
download_lesson_plan: "Descarga el plan de estudios"
try_activity_without_class: "Prueba la actividad sin crear una clase"
invite_students: "Invita a los estudiantes a unirse a tu clase enviándoles"
class_code: "CÓDIGO DE CLASE"
enter_code: "Los estudiantes pueden ingresar este código en www.ozaria.com/hoc"
class_url: "URL DE CLASE"
share_url: "Comparte la URL para que los estudiantes se unan a tu clase automáticamente."
start_activity: "Empezar actividad"
save_progress_modal: "Guarda tu progreso y continúa jugando más tarde"
want_to_save: "¿Quieres guardar tu progreso del Código de Honor?"
ask_teacher_class_code: "Pídele a tu maestro tu código de clase"
dont_have: "¡No tengo, pero quiero probar la actividad!"
hoc_activity: "Actividad de la Hora del Código"
save_progress: "Guardar progreso"
err_google_exists: "Ya existe una cuenta asociada a la cuenta de Google que seleccionaste. Elige otra cuenta de Google o inicia sesión con un nombre de usuario y una contraseña."
err_username_taken: "Ya existe una cuenta asociada al nombre de usuario que ingresaste. Elige otro nombre de usuario."
enter_it_here: "Ingrésalo aquí para guardar tu progreso del juego:"
have_a_class_code: "¿Tienes un código de clase?"
create_class_and_try_activity: "Crea una clase y prueba la actividad"
hoc_2018:
banner: "¡Feliz semana de la educación en ciencias de la computación!"
page_heading: "¡Tus estudiantes aprenderán a programar diseñando su propio juego!"
step_1: "Paso 1: Ve el video informativo"
step_2: "Paso 2: Pruébalo"
step_3: "Paso 3: Descarga el plan de estudios"
try_activity: "Prueba la actividad"
download_pdf: "Descarga el PDF"
teacher_signup_heading: "Convierte la Hora del Código en un Año del Código"
teacher_signup_blurb: "Todo lo que necesitas para enseñar ciencias de la computación sin experiencia previa."
teacher_signup_input_blurb: "Consigue el primer curso gratis:"
teacher_signup_input_placeholder: "Dirección de correo electrónico del maestro"
teacher_signup_input_button: "Consigue Ciencias de la Computación 1 gratis"
activities_header: "Más actividades de la Hora del Código"
activity_label_1: "¡Escapa de las mazmorras!"
activity_label_2: " Principiante: ¡diseña un videojuego!"
activity_label_3: "Avanzado: ¡diseña un videojuego de arcade!"
activity_button_1: "Ver lección"
about: "Acerca de CodeCombat"
about_copy: "Un programa de ciencias de la computación basado en juego creado según las normas educativas que enseña a escribir Python y JavaScript de verdad."
point1: "✓ Andamiaje"
point2: "✓ Diferenciado"
point3: "✓ Evaluaciones"
point4: "✓ Cursos basados en proyectos"
point5: "✓ Seguimiento de estudiantes"
point6: "✓ Planes de estudio completos"
title: "HORA DEL CÓDIGO"
acronym: "HDC"
hoc_2018_interstitial:
welcome: "¡Te damos la bienvenida a la Hora del Código de CodeCombat!"
educator: "Soy educador"
show_resources: "¡Muéstrame los recursos para maestros!"
student: "Soy estudiante"
ready_to_code: "¡Quiero empezar a programar!"
hoc_2018_completion:
congratulations: "¡Felicitaciones por completar <b>Programa, juega y comparte</b>!"
send: "¡Envíales a tus amigos y tu familia tu juego de la Hora del Código!"
copy: "Copiar URL"
get_certificate: "¡Obtén un certificado de finalización para celebrar con tu clase!"
get_cert_btn: "Obtener certificado"
first_name: "Nombre"
last_initial: "Inicial del apellido"
teacher_email: "Dirección de correo electrónico del maestro"
school_administrator:
title: "Panel del administrador de la escuela"
my_teachers: "Mis maestros"
last_login: "Último ingreso"
licenses_used: "licencias utilizadas"
total_students: "estudiantes en total"
active_students: "estudiantes activos"
projects_created: "proyectos creados"
other: "Otros"
notice: "Los siguientes administradores de la escuela tienen acceso de solo lectura a los datos de tu aula:"
add_additional_teacher: "¿Necesitas agregar otro maestro? Contacta a tu ejecutivo de cuenta de CodeCombat o envía un correo a support@codecombat.com. "
license_stat_description: "La cantidad de licencias disponibles incluye el número total de licencias disponibles para el maestro, incluidas las licencias compartidas."
students_stat_description: "Cuentas de estudiantes totales para todos los alumnos de todas las aulas, tengan o no una licencia activa."
active_students_stat_description: "Estudiantes activos cuenta la cantidad de alumnos que han ingresado a CodeCombat en los últimos 60 días."
project_stat_description: "Proyectos creados cuenta la cantidad total de proyectos de desarrollo web y de juegos que se han creado."
no_teachers: "No administras a ningún maestro."
interactives:
phenomenal_job: "¡Gran trabajo!"
try_again: "¡Ups, vuelve a intentar!"
select_statement_left: "¡Ups! Selecciona una instrucción de código antes de presionar Enviar."
fill_boxes: "Ups, asegúrate de completar todos los campos antes de presionar \"Enviar\"."
cannot_play_video: "Lamentablemente, no es posible reproducir este video en tu zona."
console_instructions: "Entérate por qué abriendo la consola de tu navegador: 1) haz clic derecho, 2) elige \"Inspeccionar\" y 3) haz clic en la pestaña Consola."
skip_video: "Saltar video"
unavailable: "No disponible"
admin:
license_type_full: "Cursos completos"
license_type_customize: "Personalizar cursos"
teacher_dashboard:
lock: "Bloquear"
unlock: "Desbloquear"
unassign: "Anular asignación"
choose_course: "Haz clic para seleccionar una opción del menú desplegable"
teacher_locked_message: "Tu maestro bloqueó el siguiente nivel"
plan_your_class_title: "Para planificar tu primera clase:"
plan_your_class1: "Consulta la información sobre el progreso del curso"
plan_your_class2: "Previsualiza las diapositivas de la lección y las actividades de extensión"
plan_your_class3: "Prueba el primer capítulo sin cargo"
click_dismiss: "Clic para ignorar"
track_progress: "Seguir progreso"
track_progress_desc: "Haz clic en la clase que acabas de crear para ver el progreso detallado de cada estudiante."
add_classes_title: "Agregar clases aquí"
add_classes: "¡Agrega clases para que los estudiantes empiecen el capítulo gratis!"
all_classes: "Todas las clases"
my_licenses: "Mis licencias"
resource_hub: "Centro de recursos"
pd: "Desarrollo profesional"
pd_short: "DP"
curriculum_guide: "Guía curricular"
add_class: "Agregar clase nueva"
no_licenses_yet: "Aún sin licencias"
req_licenses: "Solicitar licencias"
license_ratio_used: "__totalUsedLicenses__ de __totalSpots__"
licenses_applied: "Licencias aplicadas"
student_projects: "Proyectos de estudiantes"
no_classes_yet: "Aún no hay clases"
exemplar_project: "Proyecto modelo"
capstone_proj_for: "Proyecto final de __courseName__"
project_rubric: "Guía de evaluación del proyecto"
select_chapter: "Seleccionar capítulo"
concept_flag: "Concepto difícil"
support_learning: "Ayuda de aprendizaje"
concept_flag_desc: "Más del 50% de la clase tuvo que repetir una comprobación de conceptos 3 veces o más."
concept_flag_desc2: "El estudiante tuvo que repetir una comprobación de conceptos 3 veces o más."
click_progress_dot_tip: "Consejo: Haz clic en las burbujas de progreso para más detalles."
color_code: "Código de color"
content_guide: "Guía de contenido"
story: "Historia"
cutscenes: "Escenas"
cutscenes_tooltip: "<h3>Escena</h3><p>Un video corto que explica partes de la historia épica de Ozaria.</p>"
cinematics: "Cinemáticas"
concept_checks: "Comprobaciones de conceptos"
practice_levels: "Niveles de práctica"
challenge_levels: "Niveles de desafío"
capstone_levels: "Niveles finales"
intro: "Introducción"
practice: "Practicar"
assess: "Evaluar"
view_options: "Ver opciones"
manage_class: "Administrar clase"
assign_content: "Asignar contenido"
remove_students: "Quitar estudiantes"
revoke_licenses: "Anular licencias"
remaining_licenses: "Licencias restantes: __remaining__"
start_date: "Inicio: __date__"
end_date: "Finalización: __date__"
license_questions: "¿Tienes alguna pregunta sobre aplicar o anular licencias?"
need_more_licenses: "¿Necesitas más licencias? Te ayudaremos a crear una solución que satisfaga tus necesidades."
see_also_our: "También consulta nuestra"
for_more_funding_resources: "para enterarte de cómo aprovechar las fuentes de financiación de la ley CARES, como ESSER y GEER."
support_oz: "support@ozaria.com"
standards_alignment: "Cumplimiento de normas"
standards_sample: "Una muestra de las normas cubiertas en este capítulo:"
play_chapter: "Jugar capítulo"
class_time_range: "Tiempo de clase (rango):"
in_game_play_time: "Tiempo de juego:"
class_time: "Tiempo de clase"
solution_guide: "Guía de solución"
module: "Módulo"
need_licenses_tooltip: "<h3>¡Necesitas licencias para acceder a este contenido!</h3><p>Ve a la página <a href='/teachers/licenses'>Mis licencias</a> para más información.</p>"
lesson_slides_tooltip: "<h3>Diapositivas de la lección</h3><p>Diapositivas que puedes descargar para guiar paso a paso a los estudiantes por los objetivos de aprendizaje del módulo.</p>"
project_rubric_tooltip: "<h3>Guía de evaluación del proyecto</h3><p>Una guía que puedes descargar y modificar para evaluar el proyecto final.</p>"
exemplar_projects_tooltip: "<h3>Proyecto modelo</h3><p>Vista en vivo de un modelo de proyecto final.</p>"
want_to_save_tooltip: "<h3>¿Quieres guardar tu progreso?</h3><p>Crea una cuenta de estudiante y accede a ella para jugar Ozaria como estudiante si quieres guardar tu progreso.</p>"
intro_explain_tooltip: "Las <b>\"introducciones\"</b> presentan nuevos conceptos o hacen avanzar la historia de manera escalonada. En general, incluyen cinemáticas o comprobaciones de conceptos."
chapter_num: "Capítulo __num__"
# read: "View Only"
# write: "Full Access"
# read_blurb: "View Only permits the added teacher to view your class and student progress without the ability to make changes to your class."
# write_blurb: "Full Access grants the added teacher the ability to make modifications to your class (add/remove students, assign chapters, modify licensure)"
# shared_with_none: "This class is not currently shared with any other teachers."
# share_info: "To give other teachers access to the class, add their emails below."
# class_owner: "Class Owner"
# share: "Share"
# outcomes:
# outcomes_report: "Outcomes Report"
# customize_report: "Customize Report"
# done_customizing: "Done Customizing"
# start_date: "Start date"
# end_date: "End date"
# school_admin: "School Administrator"
# school_network: "School Network"
# school_subnetwork: "School Subnetwork"
# classroom: "Classroom"
# view_outcomes_report: "View Outcomes Report"
# key_concepts: "Key Concepts"
# code_languages: "Code Languages"
# using_codecombat: "Using CodeCombat's personalized learning engine..."
# wrote: "wrote..."
# across_an_estimated: "across an estimated..."
# in: "in..."
# include: "Include "
# archived: "Archived"
# max: "Max "
# multiple: "s"
# computer_program: "computer program"
# computer_programs: "computer programs"
# line_of_code: "line of code"
# lines_of_code: "lines of code"
# coding_hours: "coding hours"
# expressed_creativity: "and expressed creativity by building"
# report_content_1: "standalone game and web "
# project: "project"
# projects: "projects"
# progress_stats: "Progress stats based on sampling __sampleSize__ of __populationSize__ students."
# standards_coverage: "Standards Coverage"
# coverage_p1: "The full Ozaria curriculum covers major programming standards in several widely-adopted frameworks, including those of the International Society for Technology in Education (ISTE), the Computer Science Teacher Association (CSTA), and the K-12 Computer Science Framework."
# coverage_p2: "Ozaria is created by the CodeCombat, the game-based learning company. We believe that students will be most prepared for both real-world computing jobs and further study of computer science by using real, typed code in full programming languages, so instead of using block-based visual programming languages for beginners, we teach Python and JavaScript – the same languages used widely today by companies ranging from Google to the New York Times."
# questions: "Have questions or want more information? We'd be happy to help."
# reach_out_manager: "Reach out to your Account Manager __name__ at "
# stats_include: "stats include __number__ other __name__"
| 75959 | module.exports = nativeDescription: "Español (América Latina)", englishDescription: "Spanish (Latin America)", translation:
ozaria_home:
subtitle: "Informática que fascina"
heading_subtitle: "Una aventura de programación para estudiantes y una solución inmediata para enseñar Ciencias de la Computación."
item_list_p: "¡Prueba hoy mismo el capítulo 1 sin costo!"
engaging_heading_corner: "Una solución para involucrar a los estudiantes y apoyar a los maestros"
engaging_row1_h2: "Implementación sencilla"
engaging_row1_p: "Incluso sin experiencia en programación, con Ozaria puedes enseñar un plan de estudios de Ciencias de la Computación completo. Nuestros planes de estudios predefinidos y el intuitivo panel te darán las herramientas necesarias para empezar a enseñar desde el primer día."
engaging_row2_h2: "Jugabilidad inmersiva"
engaging_row2_p: "Los estudiantes se sumergirán en un juego de aventura en el cual sus conocimientos sobre Ciencias de la Computación avanzarán junto con la trama. En este entorno de aprendizaje divertido, los estudiantes desarrollarán habilidades del mundo real jugando."
engaging_row3_h2: "Planes de estudio que cumplen con las normas educativas"
engaging_row3_p: "Ozaria cumple con las normas ISTE y CSTA, por lo que enseñarás contenido de calidad a tus estudiantes, quienes dominarán conceptos esenciales de Ciencias de la Computación, desarrollarán habilidades de pensamiento computacional y aprenderán sobre la importancia de estos temas en la vida cotidiana."
pd_blurb: "Aprende las habilidades necesarias para enseñar Ciencias de la Computación de manera efectiva con nuestro curso de autoaprendizaje __pd__ acreditado por la CSTA. Obtén hasta 40 horas de crédito en cualquier momento y desde cualquier dispositivo."
back_cta_1_a: "Probar el capítulo 1 sin costo"
speech_bubble_testimonial_1_blockquote: "Una vez más, el equipo creó una reliquia del entretenimiento educativo. En mi opinión, como maestro veterano de secundaria con 26 años de experiencia, no existe mejor recurso para enseñar programación."
core_curriculum_header: "Asignaturas principales de Ciencias de la Computación"
core_curriculum_p: "Hemos desarrollado nuestro modelo de enseñanza a partir de teorías comprobadas y pruebas exhaustivas sobre la mejor forma de aprender."
core_curriculum_carousel_item1_header: "Hacer conexiones"
core_curriculum_carousel_item1_p: "Al principio de cada módulo, usa las diapositivas preexistentes de la lección para que los estudiantes hagan conexiones entre los nuevos conceptos de Ciencias de la Computación y ejemplos pertinentes de la vida diaria."
core_curriculum_carousel_item2_header: "Formar un significado propio"
core_curriculum_carousel_item2_p: "Luego, guía a los estudiantes para que comprendan mejor los nuevos conceptos completando las actividades de extensión que incluyen nuestros planes de estudios."
core_curriculum_carousel_item3_header: "Aprender nuevos conceptos"
core_curriculum_carousel_item3_p: "En la tercera etapa del ciclo de aprendizaje, los estudiantes aprenderán nuevos conceptos a través de diálogos expositivos entre los personajes de la historia de Ozaria. Las voces, los gráficos y las animaciones hacen que incorporar nueva información sea aún más accesible y divertido."
core_curriculum_carousel_item4_header: "Aplicar nuevos conocimientos"
core_curriculum_carousel_item4_p: "Luego, los estudiantes pondrán en práctica lo aprendido escribiendo código real de Python y JavaScript para resolver distintos desafíos presentados en niveles escalonados. Las pistas el juego ayudan a los estudiantes a identificar y corregir errores para que desarrollen una mayor confianza a la hora de programar."
core_curriculum_carousel_item5_header: "Proyecto sumativo"
core_curriculum_carousel_item5_p: "Al final de cada capítulo, los estudiantes se enfrentarán al desafío de exhibir sus nuevas habilidades y expresar su creatividad en proyectos sumativos en los que deberán construir sus propios juegos, historias y más."
core_curriculum_scope_sequence: "Ver alcance y secuencia"
core_curriculum_sample_lesson_slides: "Ver ejemplo de diapositivas de lección"
global_community_header: "Únete a nuestra comunidad global"
global_community_row1_p: "de estudiantes"
global_community_row2_p: "de líneas de código"
global_community_row3_p: "de maestros"
global_community_row4_p: "países"
admin_dashboard_header: "Paneles completos para administradores y maestros"
admin_dashboard_p: "Ozaria está diseñado sobre la base de opiniones de nuestra comunidad de más de 140.000 educadores y brinda las herramientas y los recursos necesarios para abordar los desafíos que conlleva enseñar Ciencias de la Computación."
admin_dashboard_row1_p: "El panel para maestros es intuitivo y permite acceder a los planes de estudio que ven los estudiantes, guías didácticas, estrategias de aprendizaje a distancia y otros recursos que seguramente te servirán."
admin_dashboard_row2_p: "La página de seguimiento del progreso te permite monitorear los avances de los estudiantes en tiempo real, obtener información valiosa sobre su desempeño e identificar de inmediato si es necesario intervenir de alguna forma."
admin_dashboard_row3_a: "Solicitar una cotización"
acodus_awards_a: "Probar el capítulo 1 sin costo"
speech_bubble_testimonial_2_blockquote: "Es el sitio de programación más accesible que conozco hasta el momento. Me gusta la historia que se plantea en Ozaria porque es una misión con la que los estudiantes pueden empatizar. La verdad, me encanta. De hecho, ¡yo también lo juego más de lo que me gustaría admitir!"
shareable_resources_header: "Recursos para compartir"
shareable_resources_p: "Comparte los siguientes recursos con maestros y administradores, o con los responsables de introducir o expandir las Ciencias de la Computación en tu escuela."
shareable_resources_a: "Descargar folleto"
back_cta_2_a: "Probar el capítulo 1 sin costo"
faq_header: "Preguntas frecuentes"
faq_row1_header: "¿Cómo se relaciona Ozaria con CodeCombat?"
faq_row1_p: "Ozaria se centra en el estudiante y es la evolución de CodeCombat, uno de los juegos de programación más populares de la historia. Desarrollamos Ozaria sobre la base de los aprendizajes obtenidos por enseñar Python y JavaScript a más de 20 millones de estudiantes. Ozaria incorpora nuevos modelos pedagógicos y una narrativa con una historia inmersiva, y está diseñado para implementarse en aulas tanto presenciales como virtuales."
faq_row2_header: "¿Qué edades o grados son los más adecuados para Ozaria?"
faq_row2_p: "Ozaria cumple con las normas ISTE y CSTA para enseñar Ciencias de la Computación en escuelas secundarias, pero estudiantes tanto mayores como menores lo han disfrutado y aprovechado."
faq_row3_header: "¿Cuánto cuesta acceder a todas las unidades y recursos disponibles?"
faq_row3_p_part1: "Personalizamos soluciones para escuelas y distritos. Podemos ayudarte a entender tus necesidades, contexto y presupuesto. "
faq_row3_p_part2: " para más detalles. También ofrecemos una "
faq_row3_p_part3: "guía de recursos de financiación"
faq_row3_p_part4: " para programas de Ciencias de la Computación en escuelas y distritos."
faq_row4_header: "En Ozaria, ¿el aprendizaje está basado en proyectos?"
faq_row4_p: "Sí. Ozaria incluye proyectos al final de cada capítulo para que los estudiantes creen sus propios juegos y puedan compartirlos. Estos proyectos son evaluaciones sumativas y una buena manera de que los estudiantes se expresen y les muestren a sus compañeros, amigos y familiares todo lo aprendido."
faq_row5_header: "¿Puedo usar Ozaria como plan de estudios principal para mi clase?"
faq_row5_p: "¡Claro que sí! Ozaria tiene todo lo que necesitas para dictar una asignatura completa de Ciencias de la Computación, incluso si vienes de otro campo: desde planificaciones de clases hasta guías de soluciones, guías de evaluación y alineaciones con normas."
faq_row6_p_part1: "Si tienes más preguntas, "
# see_faq_prefix: "See more"
# see_faq_link: "frequently asked questions in our help center"
# see_faq_suffix: "."
summary: "Ozaria es un programa de ciencias de la computación, un juego de aventura y una historia de fantasía en la que los estudiantes deben dominar la magia perdida de la programación para salvar al mundo."
value_prop1_h1: "Una historia épica. Jugabilidad inmersiva."
value_prop1_h2: "Inspira una conexión más profunda con el aprendizaje"
value_prop1_p: "En Ozaria, los estudiantes se encuentran inmersos en un nuevo mundo donde deben dominar conceptos esenciales de las ciencias de la computación para avanzar en el juego. La narrativa que se desarrolla crea una gran experiencia de aprendizaje centrada en los estudiantes, en la cual el tiempo que cada alumno invierte en la historia de Ozaria equivale al tiempo que invierten en su propio camino de aprendizaje."
value_prop2_h1: "Descubre el héroe que hay en cada estudiante"
value_prop2_h2: "Desarrolla habilidades reales jugando"
value_prop2_p: "Los conceptos y las habilidades se presentan a través de contenidos diseñados cuidadosamente que incluyen niveles de juego, diálogos de enseñanza entre personajes, escenas de video y más. Los estudiantes aprenderán a programar en Python o JavaScript, a resolver problemas usando pensamiento computacional, a demostrar su comprensión mediante evaluaciones formativas y a aplicar lo que aprendieron en sus propios proyectos."
value_prop3_h1: "Empieza tu camino de manera gratuita"
value_prop3_p: "Enseña a través de la aventura con contenido gratuito que cubre conceptos introductorios de ciencias de la computación, así como acceso a guías de aplicación y planes de estudios."
projects_inspire_heading: "Proyectos que inspiran. Recursos que empoderan."
student_creativity: "Desata la creatividad de tus estudiantes"
student_creativity_paragraph: "Al final de cada unidad, para aplicar lo que han aprendido, los estudiantes crean proyectos que van desde videojuegos hasta historias con distintos desenlaces y más. Con objetivos de andamiaje que permiten desarrollar ideas sin límites, los estudiantes arman una cartera de trabajo que pueden compartir y jugar para exhibir su identidad creativa."
teach_with_support: "Enseña con apoyo"
teach_with_support_paragraph: "Ozaria está diseñado para educadores. Cada unidad del currículo incluye un plan de estudios que detalla los objetivos de aprendizaje, las confusiones más comunes, los términos clave y las normas CSTA. Además, existe un tablero de maestros muy completo para ayudarlos a supervisar el progreso de los estudiantes y corroborar el código de cada uno de ellos."
request_demo: "Solicita una demo"
im_an_educator: "Soy educador"
im_a_student: "Soy estudiante"
global_title: "Únete a nuestra comunidad mundial de estudiantes y educadores"
global_subtitle1: "Estudiantes"
global_subtitle2: "Líneas de código"
global_subtitle3: "Maestros"
global_subtitle4: "Países"
sign_up: "Registrarse"
learner_number: "12 millones"
code_line_number: "1000 millones"
new_home:
title: "CodeCombat - Juegos de Programación para aprender Python y JavaScript" # {change}
meta_keywords: "CodeCombat, Python, JavaScript, juegos de programación, programa de Ciencias de la Computación, aventura, historia épica"
meta_description: "Aprende a esciribir código a través de un juego de programación. Aprende Python, JavaScript y HTML mientras resuelves rompecabezas y aprendes a hacer tus propios juegos de código y páginas web." # {change}
become_investor: "para invertir en CodeCombat"
built_for_teachers_title: "Un Juego de programación construido teniendo en cuenta a los maestros."
built_for_teachers_blurb: "Enseñar a los niños a programar puede ser abrumador. CodeCombat ayuda a todos los educadores a enseñar a los estudiantes cómo programar en JavaScript o Python, dos de los lenguajes de programación más populares. Con un plan de estudios comprensivo que incluye seis unidades de Ciencias de la Computación, y refuerza el aprendizaje a través de unidades en el desarrollo de juegos y desarrollo web basados en proyectos, los niños progresarán en un viaje desde la sintaxis básica hasta la recursión!"
built_for_teachers_subtitle1: "Ciencias de la Computación"
built_for_teachers_subblurb1: "Comenzando con nuestro curso gratuito de Introducción a las Ciencias de la Computación, los estudiantes dominan los conceptos básicos de programación, tales como bucles de while / for, funciones y algoritmos."
built_for_teachers_subtitle2: "Desarrollo de Juegos"
built_for_teachers_subblurb2: "Los alumnos construyen laberintos y utilizan el manejo de entrada básico para programar sus propios juegos que pueden compartir con amigos y familiares."
built_for_teachers_subtitle3: "Desarrollo Web"
built_for_teachers_subblurb3: "Usando HTML, CSS y jQuery, los estudiantes ejercitan sus músculos creativos para programar sus propias páginas web con una URL personalizada para compartir con sus compañeros de clase."
century_skills_title: "Habilidades del siglo 21"
century_skills_blurb1: "Los Estudiantes No Solo Suben de Nivel a su Héroe, Sino que se Suben de Nivel Ellos Mismos"
century_skills_quote1: "Te equivocas ... entonces piensas en todas las formas posibles de solucionarlo y luego lo intentas de nuevo. No sería capaz llegar hasta aquí sin esforzarme."
century_skills_subtitle1: "Pensamiento Crítico"
century_skills_subblurb1: "Con los rompecabezas de programación que se naturalmente se organizan en niveles cada vez más desafiantes, el juego de programación de CodeCombat asegura que los niños siempre estén practicando el pensamiento crítico."
century_skills_quote2: "Todos los demás estaban haciendo laberintos, así que pensé, 'capturar la bandera' y eso es lo que hice."
century_skills_subtitle2: "Creatividad"
century_skills_subblurb2: "CodeCombat anima a los estudiantes a mostrar su creatividad construyendo y compartiendo sus propios juegos y páginas web."
century_skills_quote3: "Si me quedo atascado en un nivel. Trabajaría con la gente a mi alrededor hasta que todos pudiéramos resolverlo."
century_skills_subtitle3: "Colaboración"
century_skills_subblurb3: "A lo largo del juego hay oportunidades para que los estudiantes colaboren cuando se atasquen y trabajen juntos utilizando nuestra guía de programación en pareja."
century_skills_quote4: "Siempre he tenido aspiraciones de diseñar videojuegos y aprender a programar ... esto me está dando un gran punto de partida."
century_skills_subtitle4: "Comunicación"
century_skills_subblurb4: "La programación requiere que los niños practiquen nuevas formas de comunicación, incluida la comunicación con la computadora y la transmisión de sus ideas utilizando el código más eficiente."
classroom_in_box_title: "Nos esforzamos por:"
classroom_in_box_blurb1: "Involucre a todos los estudiantes para que confíen que la programación es para ellos."
classroom_in_box_blurb2: "Apoderar a cualquier educador para que se sienta seguro al enseñar programación."
classroom_in_box_blurb3: "Inspirar a todos los líderes escolares para crear un programa de Ciencias de la Computación de clase mundial."
click_here: "Haz clic aquí"
creativity_rigor_title: "Donde la creatividad alcanza el rigor"
creativity_rigor_subtitle1: "Haga que la programación sea divertida y enseñe habilidades del mundo real"
creativity_rigor_blurb1: "Los estudiantes escriben Python y JavaScript real mientras juegan juegos que fomentan el ensayo y error, el pensamiento crítico y la creatividad. Luego, los estudiantes aplican las habilidades de programación que han aprendido al desarrollar sus propios juegos y sitios web en cursos basados en proyectos."
creativity_rigor_subtitle2: "Alcanza a los alumnos a sus niveles"
creativity_rigor_blurb2: "Cada nivel de CodeCombat está basado en millones de puntos de datos y optimizado para adaptarse a cada alumno. Los niveles de práctica y las sugerencias ayudan a los estudiantes cuando se atascan, y los niveles de desafío evalúan el aprendizaje de los estudiantes a lo largo del juego."
creativity_rigor_subtitle3: "Construido para todos los maestros, independientemente de la experiencia"
creativity_rigor_blurb3: "El plan de estudios de CodeCombat, a ritmo propio y alineado con los estándares, hace posible la enseñanza de Ciencias de la Computación para todos. CodeCombat equipa a los maestros con capacitación, recursos de instrucción y apoyo dedicado para sentirse seguros y exitosos en el aula."
featured_partners_title1: "Presentado en"
featured_partners_title2: "Premios y socios"
featured_partners_blurb1: "Proveedor respaldado por CollegeBoard"
featured_partners_blurb2: "Mejor herramienta de creatividad para estudiantes"
featured_partners_blurb3: "La mejor opción para aprender"
featured_partners_blurb4: "Socio oficial de Code.org"
featured_partners_blurb5: "Miembro oficial de CSforAll"
featured_partners_blurb6: "Socio de Hour of Code Activity"
for_leaders_title: "Para los líderes de la escuela"
for_leaders_blurb: "Un programa de Ciencias de la Computación, comprensible y alineado con los estándares"
for_leaders_subtitle1: "Fácil implementación"
for_leaders_subblurb1: "Un programa basado en la web que no requiere soporte de TI. Comience en menos de 5 minutos con Google o el inicio de sesión único inteligente (SSO)."
for_leaders_subtitle2: "Completo plan de estudio de programación"
for_leaders_subblurb2: "Un currículo alineado con los estándares con recursos de instrucción y desarrollo profesional para permitir que cualquier maestro enseñe Ciencias de la Computación."
for_leaders_subtitle3: "Casos de uso flexibles"
for_leaders_subblurb3: "Ya sea que desee crear una clase electiva de programación de escuela intermedia, una ruta CTE o una clase de Principios de Ciencias de la Computación, CodeCombat se adapta a sus necesidades."
for_leaders_subtitle4: "Habilidades del mundo real"
for_leaders_subblurb4: "Los estudiantes construyen y desarrollan una mentalidad de crecimiento a través de los desafíos de programación que los preparan para los más de 500k trabajos informáticos abiertos."
for_teachers_title: "Para maestros"
for_teachers_blurb: "Herramientas para abrir el potencial del estudiante"
for_teachers_subtitle1: "Aprendizaje basado en proyectos"
for_teachers_subblurb1: "Promueva la creatividad, la resolución de problemas y la confianza en los cursos basados en proyectos donde los estudiantes desarrollan sus propios juegos y páginas web."
for_teachers_subtitle2: "Tablero de maestros"
for_teachers_subblurb2: "Vea datos sobre el progreso de los alumnos, descubra recursos curriculares y acceda a soporte en tiempo real para potenciar el aprendizaje."
for_teachers_subtitle3: "Evaluaciones incorporadas"
for_teachers_subblurb3: "Personalice la instrucción y asegúrese de que los alumnos comprendan los conceptos básicos con evaluaciones formativas y aditivas."
for_teachers_subtitle4: "Diferenciación automática"
for_teachers_subblurb4: "Involucre a todos los alumnos en un aula diversa con niveles de práctica que se adapten a las necesidades de aprendizaje de cada alumno."
game_based_blurb: "CodeCombat es un programa de Ciencias de la Computación basado en juegos en los que los estudiantes escriben código real y ven a sus personajes reaccionar en tiempo real."
get_started: "Empieza ahora"
global_title: "Únete a nuestra comunidad global de estudiantes y educadores"
global_subtitle1: "Alumnos"
global_subtitle2: "Líneas de código"
global_subtitle3: "Maestros"
global_subtitle4: "Países"
go_to_my_classes: "Ir a mis clases"
go_to_my_courses: "Ir a mis cursos"
quotes_quote1: "Nombra cualquier programa en línea, ya lo he intentado. Ninguno de ellos coincide con CodeCombat. Cualquier maestro que quiera que sus estudiantes aprendan a programar ... ¡comience aquí!"
quotes_quote2: " Me sorprendió lo fácil e intuitivo que CodeCombat hace que aprendan Ciencias de la Computación. Las calificaciones en el examen AP fueron mucho más altas de lo que esperaba y creo que CodeCombat es la razón por la que este fue el caso."
quotes_quote3: "CodeCombat ha sido lo más beneficioso para enseñar a mis alumnos las capacidades de programación de la vida real. Mi esposo es ingeniero de software y ha probado todos mis programas. Puso esto como su mejor opción."
quotes_quote4: "Los comentarios ... han sido tan positivos que estamos estructurando una clase de informática en torno a CodeCombat. El programa realmente involucra a los estudiantes con una plataforma estilo juego que es entretenida e instructiva al mismo tiempo. ¡Sigan con el buen trabajo, CodeCombat!"
see_example: "Ver ejemplo"
slogan: "El juego más interesante para aprender programación." # {change}
teach_cs1_free: "Enseña programación gratis"
teachers_love_codecombat_title: "A los maestros les encanta CodeCombat"
teachers_love_codecombat_blurb1: "Informan que sus estudiantes disfrutan usando CodeCombat para aprender a programar"
teachers_love_codecombat_blurb2: "Recomendarían CodeCombat a otros maestros de Ciencias de la Computación"
teachers_love_codecombat_blurb3: "Dicen que CodeCombat los ayuda a mejorar las habilidades de resolución de problemas de sus estudiantes"
teachers_love_codecombat_subblurb: "En asociación con McREL International, líder en orientación basada en investigación y evaluaciones de tecnología educativa."
top_banner_blurb: "Nuevo: ¡Únete a nuestra misión!" # {change}
top_banner_blurb_pd: "Ahora ofrecemos opciones de desarrollo profesional para educadores."
top_banner_blurb_funding: "Nuevo: Ley CARES: guía de recursos de financiación para conseguir fondos ESSER y GEER para programas de Ciencias de la Computación."
try_the_game: "Prueba el juego"
classroom_edition: "Versión para el aula:"
learn_to_code: "Aprende a programar:"
play_now: "Jugar Ahora"
im_an_educator: "Soy un Educador"
im_a_teacher: "Soy un Maestro"
im_a_student: "Soy un Estudiante"
learn_more: "Aprender más"
classroom_in_a_box: "Un aula prediseñada para enseñar Ciencias de la Computación."
codecombat_is: "CodeCombat es una plataforma para que los estudiantes aprendan Ciencias de la Computación mientras están jugando un juego de verdad." # {change}
our_courses: "Nuestros cursos fueron probados especificamente para destacarse en el aula, incluso con maestros con poca o ninguna experiencia previa en programación." # {change}
watch_how: "Observa como CodeCombat está transformando la manera en que la gente aprende Ciencias de la Computación."
top_screenshots_hint: "Los estudiantes escriben código y ven sus cambios actualizarse en tiempo real"
designed_with: "Diseñado teniendo en cuenta a los maestros"
real_code: "Escritura de código real"
from_the_first_level: "desde el primer nivel"
getting_students: "Conseguir que los estudiantes escriban código lo más pronto posible es fundamental para que aprendan la sintaxis y la estructura apropiada."
educator_resources: "Recursos para el educador"
course_guides: "y guías de curso"
teaching_computer_science: "Enseñar Ciencias de la Computación no requiere un título costoso, porque proporcionamos herramientas para ayudar a educadores con cualquier conocimiento previo."
accessible_to: "Comprensible para"
everyone: "todos"
democratizing: "Democratizar el proceso de aprender a programar es la esencia de nuestra filosofía. Todos deberían poder aprender a programar"
forgot_learning: "Creo que ellos en realidad olvidaron de que estaban aprendiendo algo." # {change}
wanted_to_do: "Programar es algo que siempre quise hacer, y que nunca pensé que sería capaz de aprenderlo en la escuela ."
builds_concepts_up: "Me gusta cómo CodeCombat construye los conceptos. Es muy fácil de entender y es divertido averiguarlo."
why_games: "¿Por qué el aprendizaje mediante juegos es importante?"
games_reward: "Los juegos recompensan el esfuerzo productivo."
encourage: "El juego es un medio que incentiva la interacción, el descubrimiento, y la prueba-error. Un buen juego desafía al jugador a dominar habilidades con el paso del tiempo, que es un proceso crítico similar al que los estudiantes atraviesan mientran aprenden"
excel: "Los juegos se destacan en recompensar el"
struggle: "esfuerzo productivo"
kind_of_struggle: "el tipo de esfuerzo que se traduce en aprendizaje que interesa y "
motivating: "que motiva"
not_tedious: "no tedioso."
gaming_is_good: "Los estudios sugieren que jugar es bueno para el cerebro de los niños (¡es verdad!)"
game_based: "Cuando los sistemas de aprendizaje basados en juegos son"
compared: "comparados"
conventional: "con los métodos de evaluación convencionales, la diferencia es clara: los juegos son mejores al ayudar a los estudiantes a retener el conocimiento, a concentrarse y"
perform_at_higher_level: "a desempeñarse con un mayor nivel de éxito"
feedback: "Los juegos también proveen retroalimentación en tiempo real que permite a los estudiantes ajustar su camino a la solución y entender conceptos de forma más holística, en lugar de estar limitados solamente a respuestas 'correctas' e 'incorrectas'"
real_game: "Un juego de verdad, jugado con código auténtico."
great_game: "Un gran juego es más que solo medallas y logros - se trata sobre una travesía del jugador, acertijos bien diseñados, y la habilidad de abordar desafios con voluntad y confianza."
agency: "CodeCombat es un juego que ofrece a los jugadores esa voluntad y confianza mediante nuestro motor de código robusto, que ayuda tanto a principiantes como a estudiantes avanzados por igual a escribir código correcto y válido."
request_demo_title: "Invita a tus estudiantes hoy!"
request_demo_subtitle: "Solicitar una demostración y empieza a jugar con tus estudiantes en menos de una hora."
get_started_title: "Configure su clase hoy"
get_started_subtitle: "Prepare su clase, agregue cuentas de estudiantes y siga su progreso a medida que aprenden a programar."
request_demo: "Solicitar un Demo"
request_quote: "Solicitar una cotización"
setup_a_class: "Configurar una Clase"
have_an_account: "¿Ya tienes una cuenta?" # {change}
logged_in_as: "Estás actualmente conectado como"
computer_science: "Cursos de Ciencias de la Computación para todas las edades" # {change}
ffa: "Gratis para todos los estudiantes"
coming_soon: "¡Proximamente!"
courses_available_in: "Los cursos están disponibles en JavaScript, Python, y Java (¡proximamente!)" # {change}
boast: "Cuenta con acertijos lo suficiente complejos como para fascinar a jugadores y programadores por igual."
winning: "Una combinación ganadora entre un juego de rol y una tarea sobre programación que consigue hacer de la educación amigable y disfrutable para los niños."
run_class: "Todo lo que necesitas para organizar una clase de Ciencias de la Computación en tu escuela hoy mismo, sin necesidad de ningún conocimiento previo de Ciencias de la Computación."
goto_classes: "Ir a mis clases" # {change}
view_profile: "Ver mi perfíl"
view_progress: "Ver mi progreso"
go_to_courses: "Ir a mis cursos"
want_coco: "¿Quisiera CodeCombat en su escuela?"
educator: "<NAME>"
student: "Estudiante"
go_to_my_dashboard: "Ir a mi panel"
nav:
educators: "<NAME>"
follow_us: "S<NAME>"
general: "General"
map: "Mapa"
play: "Jugar" # The top nav bar entry where players choose which levels to play
community: "Comunidad"
units: "Unidades"
blog: "Blog"
forum: "Foro"
account: "Cuenta"
my_account: "Mi Cuenta"
profile: "Perfil"
home: "Inicio"
contribute: "Contribuir"
legal: "Legal"
privacy: "Privacidad"
about: "Acerca"
contact: "Contacto"
press: "Prensa"
twitter_follow: "Seguir"
my_classrooms: "Mis clases"
my_courses: "Mis cursos"
my_units: "Mis unidades"
my_teachers: "Mis maestros"
careers: "Carreras"
facebook: "Facebook"
twitter: "<NAME>"
create_a_class: "Crear una Clase"
other: "Otro"
learn_to_code: "¡Aprender a programar!"
toggle_nav: "Cambia la navigación"
schools: "Escuelas"
get_involved: "Participa"
open_source: "Código Libre (GitHub)"
support: "Soporte"
faqs: "FAQs"
copyright_prefix: "Copyright"
copyright_suffix: "Todos los derechos reservados."
help_pref: "¿Necesitas ayuda? Envianos un correó electronico!"
help_suff: "y te contactaremos pronto"
resource_hub: "Centro de recursos"
apcsp: "Principios AP CS"
parent: "Padres"
faq: "Preguntas frecuentes"
return_coco: "Volver a CodeCombat"
classes: "Clases"
term_of_service: "Términos de Servicio"
esports: "Esports"
browser_recommendation: "Para una mejor experiencia, recomendamos usar la última versión de Chrome. ¡Descarga el navegador aquí!"
ozaria_classroom: "Aula de Ozaria"
codecombat_classroom: "Aula de CodeCombat"
ozaria_dashboard: "Panel de Ozaria"
codecombat_dashboard: "Panel de CodeCombat"
professional_development: "Desarrollo profesional"
new: "¡Nuevo!"
admin: "Admin"
funding_resources_guide: "Guía de recursos de financiación"
modal:
close: "Cerrar"
okay: "OK"
cancel: "Cancelar"
try_again: "Volver a intentarlo"
not_found:
page_not_found: "Página no encontrada"
diplomat_suggestion:
title: "¡Ayuda a traducir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector.
sub_heading: "Necesitamos tus habilidades de idioma."
pitch_body: "Desarrollamos CodeCombat en inglés, pero ya tenemos jugadores de todo el mundo. Muchos de ellos quieren jugar en español pero no hablan inglés, así que si puedes hablar ambos, por favor considera registrarte pare ser un Diplomático y ayudar a traducir tanto el sitio de CodeCombat como todos los niveles al español."
missing_translations: "Hasta que podamos traducir todo al español, verás inglés cuando el español no esté disponible."
learn_more: "Aprende más sobre ser un Diplomático"
subscribe_as_diplomat: "Suscríbete como un Diplomático"
play:
title: "Juega los niveles de CodeCombat - Aprende Python, JavaScript y HTML"
meta_description: "Aprende a programar con un juego para principiantes. Aprende Python o JavaScript mientras resuelves acertijos, crea tus propios videojuegos y sube de nivel. ¡Desafía a tus amigos en niveles de arena multijugador!"
level_title: "__level__ - Aprende a programar en Python, JavaScript y HTML"
video_title: "__video__ | Nivel de video"
game_development_title: "__level__ | Desarrollo de juegos"
web_development_title: "__level__ | Desarrollo web"
anon_signup_title_1: "CodeCombat tiene un"
anon_signup_title_2: "¡Versión de aula!"
anon_signup_enter_code: "Ingresa el código de la clase:"
anon_signup_ask_teacher: "¿No tienes uno? pregunta a tu maestro"
anon_signup_create_class: "¿Quieres crear una clase?"
anon_signup_setup_class: "¡Configura una clase, agrega a tus estudiantes, y monitorea el progreso!"
anon_signup_create_teacher: "Crea una cuenta de maestro gratuita"
play_as: "Jugar Como " # Ladder page
get_course_for_class: "¡Asigna desarrollo de juegos y más a tus clases!"
request_licenses: "Contacta a nuestros especialistas escolares para más detalles."
compete: "¡Competir!" # Course details page
spectate: "Observar" # Ladder page
players: "Jugadores" # Hover over a level on /play
hours_played: "horas jugadas" # Hover over a level on /play
items: "Objetos" # Tooltip on item shop button from /play
unlock: "Desbloquear" # For purchasing items and heroes
confirm: "Confirmar"
owned: "Adquirido" # For items you own
locked: "Bloqueado"
available: "Disponible"
skills_granted: "Habilidades concedidas" # Property documentation details
heroes: "Héroes" # Tooltip on hero shop button from /play
achievements: "Logros" # Tooltip on achievement list button from /play
settings: "Configuración" # Tooltip on settings button from /play
poll: "Encuestas" # Tooltip on poll button from /play
next: "Próximo" # Go from choose hero to choose inventory before playing a level
change_hero: "Cambiar héroe" # Go back from choose inventory to choose hero
change_hero_or_language: "Cambiar héroe o lenguaje"
buy_gems: "Comprar gemas"
subscribers_only: "¡Solo para suscriptores!"
subscribe_unlock: "¡Suscríbete para desbloquear!"
subscriber_heroes: "¡Suscríbete ahora para debloquear inmediatamente a Amara, Hushbaum y Hattori!"
subscriber_gems: "¡Suscríbete ahora para comprar este héroe con gemas!"
anonymous: "<NAME>"
level_difficulty: "Dificultad: "
awaiting_levels_adventurer_prefix: "Nosotros liberamos nuevos niveles cada semana"
awaiting_levels_adventurer: "Registrate como un aventurero"
awaiting_levels_adventurer_suffix: "para ser el primero en jugar nuevos niveles."
adjust_volume: "Ajustar el volúmen"
campaign_multiplayer: "Arenas Multijugador"
campaign_multiplayer_description: "... en las que programas cara a cara contra otros jugadores."
brain_pop_done: "!Has derrotado a los Ogros programando! ¡Ganaste!"
brain_pop_challenge: "¡Desafiate a jugar de nuevo usando otro lenguaje de programación!"
replay: "Repetir"
back_to_classroom: "Volver al aula"
teacher_button: "Para maestros"
get_more_codecombat: "Consigue más CodeCombat"
back_to_dashboard: "Volver al panel"
back_to_ozaria: "Volver a ozaria.<EMAIL>"
customize_hero: "Personalizar héroe"
account_settings: "Configuración de cuenta"
back_to_tutorial: "Volver al tutorial"
teacher_vega_message: "Estos mensajes de tutorial guían a los estudiantes. Para ver estos mensajes y guardar tu progreso en el juego, crea una cuenta de estudiante y accede a ella para jugar Ozaria."
code:
if: "si" # 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: "de lo contrario"
elif: "o si"
while: "mientras"
loop: "ciclo"
for: "para"
break: "interrumpir"
continue: "continuar"
pass: "pasar"
return: "regresar"
then: "entonces"
do: "hacer"
end: "fin"
function: "función"
def: "define"
var: "variable"
self: "sí mismo"
hero: "héroe"
this: "este"
or: "o"
"||": "o"
and: "y"
"&&": "y"
not: "no"
"!": "no"
"=": "asignar"
"==": "igual a"
"===": "estrictamente igual a"
"!=": "distinto a"
"!==": "estrictamente distinto a"
">": "mayor que"
">=": "mayor o igual que"
"<": "menor que"
"<=": "menor o igual que"
"*": "multiplicado por"
"/": "dividido por"
"+": "más"
"-": "menos"
"+=": "añade y asigna"
"-=": "substrae y asigna"
True: "Verdadero"
true: "verdadero"
False: "Falso"
false: "falso"
undefined: "indefinido"
null: "nulo"
nil: "nada"
None: "Ninguno"
share_progress_modal:
blurb: "¡Estás haciendo un gran progreso! Cuéntale a tus padres cuánto has aprendido con CodeCombat."
email_invalid: "Dirección de Email inválida."
form_blurb: "¡Escribe su email debajo y les enseñaremos!"
form_label: "Dirección de Email"
placeholder: "dirección de email"
title: "Excelente Trabajo, Aprendiz"
login:
auth_sign_up: "¿Primera vez en Ozaria? Crea una cuenta"
sign_up: "Crear Cuenta"
email_or_username: "Email o Nombre de usuario" # {change}
or: "o"
log_in: "Entrar"
sign_in: "Regístrate"
logging_in: "Entrando"
log_out: "Salir"
forgot_password: "<PASSWORD>?"
finishing: "Finalizando"
sign_in_with_facebook: "Registrarse con Facebook" # {change}
sign_in_with_gplus: "Registrarse con G+" # {change}
signup_switch: "¿Quieres crear una cuenta?"
already_have_account1: "¿Ya tienes una cuenta de maestro o estudiante de CodeCombat?"
already_have_account2: "Puedes ingresar a Ozaria.com con esa cuenta."
sign_into_ozaria: "Ingresa a Ozaria.com"
individual_users_not_supported: "¡Ozaria es solo para aulas! ¡Visita CodeCombat para seguir jugando!"
accounts_merge_confirmation: "Hay una cuenta asociada al correo electrónico de esta cuenta de Google. ¿Quieres combinar las cuentas?"
signup:
complete_subscription: "Completa Suscripción"
create_student_header: "Crear Cuenta de Estudiante"
create_teacher_header: "Crear Cuenta de Maestro"
create_individual_header: "Crear Cuenta Individual"
email_announcements: "Recibe noticias por email" # {change}
sign_in_to_continue: "Inicia sesión o crea una cuenta para continuar"
teacher_email_announcements: "Mantenme actualizado sobre nuevos recursos para maestros, currículo y cursos!"
creating: "Creando Cuenta..."
sign_up: "Registrarse"
log_in: "Inicia sesión con tu contraseña"
login: "Iniciar sesión"
required: "Necesitas entrar a tu cuenta antes de continuar."
login_switch: "¿Ya tienes una cuenta?"
optional: "opcional"
connected_gplus_header: "Te has conectado exitosamente a travez de Google+!"
connected_gplus_p: "Termina el registro para que inicies sesión con tu cuenta de Google+."
connected_facebook_header: "Te has conectado exitosamente a travez de Facebook!"
connected_facebook_p: "Termina el registro para que inicies sesión con tu cuenta de Facebook."
hey_students: "Estudiante, ingresa el coódigo de clase de tu maestro."
birthday: "Cumpleaños"
parent_email_blurb: "Nosotros sabemos que tu no puedes esperar para aprender programación — nosotros tambien estamos emocionados! Tus padres recibirán un correo electrónico con más instrucciones sobre cómo crear una cuenta para ti. Envíe un correo electrónico a {{email_link}} si tienes alguna pregunta"
classroom_not_found: "Ninguna clase existe con este código de clase. Revisa tu ortografía o pidele ayuda a tu maestro."
checking: "Comprobando..."
account_exists: "Este email ya esta en uso:"
sign_in: "Iniciar Sesión"
email_good: "Tu email se ve bien!"
name_taken: "Ese nombre de usuario ya esta en uso! Intenta {{suggestedName}}?"
name_available: "Nombre de usuario disponible!"
name_is_email: "Tu email no puede ser tu nombre de usuario"
choose_type: "Elige el tipo de cuenta:"
teacher_type_1: "Enseña como programar con CodeCombat!"
teacher_type_2: "Configura tu clase"
teacher_type_3: "Accede a guías de cursos"
teacher_type_4: "Ve el progreso del estudiante"
signup_as_teacher: "Iniciar sesión como Maestro" # {change}
student_type_1: "Aprende a programar mientras que juegas"
student_type_2: "Jugar con tu clase"
student_type_3: "Compite en arenas"
student_type_4: "Escoge tu héroe!"
student_type_5: "Ten tu código de clase listo!"
signup_as_student: "Iniciar sesión como Estudiante" # {change}
individuals_or_parents: "Independientes y Padres"
individual_type: "Para jugadores que aprenden a programar fuera de clase. Los padres deben registrar una cuenta aquí."
signup_as_individual: "Registrarse como Independiente"
enter_class_code: "Ingresa el código de tu clase"
enter_birthdate: "Ingresa tu fecha de nacimiento:"
parent_use_birthdate: "Padres, usen su propia fecha de nacimiento."
ask_teacher_1: "Pregúntale a tu maestro por el código de tu clase."
ask_teacher_2: "¿No eres parte de una clase? Crea una"
ask_teacher_3: "Cuenta Independiente"
ask_teacher_4: " en cambio."
about_to_join: "Te vas a unir a:"
enter_parent_email: "Ingresa el correo eletrónico de tus padres:"
parent_email_error: "Ha ocurrido un error al tratar de enviar el correo. Verifica la dirección de correo electrónico e intenta de nuevo."
parent_email_sent: "Hemos enviado un correo electrónico con más instrucciones sobre cómo crear una cuenta. Pide a tus padres que revisen su bandeja de entrada."
account_created: "¡Cuenta Creada!"
confirm_student_blurb: "Escribe tu información para que no la olvides. Tu maestro también puede ayudarte a restablecer tu contraseña en cualquier momento."
confirm_individual_blurb: "Escribe tu información de inicio de sesión en caso de que la necesites más adelante. Verifica tu correo electrónico para que puedas recuperar tu cuenta si alguna vez olvidas la contraseña. ¡Revisa tu bandeja de entrada!"
write_this_down: "Escribe esto:" # {change}
start_playing: "¡Empieza a jugar!"
sso_connected: "Conectado exitosamente con:"
select_your_starting_hero: "Selecciona tu héroe inicial:"
you_can_always_change_your_hero_later: "Podrás cambiar tu héroe luego."
finish: "Finalizar"
teacher_ready_to_create_class: "¡Estás listo para crear tu primera clase!"
teacher_students_can_start_now: "Sus alumnos podrán comenzar a jugar el primer curso, Introducción a las Ciencias de la Computación, inmediatamente." # {change}
teacher_list_create_class: "En la siguiente pantalla podrás crear una nueva clase."
teacher_list_add_students: "Agregue alumnos a la clase haciendo clic en el enlace Ver clase y luego envíe a sus alumnos el Código de clase o la URL. También puedes invitarlos por correo electrónico si tienen."
teacher_list_resource_hub_1: "Revisar la "
teacher_list_resource_hub_2: "Guías de curso" # {change}
teacher_list_resource_hub_3: "para soluciones a todos los niveles, y la"
teacher_list_resource_hub_4: "Centro de recursos"
teacher_list_resource_hub_5: "para guías curriculares, actividades, y más."
teacher_additional_questions: "¡Eso es todo! Si necesita ayuda adicional o tiene preguntas, comuníquese con __supportEmail__."
dont_use_our_email_silly: "¡No pongas nuestro email aquí! Pon el correo de tus padres."
want_codecombat_in_school: "¿Quieres jugar CodeCombat todo el tiempo?"
eu_confirmation: "Acepto permitir que CodeCombat almacene mis datos en servidores de los Estados Unidos."
eu_confirmation_place_of_processing: "Aprender más sobre los posibles riesgos"
eu_confirmation_student: "Si no estás seguro, pregúntale a tu maestro."
eu_confirmation_individual: "Si no deseas que almacenemos tus datos en servidores de EE. UU., Siempre puedes seguir jugando de forma anónima sin guardar tu código."
request_class_code: "¡Estudiantes, pídanle un código de clase a su docente para crear una cuenta!"
educators_create_account: "¡Docentes, creen una cuenta de maestro para acceder a la primera unidad de manera gratuita!"
looking_for_classroom: "Buscando aulas..."
create_your_educator_account: "Crea una cuenta de educador"
educator_signup_list_1_title: "Ve lo mismo que tus estudiantes:"
educator_signup_list_1_desc: "Prueba cada nivel del juego en la primera unidad"
educator_signup_list_2_title: "Ve los recursos para maestros:"
educator_signup_list_2_desc: "Accede al alcance y el orden, las lecciones y más"
educator_signup_list_3_title: "Observa el progreso de tus estudiantes:"
educator_signup_list_3_desc: "Prueba gratis la primera unidad con tu clase"
signup_with_email: "Regístrate con tu correo electrónico"
already_have_account: "Ya tienes una cuenta de Ozaria o CodeCombat"
select_your_role: "Selecciona tu rol"
select_your_state: "Selecciona tu estado"
password_requirements: "Entre 8 y 64 caracteres no repetidos"
invalid: "No válido"
invalid_password: "<PASSWORD>aseña no válida"
form_validation_errors:
required: "El campo es obligatorio"
invalidEmail: "Correo no válido"
invalidPhone: "Número de teléfono no válido"
emailExists: "El correo electrónico ya existe"
numberGreaterThanZero: "Debe ser un número mayor que 0"
recover:
recover_account_title: "recuperar cuenta"
send_password: "<PASSWORD>"
recovery_sent: "Correo de recuperación enviado."
items:
primary: "Primario"
secondary: "Secundario"
armor: "Armadura"
accessories: "Accesorios"
misc: "Misceláneo"
books: "Libros"
common:
default_title: "Ozaria - Informática que fascina"
ozaria: "Ozaria"
default_meta_description: "Ozaria es un programa de ciencias de la computación, un juego de aventura y una historia de fantasía en la que los estudiantes deben dominar la magia perdida de la programación para salvar al mundo."
back: "Atrás" # When used as an action verb, like "Navigate backward"
coming_soon: "¡Próximamente!"
continue: "Continuar" # When used as an action verb, like "Continue forward"
next: "Siguiente"
default_code: "Código predeterminado"
loading: "Cargando..."
LOADING: "CARGANDO"
overview: "Vista global"
processing: "Procesando..."
solution: "Solución"
table_of_contents: "Tabla de contenidos"
intro: "Intro"
saving: "Guardando..."
sending: "Enviando..."
send: "Enviar"
sent: "Enviado"
cancel: "Cancelar"
save: "Guardar"
publish: "Publicar"
create: "Crear"
fork: "Bifurcar"
play: "Jugar" # When used as an action verb, like "Play next level"
retry: "Reintentar"
actions: "Acciones"
info: "Info"
help: "Ayuda"
watch: "Seguir"
unwatch: "No seguir"
submit_patch: "Enviar Parche"
submit_changes: "Enviar cambios"
save_changes: "Guardar cambios"
required_field: "Requisito necesario" # {change}
submit: "Enviar"
replay: "Volver a jugar"
complete: "Completado"
continue_editing: "Continuar editando"
logout: "Cerrar sesión"
empty: "Vacío"
done: "Listo"
remove: "Quitar"
locked: "Bloqueado"
general:
and: "y"
name: "Nombre"
date: "Fecha"
body: "Cuerpo"
version: "Versión"
pending: "Pendiente"
accepted: "Aceptado"
rejected: "Rechazado"
withdrawn: "Retirado"
accept: "Aceptar"
accept_and_save: "Aceptar y Guardar"
reject: "Rechazar"
withdraw: "Retirar"
submitter: "Emisor"
submitted: "Enviado"
commit_msg: "Enviar mensaje"
version_history: "Historial de Versiones"
version_history_for: "Historial de Versiones para: "
select_changes: "Selcciona dos cambios abajo para ver la diferencia"
undo_prefix: "Deshacer"
undo_shortcut: "(Ctrl+Z)"
redo_prefix: "Rehacer"
redo_shortcut: "(Ctrl+Shift+Z)"
play_preview: "Mira el avance del nivel"
result: "Resultado"
results: "Resultados"
description: "Descripción"
or: "o"
subject: "Asunto"
email: "Email"
password: "<PASSWORD>"
confirm_password: "<PASSWORD>"
message: "Mensaje"
code: "Código"
ladder: "Escalera"
when: "Cuando"
opponent: "Oponente"
rank: "Posición"
score: "Puntuación"
win: "Ganada"
loss: "Perdida"
tie: "Empate"
easy: "Fácil"
medium: "Medio"
hard: "Difícil"
player: "<NAME>"
player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard
warrior: "Guerrero"
ranger: "Guardabosques"
wizard: "Mago"
first_name: " <NAME>"
last_name: "<NAME>"
last_initial: "Última inicial"
username: "Nombre de usuario"
contact_us: "Contáctenos"
close_window: "Cerrar ventana"
learn_more: "Aprende Más"
more: "Más"
fewer: "Menos"
with: "con"
archived: "Archivado"
chat: "Chat"
chat_with_us: "Chatea con nosotros"
email_us: "Envíanos un correo electrónico"
sales: "Ventas"
support: "Ayuda"
units:
second: "segundo"
seconds: "segundos"
sec: "seg"
minute: "minuto"
minutes: "minutos"
hour: "hora"
hours: "horas"
day: "día"
days: "días"
week: "semana"
weeks: "semanas"
month: "mes"
months: "meses"
year: "año"
years: "años"
play_level:
back_to_map: "Volver al Mapa"
directions: "Instrucciones"
edit_level: "Editar Nivel"
keep_learning: "Sigue aprendiendo"
explore_codecombat: "Explorar CodeCombat"
finished_hoc: "He terminado con mi Hora of Código"
get_certificate: "¡Obtén tu certificado!"
level_complete: "Nivel completo"
completed_level: "Nivel Completado:"
course: "Curso:"
done: "Listo"
next_level: "Siguiente Nivel"
combo_challenge: "Desafío Combo"
concept_challenge: "Desafío de Concepto"
challenge: "Desafío"
challenge_unlocked: "Desafío Desbloqueado"
combo_challenge_unlocked: "Desafío Combo Desbloqueado"
concept_challenge_unlocked: "Desafío de Concepto Desbloqueado"
concept_challenge_complete: "Desafío de Concepto Completado!"
combo_challenge_complete: "Deasfío Combo Completado!"
combo_challenge_complete_body: "Buen trabajo, parece que te va bien entendiendo __concept__!"
replay_level: "Reiniciar nivel"
combo_concepts_used: "__complete__/__total__ Conceptos usados"
combo_all_concepts_used: "Usaste todos los conceptos posibles para resolver el desafío. ¡Buen trabajo!"
combo_not_all_concepts_used: "Usaste __complete__ de __total__ conceptos posibles para resolver el desafío. ¡Intenta obtener todos los __total__ conceptos la próxima vez!"
start_challenge: "Empezar Desafío"
next_game: "Siguiente juego"
languages: "Lenguajes"
programming_language: "Lenguajes de programación"
show_menu: "Mostrar menú de juego"
home: "Inicio" # Not used any more, will be removed soon.
level: "Nivel" # Like "Level: Dungeons of Kithgard"
skip: "Omitir"
game_menu: "Menú del Juego"
restart: "Reiniciar"
goals: "Objetivos"
goal: "Objetivo"
challenge_level_goals: "Metas del Nivel de Desafío"
challenge_level_goal: "Meta del Nivel de Desafío"
concept_challenge_goals: "Metas del Desafío de Concepto"
combo_challenge_goals: "Metas del Nivel de Desafío"
concept_challenge_goal: "Metas del Desafío de Concepto"
combo_challenge_goal: "Meta del Nivel de Desafío"
running: "Andando..."
success: "¡Éxito!"
incomplete: "Incompleto"
timed_out: "Acabó el tiempo"
failing: "Fallando"
reload: "Recargar"
reload_title: "¿Recargar Todo el Código?"
reload_really: "¿Estás seguro de que quieres empezar este nivel desde el principio?"
reload_confirm: "Recargar Todo"
restart_really: "¿Seguro que quieres reiniciar el nivel? Perderás todo el código que has escrito."
restart_confirm: "Sí, reiniciar"
test_level: "Probar Nivel"
victory: "Victoria"
victory_title_prefix: "¡"
victory_title_suffix: "¡Completo!"
victory_sign_up: "Regístrate para recibir actualizaciones"
victory_sign_up_poke: "¿Quieres recibir las últimas noticias por correo? ¡Crea una cuenta gratuita y te mantendremos informado!"
victory_rate_the_level: "¿Cómo de divertido estuvo este nivel?"
victory_return_to_ladder: "Volver a la escalera"
victory_saving_progress: "Guardando Progreso"
victory_go_home: "Ir al Inicio"
victory_review: "¡Cuéntanos más!"
victory_review_placeholder: "¿Cómo estuvo el nivel?"
victory_hour_of_code_done: "¿Has acabado?"
victory_hour_of_code_done_yes: "¡Si, he terminado con mi Hora de Código!"
victory_experience_gained: "XP Ganada"
victory_gems_gained: "Gemas Ganadas"
victory_new_item: "Objeto Nuevo"
victory_new_hero: "Nuevo Héroe"
victory_viking_code_school: "¡Changos macacos!, ¡el nivel que acabas de pasar era dificil! Si todavía no eres un desarrollador de software, deberías serlo. Acabas de conseguir una aceptación por vía rápida con la Escuela Vikinga de Có, donde tú puedes llevar tus habilidades al siguiente nivel y convertirte en un desarrollador web profesional en 14 semanas."
victory_become_a_viking: "Conviértete en un Vikingo"
victory_no_progress_for_teachers: "El progreso no es guardado para maestros. Pero puede añadir cuenta de estudiante a su aula, por su mismo."
tome_cast_button_run: "Ejecutar"
tome_cast_button_running: "Ejecutando"
tome_cast_button_ran: "Ejecutado"
tome_cast_button_update: "Actualizar"
tome_submit_button: "Enviar"
tome_reload_method: "Recargar código original para este método" # {change}
tome_available_spells: "Hechizos Disponibles"
tome_your_skills: "Tus habilidades"
hints: "Pistas"
videos: "Videos"
hints_title: "Pistas {{number}}"
code_saved: "Código Guardado"
skip_tutorial: "Saltar (esc)"
keyboard_shortcuts: "Atajos de teclado"
loading_start: "Iniciar nivel"
loading_start_combo: "Iniciar Desafío Combo"
loading_start_concept: "Iniciar Desafío de Concepto"
problem_alert_title: "Revisa tu código"
time_current: "Ahora:"
time_total: "Max:"
time_goto: "Ir a:"
non_user_code_problem_title: "No se puede cargar el nivel"
infinite_loop_title: "Ciclo infinito detectado"
infinite_loop_description: "El código inicial para construir el mundo no terminó de ejecutarse. Probablemente es muy lento o tiene un loop infinito. O puede ser un bug. Puedes tratar ejecutando este código nuevamente o reiniciar el código a su estado por defecto. Si eso no lo arregla, haznos saber."
check_dev_console: "Tú puedes también abrir la consola de desarrollo para ver que puede salir mal."
check_dev_console_link: "(instrucciones)"
infinite_loop_try_again: "Intentar nuevamente"
infinite_loop_reset_level: "Reiniciar Nivel"
infinite_loop_comment_out: "Comenta Mi Código"
tip_toggle_play: "Activa jugar/pausa con Ctrl+P."
tip_scrub_shortcut: "Ctrl+[ y Ctrl+] para rebobinar y avanzar rápido."
tip_guide_exists: "Haga click en la guía en la parte superior de la página para obtener información útil"
tip_open_source: "¡CodeCombat es 100% código abierto!" # {change}
tip_tell_friends: "¿Disfrutando de CodeCombat? ¡Cuéntale a tus amigos acerca de nosotros!"
tip_beta_launch: "CodeCombat lanzó su beta en Octubre del 2013."
tip_think_solution: "Piensa en la solución, no en el problema."
tip_theory_practice: "En teoría, no hay diferencia entre la teoría y la práctica. Pero en la práctica, si la hay. - <NAME>"
tip_error_free: "Hay dos formas de escribir programas libres de errores; sólo la tercera funciona. - <NAME>"
tip_debugging_program: "Si depurar es el proceso de remover errores, entonces programar debe ser el proceso de colocarlos. - <NAME>"
tip_forums: "¡Dirígite a los foros y dinos lo que piensas!"
tip_baby_coders: "En el futuro, incluso los bebés serán Archimagos."
tip_morale_improves: "La carga continuará hasta que la moral mejore."
tip_all_species: "Creemos en la igualdad de oportunidades para aprender a programar para todas las especies."
tip_reticulating: "Espinas reticulantes."
tip_harry: "Eres un Hechicero, "
tip_great_responsibility: "Con una gran habilidad de hacer código viene una gran responsabilidad de depuración."
tip_munchkin: "Si no comes tus verduras, un enano vendrá por ti mientras estés dormido."
tip_binary: "Sólo hay 10 tipos de personas en el mundo: aquellas que entienden binario y las que no."
tip_commitment_yoda: "Un programador debe tener el compromiso más profundo, la mente más seria. ~ Yoda"
tip_no_try: "Haz. O no hagas. No hay intento. - Yoda"
tip_patience: "Paciencia debes tener, joven Padawan. - Yoda"
tip_documented_bug: "Un error documentado no es un error; es una característica."
tip_impossible: "Siempre parece imposible hasta que se hace. - <NAME>"
tip_talk_is_cheap: "Hablar es barato. Muéstrame el código. - <NAME>"
tip_first_language: "La cosa más desastrosa que puedes aprender es tu primer lenguaje de programación. - <NAME>"
tip_hardware_problem: "P: ¿Cuántos programadores son necesarios para cambiar una bombilla eléctrica? R: Ninguno, es un problema de hardware."
tip_hofstadters_law: "Ley de Hofstadter: Siempre toma más tiempo del que esperas, incluso cuando tienes en cuenta la ley de Hofstadter."
tip_premature_optimization: "La optimización prematura es la raíz de la maldad. - <NAME>"
tip_brute_force: "Cuando tengas duda, usa la fuerza bruta. - <NAME>"
tip_extrapolation: "Solo hay dos tipos de personas: Esas que pueden extrapolar desde información incompleta..."
tip_superpower: "Programar es lo más cercano que tenemos a superpoderes."
tip_control_destiny: "En el Open Source real, tú tienes el derecho de controlar tu propio destino. - <NAME>"
tip_no_code: "Ningún código es más rápido que nada de código."
tip_code_never_lies: "El código nunca miente, los comentarios a veces sí. — <NAME>"
tip_reusable_software: "Antes de que el software sea reusable, primero tiene que ser usable."
tip_optimization_operator: "Cada lenguaje tiene un operador de optimización. En la mayoría de ellos, ese operador es ‘//’"
tip_lines_of_code: "Medir el progreso en la programación en líneas de código es como medir el progreso de construcción de una aeronave por su peso. — <NAME>"
tip_source_code: "Quisiera cambiar el mundo, pero no me dan el código fuente."
tip_javascript_java: "Java es a Javascript lo mismo que Comer es a Comercial. - <NAME>"
tip_move_forward: "Hagas lo que hagas, siempre sigue hacia delante. - <NAME> Jr."
tip_google: "¿Tienes un problema que no puedes resolver? ¡Googléalo!"
tip_adding_evil: "Agregando una pizca de maldad."
tip_hate_computers: "Esa es la razón por la cual la gente piensa que odia las computadoras. Lo que ellos odian de verdad, es los pesimos programadores. - <NAME>"
tip_open_source_contribute: "¡Tú puedes ayudar a CodeCombat a mejorar!"
tip_recurse: "Iterar es humano, recursar es divino. - <NAME>"
tip_free_your_mind: "Tienes que dejar ir todo, Neo. Miedo, duda, e incredulidad. Libera tu mente. - Morpheus"
tip_strong_opponents: "Hasta los oponentes mas fuertes siempre tienen una debilidad. - <NAME>"
tip_paper_and_pen: "Antes de comenzar a programar, siempre puedes planear con una hoja de papel y un lapicero."
tip_solve_then_write: "Primero, resuelve el problema. Entonces, escribe el código. - <NAME>"
tip_compiler_ignores_comments: "A veces pienso que el compilador ignora mis comentarios."
tip_understand_recursion: "La única manera de entender la recursividad es entender la recursividad."
tip_life_and_polymorphism: "El Open Source es como una estructura heterogénea totalmente polimórfica: Todos los tipos son bienvenidos."
tip_mistakes_proof_of_trying: "Errores en tu código son solo evidencia de que estas intentando."
tip_adding_orgres: "Redondendo ogres."
tip_sharpening_swords: "Afilando las espadas."
tip_ratatouille: "No debes dejar que nadie defina tus límites a causa de donde venas. Tu único límite es tu alma. - <NAME>"
tip_nemo: "¿Cuando huye la suerte, sabes que hay que hacer? Sigue nadando, sigue nadando. - <NAME>"
tip_internet_weather: "Debes moverte al intenet, es genial aquí. Tenemos la oportunidad de vivir dentro donde el clima es siempre sorprendente. - <NAME>"
tip_nerds: "A los Nerds se les permite amor cosas, como saltar-arriba-y-abajo-en-la-silla-no-te-puedes-controlar-tu-mismo quiérelo. - <NAME>"
tip_self_taught: "Me enseñé a mí mismo el 90% de lo que he aprendido. ¡Y eso es normal! - <NAME>"
tip_luna_lovegood: "No te preocupes, estas tan cuerdo como yo. - <NAME>"
tip_good_idea: "La mejor forma de tener una buena idea es tener un montón de ideas. - <NAME>"
tip_programming_not_about_computers: "Las Ciencias de la Computación está tan alejada de computadoras como la astronomía de telescopios. - <NAME>"
tip_mulan: "Si crees que puedes, entonces lo harás. - <NAME>"
project_complete: "¡Proyecto completo!"
share_this_project: "Comparte este proyecto con familia y amigos:"
ready_to_share: "¿Listo para publicar tu proyecto?"
click_publish: "Haz click en \"Publicar\" para que aparezca en la galería de la clase, a continuación ¡echa un vistazo a lo que construyeron tus compañeros! Puedes volver y seguir trabajando en este proyecto. Cualquier cambio adicional se guardará automáticamente y se compartirá con tus compañeros."
already_published_prefix: "Tus cambios se han publicado en la galería de la clase."
already_published_suffix: "¡Sigue experimentando y haciendo este proyecto aún mejor, o mira lo que el resto de la clase ha construido! Tus cambios se guardarán automáticamente y se compartirán con tus compañeros."
view_gallery: "Ver Galería"
project_published_noty: "¡Tu nivel ha sido publicado!"
keep_editing: "Continuar editando"
learn_new_concepts: "Aprende nuevos conceptos"
watch_a_video: "Mira un video de __concept_name__"
concept_unlocked: "Concepto desbloqueado"
use_at_least_one_concept: "Usa al menos un concepto: "
command_bank: "Banco de códigos"
learning_goals: "Metas de aprendizaje"
start: "Empezar"
vega_character: "Personaje Vega"
capella_character: "Personaje Capella"
octans_character: "Personaje Octans"
click_to_continue: "Haz clic para continuar"
share_your_project: "Comparte tu proyecto"
keep_editing_your_project: "Siempre puedes seguir editando tu proyecto, incluso después compartirlo."
copy_url: "Copiar URL"
level_status: "Estado"
level_status_locked: "Bloqueado"
level_status_in_progress: "En curso"
level_status_complete: "Completado"
level_type_practice: "Práctica"
level_type_challenge: "Desafío"
level_type_cutscene: "Escena"
level_type_capstone: "Final"
level_type_intro: "Introducción"
level_type_practice_level: "Nivel de práctica"
level_type_challenge_level: "Nivel de desafío"
level_type_cutscene_level: "Nivel de escena"
level_type_capstone_level: "Nivel final"
level_type_capstone_project: "Proyecto final"
level_type_intro_level: "Nivel introductorio"
content_type_avatar: "Selección de avatar"
content_type_cinematic: "Cinemática"
content_type_interactive: "Comprobación de conceptos"
feedback: "Comentarios"
apis:
methods: "Métodos"
events: "Eventos"
handlers: "Manipuladores"
properties: "Propiedades"
snippets: "Fragmentos"
spawnable: "Generable"
html: "HTML"
math: "Cálculos"
array: "Arreglo"
object: "Objeto"
string: "Cadena de texto"
function: "Función"
vector: "Vector"
date: "Fecha"
jquery: "jQuery"
json: "JSON"
number: "Número"
webjavascript: "JavaScript"
amazon_hoc:
title: "¡Sigue aprendiendo con Amazon!"
congrats: "¡Felicitaciones por conquistar esa desafiante Hora de Código!"
educate_1: "Ahora, continúa aprendiendo sobre programación y computación en la nube con AWS Educate, un programa emocionante y gratuito de Amazon para estudiantes y maestros. Con AWS Educate, puedes obtener insignias geniales a medida que aprendes sobre los conceptos básicos de la nube y las tecnologías de vanguardia, como los juegos, la realidad virtual y Alexa."
educate_2: "Aprende más y regístrate aquí"
future_eng_1: "También puedes intentar construir tu propia habilidad de datos escolares para Alexa."
future_eng_2: "aquí"
future_eng_3: "(No se requiere dispositivo). Esta actividad de Alexa es traída a ti por el"
future_eng_4: "Amazon Future Engineer"
future_eng_5: "programa que crea oportunidades de aprendizaje y trabajo para todos los estudiantes de K-12 en los Estados Unidos que desean dedicarse a Ciencias de la Computación."
play_game_dev_level:
created_by: "Creado por {{name}}"
created_during_hoc: "Creado durante Hora de Código"
restart: "Reiniciar Nivel"
play: "Iniciar Nivel"
learn_about_ozaria: "Learn About Ozaria"
default_student_instructions: "¡Haz clic para controlar a tu héroe y ganar tu juego!"
goal_survive: "Sobrevive."
goal_survive_time: "Sobrevive por __seconds__ segundos."
goal_defeat: "Derrota a todos los enemigos."
goal_defeat_amount: "Derrota __amount__ enemigos."
goal_move: "Muévete a todas las marcas X rojas."
goal_collect: "Recoge todos los objetos."
goal_collect_amount: "Recoge __amount__ objetos."
game_menu:
inventory_tab: "Inventario"
save_load_tab: "Guardar/Cargar"
options_tab: "Opciones"
guide_tab: "Guía"
guide_video_tutorial: "Guía en video"
guide_tips: "Pistas"
multiplayer_tab: "Multijugador"
auth_tab: "Entrar"
inventory_caption: "Equipar a tu héroe"
choose_hero_caption: "Elegir héroe, lenguaje"
options_caption: "Hacer ajustes"
guide_caption: "Documentos y consejos"
multiplayer_caption: "¡Jugar con amigos!"
auth_caption: "Guarda tu progreso."
leaderboard:
view_other_solutions: "Ver la Tabla de Posiciones"
scores: "Puntajes"
top_players: "Mejores jugadores"
day: "Hoy"
week: "Esta Semana"
all: "Siempre"
latest: "Mas reciente"
time: "Tiempo"
damage_taken: "Daño Recibido"
damage_dealt: "Daño Infligido"
difficulty: "Dificultad"
gold_collected: "Oro Recolectado"
survival_time: "Sobrevivido"
defeated: "Enemigos Derrotados"
code_length: "Líneas de código"
score_display: "__scoreType__: __score__"
inventory:
equipped_item: "Equipado"
required_purchase_title: "Requerido"
available_item: "Disponible"
restricted_title: "Restringido"
should_equip: "(doble-click para equipar)"
equipped: "(equipado)"
locked: "(bloqueado)"
restricted: "(restringido en este nivel)"
equip: "Equipar"
unequip: "Sacar"
warrior_only: "Sólo para Gerrero"
ranger_only: "Sólo para Arquero"
wizard_only: "Sólo para Mago"
buy_gems:
few_gems: "Pocas gemas"
pile_gems: "Pila de gemas"
chest_gems: "Cofre de gemas"
purchasing: "Comprando..."
declined: "Su tarjeta fue rechazada"
retrying: "Error del servidor, recargando."
prompt_title: "Gemas insuficientes"
prompt_body: "¿Quieres obtener más?"
prompt_button: "Entrar al mercado"
recovered: "Se recuperaron las anteriores compras de gemas. Por favor recarga la página"
price: "x{{gems}} / mes"
buy_premium: "Comprar Premium"
purchase: "Compra"
purchased: "Comprado"
subscribe_for_gems:
prompt_title: "¡Gemas suficientes!"
prompt_body: "¡Suscríbete a Premium para obtener gemas y acceso a más niveles!"
earn_gems:
prompt_title: "Gemas Insuficientes"
prompt_body: "¡Sigue jugando para ganar más!"
subscribe:
best_deal: "¡La mejor ofera!"
confirmation: "¡Felicitaciones! Ahora tienes una suscripción Premium de CodeCombat!"
premium_already_subscribed: "¡Ya tienes una suscripción Premium!"
subscribe_modal_title: "CodeCombat Premium"
comparison_blurb: "Agudiza tus habilidades con la suscripción a CodeCombat!" # {change}
must_be_logged: "Debes iniciar sesión primero. Por favor crea una cuenta o inicia sesión desde el menú superior."
subscribe_title: "Suscribirse" # Actually used in subscribe buttons, too
unsubscribe: "Cancelar suscripción"
confirm_unsubscribe: "Confirmar cancelación de suscripción"
never_mind: "Olvidalo, Te sigo queriendo"
thank_you_months_prefix: "Gracias por tu apoyo en estos últimos"
thank_you_months_suffix: "meses."
thank_you: "Gracias por apoyar CodeCombat."
sorry_to_see_you_go: "¡Sentimos que te vayas! Por favor, haznos saber lo que podríamos haber hecho mejor."
unsubscribe_feedback_placeholder: "¿Pero qué hemos hecho?"
stripe_description: "Suscripción Mensual"
buy_now: "Comprar ahora"
subscription_required_to_play: "Necesitas una suscripción para jugar este nivel."
unlock_help_videos: "Suscríbete para desbloquear todos los video tutoriales."
personal_sub: "Suscripción Personal" # Accounts Subscription View below
loading_info: "Cargando información de suscripción..."
managed_by: "Administrado por"
will_be_cancelled: "Será cancelado en"
currently_free: "Actualmente tienes una suscripción gratuita"
currently_free_until: "Actualmente tienes una suscripción gratuita hasta"
free_subscription: "Suscripción gratuita"
was_free_until: "Tuviste una suscripción gratuita hasta"
managed_subs: "Suscripciones administradas"
subscribing: "Suscribiendo..."
current_recipients: "Recipientes actuales"
unsubscribing: "Dando de baja..."
subscribe_prepaid: "Click en suscribirse para utlizar un código prepago"
using_prepaid: "Usar código prepago para una suscribción mensual"
feature_level_access: "Accede a 300+ niveles disponibles"
feature_heroes: "Desbloquea héroes y mascotas exclusivas"
feature_learn: "Aprende a crear juegos y páginas web"
month_price: "$__price__"
first_month_price: "¡Sólo $__price__ en tu primer mes!"
lifetime: "Acceso de por vida"
lifetime_price: "$__price__"
year_subscription: "Suscripción anual"
year_price: "$__price__/por año"
support_part1: "¿Necesitas ayuda con el pago o prefieres Paypal? Correo electrónico"
support_part2: "<EMAIL>"
announcement:
now_available: "¡Ahora disponible para suscriptores!"
subscriber: "suscriptor"
cuddly_companions: "¡Compañeros de peluche!" # Pet Announcement Modal
kindling_name: "Elemental de Leña"
kindling_description: "Los Elemental de Leña sólo quieren mantenerte tibio durante la noche. Y durante el día. Todo el tiempo, realmente."
griffin_name: "<NAME>"
griffin_description: "Los Grifos son mitad ágila, mitad león, son adorables."
raven_name: "<NAME>"
raven_description: "Los Cuervos son excelentes para recolectar botellas brillantes llenas de salud para ti."
mimic_name: "<NAME>"
mimic_description: "Los Mimos pueden recoger monedas por tí. Colócalos sobre las monedas para aumentar tu suministro de oro."
cougar_name: "<NAME>"
cougar_description: "Los Pumas deberían ganar un doctorado por el ronroneo feliz de todos los días."
fox_name: "<NAME>"
fox_description: "¡Los zorros azules son muy inteligentes y les encanta cavar en la tierra y la nieve!"
pugicorn_name: "<NAME>"
pugicorn_description: "¡Los pugicornios son unas de las criaturas más raras y pueden lanzar hechizos!"
wolf_name: "<NAME>"
wolf_description: "¡Los Lobitos son excelentes en la caza, la recolección y jugando el escondite!"
ball_name: "<NAME>"
ball_description: "ball.squeak()"
collect_pets: "¡Consigue mascotas para tus héroes!"
each_pet: "¡Cada mascota tiene una habilidad de ayuda única!"
upgrade_to_premium: "Vuélvete un {{subscriber}} para usar mascotas."
play_second_kithmaze: "Juega {{the_second_kithmaze}} para desbloquear al Lobito!"
the_second_kithmaze: "El segundo Kithmaze"
keep_playing: "¡Sigue jugando para descubrir la primera mascota!"
coming_soon: "Muy pronto"
ritic: "Ritic el frío" # Ritic Announcement Modal
ritic_description: "Ritic elfrío. Atrapado en el glaciar <NAME> durante incontables edades, finalmente libre y listo para atender a los ogros que lo encarcelaron."
ice_block: "Un bloque de hielo"
ice_description: "Parece que hay algo atrapado adentro..."
blink_name: "Parpadeo"
blink_description: "Ritic desaparece y aparece en un abrir y cerrar de ojos, dejando nada más que una sombra."
shadowStep_name: "Pasombra"
shadowStep_description: "Un asesino maestro sabe como caminar entre las sombras."
tornado_name: "Tornado"
tornado_description: "Es bueno tener un botón de reinicio cuando la tapa está quemada."
wallOfDarkness_name: "Pared de la Oscuridad"
wallOfDarkness_description: "Se oculta detrás de un muro de sombras para evitar las miradas indiscretas."
avatar_selection:
pick_an_avatar: "Elige un avatar que te representará como jugador"
select_avatar_title: "Elige un avatar de jugador"
premium_features:
get_premium: "Obtén<br>CodeCombat<br>Premium" # Fit into the banner on the /features page
master_coder: "¡Conviértete en un programador experto suscribiéndote hoy!"
paypal_redirect: "Serás redirigido a PayPal para completar el proceso de suscripción."
subscribe_now: "Suscríbete ahora"
hero_blurb_1: "Accede a __premiumHeroesCount__ héroes super cargados sólo para suscriptores! Aprovecha el poder imparable de Okar Stompfoot, la precisión mortal de Naria of the Leaf, o invoca esqueletos \"adorables\" con Nalfar Cryptor."
hero_blurb_2: "Los Guerreros Premium desbloquean impresionantes habilidades marciales como Llanto de guerra, Paso firme y Lanzar enemigo. O, ¡juega como un arquero, usando sigilo y arcos, lanzando cuchillos y trampas! ¡Prueba tu habilidad como un verdadero mago programador, y ¡libera una poderosa variedad de magia Primordial, Nigromántica o Elemental!"
hero_caption: "¡Nuevos héroes emocionantes!"
pet_blurb_1: "Las mascotas no son solo compañeros adorables, sino que también proporcionan una funcionalidad y métodos únicos. El Grifo Bebé puede transportar unidades por el aire, el Lobito juega con las flechas del enemigo, al Puma le gusta perseguir a los ogros, ¡y el Mimo atrae monedas como un imán!"
pet_blurb_2: "¡Consigue todas las mascotas para descubrir sus habilidades únicas!"
pet_caption: "¡Adopta mascotas para que acompañen a tu héroe!"
game_dev_blurb: "¡Aprende scripts de juegos y crea nuevos niveles para compartir con tus amigos! Coloca los elementos que desees, escribe el código para la lógica y el comportamiento de la unidad, ¡y mira si tus amigos pueden superar el nivel!"
game_dev_caption: "¡Diseña tus propios juegos para desafiar a tus amigos!"
everything_in_premium: "Todo lo que obtienes en CodeCombat Premium:"
list_gems: "Recibe gemas de bonificación para comprar equipo, mascotas y héroes."
list_levels: "Obtén acceso a otros __premiumLevelsCount__ niveles"
list_heroes: "Desbloquea héroes exclusivos, incluye las clases Arquero y Mago"
list_game_dev: "Crea y comparte juegos con tus amigos"
list_web_dev: "Crea páginas web y aplicaciones interactivas"
list_items: "Equipa elementos únicos para Premium, como mascotas"
list_support: "Obtén soporte Premium para ayudarte a depurar código complicado"
list_clans: "Crea clanes privados para invitar a tus amigos y competir en una tabla de clasificación de grupo."
choose_hero:
choose_hero: "Elige tu héroe"
programming_language: "Lenguaje de programación"
programming_language_description: "¿Qué lenguaje de programación vas a elegir?"
default: "por Defecto"
experimental: "Experimental"
python_blurb: "Simple pero poderoso."
javascript_blurb: "El lenguaje de la web (no es Java)."
coffeescript_blurb: "JavaScript pero más bonito."
lua_blurb: "Lenguaje para Juegos."
java_blurb: "(Sólo para Suscriptiores) Android y Empresarial."
status: "Estado"
weapons: "Armas"
weapons_warrior: "Espada - Corto Alcance, Sin Magia"
weapons_ranger: "Ballestas, Armas - Largo Alcance, Sin Magia"
weapons_wizard: "Barita, - Largo Alcance, Mágico"
attack: "Daño" # Can also translate as "Attack"
health: "Salud"
speed: "Velocidad"
regeneration: "Regeneración"
range: "Rango" # As in "attack or visual range"
blocks: "Bloqueo" # As in "this shield blocks this much damage"
backstab: "Apuñala" # As in "this dagger does this much backstab damage"
skills: "Habilidades"
attack_1: "Ofertas"
attack_2: "de la lista"
attack_3: "daño de arma."
health_1: "Gana"
health_2: "de la lista"
health_3: "salud de la armadura."
speed_1: "Se mueve a"
speed_2: "metros por segundo."
available_for_purchase: "Disponible para Comprar" # Shows up when you have unlocked, but not purchased, a hero in the hero store
level_to_unlock: "Nivel para desbloquear:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see)
restricted_to_certain_heroes: "Sólo ciertos héroes pueden jugar este nivel."
char_customization_modal:
heading: "Personaliza a tu héroe"
body: "Cuerpo"
name_label: "Nombre del héroe"
hair_label: "Color de pelo"
skin_label: "Color de piel"
skill_docs:
function: "función" # skill types
method: "método"
snippet: "fragmento"
number: "número"
array: "arreglo"
object: "objeto"
string: "cadena"
writable: "escribible" # Hover over "attack" in Your Skills while playing a level to see most of this
read_only: "Sólo Lectura"
action: "Acción"
spell: "Conjuro"
action_name: "nombre"
action_cooldown: "Toma"
action_specific_cooldown: "Enfriamiento"
action_damage: "Daño"
action_range: "Rango"
action_radius: "Radio"
action_duration: "Duración"
example: "Ejemplo"
ex: "ej" # Abbreviation of "example"
current_value: "Valor actual"
default_value: "Valor por defecto"
parameters: "Parámetros"
required_parameters: "Parámetros Requeridos"
optional_parameters: "Parámetros Opcionales"
returns: "Devoluciones"
granted_by: "Concedido por"
description_coming_soon: "Descripción próximamente"
save_load:
granularity_saved_games: "Guardado"
granularity_change_history: "Historia"
options:
general_options: "Opciones Generales" # Check out the Options tab in the Game Menu while playing a level
volume_label: "Volúmen"
music_label: "Música"
music_description: "Música encendida/apagada."
editor_config_title: "Configuración del Editor" # {change}
editor_config_livecompletion_label: "Autocompletado automático" # {change}
editor_config_livecompletion_description: "Despliega sugerencias de autocompletado mientras escribes."
editor_config_invisibles_label: "Mostrar Invisibles"
editor_config_invisibles_description: "Visualiza invisibles tales como espacios o tabulaciones."
editor_config_indentguides_label: "Mostrar guías de indentación"
editor_config_indentguides_description: "Visualiza líneas verticales para ver mejor la indentación."
editor_config_behaviors_label: "Comportamientos Inteligentes" # {change}
editor_config_behaviors_description: "Autocompleta corchetes, llaves y comillas."
# editor_config_screen_reader_mode_label: "Enable Screen Reader Mode"
# editor_config_screen_reader_mode_description: "Display levels in text rather than visually."
about:
title: "Acerca de CodeCombat - Involucrar a estudiantes, empoderar a docentes, inspirar la creación"
meta_description: "Nuestra misión es equilibrar los niveles de informática mediante el aprendizaje basado en juego y hacer que la programación sea accesible para todo el que quiera aprender. Creemos que la programación es magia y queremos que los estudiantes tengan la capacidad de crear lo que quieran con solo imaginarlo."
learn_more: "Aprende más"
main_title: "Si queres aprender a programar, necesitas escribir (un montón de) código."
main_description: "En CodeCombat, nuestro trabajo es asegurarnos que estás haciendo eso con una sonrisa en tu cara."
mission_link: "Misión"
team_link: "Equipo"
story_link: "Historia"
press_link: "Prensa"
mission_title: "Nuestra misión: hacer accesible la programación para cada estudiante en la Tierra." # {change}
mission_teach: "Enseña a través de la aventura"
mission_desc_1: "En el mundo de hoy, los niños están bombardeados con entretenimiento que cada año se vuelve más atrapante. Cada aplicación, video, juego y publicidad se crea con el objetivo de captar y retener su atención. Para competir con esa situación, la educación debe encontrar maneras de retener la atención de los estudiantes y capturar su imaginación."
mission_desc_2: "Creemos que aprender ciencias de la computación puede ser fascinante. Debe parecer mágico. Después de todo, la programación le da a cualquiera la posibilidad de explorar nuevas ideas, construir algo a partir de la imaginación e interactuar con otros de nuevas maneras. Nuestra meta es inspirar una conexión con la creatividad y la imaginación inherentes de las ciencias de la computación creando videojuegos educativos que sean creativos e imaginativos."
mission_desc_3: "A lo largo de los últimos cinco años, más de doce millones de personas han aprendido a programar en Python y JavaScript con CodeCombat, lo que lo convirtió en uno de los juegos de programación más populares de la historia. Ahora nos complace anunciar Ozaria y ampliar nuestro compromiso de inspirar a una nueva generación de estudiantes a aprender ciencias de la computación. Ozaria es un juego de aventura que pone a cada estudiante en el centro de una historia legendaria en la que, para salvar al planeta Ozaria de la oscuridad inminente, deben dominar la magia perdida de la programación. A medida que la narrativa se desarrolla, se crea una gran experiencia de aprendizaje centrada en los estudiantes, en la cual el tiempo que cada alumno invierte en la historia de Ozaria equivale al tiempo que invierten en su propio camino de aprendizaje." # {change}
team_title: "Conoce al equipo de CodeCombat"
team_values: "Valoramos el diálogo abierto y respetuoso, donde gana la mejor idea. Nuestras decisiones se basan en la investigación del cliente y nuestro método se centra en obtener resultados tangibles para ellas. Todos están echando una mano, desde nuestro CEO hasta nuestros contribuidores en GitHub, porque en nuestro equipo valoramos el crecimiento y el aprendizaje. " # {change}
nick_title: "<NAME>"
csm_title: "Gerente de relaciones comerciales"
scsm_title: "Gerente de relaciones comerciales senior"
ae_title: "Ejecutivo de cuentas"
sae_title: "Ejecutivo de cuentas senior"
sism_title: "Gerente de ventas internas senior"
shan_title: "Encargada principal de establecimiento de asociaciones, China"
run_title: "Jefe de operaciones, China"
lance_title: "Pasante de ingeniería de software, China"
zhiran_title: "Jefa de planes de estudio, China"
yuqiang_title: "Jefe de innovación, China"
swe_title: "Ingeniero de software"
sswe_title: "Ingeniero de software senior"
css_title: "Especialista en atención al cliente"
css_qa_title: "Especialista en atención al cliente / control de calidad"
maya_title: "Desarrolladora de planes de estudio senior"
bill_title: "Gerente general, China"
pvd_title: "Diseñador visual y de productos"
spvd_title: "Diseñador visual y de productos senior"
daniela_title: "Gerente de marketing"
bobby_title: "Diseñador de juegos"
brian_title: "Diseñador de juegos principal" # {change}
stephanie_title: "Especialista en atención al cliente"
sdr_title: "Representante de desarrollo de ventas"
retrostyle_title: "Ilustración"
retrostyle_blurb: "Juegos con estilo Retro"
community_title: "...y nuestra comunidad open-source"
bryukh_title: "Desarrollador de jugabilidad senior"
oa_title: "Asistente de operaciones"
ac_title: "Coordinador administrativo"
ea_title: "Asistente ejecutivo"
om_title: "Gerente de operaciones"
mo_title: "Gerente de operaciones"
smo_title: "Gerente de operaciones senior"
scd_title: "Desarrollador de planes de estudio senior"
lcd_title: "Desarrollador de planes de estudio principal"
vpm_title: "Vicepresidente de marketing"
community_subtitle: "¡Más de 450 contribuidores que ayudaron a contruir CodeCombat, y más uniendose cada semana!" # {change}
community_description_3: "CodeCombat es un"
community_description_link_2: "proyecto comunitario"
community_description_1: "CodeCombat es un proyecto comunitario, con cientos de jugadores haciendo trabajo voluntario al crear niveles, contribuir a nuestro código para añadir características, arreglar bugs, testear, e incluso traducir el juego a 50 idiomas hasta ahora. Empleados, contribuidores y la página ganan al compartir las ideas Echa un vistazo a nuestra" # {change}
community_description_link: "página de contribución"
community_description_2: "para más información."
number_contributors: "Más de 450 contribuidores dieron su apoyo y tiempo a este proyecto."
story_title: "Nuestra historia hasta ahora"
story_subtitle: "Desde 2013, CodeCombat creció desde un mero conjunto de bocetos hasta un juego próspero, vivo."
story_statistic_1a: "+5,000,000" # {change}
story_statistic_1b: "jugadores totales"
story_statistic_1c: "comenzaron su viaje en la programación mediante CodeCombat" # {change}
story_statistic_2a: "We’ve been translated into over 50 languages — nuestros jugadores son de"
story_statistic_2b: "+200 países" # {change}
story_statistic_3a: "Juntos, escribieron"
story_statistic_3b: "1 mil millones de líneas de código, y contando"
story_statistic_3c: "en seis lenguajes de programación distintos" # {change}
story_long_way_1: "Aunque hemos recorrido un largo camino..."
story_sketch_caption: "El primer boceto de Nick representando un juego de programación en acción."
story_long_way_2: "todavía nos queda mucho por hacer antes de que completemos nuestra misión, asi que..."
jobs_title: "¡Ven a trabajar con nosotros y ayuda a escribir la historia de CodeCombat!" # {change}
jobs_subtitle: "¿No encontras una buena opción pero estás interesado en mantener el contacto? Mirá nuestra entrada \"Crear Tu Propio\"."
jobs_benefits: "Beneficios del empleado"
jobs_benefit_4: "Días personales/enfermo ilimitados" # {change}
jobs_benefit_5: "Desarrollo profesional y soporte de formación continua" # {change}
jobs_benefit_6: "Seguro médico/dental/vista" # {change}
jobs_benefit_9: "Ventana opcional de ejercicio por 10 años"
jobs_benefit_10: "Permiso de maternidad: 12 semanas pagadas, luego 6 @ 55% del salario"
jobs_benefit_11: "Permiso de paternidad: 12 semanas pagadas"
jobs_custom_title: "Crear Tu Propio"
jobs_custom_description: "¿Te apasiona CodeCombat pero nos ves un puesto de trabajo que coincida con tus cualificaciones? Escríbenos y muestrenos como cree que puede contribuir a nuestro equipo. ¡Nos encantaría saber de vos!"
jobs_custom_contact_1: "¡Envíanos una nota a"
jobs_custom_contact_2: "presentándote y ¡podremos estar en contacto en el futuro!"
contact_title: "Prensa & Contacto"
contact_subtitle: "¿Necesitas más información? Contáctanos en"
press_subtitle: "o visita nuestro sitio de prensa en"
screenshots_title: "Capturas de pantalla del Juego"
screenshots_hint: "(click para ver en tamaño completo)"
downloads_title: "Descargar Recursos & Información"
about_codecombat: "Acerca de CodeCombat"
logo: "Logo"
screenshots: "Capturas de pantalla"
character_art: "Arte de Personajes"
download_all: "Descargar Todo"
previous: "Anterior"
location_title: "Nos encontramos en el centro de SF:"
teachers:
licenses_needed: "Licencias necesarias"
google_classroom_disabled_text: "Para vincular Google Classroom, inicia sesión con el SSO de Google"
select_class: "Selecciona una clase"
programming_language: "Lenguaje de programación"
programming_language_edit_desc: "No es posible cambiar el lenguaje una vez que ya hay estudiantes en la clase. Recomendamos crear una nueva clase para los mismos estudiantes."
add_a_class: "Agregar una clase nueva"
select_desired_lang: "Seleccionar el idioma de la clase"
elementary: "Primaria (elementary school)"
middle: "Intermedia (middle school)"
high_school: "Secundaria (high school)"
class_name: "Nombre de la clase"
grades: "Grados"
select_all_that_apply: "Selecciona las opciones que correspondan"
class_info_modal_sub_title: "Para invitar a los estudiantes a que se unan a tu clase, envíales lo siguiente:"
class_url: "Enlace de la clase"
class_url_desc: "Comparte el enlace para que los estudiantes se unan a tu clase tras registrarse"
class_code: "Código de la clase"
class_code_desc: "Los estudiantes pueden ingresar este código al registrarse en www.ozaria.com"
invite_by_email: "Invitación por correo electrónico"
# regenerate_class_code: "Regenerate"
invite_modal_sub_title: "Separa cada dirección de correo con un salto de línea o una coma"
no_new_students_imported: "No se importó ningún estudiante nuevo"
error_in_importing_classrooms: "Error al importar aulas"
error_in_importing_students: "Error al importar estudiantes"
no_licenses_page:
are_your_students_ready: "¿Tus estudiantes están entusiasmados por aprender más?"
once_students_have_completed: "Una vez que los estudiantes hayan completado el capítulo 1, necesitarán licencias para continuar aprendiendo con los próximos capítulos."
get_licenses: "Conseguir licencias"
get_full_access_to_ozaria: "Obtener acceso completo a Ozaria"
unlock_all: "Desbloquea todo lo anterior y recibe apoyo para maestros"
unlock_all_dsa: "Desbloquea todo lo anterior y todo el apoyo que necesitan los maestros"
comprehensive_dashboards: "Paneles muy completos para maestros y administradores"
lesson_plans_rubrics_guides: "Planes de estudios, guías de evaluación, guías de soluciones y más"
dedicated_customer_success_manager: "Un gerente exclusivo de satisfacción del cliente"
automatic_access: "Acceso automático a nuevas funciones y contenido"
license_quote: "\"En mi opinión, como maestro veterano de secundaria con 26 años de experiencia, no existe mejor recurso para enseñar programación\"."
join_our_community: "Únete a nuestra comunidad"
join_our_community_desc: "Más de 12 millones de personas han aprendido a escribir en Python y JavaScript con CodeCombat. Ahora te invitamos a unirte a nuestra comunidad de más de 82 000 educadores y 25 000 escuelas que usan Ozaria, un programa diseñado para docentes que quieren inspirar a la nueva generación de estudiantes a aprender Ciencias de la Computación."
teach_real_typed_code: "Enseña código real y práctico"
teach_real_typed_code_desc: "Los estudiantes aprenden Python y JavaScript, los dos lenguajes de programación más populares, y desarrollan habilidades del siglo XXI que les servirán para cualquier carrera."
support_student_progress: "Ayuda a los estudiantes a progresar"
support_student_progress_desc: "Obtén datos de evaluaciones formativas y sumativas a partir de comprobaciones de conceptos, niveles y proyectos finales para ayudar a los estudiantes a progresar."
creative_projects: "Proyectos creativos"
creative_projects_desc: "Despierta la imaginación y desata la creatividad de tus estudiantes con los proyectos finales. Por ejemplo, en el capítulo 2, deben diseñar su propio juego narrativo, que luego pueden compartir con quien quieran. "
looking_for_engaging: "¿Estás buscando un plan de estudios de Ciencias de la Computación interesante?"
licenses_are_required: "Para que los estudiantes continúen su camino después del capítulo 1, necesitarán licencias."
real_world_skills: "Habilidades del mundo real"
real_world_skills_desc: "Los estudiantes aprenden a escribir Python y JavaScript, los dos lenguajes de programación más populares, y perfeccionan sus habilidades de pensamiento crítico, su creatividad y su resiliencia, lo que les servirá para cualquier carrera."
personalized_learning: "Aprendizaje personalizado y enseñanza escalonada"
personalized_learning_desc: "Los estudiantes aprenden conceptos a su propio ritmo. Los niveles aumentan de dificultad a la vez que dan pistas predefinidas para fomentar la persistencia y la determinación."
flexible_curriculum: "Planes de estudio flexibles y alineados con estándares"
flexible_curriculum_desc: "Planes de estudio 100% alineados con la norma CSTA que se pueden adaptar con facilidad a cualquier cronograma, situación o entorno."
resources_to_support: "Recursos para ayudar a los maestros"
resources_to_support_desc: "Planificaciones de clases, actividades de extensión, guías curriculares y más recursos educativos diseñados para funcionar en entornos remotos e híbridos."
actionable_insights: "Información útil para maestros"
actionable_insights_desc: "Empodera a los educadores con datos intuitivos sobre el progreso y las evaluaciones de los estudiantes que posibilitan la enseñanza diferenciada."
special_offer:
special_offer: "Oferta Especial"
project_based_title: "Cursos basados en proyectos"
project_based_description: "Los cursos de desarrollo web y de juegos presentan proyectos finales compartibles."
great_for_clubs_title: "Ideal para clubes y clases electivas"
great_for_clubs_description: "Los maestros pueden comprar hasta __maxQuantityStarterLicenses__ Licencias de Principiante."
low_price_title: "Sólo __starterLicensePrice__ por estudiante"
low_price_description: "Las Licencias de Principiante se mantienen activas por for __starterLicenseLengthMonths__ meses desde la compra."
three_great_courses: "Tres grandes cursos incluidos en la Licencia de Principiante:"
license_limit_description: "Los maestros pueden comprar hasta __maxQuantityStarterLicenses__ Licencias de Principiante. Ya has comprado __quantityAlreadyPurchased__. Si necesitas más, contacta a __supportEmail__. Las Licencias de Principiante son válidas por __starterLicenseLengthMonths__ meses."
student_starter_license: "Licencia de Estudiante Principiante"
purchase_starter_licenses: "Comprar Licencias de Principiante"
purchase_starter_licenses_to_grant: "Compra Licencias de Principiante para acceder a __starterLicenseCourseList__"
starter_licenses_can_be_used: "Licencias de Principiante pueden usarse para agregar cursos adicionales inmediatamente luego de la compra."
pay_now: "Paga Ahora"
we_accept_all_major_credit_cards: "Aceptamos las principales tarjetas de crédito."
cs2_description: "se basa en la base de Introducción a las Ciencias de la Computación, adentrándose en declaraciones if, funciones, eventos y más."
wd1_description: "presenta los conceptos básicos de HTML y CSS al tiempo que enseña las habilidades necesarias para que los estudiantes construyan su primera página web."
gd1_description: "usa la sintaxis con la que los estudiantes ya están familiarizados para mostrarles cómo construir y compartir sus propios niveles de juego."
see_an_example_project: "mira un proyecto de ejemplo"
get_started_today: "¡Comienza Hoy!"
want_all_the_courses: "¿Quieres todos los cursos? Solicita información de nuestras Licencias Completas."
compare_license_types: "Compara los Typos de Licencia:"
cs: "Ciencias de la Computación"
wd: "Desarrollo Web"
wd1: "Desarrollo Web 1"
gd: "Desarrollo de Videojuegos"
gd1: "Desarrollo de Videojuegos 1"
maximum_students: "# Máximo de Estudiantes"
unlimited: "Ilimitado"
priority_support: "Apoyo prioritario"
yes: "Si"
price_per_student: "__price__ por estudiante "
pricing: "Precios"
free: "Gratis"
purchase: "Comprar"
courses_prefix: "Cursos"
courses_suffix: ""
course_prefix: "Curso"
course_suffix: ""
teachers_quote:
subtitle: "¡Obtén CodeCombat en tu clase, club, escuela o distrito!" # {change}
email_exists: "Existe un usuario con este email."
phone_number: "Teléfono"
phone_number_help: "¿Dónde podemos contactarte durante el horario de trabajo ?"
primary_role_label: "Tu Rol Primario"
role_default: "Seleccione Rol"
primary_role_default: "Seleccione Rol Primario"
purchaser_role_default: "Seleccione Rol de Comprador"
teacher: "<NAME>"
tech_coordinator: "Coordinador de tecnología"
advisor: "<NAME>" # {change}
principal: "<NAME>"
superintendent: "<NAME>"
parent: "Padre"
purchaser_role_label: "Tu Rol de Comprador"
influence_advocate: "Influencia/Partidario"
evaluate_recommend: "Evaluar/Recomendar"
approve_funds: "Aprobar Fondos"
no_purchaser_role: "Ningún papel en las decisiones de compra"
district_label: "Distrito"
district_name: "Nombre del Distrito"
district_na: "Ingresa N/A si no aplica"
organization_label: "Escuela / Distrito" # {change}
school_name: "Nombre de la Escuela"
city: "Ciudad"
state: "Estado" # {change}
country: "País"
num_students_help: "¿Cuántos prevees inscribir en CodeCombat?" # {change}
num_students_default: "Seleccionar Rango"
education_level_label: "Nivel Educativo de los Estudiantes"
education_level_help: "Elegí todas las que correspondan."
elementary_school: "Escuela Primaria"
high_school: "Escuela Secundaria"
please_explain: "(describa, por favor)"
middle_school: "Escuela Intermedia"
college_plus: "Universidad o superior"
referrer: "¿Cómo supiste de nosotros?"
referrer_help: "Por ejemplo: por otro maestro, una conferencia, tus estudiantes, Code.org, etc."
referrer_default: "Selecciona Una"
referrer_conference: "Conferencia (p. ej. ISTE)"
referrer_hoc: "Code.org/Hour of Code"
referrer_teacher: "Un Maestro"
referrer_admin: "Un Administrador"
referrer_student: "Un Estudiante"
referrer_pd: "Capacitaciones/Talleres Profesionales"
referrer_web: "Google"
referrer_other: "Otro"
anything_else: "¿Algo más que deberíamos saber?" # {change}
thanks_header: "¡Gracias por solicitar un presupuesto!" # {change}
thanks_sub_header: "Gracias por el interés de su institución en CodeCombat" # {change}
thanks_p: "Estaremos en contacto pronto. ¿Preguntas? Escríbenos:" # {change}
back_to_classes: "Volver a las clases"
finish_signup: "Termine la creación de su cuenta de maestro:"
finish_signup_p: "Crear una cuenta para configurar la clase, agregar estudiante y monitorear su progreso a medida que aprenden programacioón"
signup_with: "Registrarse con:"
connect_with: "Conectar con:"
conversion_warning: "ADVERTENCIA: Su cuenta actual es de tipo <em>Estudiante</em>. Una vez que envie este formulario, su cuenta será actualizada como cuenta de maestro."
learn_more_modal: "Cuentas de maestro en CodeCombat tienen la ventaja de monitorear el progreso del estudiante, asignar inscripciónes y administrar salones de clases. Cuentas de maestro no pueden ser parte de los salones de clases. Si usted está registrado en una clase utilizando una cuenta de estudiante, no podrá acceder hasta que tenga una Cuenta de maestro." # {change}
create_account: "Crear una Cuenta de maestro"
create_account_subtitle: "Obtenga acceso a herramientas exclusivas para maestros de CodeCombat. <strong>Configurar una clase</strong>, agregar estudiantes, y <strong>monitorear su progreso</strong>!"
convert_account_title: "Actualizar mi perfil a Cuenta de maestro"
not: "No"
full_name_required: "Nombre y apellido requeridos"
versions:
save_version_title: "Guardar nueva versión"
new_major_version: "Nueva Gran Versión"
submitting_patch: "Publicando Parche..."
cla_prefix: "Para guardar los cambios, primero debes estar de acuerdo con nuestro"
cla_url: "CLA"
cla_suffix: "."
cla_agree: "ACEPTO"
owner_approve: "Necesita la aprobación de un propietario para que los cambios sean visibles."
contact:
contact_us: "Contacta a CodeCombat"
welcome: "¡Qué bueno es escuchar algo de ti! Usa este formulario para enviarnos un mensaje"
forum_prefix: "Para cualquier cosa pública, por favor prueba "
forum_page: "nuestro foro "
forum_suffix: "en su lugar."
faq_prefix: "También hay un"
faq: "FAQ"
subscribe_prefix: "Si necesitas ayuda para resolver un nivel, por favor"
subscribe: "compra una suscripción de CodeCombat"
subscribe_suffix: "y nosotros estaremos felices de ayudarte con tu código."
subscriber_support: "Como estás suscrito a CodeCombat, tu email tendrá prioridad."
screenshot_included: "Captura de pantalla incluida."
where_reply: "¿A dónde deberíamos responder?"
send: "Enviar Comentario"
account_settings:
title: "Configuración de la Cuenta"
not_logged_in: "Inicia sesión o crea una cuenta para cambiar tu configuración."
me_tab: "Yo"
picture_tab: "Imagen"
delete_account_tab: "Borra tu cuenta"
wrong_email: "Mail Incorrecto"
wrong_password: "<PASSWORD>"
delete_this_account: "Borrar esta cuenta permanentemente"
reset_progress_tab: "Reiniciar Todo Progreso"
reset_your_progress: "Limpiar todo tu progreso y comenzar de nuevo"
god_mode: "Modo Dios"
emails_tab: "Correos"
admin: "Admin"
manage_subscription: "Click aquí para administrar tu subscripción"
new_password: "<PASSWORD>"
new_password_verify: "Verificar"
type_in_email: "Ingrese su correo electrónico para confirmar la eliminación de su cuenta." # {change}
type_in_email_progress: "Ingrese su correo para confirmar la eliminación de su progreso."
type_in_password: "<PASSWORD>, ingrese su contraseña."
email_subscriptions: "Suscripciones de Email"
email_subscriptions_none: "No tienes suscripciones."
email_announcements: "Noticias"
email_announcements_description: "Recibe correos electrónicos con las últimas noticias y desarrollos de CodeCombat."
email_notifications: "Notificaciones"
email_notifications_summary: "Controles para tus notificaciones por correo electrónico automáticas y personalizadas relativas a tu actividad en CodeCombat."
email_any_notes: "Algunas notificaciones"
email_any_notes_description: "Desactiva para detener toda la actividad de correos de notificaciones."
email_news: "Noticias"
email_recruit_notes: "Oportunidades Laborales"
email_recruit_notes_description: "Si juegas realmente bien podríamos contactarte para ofrecerte un (mejor) trabajo."
contributor_emails: "Emails Clase Contribuyente"
contribute_prefix: "¡Estamos buscando gente que se una a nuestro grupo! Echa un vistazo a la "
contribute_page: "página de contribución"
contribute_suffix: "para averiguar más."
email_toggle: "Activar Todo"
error_saving: "Error al Guardar"
saved: "Cambios Guardados"
password_mismatch: "La contraseña no coincide."
password_repeat: "Por favor repita su contraseña."
keyboard_shortcuts:
keyboard_shortcuts: "Atajos de teclado"
space: "Barra espaciadora"
enter: "Enter"
press_enter: "Toca enter"
escape: "Escape"
shift: "Shift"
run_code: "Ejecutar el código."
run_real_time: "Ejecutar en tiempo real."
continue_script: "Continuar hasta finalizado el script."
skip_scripts: "Omitir todos los scripts omitibles."
toggle_playback: "Aplicar ejecutar/pausar."
scrub_playback: "Devolverse y avanzar en el tiempo."
single_scrub_playback: "Devolverse y avanzar en el tiempo de a un cuadro."
scrub_execution: "Scrub through la ejecución del hechizo actual."
toggle_debug: "Mostrar/ocultar depuración."
toggle_grid: "Mostrar/ocultar rejilla."
toggle_pathfinding: "Mostrar/ocultar buscador de rutas."
beautify: "Hacer bello tu código estandarizando formato."
maximize_editor: "Maximizar/minimizar editor de código."
cinematic:
click_anywhere_continue: "haz clic en cualquier lado para continuar" # {change}
instructional_tooltip: "Haz clic en los botones de flechas para avanzar o retroceder. También puedes usar las teclas de dirección del teclado."
community:
main_title: "Comunidad CodeCombat"
introduction: "Mira las maneras en las que puedes involucrarte adelante y decide qué es más divertido. ¡Queremos trabajar contigo!"
level_editor_prefix: "Usar CodeCombat"
level_editor_suffix: "para crear y editar niveles. Los han creado niveles para sus clases, amigos, hackatones, estudiantes, familiares. Si crear un nuevo juego luce intimidante puedes ¡comenzar con base en uno nuestro!"
thang_editor_prefix: "Nosotros llamamos a las unidades del juego 'Tiliches'. Usa el"
thang_editor_suffix: "para modificar el arte de CodeCombat. Permite a las unidades lanzar proyectiles, altera la dirección de una animación, cambia los puntos de vida de una unidad o sube tu propio sprite de vectores."
article_editor_prefix: "¿Ves algún error en nuestros documentos? ¿Quieres hacer algunas instrucciones para tus propias creaciones? Revisa el"
article_editor_suffix: "y ayuda a los jugadores de CodeCombat conseguir lo más posible de su tiempo jugando."
find_us: "Encuentranos en etsos sitios"
social_github: "Revisa todo nuestro código en GitHub"
social_blog: "Lee el blog de CodeCombat en Sett"
social_discource: "Únete a la discusión en nuestro foro"
social_facebook: "Me Gusta CodeCombat en Facebook"
social_twitter: "Sigue a CodeCombat en Twitter"
social_gplus: "Únete a CodeCombat con Google+"
social_slack: "Conversa con nosotros en nuestro canal de Slack"
contribute_to_the_project: "Contribuir al proyecto"
clans:
title: "Únete a los clanes de CodeCombat - Aprende a programar en Python, JavaScript y HTML"
clan_title: "__clan__ - Únete a los clanes de CodeCombat y aprende a programar"
meta_description: "Únete a un clan o crea tu propia comunidad de programadores. Juega en niveles de arena multijugador y mejora tu héroe y tus habilidades de programación."
clan: "Clan"
clans: "Clanes"
new_name: "Nuevo nombre de clan"
new_description: "descripción del clan"
make_private: "Hacer clan privado"
subs_only: "solo suscriptores"
create_clan: "Crear nuevo clan"
private_preview: "Vista previa"
private_clans: "Clanes Privados"
public_clans: "Clanes publicos"
my_clans: "Mis Clanes"
clan_name: "Nombre del clan"
name: "<NAME>"
chieftain: "Líder del Clan"
edit_clan_name: "Editar el nombre del Clan"
edit_clan_description: "Editar descripción del clan"
edit_name: "editar nombre"
edit_description: "editar descripción"
private: "(privado)"
summary: "Resumen"
average_level: "Nivel Promedio"
average_achievements: "Logros Promedio"
delete_clan: "Borrar Clan"
leave_clan: "Abandonar Clan"
join_clan: "Ingresar Clan"
invite_1: "Invitar:"
invite_2: "*Invitar jugadores al clan, mandandoles este link."
members: "<NAME>"
progress: "Progreso"
not_started_1: "no iniciado"
started_1: "iniciado"
complete_1: "completo"
exp_levels: "Expand levels"
rem_hero: "Remover Heróe"
status: "Estado"
complete_2: "Completo"
started_2: "Iniciado"
not_started_2: "No iniciado"
view_solution: "Click para ver la solución."
view_attempt: "Click para ver intento."
latest_achievement: "último logro"
playtime: "Tiempo de juego"
last_played: "Último jugado"
leagues_explanation: "Juega en una liga contra otros miembros del clan en estas instancias de arena multijugador."
track_concepts1: "Haga un seguimiento de los conceptos"
track_concepts2a: "aprendidos por cada estudiante"
track_concepts2b: "aprendidos por cada miembro"
track_concepts3a: "Haga un seguimiento de los niveles completados por cada estudiante"
track_concepts3b: "Haga un seguimiento de los niveles completados por cada miembro"
track_concepts4a: "Ve a tus estudiantes'"
track_concepts4b: "Ve a tus miembros'"
track_concepts5: "soluciones"
track_concepts6a: "Ordene a sus estudiantes por nombre o progreso"
track_concepts6b: "Ordene a sus miembros por nombre o progreso"
track_concepts7: "Requiere invitación"
track_concepts8: "para unirse"
private_require_sub: "Los clanes privados requieren una suscripción para crearlos o unírseles."
courses:
create_new_class: "Crear Nueva Clase"
hoc_blurb1: "Intenta"
hoc_blurb2: "Programa, Juega, Comparte"
hoc_blurb3: "¡actividad! Construye cuatro minijuegos diferentes para aprender los conceptos básicos del desarrollo de juegos, ¡luego crea los tuyos!"
solutions_require_licenses: "Las soluciones de nivel están disponibles para los maestros que tienen licencias."
unnamed_class: "Grupo Anónimo"
edit_settings1: "Editar Configuraciónes de Grupos"
add_students: "Agregar Estudiantes"
stats: "Estadísticas"
student_email_invite_blurb: "Sus estudiantes también pueden usar el código de clase <strong> __classCode__ </strong> al crear una Cuenta de Estudiante, no se requiere correo electrónico."
total_students: "Total de Estudiantes:"
average_time: "Tiempo Promedio de juego por nivel:"
total_time: "Tiempo total de juego:"
average_levels: "Niveles Promedio completados:"
total_levels: "Total de niveles completados:"
students: "Estudiantes"
concepts: "Con ceptos"
play_time: "Tiempo de Juego:"
completed: "Completados:"
enter_emails: "Introducir los emails de los estudiantes a invitar, uno por línea" # {change}
send_invites: "¿Mandar Invitaciones?" # {change}
number_programming_students: "Número de Estudiantes"
number_total_students: "Total de Estudiantes en Escuela/Distrito/Facultad"
enroll: "Inscribirse"
enroll_paid: "Anotar estudiantes en cursos pagos."
get_enrollments: "Obtener Más Matrículas"
change_language: "Cambiar idioma del curso"
keep_using: "Seguir Usando"
switch_to: "Cambiar a"
greetings: "Saludos!"
back_classrooms: "Volver a mis aulas"
back_classroom: "Volver a mi aula" # {change}
back_courses: "Volver a mis cursos" # {change}
edit_details: "Editar detalles de clase"
purchase_enrollments: "Comprar Matrículas" # {change}
remove_student: "Eliminar alumno"
assign: "Asignar"
to_assign: "para asignar cursos pagos."
student: "<NAME> <NAME>"
teacher: "<NAME>"
arena: "Arena"
available_levels: "Niveles Disponibles"
started: "iniciado"
complete: "completado"
practice: "práctica"
required: "obligatorio"
welcome_to_courses: "Aventureros, Bienvenidos a los Cursos!"
ready_to_play: "¿Estás listo?"
start_new_game: "Iniciar un Nuevo Juego"
play_now_learn_header: "Juega y Aprende"
play_now_learn_1: "Sintaxis básica para controlar a tu personaje"
play_now_learn_2: "bucles while para resolver rompecabezas molestos"
play_now_learn_3: "cadenas y variables para personalizar acciones"
play_now_learn_4: "como vencer a un ogro (¡habilidades importantes en la vida!)"
welcome_to_page: "¡Bienvenido a tu página de cursos!" # {change}
my_classes: "Mis Clases" # {change}
class_added: "¡Clase añadida satisfactoriamente!"
view_map: "ver mapa"
view_videos: "ver videos"
view_project_gallery: "ver proyectos de mis compañeros"
join_class: "Unirse a clase" # {change}
join_class_2: "Unirse a clase"
ask_teacher_for_code: "Preguntalé a tu maestro si tu tienes un código de CodeCombat! Si lo tiene, ingresalo debajo:" # {change}
enter_c_code: "<Ingresar Código de la Clase>" # {change}
join: "Unirse"
joining: "Uniéndose a clase __claseJoining__ "
unit_complete: "Unidad completada"
play_arena: "Jugar Arena"
view_project: "Ver Proyecto"
start: "Iniciar"
last_level: "Último nivel" # {change}
not_you: "¿No eres tú?"
continue_playing: "Seguir jugando"
option1_header: "Opción 1: Invitar estudiantes vía email" # {change}
remove_student1: "Quitar alumno"
are_you_sure: "¿Estás seguro que quieres eliminar a este alumno de tu clase?"
remove_description1: "El estudiante perderá acceso a esta aula y a sus clases asignadas. El progreso y la experiencia del juego NO se pierde, y el estudiante puede ser agregado de vuelta al aula en cualquier momento."
remove_description2: "La matrícula paga activada no será devuelta."
license_will_revoke: "La licencia paga de este estudiante será revocada y estará disponible para asignarla a otro estudiante."
keep_student: "Mantener alumno"
removing_user: "Eliminando usuario"
subtitle: "Revisar guías del curso, soluciones y niveles." # {change}
changelog: "Ver los últimos cambios en los niveles del curso."
select_language: "Seleccionar lenguaje"
select_level: "Seleccionar nivel"
play_level: "Jugar Nivel"
concepts_covered: "Conceptos Cubiertos"
view_guide_online: "Ver Guía En Línea(PDF)" # {change}
grants_lifetime_access: "Otorgar derecho de acceso a todos los cursos."
enrollment_credits_available: "Créditos de Inscripción Disponibles :" # {change}
language_select: "Seleccionar Lenguaje" # ClassroomSettingsModal
language_cannot_change: "El lenguaje no puede ser cambiado una vez que el estudiante ingreso a la clase."
avg_student_exp_label: "Promedio de la experiencia en programación del estudiante"
avg_student_exp_desc: "Esto nos ayudará a entender como llevar el ritmo de los cursos."
avg_student_exp_select: "Selecciona la mejor opción"
avg_student_exp_none: "Sin experiencia - poca o ninguna experiencia"
avg_student_exp_beginner: "Principiante - cierto grado de exposición o basado en bloque"
avg_student_exp_intermediate: "Intermedio - un poco de experiencia con código escrito"
avg_student_exp_advanced: "Avanzado - amplia experiencia con código escrito"
avg_student_exp_varied: "Niveles Variados de Experiencia"
student_age_range_label: "Rango de Edad del Estudiante"
student_age_range_younger: "Menor que 6"
student_age_range_older: "Mayor que 18"
student_age_range_to: "a"
estimated_class_dates_label: "Fechas Estimadas de Clase"
estimated_class_frequency_label: "Frecuencia Estimada de Clase"
classes_per_week: "clases por semana"
minutes_per_class: "minutos por clase"
create_class: "Crear Grupo"
class_name: "Nombre de clase"
teacher_account_restricted: "Tu cuenta es una cuenta de maestro, y no puedes acceder al contenido del estudiante." # {change}
account_restricted: "Necesitas una cuenta de Estudiante para acceder a esta pagina."
update_account_login_title: "Inicia sesión para actualizar tu cuenta"
update_account_title: "¡Tu cuenta necesita atención!"
update_account_blurb: "Antes de acceder a tus clases, selecciona como quieres usar esta cuenta."
update_account_current_type: "Tipo de Cuenta Actual:"
update_account_account_email: "Nombre/Correo electrónico de la Cuenta:"
update_account_am_teacher: "Soy un Maestro"
update_account_keep_access: "Mantener el acceso a las clases que he creado"
update_account_teachers_can: "Las cuentas de maestro pueden:"
update_account_teachers_can1: "Crear/administrar/agregar clases"
update_account_teachers_can2: "Asignar/inscribir estudiantes en cursos"
update_account_teachers_can3: "Desbloquea todos los niveles del curso para probar"
update_account_teachers_can4: "Accede a las nuevas funciones solo para maestros a medida que las lanzamos"
update_account_teachers_warning: "Advertencia: se lo eliminará de todas las clases a las que se haya unido anteriormente y no podrá jugar como estudiante."
update_account_remain_teacher: "Mantener Maestro"
update_account_update_teacher: "Actualizar Maestro"
update_account_am_student: "Soy un estudiante"
update_account_remove_access: "Eliminar acceso a las clases que he creado"
update_account_students_can: "Las cuentas de Estudiante pueden:"
update_account_students_can1: "Unirse a classes"
update_account_students_can2: "Juega a través de cursos como estudiante y sigue tu propio progreso"
update_account_students_can3: "Compite contra otros compañeros en arenas"
update_account_students_can4: "Accede a nuevas funciones solo para estudiantes a medida que las lanzamos"
update_account_students_warning: "Advertencia: No podrá administrar ninguna clase que haya creado anteriormente o crear nuevas clases."
unsubscribe_warning: "Advertencia: Se le dará de baja de su suscripción mensual."
update_account_remain_student: "Manener Estudiante"
update_account_update_student: "Actualizar Estudiante"
need_a_class_code: "Necesitarás un Código de Clase para la clase a la que te estás uniendo:"
update_account_not_sure: "¿No sabes cuál elegir? Correo electrónico"
update_account_confirm_update_student: "¿Estás seguro de que deseas actualizar tu cuenta a una experiencia de estudiante?"
update_account_confirm_update_student2: "No podrás administrar ninguna clase que hayas creado anteriormente o crear nuevas clases. Las clases creadas anteriormente se eliminarán de CodeCombat y no se podrán restaurar."
instructor: "Instructor: "
youve_been_invited_1: "Has sido invitado para unirte "
youve_been_invited_2: ", donde aprenderás "
youve_been_invited_3: " con tus compañeros en CodeCombat."
by_joining_1: "Unié<NAME> "
by_joining_2: "podrás ayudar a restablecer tu contraseña si la olvidas o la pierdes. También puedes verificar tu dirección de correo electrónico para que puedas restablecer la contraseña tu mismo."
sent_verification: "Hemos enviado un correo electrónico de verificación a:"
you_can_edit: "Puedes editar tu dirección de correo electrónico en "
account_settings: "Configuración de Cuenta"
select_your_hero: "Selecciona tu Héroe"
select_your_hero_description: "Siempre puedes cambiar tu héroe entrando en tu página de Cursos y haciendo click en \"Cambiar Héroe\""
select_this_hero: "Seleccionar este Héroe"
current_hero: "Héroe Actual:"
current_hero_female: "Heroína Actual:"
web_dev_language_transition: "Todas las clases programan en HTML / JavaScript para este curso. Las clases que han estado usando Python comenzarán con niveles de introducción de JavaScript adicionales para facilitar la transición. Las clases que ya están usando JavaScript omitirán los niveles de introducción."
course_membership_required_to_play: "Deberás unirte a un curso para jugar a este nivel."
license_required_to_play: "¡Pídele a tu maestro que te asigne una licencia para que puedas continuar jugando CodeCombat!" # {change}
update_old_classroom: "¡Nuevo año escolar, nuevos niveles!"
update_old_classroom_detail: "Para asegurarte de que estás obteniendo los niveles más actualizados, asegúrate de crear una nueva clase para este semestre haciendo clic en Crear una Nueva Clase en su"
teacher_dashboard: "tablero de maestros"
update_old_classroom_detail_2: "y entregando a los estudiantes el nuevo Código de Clase que aparecerá."
view_assessments: "Ver evaluaciones"
view_challenges: "ver niveles de desafío"
challenge: "Desafío:"
challenge_level: "Nivel de Desafío:"
status: "Estado:"
assessments: "Evaluaciones"
challenges: "Desafíos"
level_name: "Nombre del Nivel:"
keep_trying: "Sigue Intentando"
start_challenge: "Iniciar Desafío"
locked: "Bloqueado"
concepts_used: "Conceptos Usados:"
show_change_log: "Mostrar cambios a los niveles de este curso"
hide_change_log: "Ocultar cambios a los niveles de este curso"
concept_videos: "Videos de Concepto"
concept: "Concepto:"
basic_syntax: "Sintaxis Básica"
while_loops: "Bucles While"
variables: "Variables"
basic_syntax_desc: "La sintaxis es cómo escribimos código. Al igual que la ortografía y la gramática son importantes para escribir narraciones y ensayos, la sintaxis es importante al escribir código. Los humanos son buenos para entender lo que significa algo, incluso si no es exactamente correcto, pero las computadoras no son tan inteligentes, y necesitan que escribas con mucha precisión."
while_loops_desc: "Un bucle es una forma de repetir acciones en un programa. Puedes usarlos para no tener que seguir escribiendo códigos repetitivos, y cuando no sepas exactamente cuántas veces tendrá que ocurrir una acción para completar una tarea."
variables_desc: "Trabajar con variables es como organizar cosas en cajas de zapatos. Le das un nombre a la caja de zapatos, como \"Útiles escolares \", y luego pones las cosas dentro. El contenido exacto de la caja puede cambiar con el tiempo, pero todo lo que haya dentro siempre se llamará \"Útiles escolares \". En la programación, las variables son símbolos utilizados para almacenar datos que cambiarán a lo largo del programa. Las variables pueden contener una variedad de tipos de datos, incluidos números y cadenas de texto."
locked_videos_desc: "Sigue jugando para desbloquear el video del concepto __concept_name__."
unlocked_videos_desc: "Revisa el video del concepto __concept_name__."
video_shown_before: "mostrado antes de __level__"
link_google_classroom: "Enlace a Google Classroom"
select_your_classroom: "Selecciona tu Aula"
no_classrooms_found: "No se encontraron sulas"
create_classroom_manually: "Crear un aula manualmente"
classes: "Clases"
certificate_btn_print: "Imprimir"
certificate_btn_toggle: "Alternar"
module_coming_soon: "¡Próximamente, se vienen los módulos 4 a 6 del capítulo 1!"
error_in_creating_data: "Error al crear datos para el nivel introductorio."
project_gallery:
no_projects_published: "¡Sé el primero en publicar un proyecto en este curso!"
view_project: "Ver Proyecto"
edit_project: "Editar Proyecto"
teacher:
assigning_course: "Asignando curso"
back_to_top: "Volver arriba"
click_student_code: "Haz clic en cualquier nivel que el estudiante haya comenzado o completado para ver el código que escribió."
code: "Código de __name__"
complete_solution: "Solución completa"
course_not_started: "El estudiante todavía no ha completado este curso."
appreciation_week_blurb1: "¡Por la <strong>semana de apreciación al maestro de 2019</strong>, ofrecemos licencias gratuitas de una semana!<br />Debes escribirle a <NAME> (<a href=\"mailto:<EMAIL>?subject=Teacher Appreciation Week\"><EMAIL></a>) con el asunto \"<strong>Semana de apreciación al maestro</strong>\" e incluir:"
appreciation_week_blurb2: "la cantidad de licencias de una semana que quieres (una por estudiante)"
appreciation_week_blurb3: "la dirección de correo electrónico de tu cuenta de maestro de CodeCombat"
appreciation_week_blurb4: "si quieres licencias para la semana 1 (6 a 10 de mayo) o para la semana 2 (13 a 17 de mayo)"
hoc_happy_ed_week: "¡Feliz semana de la educación en ciencias de la computación!"
hoc_blurb1: "¡Entérate de la actividad gratuita"
hoc_blurb2: "Programa, juega y comparte,"
hoc_blurb3: "descarga un nuevo plan de estudios para maestros y dile a tus estudiantes que ingresen a jugar!"
hoc_button_text: "Ver actividad"
no_code_yet: "El estudiante aún no ha escrito nada de código para este nivel."
open_ended_level: "Nivel abierto"
partial_solution: "Solución parcial"
capstone_solution: "Solución final"
removing_course: "Quitando curso"
solution_arena_blurb: "Se alienta a los estudiantes a solucionar los niveles de arena con creatividad. La siguiente solución cumple con los requisitos del nivel."
solution_challenge_blurb: "Se alienta a los estudiantes a resolver los niveles abiertos con creatividad. La siguiente es una solución posible."
solution_project_blurb: "Se alienta a los estudiantes a crear un proyecto creativo en este nivel. Consulta las guías curriculares del centro de recursos para más información sobre cómo evaluar estos proyectos."
feedback_capstone: "El estudiante creará un proyecto básico en la parte 1 y hará actualizaciones creativas a partir de los comentarios de sus compañeros en la parte 2. Puedes compartir esta <a target=\"_blank\" rel=\"noopener\" href=\"https://docs.google.com/document/d/1u8LtMHlWnpEgLZQtZomPfe82s-Swden7iIacCzdYYxk\">plantilla de comentarios</a> con tus estudiantes."
students_code_blurb: "Cuando corresponde, se ofrece una solución correcta para el nivel. En algunos casos, es posible que el estudiante lo resuelva con un código distinto. No se muestran las soluciones de los niveles que el estudiante no ha comenzado."
course_solution: "Solución del curso"
level_overview_solutions: "Resumen del nivel y soluciones"
no_student_assigned: "No hay ningún estudiante asignado a este curso."
paren_new: "(nuevo)"
student_code: "Código del estudiante __name__"
teacher_dashboard: "Tablero del maestro" # Navbar
my_classes: "Mis Clases" # {change}
courses: "Cursos" # {change}
enrollments: "Recursos"
resources: "Resources"
help: "Ayuda"
language: "Lenguaje"
edit_class_settings: "editar configuración de la clase"
access_restricted: "Se requiere Actualización de la Cuenta"
teacher_account_required: "Una cuenta de Maestro es requerida para acceder a este contenido."
create_teacher_account: "Crear Cuenta de Maestro" # {change}
what_is_a_teacher_account: "Qué es una Cuenta de Maestro?"
teacher_account_explanation: "Una Cuenta de Maestro en CodeCombat da permiso a crear salones de clases, monitorear el progreso de los estudiantes mientras ellos trabajan a través de los cursos, manejar inscripciones y acceder a recursos para la creación de su plan de estudio." # {change}
current_classes: "Clases Recientes"
archived_classes: "Clases Archivadas"
# shared_classes: "Shared Classes"
archived_classes_blurb: "Las Clases pueden ser archivadas para futuras referencias. Desarchiva una Clase para verla en la lista de Clases Recientes de nuevo."
view_class: "ver clase"
archive_class: "almacenar clase"
unarchive_class: "desarchivar clase"
unarchive_this_class: "desarchivar esta clase"
no_students_yet: "Esta clase no tienes estudiantes todavía."
no_students_yet_view_class: "Ver clase para agregar estudiantes."
try_refreshing: "(Necesitarás recargar la página)"
create_new_class: "Crear una Nueva Clase"
class_overview: "Resumen de la Clase" # View Class page
avg_playtime: "Nivel medio de tiempo de juego"
total_playtime: "Tiempo Total de juego"
avg_completed: "Promedio de niveles completados"
total_completed: "Total de niveles completados"
created: "Creado"
concepts_covered: "Conceptos cubiertos"
earliest_incomplete: "Nivel incompleto más Reciente"
latest_complete: "Último nivel completado"
enroll_student: "Inscribir estudiante"
apply_modal_subtitle: "Se te redirigirá a la página Mis clases, donde podrás aplicar licencias a tus estudiantes de las siguientes formas:"
apply_modal_list_item_1: "Seleccionando o creando una clase"
apply_modal_list_item_2: "Seleccionando a los estudiantes a los que quieres aplicar licencias"
apply_modal_list_item_3: "Haciendo clic en el botón “Aplicar licencias”"
apply_license: "Aplicar Licencia"
revoke_license: "Eliminar Licencia"
revoke_licenses: "ELiminar Todas las Licencias"
course_progress: "Progreso del curso"
unit_progress: "Progreso de la unidad"
not_applicable: "N/A"
edit: "editar"
edit_2: "Editar"
remove: "eliminar"
latest_completed: "Último Completado" # {change}
sort_by: "Ordenado por"
progress: "Progreso"
concepts_used: "Conceptos usados por el Estudiante:"
concept_checked: "Concepto verificado:"
completed: "Completado"
practice: "Práctica"
started: "Iniciado"
no_progress: "Sin progreso"
not_required: "No requerido"
view_student_code: "Haz clic para ver el código de estudiante"
select_course: "Selecciona el curso a ver" # {change}
progress_color_key: "Color clave de Progreso:"
level_in_progress: "Nivel en Progreso"
level_not_started: "Nivel no Iniciado"
project_or_arena: "Proyecto o Arena"
students_not_assigned: "Estudiantes que no han sido asignados {{courseName}}"
course_overview: "Resumen del Curso"
copy_class_code: "Copiar código de la Clase"
class_code_blurb: "Nuevos estudiantes pueden entrar a este código de la clase en su tablero o visitar codecombat.com/courses para unirse a la clase." # {change}
copy_class_url: "Copia la URL de la Clase"
class_join_url_blurb: "Nuevos estudiantes pueden visitar esta URL mientras esten logeados para unirse a la clase." # {change}
add_students_manually: "Agregar Estudiantes Manualmente" # {change}
bulk_assign: "Mayor a asignar" # {change}
assigned_msg_1: "Se asignaron {{numberAssigned}} estudiantes a {{courseName}}."
assigned_msg_2: "Se aplicaron {{numberEnrolled}} licencias."
assigned_msg_3: "Tienes {{remainingSpots}} licencias disponibles restantes."
assign_course: "Asignar unidad"
removed_course_msg: "Se quitaron {{numberRemoved}} estudiantes de {{courseName}}."
remove_course: "Quitar unidad"
not_assigned_modal_title: "No se asignaron unidades"
not_assigned_modal_starter_body_1: "Este curso requiere una licencia de principiante. No tienes suficientes licencias de ese tipo para asignar este curso a los __selected__ estudiantes seleccionados."
not_assigned_modal_starter_body_2: "Compra licencias de principiante para brindar acceso a este curso."
not_assigned_modal_full_body_1: "Esta unidad requiere una licencia completa. No tienes suficientes licencias de ese tipo para asignar este curso a los __selected__ estudiantes seleccionados."
not_assigned_modal_full_body_2: "Solo tienes __numFullLicensesAvailable__ licencias completas disponibles (hay __numStudentsWithoutFullLicenses__ estudiantes que actualmente no tienen una licencia completa activa)."
not_assigned_modal_full_body_3: "Selecciona a menos estudiantes o escribe a __supportEmail__ para recibir asistencia."
assigned: "Asignado"
enroll_selected_students: "Inscribir Estudiantes Seleccionados"
no_students_selected: "No fueron seleccionados estudiantes."
show_students_from: "Muestra estudiantes de" # Enroll students modal
apply_licenses_to_the_following_students: "Aplicar licencias a los siguientes estudiantes"
students_have_licenses: "Los siguientes estudiantes ya tienen licencias aplicadas:"
all_students: "Todos los estudiantes"
apply_licenses: "Aplicar licencias"
not_enough_enrollments: "No tienes suficientes Inscripciones disponibles." # {change}
enrollments_blurb: "Los estudiantes deben tener una licencia para acceder al contenido luego de la primera unidad."
how_to_apply_licenses: "Cómo aplicar licencias"
export_student_progress: "Exportar el Progreso del Estudiante(CSV)"
send_email_to: "Enviar correo de recuperación de contraseña a:"
email_sent: "Correo enviado"
send_recovery_email: "Enviar correo de recuperación"
enter_new_password_below: "Ingresa la nueva contraseña:"
change_password: "<PASSWORD>"
changed: "Modificada"
available_credits: "Licencias disponibles"
pending_credits: "Licencias pendientes"
empty_credits: "Licencias vencidas"
license_remaining: "licencia restante"
licenses_remaining: "licencias restantes"
one_license_used: "Se ha utilizado 1 licencia de __totalLicenses__"
num_licenses_used: "Se han utilizado __numLicensesUsed__ licencias de __totalLicenses__"
starter_licenses: "licencias de principiante"
start_date: "fecha de inicio:"
end_date: "fecha de finalización:"
get_enrollments_blurb: " Te ayudaremos a crear una solución que satisfaga las necesidades de tu clase, escuela o distrito."
how_to_apply_licenses_blurb_1: "Cuando un maestro le asigna una unidad a un estudiante por primera vez, aplicaremos la licencia automáticamente. Utiliza la lista desplegable Seleccionar unidad en tu aula para asignar una unidad a los estudiantes seleccionados:"
how_to_apply_licenses_blurb_2: "¿Puedo aplicar una licencia sin asignar una unidad?"
how_to_apply_licenses_blurb_3: "Sí. Ve a la pestaña Estado de licencia en tu aula y haz clic en \"Aplicar licencia\" sobre todo estudiante que no tenga una licencia activa."
request_sent: "¡Solicitud enviada!"
assessments: "Evaluaciones"
license_status: "Estado de licencia"
status_expired: "Vencida el {{date}}"
status_not_enrolled: "No inscripto"
status_enrolled: "Vence el {{date}}"
select_all: "Seleccionar todo"
project: "Proyecto"
project_gallery: "Galería de proyectos"
view_project: "Ver proyecto"
unpublished: "(sin publicar)"
view_arena_ladder: "Ver clasificación de arena"
resource_hub: "Centro de recursos"
pacing_guides: "Guías didácticas de aula virtual"
pacing_guides_desc: "¡Aprende a incorporar todos los recursos de CodeCombat para planificar tu año académico!"
pacing_guides_elem: "Guía didáctica para primaria (Elementary School)"
pacing_guides_middle: "Guía didáctica para secundaria (Middle School)"
pacing_guides_high: "Guía didáctica para preparatoria (High School)"
getting_started: "Primeros pasos"
# student_resources: "Student Resources"
# lesson_slides: "Lesson Slides"
# section: "Section"
educator_faq: "Preguntas frecuentes de educadores"
educator_faq_desc: "Preguntas frecuentes sobre el uso de Ozaria en el aula o la escuela."
teacher_getting_started: "Guía introductoria para maestros"
teacher_getting_started_desc: "¿Primera vez en Ozaria? Descarga la guía introductoria para maestros para configurar tu cuenta, crear tu primera clase e invitar a tus estudiantes a trabajar en la primera unidad."
student_getting_started: "Guía de inicio rápido para estudiantes"
student_getting_started_desc: "Puedes compartir esta guía con tus estudiantes antes de empezar a jugar CodeCombat para que se familiaricen con el editor de código. Esta guía sirve para aulas de Python y JavaScript."
ap_cs_principles: "Fundamentos de Ciencias de la Computación AP"
ap_cs_principles_desc: "Con Fundamentos de Ciencias de la Computación AP, los estudiantes reciben una amplia introducción sobre la potencia, el impacto y las posibilidades de la informática. Este curso hace énfasis en el pensamiento computacional y la resolución de problemas a la vez que enseña conceptos básicos de programación."
cs1: "Introducción a las Ciencias de la Computación"
cs2: "Ciencias de la Computación 2"
cs3: "Ciencias de la Computación 3"
cs4: "Ciencias de la Computación 4"
cs5: "Ciencias de la Computación 5"
cs1_syntax_python: "Guía de sintaxis para el curso 1 de Python"
cs1_syntax_python_desc: "Apunte con referencias a la sintaxis habitual de Python que los estudiantes aprenderán en Introducción a las Ciencias de la Computación."
cs1_syntax_javascript: "Guía de sintaxis para el curso 1 de JavaScript"
cs1_syntax_javascript_desc: "Apunte con referencias a la sintaxis habitual de JavaScript que los estudiantes aprenderán en Introducción a las Ciencias de la Computación."
coming_soon: "¡Próximamente más guías!"
engineering_cycle_worksheet: "Hoja de ejercicios sobre el ciclo de ingeniería"
engineering_cycle_worksheet_desc: "Usa esta hoja de ejercicios para enseñarles a los estudiantes las bases del ciclo de ingeniería: análisis, diseño, implementación y depuración. Consulta la hoja de ejemplo completada como guía."
engineering_cycle_worksheet_link: "Ver ejemplo"
progress_journal: "Diario de progreso"
progress_journal_desc: "Alienta a los estudiantes a mantener un registro de sus avances en su diario de progreso."
cs1_curriculum: "Introducción a las Ciencias de la Computación - Guía curricular"
cs1_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 1."
arenas_curriculum: "Niveles de arena - Guía para maestros"
arenas_curriculum_desc: "Instrucciones sobre cómo jugar las arenas multijugador <NAME> de <NAME>akka, Huesos cruzados y Pico de poder con tu clase."
assessments_curriculum: "Niveles de evaluación - Guía para maestros"
assessments_curriculum_desc: "Aprende a usar los niveles de desafío y los niveles de desafío combo para evaluar el aprendizaje de los estudiantes."
cs2_curriculum: "Ciencias de la Computación 2 - Guía curricular"
cs2_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 2."
cs3_curriculum: "Ciencias de la Computación 3 - Guía curricular"
cs3_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 3."
cs4_curriculum: "Ciencias de la Computación 4 - Guía curricular"
cs4_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 4."
cs5_curriculum_js: "Ciencias de la Computación 5 - Guía curricular (JavaScript)"
cs5_curriculum_desc_js: "Alcance y orden, planes de estudio, actividades y más para las clases del curso 5 sobre JavaScript."
cs5_curriculum_py: "Ciencias de la Computación 5 - Guía curricular (Python)"
cs5_curriculum_desc_py: "Alcance y orden, planes de estudio, actividades y más para las clases del curso 5 sobre Python."
cs1_pairprogramming: "Actividad de programación en pareja"
cs1_pairprogramming_desc: "Enfrenta a los estudiantes a un ejercicio de programación en pareja que los ayudará a escuchar y comunicar mejor."
gd1: "Desarrollo de Juegos 1"
gd1_guide: "Desarrollo de Juegos 1 - Guía de proyecto"
gd1_guide_desc: "Usa esta guía para orientar a tus estudiantes mientras crean su primer proyecto de videojuego para compartir en cinco días."
gd1_rubric: "Desarrollo de Juegos 1 - Guía de evaluación del proyecto"
gd1_rubric_desc: "Usa esta guía de evaluación al finalizar Desarrollo de Juegos 1."
gd2: "Desarrollo de Juegos 2"
gd2_curriculum: "Desarrollo de Juegos 2 - Guía curricular"
gd2_curriculum_desc: "Planes de estudio para Desarrollo de Juegos 2."
gd3: "Desarrollo de Juegos 3"
gd3_curriculum: "Desarrollo de Juegos 3 - Guía curricular"
gd3_curriculum_desc: "Planes de estudio para Desarrollo de Juegos 3."
wd1: "Desarrollo Web 1"
wd1_curriculum: "Desarrollo Web 1 - Guía curricular"
wd1_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para Desarrollo Web 1."
wd1_headlines: "Actividad sobre títulos y encabezados"
wd1_headlines_example: "Ver ejemplo de solución"
wd1_headlines_desc: "¿Por qué son importantes las etiquetas de párrafo y encabezado? Usa esta actividad para demostrar que elegir bien los encabezados facilita la lectura de un sitio web. ¡Existen muchas soluciones correctas!"
wd1_html_syntax: "Guía de sintaxis HTML"
wd1_html_syntax_desc: "Hoja de referencia sobre los estilos de HTML que los estudiantes aprenderán en Desarrollo Web 1."
wd1_css_syntax: "Guía de sintaxis CSS"
wd1_css_syntax_desc: "Hoja de referencia sobre la sintaxis de CSS y de estilos que los estudiantes aprenderán en Desarrollo Web 1."
wd2: "Desarrollo Web 2"
wd2_jquery_syntax: "Guía de sintaxis para las funciones jQuery"
wd2_jquery_syntax_desc: "Hoja de referencia sobre las funciones jQuery que los estudiantes aprenderán en Desarrollo Web 2."
wd2_quizlet_worksheet: "Hoja de ejercicios para planificar el cuestionario"
wd2_quizlet_worksheet_instructions: "Ver instrucciones y ejemplos"
wd2_quizlet_worksheet_desc: "Antes de que tus estudiantes armen su proyecto de cuestionario de personalidad al finalizar Desarrollo Web 2, deben planificar las preguntas, los resultados y las respuestas con esta hoja de trabajo. Los maestros pueden distribuir las instrucciones y los ejemplos para consulta de los estudiantes."
student_overview: "Resumen"
student_details: "Detalles del estudiante"
student_name: "Nombre del estudiante"
no_name: "No ingresó nombre."
no_username: "No ingresó nombre de usuario."
no_email: "El estudiante no asignó ningún correo electrónico."
student_profile: "Perfil del estudiante"
playtime_detail: "Tiempo de juego detallado"
student_completed: "Completado por estudiante"
student_in_progress: "Estudiante en curso"
class_average: "Promedio de la clase"
not_assigned: "no cuenta con los siguientes cursos asignados"
playtime_axis: "Tiempo de juego en segundos"
levels_axis: "Niveles en"
student_state: "¿Cómo viene"
student_state_2: "en sus cursos?"
student_good: "viene bien en"
student_good_detail: "Este estudiante está a la par de la clase."
student_warn: "tal vez necesite ayuda con"
student_warn_detail: "Este estudiante tal vez necesite ayuda con nuevos conceptos que se han presentado en este curso."
student_great: "viene muy bien en"
student_great_detail: "Este estudiante tal vez pueda ayudar a otros alumnos de este curso."
full_license: "Licencia full"
starter_license: "Licencia de principiante"
trial: "Prueba"
hoc_welcome: "Feliz semana de la educación en ciencias de la computación"
hoc_title: "Juegos de la Hora del Código - Actividades gratuitas para aprender lenguajes de programación reales"
hoc_meta_description: "¡Crea tu propio juego o escapa de la mazmorra programando! CodeCombat tiene cuatro actividades de la Hora del Código y más de 60 niveles para jugar, crear y aprender a programar."
hoc_intro: "Hay tres maneras en las que tu clase puede participar de la Hora del Código con CodeCombat"
hoc_self_led: "Juego individual"
hoc_self_led_desc: "Los estudiantes pueden jugar dos tutoriales de la Hora del Código de CodeCombat por sí solos"
hoc_game_dev: "Desarrollo de juegos"
hoc_and: "y"
hoc_programming: "programación en JavaScript/Python"
hoc_teacher_led: "Lecciones dirigidas por el docente"
hoc_teacher_led_desc1: "Descarga nuestros"
hoc_teacher_led_link: "planes de estudio de Introducción a las Ciencias de la Computación"
hoc_teacher_led_desc2: "para que tus estudiantes aprendan conceptos de programación con actividades sin conexión"
hoc_group: "Juego grupal"
hoc_group_desc_1: "Los maestros pueden combinar las lecciones con nuestro curso de Introducción a las Ciencias de la Computación para supervisar el progreso de los estudiantes. Consulta nuestra"
hoc_group_link: "guía de inicio"
hoc_group_desc_2: "para más detalles"
hoc_additional_desc1: "Para acceder a más recursos y actividades de CodeCombat, consulta nuestras"
hoc_additional_desc2: "Preguntas"
hoc_additional_contact: "Contáctanos"
revoke_confirm: "¿Seguro quieres anular la licencia completa de {{student_name}}? La licencia estará disponible para asignársela a otro estudiante."
revoke_all_confirm: "¿Seguro quieres anular las licencias completas de todos los estudiantes de esta clase?"
revoking: "Anulando..."
unused_licenses: "¡Tienes licencias sin usar que te permiten asignar cursos pagos a estudiantes cuando estén listos para seguir aprendiendo!"
remember_new_courses: "¡Recuerda asignar cursos nuevos!"
more_info: "Más información"
how_to_assign_courses: "Cómo asignar cursos"
select_students: "Seleccionar Estudiantes"
select_instructions: "Haz clic en la casilla de verificación junto a cada estudiante para asignarle un curso."
choose_course: "Elegir curso"
choose_instructions: "Selecciona de la lista desplegable el curso que quieres asignar y luego haz clic en Asignar a los estudiantes seleccionados."
push_projects: "Recomendamos asignar Desarrollo Web 1 o Desarrollo de Juegos 1 una vez que los estudiantes hayan completado Introducción a las Ciencias de la Computación. Consulta nuestro {{resource_hub}} para más información sobre esos cursos."
teacher_quest: "El camino del maestro hacia el éxito"
quests_complete: "Misiones completadas"
teacher_quest_create_classroom: "Crear aula"
teacher_quest_add_students: "Agregar estudiantes"
teacher_quest_teach_methods: "Ayuda a tus estudiantes a aprender a `llamar métodos`."
teacher_quest_teach_methods_step1: "Consigue que el 75% de al menos una clase supere el primer nivel, __Mazmorras de Kithgard__"
teacher_quest_teach_methods_step2: "Imprime la [guía de inicio rápido para estudiantes](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) del centro de recursos."
teacher_quest_teach_strings: "Suéltales la cadena a tus estudiantes. Enséñales qué son las `cadenas`."
teacher_quest_teach_strings_step1: "Consigue que el 75% de al menos una clase supere __Nombres verdaderos__"
teacher_quest_teach_strings_step2: "Usa el selector de niveles para maestros que hay en la página [Guías de curso](/teachers/units) para previsualizar __Nombres verdaderos__."
teacher_quest_teach_loops: "Repíteles a tus estudiantes una y otra vez el concepto de `bucle`."
teacher_quest_teach_loops_step1: "Consigue que el 75% de al menos una clase supere __Danza con fuego__."
teacher_quest_teach_loops_step2: "Usa la __actividad sobre bucles__ de la [Guía curricular CS1](/teachers/resources/cs1) para reforzar este concepto."
teacher_quest_teach_variables: "Varía los conceptos con las `variables`."
teacher_quest_teach_variables_step1: "Consigue que el 75% de al menos una clase supere __Enemigo reconocido__."
teacher_quest_teach_variables_step2: "Fomenta la colaboración usando la [actividad de programación en pareja](/teachers/resources/pair-programming)."
teacher_quest_kithgard_gates_100: "Escapa por las Puertas de Kithgard con tu clase."
teacher_quest_kithgard_gates_100_step1: "Consigue el 75% de al menos una clase supere __Puertas de Kithgard__."
teacher_quest_kithgard_gates_100_step2: "Orienta a los estudiantes para que resuelvan problemas difíciles usando la [hoja de ejercicios sobre el ciclo de ingeniería](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)."
teacher_quest_wakka_maul_100: "Prepárate para un duelo en la Batalla de Wakka."
teacher_quest_wakka_maul_100_step1: "Consigue que el 75% de al menos una clase supere __Batalla de Wakka__."
teacher_quest_wakka_maul_100_step2: "Consulta la [guía de arenas](/teachers/resources/arenas) del [centro de recursos](/teachers/resources) para recibir sugerencias sobre cómo organizar un día de arena."
teacher_quest_reach_gamedev: "¡Explora nuevos mundos!"
teacher_quest_reach_gamedev_step1: "¡[Consigue licencias](/teachers/licenses) para que tus estudiantes exploren nuevos mundos, como el desarrollo web o de videojuegos!"
teacher_quest_done: "¿Quieres que tus estudiantes aprendan aún más sobre programación? ¡Ponte en contacto con nuestros [especialistas escolares](mailto:<EMAIL>) de inmediato!"
teacher_quest_keep_going: "¡Sigue avanzando! Esto es lo que puedes hacer ahora:"
teacher_quest_more: "Ver todas las misiones"
teacher_quest_less: "Ver menos misiones"
refresh_to_update: "(actualiza la página para ver actualizaciones)"
view_project_gallery: "Ver galería de proyectos" # {change}
office_hours: "Seminarios web para maestros"
office_hours_detail: "Aprende a seguir el ritmo de tus estudiantes mientras crean juegos y transitan el camino de la programación. Asiste a nuestros"
office_hours_link: "seminarios web"
office_hours_detail_2: "para maestros."
success: "Éxito"
in_progress: "En curso"
not_started: "Sin comenzar"
mid_course: "Mitad de curso"
end_course: "Fin de curso"
none: "Aún sin detectar"
explain_open_ended: "Nota: Se alienta a los estudiantes a resolver este nivel con creatividad. La siguiente es una solución posible."
level_label: "Nivel:"
time_played_label: "Tiempo jugado:" # {change}
back_to_resource_hub: "Volver al centro de recursos"
back_to_course_guides: "Volver a las guías de curso"
print_guide: "Imprimir esta guía"
combo: "Combo"
combo_explanation: "Los estudiantes superan los niveles de desafío combo si utilizan al menos uno de los conceptos enumerados. Puedes revisar el código de los estudiantes haciendo clic en el punto de progreso."
concept: "Concepto"
sync_google_classroom: "Sincronizar Google Classroom"
unit_overview: "Resumen de la unidad"
module_overview: "Resumen del módulo"
chapter1_unit_overview_desc: "Resumen de la experiencia del estudiante que incluye escenas de video, niveles de práctica, introducciones y el proyecto final del capítulo 1."
lesson_plan: "Plan de estudios"
chapter1_lesson_plan_desc: "Guía detallada que incluye objetivos de aprendizaje, normas CSTA, actividades de reflexión, sugerencias de facilitación y más."
capstone_rubric: "Guía de evaluación del proyecto final"
chapter1_capstone_rubric_desc: "Guía para evaluar los proyectos finales y las actividades de reflexión de los estudiantes al final de la unidad."
chapter1: "Capítulo 1: Bailarines de la luna" # {change}
chapter2: "Capítulo 2: Bailarines de la luna"
chapter3: "Capítulo 3: Tierras de Phoenix"
module1: "Módulo 1" # {change}
module2: "Módulo 2" # {change}
module3: "Módulo 3" # {change}
module4: "Módulo 4" # {change}
module5: "Módulo 5" # {change}
module6: "Módulo 6" # {change}
algorithms_and_syntax: "Algoritmos y sintaxis"
debugging: "Depuración"
variables: "Variables"
conditionals: "Condicionales"
capstone_intro: "Inicio del proyecto final"
capstone_project: "Proyecto final"
level_code: "Código de nivel"
review_needed: "Repaso necesario"
review_tooltip_heading: "¿Qué significa esto?"
review_tooltip_text: "Aparecerán señales de advertencia junto a las comprobaciones de conceptos en caso de que al menos un estudiante haya intentando responder la pregunta tres veces o más. En la sección <strong>Resumen del curso</strong>, aparecerán señales de advertencia junto a las comprobaciones de conceptos si al menos el 50% de los estudiantes que han comenzado o completado la comprobación lo intentaron tres veces o más."
scroll_to_see_more: "Desplázate para más información"
click_to_view_concept_check: "Haz clic para ver la comprobación de conceptos"
click_to_view_project_gallery: "Haz clic para ver la galería de proyectos"
review_learning_goal: "Repasar \"Meta de aprendizaje: __learningGoal__\" con los estudiantes."
view_capstone_project: "Ver proyecto final"
ozaria_dashboard_guide: "Guía de panel para maestros"
dashboard_guide_desc: "Un recorrido por las funciones del panel para maestros de Ozaria que te ayudará a supervisar el progreso y el trabajo de los estudiantes."
review: "Repaso"
for_loops: "Bucles for"
peer_feedback: "Formulario de comentarios"
presentation_checklist: "Lista de verificación para presentaciones"
teacher_licenses:
active_licenses: "Licencias activas"
expired_licenses: "Licencias vencidas"
share_licenses:
share_licenses: "Compartir licencias"
shared_by: "Compartido por:"
add_teacher_label: "Ingresar el correo electrónico del maestro:"
add_teacher_button: "Agregar maestro"
modal_subtitle: "Puedes compartir tus licencias con otros maestros de tu conjunto compartido."
modal_list_item_1: "Cada licencia puede utilizarse solamente para un estudiante a la vez."
modal_list_item_2: "Cuando los maestros anulan la licencia de algún estudiante, esa licencia regresa al conjunto compartido para que puedan usarla otros maestros del grupo."
subheader: "Puedes compartir tus licencias con otros maestros de tu institución. Cada licencia puede utilizarse solamente para un estudiante a la vez."
teacher_not_found: "Maestro no encontrado. Asegúrate de que el maestro ya tenga creada una cuenta de maestro."
teacher_not_valid: "Esta no es una cuenta de maestro válida. Solo los maestros pueden compartir licencias desde sus cuentas."
already_shared: "Ya has compartido estas licencias con ese maestro."
teachers_using_these: "Maestros que pueden acceder a estas licencias:"
footer: "Cuando los maestros anulan la licencia de algún estudiante, esa licencia regresa al conjunto compartido para que puedan usarla otros maestros del grupo."
you: "(tú)"
one_license_used: "(1 licencia utilizada)"
licenses_used: "(__licensesUsed__ licencias utilizadas)"
licenses_used_no_braces: "__licensesUsed__ licencias utilizadas"
more_info: "Más información"
shared_pool_label: "Maestros en tu conjunto compartido:"
sharing:
game: "Juego"
webpage: "Sitio web"
your_students_preview: "Tus estudiantes harán clic aquí para ver sus proyectos finalizados. No disponible en la vista previa del maestro."
unavailable: "No es posible compartir enlaces en la vista previa del maestro."
share_game: "Compartir este juego"
share_web: "Compartir este sitio web"
victory_share_prefix: "Comparte este enlace para invitar a tus amigos y familia a"
victory_share_prefix_short: "Invita a otras personas a"
victory_share_game: "jugar tu nivel del juego"
victory_share_web: "ver tu página web"
victory_share_suffix: "."
victory_course_share_prefix: "Este enlace les permitirá a tus amigos y familia"
victory_course_share_game: "jugar el videojuego"
victory_course_share_web: "ver la página web"
victory_course_share_suffix: "que has creado."
copy_url: "Copiar URL"
share_with_teacher_email: "Enviar a tu maestro"
game_dev:
creator: "<NAME>"
web_dev:
image_gallery_title: "Galería de imágenes"
select_an_image: "Selecciona la imagen que quieres usar"
scroll_down_for_more_images: "(Desplazar hacia abajo para ver más imágenes)"
copy_the_url: "Copiar la URL de abajo"
copy_the_url_description: "Útil si quieres reemplazar una imagen existente."
copy_the_img_tag: "Copiar la etiqueta <img>"
copy_the_img_tag_description: "Útil si quieres insertar una nueva imagen."
copy_url: "Copiar URL"
copy_img: "Copiar <img>"
how_to_copy_paste: "Cómo copiar y pegar"
copy: "Copiar"
paste: "Pegar"
back_to_editing: "Volver a editar"
classes:
archmage_title: "Archimago"
archmage_title_description: "(Desarrollador)"
archmage_summary: "Si eres un programador interesado en juegos educativos, conviértete en un archimago y ayúdanos a construir CodeCombat!"
artisan_title: "Artesano"
artisan_title_description: "(Constructor de Niveles)"
artisan_summary: "Construye y comparte niveles para que tú y tus amigos jueguen. Conviértete en un Artesano y aprende el arte the enseñar a los demás a programar."
adventurer_title: "Aventurero"
adventurer_title_description: "(Probador de Niveles)"
adventurer_summary: "Consigue nuestros nuevos niveles| (even our subscriber content) for free one week early and help us work out bugs before our public release."
scribe_title: "<NAME>"
scribe_title_description: "(Editor de Artículos)"
scribe_summary: "Buen código necesita buena documentación. Escribe, edita y mejora los documentos leídos por millones de jugadores en el mundo."
diplomat_title: "Diplomático"
diplomat_title_description: "(Traductor)"
diplomat_summary: "CodeCombat está traducido a más de 45 idiomas por nuestros diplomáticos. Ayúdanos y contribuye con las traducciones."
ambassador_title: "Embajador"
ambassador_title_description: "(Soporte)"
ambassador_summary: "Ayuda a responder las preguntas de los usuarios del foro. Nuestros Embajadores representan CodeCombat en todo el mundo."
teacher_title: "Maestro"
editor:
main_title: "Editor de CodeCombat"
article_title: "Editor de Artículo"
thang_title: "Editor de Tiliches"
level_title: "Editor de Nivel"
course_title: "Editor de Curso"
achievement_title: "Editor de logros"
poll_title: "Editor de Encuesta"
# resource_title: "Resource Editor"
back: "Atrás"
revert: "Revertir"
revert_models: "Revertir Modelos"
pick_a_terrain: "Elije un Terreno"
dungeon: "Calabozo"
indoor: "Interior"
desert: "Desierto"
grassy: "Herboso"
mountain: "Montaña"
glacier: "Glaciar"
small: "Pequeño"
large: "Grande"
fork_title: "Fork de Nueva Versión"
fork_creating: "Creando Fork..."
generate_terrain: "Generar terreno"
more: "Más"
wiki: "Wiki"
live_chat: "Chat en vivo"
thang_main: "Principal"
thang_spritesheets: "Hojas de figuras( para animaciones )"
thang_colors: "Colores"
level_some_options: "¿Algunas opciones?"
level_tab_thangs: "Tiliches"
level_tab_scripts: "Scripts"
level_tab_components: "Componentes"
level_tab_systems: "Sistemas"
level_tab_docs: "Documentación"
level_tab_thangs_title: "Tiliches Actuales"
level_tab_thangs_all: "Todo"
level_tab_thangs_conditions: "Condiciones Iniciales"
level_tab_thangs_add: "Agregar Thangs"
level_tab_thangs_search: "Buscar Thangs"
add_components: "Agregar Componentes"
component_configs: "Configuraciones del Componente"
config_thang: "Doble clic para configurar un Tiliche"
delete: "Borrar"
duplicate: "Duplicar"
stop_duplicate: "Parar de Duplicar"
rotate: "Rotar"
level_component_tab_title: "Componentes Actuales"
level_component_btn_new: "Crear Nuevo Componente"
level_systems_tab_title: "Sistemas Actuales"
level_systems_btn_new: "Crear Nuevo Sistema"
level_systems_btn_add: "Agregar Sistema"
level_components_title: "Regresar a todos los Tiliches"
level_components_type: "Tipo"
level_component_edit_title: "Editar Componente"
level_component_config_schema: "Config Schema"
level_system_edit_title: "Editar Sistema"
# course_edit_title: "Edit Course"
# resource_edit_title: "Edit Resource"
create_system_title: "Crear Nuevo Sistema"
new_component_title: "Crear Nuevo Componente"
new_component_field_system: "Sistema"
new_article_title: "Crear un Nuevo Artículo"
new_thang_title: "Crear un Nuevo tipo de Tiliche"
new_level_title: "Crear un Nuevo Nivel"
new_article_title_login: "Ingresa para Crear un Nuevo Artículo"
new_thang_title_login: "Ingresa para crear un nuevo tipo de Tiliche"
new_level_title_login: "Ingresa para Crear un Nuevo Nivel"
new_achievement_title: "Crear un Nuevo Logro"
new_achievement_title_login: "Ingresa para Crear un Nuevo Logro"
new_poll_title: "Crear una nueva encuesta"
new_poll_title_login: "Ingresa para crear una nueva encuesta"
# new_course_title: "Create a New Course"
# new_course_title_login: "Log In to Create a New Course"
# new_resource_title: "Create a New Resource"
# new_resource_title_login: "Log In to Create a New Resource"
article_search_title: "Buscar Artículos aquí"
thang_search_title: "Buscar tipos de Tiliche aquí"
level_search_title: "Buscar Niveles aquí"
achievement_search_title: "Buscar logros"
poll_search_title: "Buscar Encuesta"
# course_search_title: "Search Courses"
# resource_search_title: "Search Resources"
read_only_warning2: "Nota: no puedes guardar ediciones aquí, porque no estas logueado."
no_achievements: "No hay logros agregados en este nivel por ahora."
achievement_query_misc: "Objetivo clave de misceláneo"
achievement_query_goals: "Objetivo clave de los objetivos de nivel"
level_completion: "Nivel Completado"
pop_i18n: "Poblar I18N"
tasks: "Tareas"
clear_storage: "Borrar tus cambios locales"
add_system_title: "Agregar Sistemas al Nivel"
done_adding: "Finalizar"
# product: "Product"
# link: "Link"
article:
edit_btn_preview: "Vista previa"
edit_article_title: "Editar Artículo"
polls:
priority: "Prioridad"
contribute:
page_title: "Contribuyendo"
intro_blurb: "CodeCombat es 100% open source! Cientos de jugadores dedicados nos han ayudado a contruir el juego. Únete y escribe el siguiente capítulo de la misión de CodeCombat de enseñar al mundo a programar!" # {change}
alert_account_message_intro: "¡Hola!"
alert_account_message: "Para suscribirte para los correos, necesitas ingresar primero."
archmage_introduction: "Una de las mejores partes de hacer juegos es que sintetizan muchas cosas diferentes. Gráficas, sonido, redes, redes sociales y muchos aspectos comunes de programación, desde manejo de bases de datos y administración de servidores, hasta trabajar en el diseño y construcción de interfaces. Hay mucho para hacer, y si eres un programador con experiencia con el deseo de ingresar en el meollo del asunto de CodeCombat, esta clase puede ser para ti. Nos encantaría contar con tu ayuda para construir el mejor juego de programación."
class_attributes: "Atributos de Clase"
archmage_attribute_1_pref: "Conocimiento en "
archmage_attribute_1_suf: ", o un deseo de aprender. La mayor parte de nuestro código está en este lenguaje. Si eres un fan de Python o Ruby, te sentirás en casa. Es Javascript, pero con un mejor syntax."
archmage_attribute_2: "Alguna experiencia programando e iniciativa personal. Te ayudaremos a orientarte, pero no podemos perder mucho tiempo entrenando."
how_to_join: "Unirse:"
join_desc_1: "¡Cualquiera puede unirse! Sólo checa nuestro "
join_desc_2: "para comenzar, y pon un check abajo para marcarte como un valiente Archimago y conseguir las últimas noticias por email. ¿Quieres chatear sobre qué hacer o cómo involucrarte más? "
join_desc_3: ", o encuéntranos en "
join_desc_4: "y ahí empezaremos!"
join_url_email: "Escríbenos"
join_url_slack: "Canal de Slack"
archmage_subscribe_desc: "Obten correos de nuevas oportunidades y anuncios."
artisan_introduction_pref: "¡Debemos construir niveles adicionales! La gente ruega por más contenido, y podemos hacer tanto por nosotros mismos. De momento tu estación de trabajo es nivel 1 ; Nuestro editor de niveles es apenas útil incluso para sus creadores, así que sea cauteloso. Si tuviera visiones de campañas apareciendo para ciclos for"
artisan_introduction_suf: ", entonces esta lase es ideal para ti."
artisan_attribute_1: "Cualquier experiencia creando contenido similar estaría bien, como por ejemplo el editor de niveles de Blizzard. ¡Aunque no es necesaria!"
artisan_attribute_2: "Un anhelo de hacer un montón de pruebas e iteraciones. Para hacer buenos niveles necesitas mostrárselos a otros y mirar como juegan, además de estar preparado para encontrar los fallos a reparar."
artisan_attribute_3: "Por el momento, la resistencia va a la par con el Aventurero. Nuestro editor de niveles está a un nivel de desarrollo temprano y puede ser muy frustrante usarlo. ¡Estás advertido!"
artisan_join_desc: "Sigue las siguientes indicaciones para usar el editor de niveles. Tómalo o déjalo:"
artisan_join_step1: "Lee la documentación."
artisan_join_step2: "Crea un nuevo nivel y explora los niveles existentes."
artisan_join_step3: "Busca nuestra sala pública de Slack en busca de ayuda."
artisan_join_step4: "Publica tus niveles en el foro para recibir comentarios críticos."
artisan_subscribe_desc: "Recibe correos sobre actualizaciones del editor de niveles y anuncios."
adventurer_introduction: "Hablemos claro sobre tu papel: eres el tanque. Vas a recibir fuertes daños. Necesitamos gente para probar nuestros flamantes niveles y ayudar a mejorarlos. El dolor será enorme; hacer buenos juegos es un proceso largo y nadie lo consigue a la primera. Si puedes resistir y tener una puntuación alta en resistencia, entonces esta clase es para ti."
adventurer_attribute_1: "Estar sediento de conocimientos. Quieres aprender a programar y nosotros queremos enseñarte a hacerlo. Aunque en este caso es más probable que seas tú el que esté haciendo la mayor parte de la enseñanza."
adventurer_attribute_2: "Carismático. Se amable pero claro a la hora de desglosar qué necesita ser mejorado y sugiere de qué formas podría hacerse."
adventurer_join_pref: "Reúnete con (¡o recluta!) un Artesano y trabaja con ellos, o marca la casilla de abajo para recibir un correo cuando haya nuevos niveles para probar. También publicaremos en nuestras redes nuevos niveles para revisar"
adventurer_forum_url: "nuestro foro"
adventurer_join_suf: "así que si prefieres estar informado en esa forma, ¡crea una cuenta allí!"
adventurer_subscribe_desc: "Recibe correos cuando haya nuevos niveles para testar."
scribe_introduction_pref: "CodeCombat no será solo un montón de niveles. También será una fuente de conocimientos, una wiki de conceptos de programación a la que los niveles se engancharan. De esa forma, en lugar de que cada Artesano tenga que describir en detalle qué es un operador de comparación, podrá simplemente enlazar el nivel al Artículo que los describe y que ya ha sido escrito para edificación del jugador. Algo en la línea de lo que la "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: " ha construido. Si tu idea de diversión es articular los conceptos de la programación de una forma sencilla, entonces esta clase es para ti."
scribe_attribute_1: "Habilidad a la hora de escribir es casi todo lo que necesitas. No solo dominar la gramática y la ortografía sino también expresar ideas complicadas a los demás de forma sencilla."
contact_us_url: "Escribenos un correo electrónico" # {change}
scribe_join_description: "cuéntanos más sobre ti, tu experiencia en el mundo de la programación y sobre qué cosas te gustaría escribir. ¡Y continuaremos a partir de ahí!"
scribe_subscribe_desc: "Recibe correos sobre anuncios de redacción de Artículos."
diplomat_introduction_pref: "Hemos aprendido algo gracias a la "
diplomat_introduction_url: "comunidad de código abierto:"
diplomat_introduction_suf: "hay un interés considerable en CodeCombat en otros paises, ¡especialmente Brasil! Estamos formando un cuerpo de traductores con ganas de traducir un grupo de palabras tras otro para hacer CodeCombat tan accesible para todo el mundo como sea posible. Si quieres recibir avances de próximos contenidos y quieres poner esos niveles a disposición de los que comparten tu idioma tan pronto como sea posible, entonces esta Clase es para ti."
diplomat_attribute_1: "Fluidez con el ingles y el lenguaje al que quieras traducir. Cuando de transmitir ideas complejas se trata, ¡es importante tener grandes conocimientos de ambas!"
diplomat_i18n_page_prefix: "Puedes traducir nuestros niveles yendo a nuestra"
diplomat_i18n_page: "página de traducciones"
diplomat_i18n_page_suffix: ", o en nuestra interfaz y sitio web en GitHub."
diplomat_join_pref_github: "Encuentra el fichero local de tu idioma "
diplomat_github_url: "en GitHub"
diplomat_join_suf_github: ", edítalo online, y solicita que sea revisado. Además, marca la casilla de abajo para mantenerte informado en nuevos progresos en Internacionalización."
diplomat_subscribe_desc: "Recibe correos sobre nuevos niveles y desarrollos para traducir."
ambassador_introduction: "Esta es una comunidad en construcción y tú eres parte de las conexiones. Tenemos chat <NAME>, correos electrónicos y las redes sociales con una gran cantidad de personas con quienes hablar, ayudar a familiarizarse con el juego y aprender. Si quieres ayudar a la gente a que se involucre, se divierta, y tenga buenas sensaciones sobre CodeCombat y hacia dónde vamos, entonces esta clase es para ti."
ambassador_attribute_1: "Habilidades de comunicación. Ser capaz de identificar los problemas que los jugadores están teniendo y ayudarles a resolverlos. Además, mantener al resto de nosotros informados sobre lo que los jugadores están diciendo, lo que les gusta, lo que no ¡y de lo que quieren más!"
ambassador_join_desc: "cuéntanos más sobre ti, que has hecho y qué estarías interesado en hacer. ¡Y continuaremos a partir de ahí!"
ambassador_subscribe_desc: "Recibe correos sobre actualizaciones de soporte y desarrollo del multijugador."
teacher_subscribe_desc: "Obtener actulizaciones y anuncios para maestros en su correo electrónico."
changes_auto_save: "Los cambios son guardados automáticamente cuando marcas las casillas de verificación."
diligent_scribes: "Nuestros diligentes Escribas:"
powerful_archmages: "Nuestros poderosos Archimagos:"
creative_artisans: "Nuestros creativos Artesanos:"
brave_adventurers: "Nuestros bravos Aventureros:"
translating_diplomats: "Nuestros políglotas Diplomáticos:"
helpful_ambassadors: "Nuestros amables Embajadores:"
ladder:
title: "Arenas multijugador"
arena_title: "__arena__ | Arenas multijugador"
my_matches: "Mis Partidas"
simulate: "Simular"
simulation_explanation: "¡Simulando tus juegos puedes mejorar tu posición más rápido!"
simulation_explanation_leagues: "Principalmente ayudarás a simular juegos para jugadores aliados en tus clanes y cursos."
simulate_games: "¡Simular Juegos!"
games_simulated_by: "Juegos simulados por ti:"
games_simulated_for: "Juegos simulados para ti:"
games_in_queue: "Juegos actualmente en cola:"
games_simulated: "Juegos simulados"
games_played: "Juegos jugados"
ratio: "Proporción"
leaderboard: "Tabla de Posiciones"
battle_as: "Combate como "
summary_your: "Tus "
summary_matches: "Partidas - "
summary_wins: " Ganadas, "
summary_losses: " Perdidas"
rank_no_code: "Sin Código Nuevo para Clasificar"
rank_my_game: "¡Clasifica Mi Juego!"
rank_submitting: "Enviando..."
rank_submitted: "Enviado para Clasificación"
rank_failed: "Fallo al Clasificar"
rank_being_ranked: "Juego Siendo Clasificado"
rank_last_submitted: "Presentado"
help_simulate: "¿Ayudar simulando juego?"
code_being_simulated: "Tu nuevo código está siendo simulado por otros jugadores para clasificación. Esto se refrescará a medida que vengan nuevas partidas."
no_ranked_matches_pre: "Sin partidas clasificadas para el "
no_ranked_matches_post: " equipo! Juega en contra de algunos competidores y luego vuelve aquí para ver tu juego clasificado."
choose_opponent: "Escoge un Oponente"
select_your_language: "Selecciona tu idioma"
tutorial_play: "Juega el Tutorial"
tutorial_recommended: "Recomendado si nunca has jugado antes"
tutorial_skip: "Saltar Tutorial"
tutorial_not_sure: "¿No estás seguro de que sucede?"
tutorial_play_first: "Juega el Tutorial primero."
simple_ai: "IA Simple"
warmup: "Calentamiento"
friends_playing: "Amigos Jugando"
log_in_for_friends: "Ingresa para jugar con tus amigos!"
social_connect_blurb: "Conectate y juega contra tus amigos!"
invite_friends_to_battle: "Invita a tus amigos para que se unan a la Batalla!"
fight: "Pelea!"
watch_victory: "Observa tu Victoria"
defeat_the: "Derrota a"
watch_battle: "Mirar la batalla"
tournament_started: ", iniciado"
tournament_ends: "Final de Torneo"
tournament_ended: "Finalizó el Torneo"
tournament_rules: "Reglas del Torneo"
tournament_blurb: "Escribe código, recolecta oro, arma ejercitos, aplasta adversarios, gana premios, y asciende en tu carrera por $40,000 en el Torneo Codicia! Echa un vistazo a los detalles"
tournament_blurb_criss_cross: "Gana apuestas, construye caminos, burla tus oponentes, agarra gemas, y asciende tu perfil en nuestro torneo Cruzado! Echa un vistazo a los detalles"
tournament_blurb_zero_sum: "Suelta tus habilidades de código en recolección de oro y tácticas de batalla en este partido espejo alpino entre el hechicero rojo y el hechicero azul. El torneo comenzó el Viernes, 27 de Marzo y se extenderá hasta el Lunes, 6 de Abril a las 5PM PDT. Compite por la diversión y la gloria ! Echa un vistazo a los detalles:"
tournament_blurb_ace_of_coders: "¡Lucha en el glaciar congelado en este encuentro con estilo dominación en espejo! El torneo comienza el Miércoles 16 de Septiembre, y se ejecutará hasta el Miércoles 14 de Octubre hasta las 5PM PDT. Revisa los detalles"
tournament_blurb_blog: "en nuestro blog"
rules: "Reglas"
winners: "<NAME>"
league: "Liga"
red_ai: "IA Roja" # "Red AI Wins", at end of multiplayer match playback
blue_ai: "<NAME>"
wins: "Gana" # At end of multiplayer match playback
humans: "<NAME>" # Ladder page display team name
ogres: "Azul"
live_tournament: "Torneo en vivo"
awaiting_tournament_title: "Torneo inactivo"
awaiting_tournament_blurb: "La arena de torneos no se encuentra activa en este momento."
tournament_end_desc: "El torneo ha terminado. ¡Gracias por jugar!"
age: "Edad"
bracket_0_11: "0-11"
bracket_11_14: "11-14"
bracket_14_18: "14-18"
# bracket_11_18: "11-18"
bracket_open: "Abierto"
user:
user_title: "__name__ - Aprende a programar con CodeCombat"
stats: "Estados"
singleplayer_title: "Nivel un jugador"
multiplayer_title: "Niveles multijugador"
achievements_title: "Logros"
last_played: "Último jugado"
status: "Estado"
status_completed: "Completo"
status_unfinished: "Incompleto"
no_singleplayer: "No hay juegos para un jugador todavía."
no_multiplayer: "No hay juegos multijugador todavía."
no_achievements: "Sin Logros todavía."
favorite_prefix: "Idioma favorito "
favorite_postfix: "."
not_member_of_clans: "No eres miembro de ningún clan todavía."
certificate_view: "ver certificado"
certificate_click_to_view: "haz clic para ver certificado"
certificate_course_incomplete: "curso incompleto"
certificate_of_completion: "Certificado de Aprobación"
certificate_endorsed_by: "Avalado por"
certificate_stats: "Estadísticas de Curso"
certificate_lines_of: "líneas de"
certificate_levels_completed: "niveles completados"
certificate_for: "Por"
certificate_number: "No."
achievements:
last_earned: "Último Ganado"
amount_achieved: "Cantidad"
achievement: "Logros"
current_xp_prefix: ""
current_xp_postfix: " en total"
new_xp_prefix: ""
new_xp_postfix: " ganado"
left_xp_prefix: ""
left_xp_infix: " hasta el nivel "
left_xp_postfix: ""
account:
title: "Cuenta"
settings_title: "Configuración de cuenta"
unsubscribe_title: "Cancelar suscripción"
payments_title: "Pagos"
subscription_title: "Suscripción"
invoices_title: "Facturas"
prepaids_title: "Prepagados"
payments: "Pagos"
prepaid_codes: "Códigos Prepagados"
purchased: "Comprado"
subscribe_for_gems: "Suscríbete para obtener gemas"
subscription: "Suscripción"
invoices: "Facturas"
service_apple: "Apple"
service_web: "Web"
paid_on: "Pagado en"
service: "Servicio"
price: "Precio"
gems: "Gemas"
active: "Activo"
subscribed: "Suscrito"
unsubscribed: "Desuscrito"
active_until: "Activo Hasta"
cost: "Costo"
next_payment: "Próximo Pago"
card: "Tarjeta"
status_unsubscribed_active: "No estas suscrito y no se te cobrará, pero tu cuenta está activa por ahora."
status_unsubscribed: "¡Obtén acceso a nuevos niveles, héroes, items y gemas extras con la suscripción a CodeCombat!"
not_yet_verified: "No verificado todavía."
resend_email: "Reenviar email"
email_sent: "¡Email enviado! Revisa tu casilla."
verifying_email: "Verificando tu email..."
successfully_verified: "¡Has verificado tu email con exito!"
verify_error: "Algo salio mal al verificar tu email :("
unsubscribe_from_marketing: "¿Cancelar suscripción de __email__ de todos los correos de marketing de CodeCombat?"
unsubscribe_button: "Si, cancelar suscripción"
unsubscribe_failed: "Error"
unsubscribe_success: "¡Éxito!"
account_invoices:
amount: "Cantidad en dólares."
declined: "La tarjeta fue rechazada."
invalid_amount: "Por favor ingrese cantidad en dólares."
not_logged_in: "Ingresate o crea una cuenta para acceder a las facturas."
pay: "Pagar Factura"
purchasing: "Comprando..."
retrying: "Error de Servidor, reintentando..."
success: "Listo, fue cobrado. Gracias!"
account_prepaid:
purchase_code: "Adquirir un Código de Suscripción"
purchase_code1: "Los códigos de suscripción pueden ser canjeados para agregar tiempo de suscripción premium para una o más cuentas CodeCombat." # {change}
purchase_code2: "Cada cuenta CodeCombat puede canjear una sola vez un Código de Suscripción en particular."
purchase_code3: "Los meses del Código de Suscripción serán agregados al final de la suscripción existente de la cuenta."
purchase_code4: "Los códigos de suscripción son para las cuentas que juegan la versión doméstica de CodeCombat, no se pueden usar en lugar de las licencias de estudiante para la versión de aula."
purchase_code5: "Para obtener más información sobre licencias de estudiantes, comunícate con"
users: "Usuarios"
months: "Meses"
purchase_total: "Total"
purchase_button: "Enviar Adquisición"
your_codes: "Tus Códigos:"
redeem_codes: "Reclamar un Código de Suscripción"
prepaid_code: "Código Prepagado"
lookup_code: "Buscar código prepagado"
apply_account: "Aplicara tu cuenta"
copy_link: "Puedes copiarl el enlace del código y enviarlo a alguien."
quantity: "Cantidad"
redeemed: "Reclamado"
no_codes: "¡Aún sin códigos!"
you_can1: "Puedes"
you_can2: "comprar un código prepagado"
you_can3: "que puede ser aplicado a tu propia cuenta o regalado a otros."
ozaria_chrome:
sound_off: "Sonido apagado"
sound_on: "Sonido encendido"
back_to_map: "Volver al mapa"
level_options: "Opciones de nivel"
restart_level: "Reiniciar nivel"
max_browser: "Maximizar navegador"
loading_error:
could_not_load: "Error cargando del servidor" # {change}
connection_failure: "Fallo de conexión."
connection_failure_desc: "Al parecer no estás conectado a internet! Revisa tu conección de red y actualiza la página."
login_required: "Login Requerido"
login_required_desc: "Necesitas iniciar sesión para acceder a esta página."
unauthorized: "Necesitas acceder. ¿Tienes desabilitadas las cookies?"
forbidden: "No tienes los permisos."
forbidden_desc: "Oh no, no hay nada que podemos mostrarte aquí! Asegurate que has iniciado sesión en la cuenta correcta, o visita uno de los siguientes enlaces para regresar a programar!"
not_found: "No encontrado."
not_found_desc: "Mmm, no hay nada aquí. Visita uno de los siguientes enlaces para regresar a programar!"
not_allowed: "Método no permitido."
timeout: "Expiró el tiempo del servidor." # {change}
conflict: "Conflicto de recurso."
bad_input: "Mala entrada."
server_error: "Error de servidor."
unknown: "Error desconocido." # {change}
error: "ERROR"
general_desc: "Ocurrió un errór, probablemente es tu culpa. Espera un poco y luego refresca la página, o visíta uno de los siguientes enlaces para regresar a programar!"
too_many_login_failures: "Hubo demasiados intentos de acceso fallidos. Vuelve a intentarlo más tarde."
something_went_wrong: "¡Ups! Hubo un error."
resources:
level: "Nivel"
patch: "Parche"
patches: "Parches"
system: "Sistema"
systems: "Sistemas"
component: "Componente"
components: "Componentes"
hero: "Heróe"
campaigns: "Campañas"
concepts:
advanced_css_rules: "Reglas CSS Avanzadas"
advanced_css_selectors: "Selectores CSS Avanzados"
advanced_html_attributes: "Atributos HTML Avanzados"
advanced_html_tags: "Etiquetas HTML Avanzados"
algorithm_average: "Algoritmo Promedio"
algorithm_find_minmax: "Algoritmo Buscar Min/Max"
algorithm_search_binary: "Algoritmo Búsqueda Binaria"
algorithm_search_graph: "Algoritmo Búsqueda Grafica"
algorithm_sort: "Algoritmo Ordenar"
algorithm_sum: "Algoritmo Suma"
arguments: "Argumentos"
arithmetic: "Aritmética"
array_2d: "Matrices Bidimencionales"
array_index: "Indexando Matrices"
array_iterating: "Iterando Sobre Matrices"
array_literals: "Matrices Literales"
array_searching: "Buscando en Matrices"
array_sorting: "Array Sorting"
arrays: "Arreglos"
basic_css_rules: "Reglas CSS Básicas"
basic_css_selectors: "Selectores CSS Básicos"
basic_html_attributes: "Atributos HTML Básicos"
basic_html_tags: "Etiquetas HTML Básicas"
basic_syntax: "Sintaxis Básica"
binary: "Binario"
boolean_and: "Booleanos Y"
boolean_inequality: "Desigualdad Booleana"
boolean_equality: "Booleano Equidad"
boolean_greater_less: "Booleano Mayor/Menor que"
boolean_logic_shortcircuit: "Booleano Cortocircuito Lógico"
boolean_not: "Booleano Negación"
boolean_operator_precedence: "Booleano Precedencia de Operadores"
boolean_or: "Booleano O"
boolean_with_xycoordinates: "Comparación de Coordenadas"
bootstrap: "Bootstrap"
break_statements: "Declaraciones Break"
classes: "Clases"
conditionals: "Condicionales"
continue_statements: "Declaraciones Continue"
debugging: "Depuración"
dom_events: "Eventos de DOM"
dynamic_styling: "Estilos Dinámicos"
events: "Eventos"
event_concurrency: "Concurrencia de Eventos"
event_data: "Datos de Evento"
event_handlers: "Manejadores de Evento"
event_spawn: "Generador de Eventos"
for_loops: "Bucle For"
for_loops_nested: "Bucles For Anidados"
for_loops_range: "Bucle For en Rangos"
functions: "Funciones"
functions_parameters: "Parámetros"
functions_multiple_parameters: "Múltiples Parámetros"
game_ai: "IA de Juego"
game_design: "Diseño de juegos"
game_goals: "Objetivos del Juego"
game_spawn: "Generador del Juego"
graphics: "Gráficos"
graphs: "Gráfico"
heaps: "Montículos"
if_condition: "Declaraciones Condicionales If"
if_else_if: "Declaraciones If/Else If"
if_else_statements: "Declaraciones If/Else"
if_statements: "Declaraciones If"
if_statements_nested: "Declaraciones If Anidadas" # {change}
indexing: "Indexado de Arreglos"
input_handling_flags: "Manejo de Entradas - Flags"
input_handling_keyboard: "Manejo de Entradas - Keyboard"
input_handling_mouse: "Manejo de Entradas - Mouse"
intermediate_css_rules: "Reglas CSS Intermedias"
intermediate_css_selectors: "Selectores CSS Intermedios"
intermediate_html_attributes: "Atributos HTML Intermedios"
intermediate_html_tags: "Etiquetas HTML Intermedias"
jquery: "jQuery"
jquery_animations: "Animaciones jQuery"
jquery_filtering: "Filtrado de Elementos jQuery"
jquery_selectors: "Selectores jQuery"
length: "Longitud de Matrices"
math_coordinates: "Coordenadas Matemáticas"
math_geometry: "Geometría"
math_operations: "Operaciones Matemáticas"
math_proportions: "Proporciones Matemáticas"
math_trigonometry: "Trigonometría"
object_literals: "Objetos Literales"
parameters: "Parámetros"
problem_solving: "Solución de problemas"
programs: "Programas"
properties: "Propiedades"
property_access: "Acceso a Propiedades"
property_assignment: "Asignación de Propiedades"
property_coordinate: "Coordinación de Propiedades"
queues: "Estructuras de Datos - Colas"
reading_docs: "Leyendo Documentos"
recursion: "Recursividad"
return_statements: "declaraciones de Return"
sequences_algorithms: "Secuencias y algoritmos"
stacks: "Estructuras de Datos - Pilas"
strings: "Cadenas"
strings_concatenation: "Concatenación de Cadenas"
strings_substrings: "Subcadenas"
student_code: "Código de estudiante"
syntax: "Sintaxis"
trees: "Estructuras de Datos - Arboles"
variables: "Variables"
vectors: "Vectores"
while_condition_loops: "Bucles While con Condicionales"
while_loops_simple: "Bucles While"
while_loops_nested: "Bucles While Anidados"
xy_coordinates: "Coordenadas Cartesianas"
advanced_strings: "Cadenas - Avanzado" # Rest of concepts are deprecated
algorithms: "Algoritmos"
boolean_logic: "Lógica Booleana"
basic_html: "HTML Básico"
basic_css: "CSS Básico"
basic_web_scripting: "Web Scripting Básico"
intermediate_html: "HTML Intermedio"
intermediate_css: "CSS Intermedio"
intermediate_web_scripting: "Web Scripting Intermedio"
advanced_html: "HTML Avanzado"
advanced_css: "CSS Avanzado"
advanced_web_scripting: "Web Scripting Avanzado"
input_handling: "Manejo de Entradas"
while_loops: "Bucles"
place_game_objects: "Poner objetos en el juego"
construct_mazes: "Construir laberintos"
create_playable_game: "Crear un proyecto de juego jugable y compartible"
alter_existing_web_pages: "Editar página web existente"
create_sharable_web_page: "Crear página web compartible"
basic_input_handling: "Manejo de Entradas Básico"
basic_game_ai: "IA de Juego Básico"
basic_javascript: "JavaScript Básico"
basic_event_handling: "Manejo de Eventos Básico"
create_sharable_interactive_web_page: "Crear página web interactiva compartible"
iteration: "Iteración"
nesting: "Anidamiento"
data_types: "Tipos de datos"
objects: "Objetos"
methods: "Métodos"
compound_conditionals: "Condicionales compuestos"
comparators: "Comparadores"
data_and_analysis: "Datos y análisis"
anonymous_teacher:
notify_teacher: "Notificar al Maestro"
create_teacher_account: "Crear una cuenta de maestro gratuita"
enter_student_name: "Tu nombre:"
enter_teacher_email: "Correo electrónico de tu maestro:"
teacher_email_placeholder: "<EMAIL>"
student_name_placeholder: "escribe tu nombre aquí"
teachers_section: "Maestros:"
students_section: "Estudiantes:"
teacher_notified: "¡Hemos notificado a tu maestro que quieres jugar más CodeCombat en tu clase!"
delta:
added: "Agregado"
modified: "Modificado"
not_modified: "No Modificado"
deleted: "Borrado"
moved_index: "Índice movido"
text_diff: "Diferir Texto"
merge_conflict_with: "UNIR CONFLICTO CON"
no_changes: "Sin cambios"
legal:
page_title: "Información legal"
opensource_introduction: "CodeCombat es parte de la comunidad open source."
opensource_description_prefix: "Echa un vistazo a "
github_url: "nuestro GitHub"
opensource_description_center: "y ayudanos si quieres! CodeCombat esta construido por docenas de proyectos open source, y los amamos. Mira "
archmage_wiki_url: "nuestra wiki de Archimago"
opensource_description_suffix: "Para la lista de softwares que hacen al juego posible."
practices_title: "Mejores prácticas respetuosas"
practices_description: "Estas son nuestras promesas hacia ti, el jugador, en términos menos legales."
privacy_title: "Privacidad"
privacy_description: "No vederemos nada sobre tu información personalWe will not sell any of your personal information."
security_title: "Seguridad"
security_description: "Queremos mantener tu información personal privada. Como un proyecto open source, cualquiera puede revisar y mejorar nuestros sistemas de seguridad."
email_title: "Mail"
email_description_prefix: "No te vamos a inundar de Spam. Mediante"
email_settings_url: "tus opciones de mail"
email_description_suffix: "o mediante links en los mails que mandamos, tu puedas cambiar tus preferencias y fácilmente desuscribirte en cualquier momento."
cost_title: "Costo"
cost_description: "CodeCombat es gratuito para todos sus niveles principales, con una suscripción de ${{price}} USD/mes con acceso a niveles adicionales y un bonus de {{gems}} gemas cada mes. Puedes cancelar con un click y ofrecemos una garantía del 100%."
copyrights_title: "Derechos y Licencias"
contributor_title: "Contributor License Agreement"
contributor_description_prefix: "Todas las Contribuciones, tanto en el website como en nuestro Repositorio GitHub, estan sujetos a nuestra aprobación."
cla_url: "CLA"
contributor_description_suffix: "A lo que debes de estar de acuerdo antes de contribuir."
code_title: "Código - MIT" # {change}
client_code_description_prefix: "Todo el código del lado del cliente para codecombat.com en el repositorio público de GitHub y en la base de datos de codecombat.com, está bajo la "
mit_license_url: "Licencia MIT"
code_description_suffix: "Esto incluye todo el código en Systems and Components that are made available by CodeCombat for the purpose of creating levels."
art_title: "Arte/Música - Comunas Creativas "
art_description_prefix: "Todo el Contenido Comunal está disponible bajo la"
cc_license_url: "Licencia Internacional de Atribución Comunas Creativas (CC) 4.0"
art_description_suffix: "Contenido Comunal es cualquiera hecho por CodeCombat y disponile con el propósito de crear niveles. Esto incluye:"
art_music: "Música"
art_sound: "Sonido"
art_artwork: "Trabajo Artístico"
art_sprites: "Sprites"
art_other: "Cualquier otro trabajo creativo (no necesariamente código) que están disponibles cuando se crean niveles."
art_access: "Actualmente no hay un sistema fácil y universal para obtener estos activos. En general, obtenlos de los URLs tal y como son usados por el sitio, contáctanos si necesitas ayuda, o ayúdanos extendiendo el sitio para hacer estos activos accesibles más fácilmente."
art_paragraph_1: "Para atribución, por favor nombre y enlace a codecombat.com cerca de donde esta fuente sea usada o donde sea apropiado en el medio usado. Por ejemplo:"
use_list_1: "Si es usado en una película o en otro juego, incluya codecombat.com en los créditos."
use_list_2: "Si es usado en un website, incluya un link cerca donde es usado, por ejemplo debajo de una imagen, o en las atribuciones generales de la página, donde pueda mencionar también otros trabajos bajo Creative Commons o de código abierto que sean usados en el sitio web. Cualquier otro website que haga clara referencia a CodeCombat, tal como un blog post mencionando a CodeCombat, no necesita una atribución separada."
art_paragraph_2: "Si el contenido usado no fue creado por CodeCombat, sino por un usuario de codecombat.com, atribuya al usuario y siga las directivas de atribución provistas en la descripción del recurso, en caso las haya."
rights_title: "Derechos Reservados"
rights_desc: "Todos los derechos estan reservados para los niveles mismos. Esto incluye."
rights_scripts: "Scripts"
rights_unit: "Configuración de la unidad"
rights_writings: "Escritos"
rights_media: "Media (sonidos, música) y cualquier otro contenido creativo hecho específicamente para un nivel y que no haya sido hecho disponible al público cuando se crearon los niveles."
rights_clarification: "Aclarando, todo contenido puesto a disposición en el Editor de Niveles con el propósito de hacer más niveles se encuentra bajo licencia CC, mientras todo contenido creado con el Editor de Niveles o cargado durante la creación de Niveles no lo está."
nutshell_title: "En una palabra"
nutshell_description: "Cualquier recurso que te proveamos en el Editor de Niveles es gratis de usar como te plazca para la creación de Niveles. Sin embargo, nos reservamos el derecho de restringir la distribución de los niveles por sí mismos (aquellos creados en codecombat.com) para así poder cobrar por ellos en el futuro, si es que eso es lo que termina pasando."
nutshell_see_also: "Mira También:"
canonical: "La versión en inglés de este documento es la versión canónica y definitiva. Si hay alguna discrepancia entre las traducciones, la versión en inglés toma precedencia."
third_party_title: "Servicios de Terceros"
third_party_description: "CodeCombat utiliza los siguientes servicios de terceros (entre otros):"
cookies_message: "CodeCombat utiliza algunas cookies esenciales y no esenciales."
cookies_deny: "Rechazar las cookies no esenciales"
cookies_allow: "Permitir cookies"
ladder_prizes:
title: "Premios de Torneos" # This section was for an old tournament and doesn't need new translations now.
blurb_1: "Estos premios seran dados de acuerdo a "
blurb_2: "las reglas del torneo"
blurb_3: "a los mejores jugadores humanos y ogros."
blurb_4: "Dos equipos significan el doble de premios!"
blurb_5: "(Habrán dos ganadores en el primer puesto, dos en el segundo puesto, etc.)"
rank: "Ranking"
prizes: "Premios"
total_value: "Valor Total"
in_cash: "en dinero"
custom_wizard: "CodeCombat Mago Personalizado"
custom_avatar: " CodeCombat Avatar Personalizado"
heap: "Por seis meses acceso \"Startup\"."
credits: "creditos"
one_month_coupon: "Cupón: elige entre Rails o HTML."
one_month_discount: "descuento del 30%: elige entre Rails o HTML"
license: "licencia"
oreilly: "ebook de su elección"
calendar:
year: "Año"
day: "Día"
month: "Mes"
january: "Enero"
february: "Febrero"
march: "Marzo"
april: "Abril"
may: "Mayo"
june: "Junio"
july: "Julio"
august: "Agosto"
september: "Septiembre"
october: "Octubre"
november: "Noviembre"
december: "Diciembre"
code_play_create_account_modal:
title: "¡LO LOGRASTE!" # This section is only needed in US, UK, Mexico, India, and Germany
body: "Pronto serás un programador experto. Regístrate para recibir <strong>100 GEMAS</strong> adicionales y participar en un sorteo donde podrás <strong>GANAR $50,000 Y OTROS PREMIOS DE LENOVO</strong>."
sign_up: "REGÍSTRATE Y SIGUE PROGRAMANDO ▶"
victory_sign_up_poke: "¡ABRE UNA CUENTA GRATUITA PARA GUARDAR TU CÓDIGO Y PARTICIPAR EN UN SORTEO DONDE PODRÁS GANAR PREAMIOS!"
victory_sign_up: "REGÍSTRATE PARA PODER <strong>GANAR $50,000</strong>"
server_error:
email_taken: "Email ya utilizado"
username_taken: "El nombre de usuario ya existe"
esper:
line_no: "Linea $1: "
uncaught: "$1 no detectado" # $1 will be an error type, eg "Uncaught SyntaxError"
reference_error: "Referencia Errónea: "
argument_error: "Argumento Erróneo: "
type_error: "Tipo Erróneo: "
syntax_error: "Sintaxis Errónea: "
error: "Error: "
x_not_a_function: "$1 no es una función"
x_not_defined: "$1 no está definido"
spelling_issues: "Corrige la ortografía: ¿quisiste decir `$1` en lugar de `$2`?"
capitalization_issues: "Cuidado con las mayúsculas: `$1` debe ser `$2`."
py_empty_block: "$1 vacío. Adelanta 4 espacios las declaraciones dentro del bloque $2."
fx_missing_paren: "Si deseas llamar `$1` como función, pon paréntesis `()` al final"
unmatched_token: "`$1` no coincide. Cada apertura de `$2` necesita un cierre de `$3` para coincidir."
unterminated_string: "Cadena sin terminar. Agrega `\"` al final de la cadena."
missing_semicolon: "Falta punto y coma."
missing_quotes: "Faltan comillas. Intenta `$1`"
argument_type: "El argumento `$2` de `$1` debe tener un tipo `$3`, pero tiene `$4`: `$5`."
argument_type2: "El argumento `$2` de `$1` debe tener un tipo `$3`, pero tiene `$4`."
target_a_unit: "Apuntar a una unidad."
attack_capitalization: "Ataca a $1, no a $2. (Mayúsculas son importantes.)"
empty_while: "Sentencia while vacía. Adelanta 4 espacios las declaraciones dentro del bloque while."
line_of_site: "El argumento `$2` de `$1` tiene un problema. ¿Hay algún enemigo en la línea de visión?"
need_a_after_while: "Necesitas un `$1` después de `$2`."
too_much_indentation: "Demasiada indentación al inicio de esta línea."
missing_hero: "Falta la palabra clave `$1`; debe ser `$2`."
takes_no_arguments: "`$1` no acepta argumentos."
no_one_named: "No se puede apuntar a \"$1\" porque nadie se llama así."
separated_by_comma: "Al llamar una función los parámetros deben estar separados con `,`"
protected_property: "No se puede leer propiedad protegida: $1"
need_parens_to_call: "Si deseas llamar `$1` como función, pon paréntesis `()` al final"
expected_an_identifier: "Se esperaba un identificador y en su lugar se recibió '$1'."
unexpected_identifier: "Identificador inesperado"
unexpected_end_of: "Fin de entrada inesperado"
unnecessary_semicolon: "Punto y coma innecesario."
unexpected_token_expected: "Símbolo inesperado: se esperaba $1 pero se encontró $2 mientras se analizaba $3"
unexpected_token: "Símbolo $1 inesperado"
unexpected_token2: "Símbolo inesperado"
unexpected_number: "Número inesperado"
unexpected: "No se esperaba '$1'."
escape_pressed_code: "Escape presionado; código anulado."
target_an_enemy: "Apunta a un enemigo por su nombre, como `$1`, no la cadena `$2`."
target_an_enemy_2: "Apunta a un enemigo por su nombre, como $1."
cannot_read_property: "No se puede leer la propiedad '$1' de indefinido"
attempted_to_assign: "Se intentó asignar una propiedad de solo lectura."
unexpected_early_end: "Fin del programa antes de lo esperado."
you_need_a_string: "Necesitas una cadena para construir; una de $1"
unable_to_get_property: "No se puede obtener la propiedad '$1' de una referencia nula o indefinida" # TODO: Do we translate undefined/null?
code_never_finished_its: "El código no finalizo. Es demasiado lento o tiene un bucle infinito."
unclosed_string: "Cadena sin cerrar."
unmatched: "No coincide '$1'."
error_you_said_achoo: "Dijiste: $1, pero la contraseña es: $2. (Mayúsculas y minúsculas son importantes.)"
indentation_error_unindent_does: "Error de Indentación: no coincide con ningun nivel de indentación"
indentation_error: "Error de Indentación."
need_a_on_the: "Necesitas un `:` al final de la linea seguido de `$1`."
attempt_to_call_undefined: "se intento llamar '$1' (un valor nulo)"
unterminated: "`$1` sin terminar"
target_an_enemy_variable: "Apunta a la variable $1, y no al string $2. (Intenta usar $3.)"
error_use_the_variable: "Usa el nombre de la variable como `$1` en lugar de la cadena como `$2`"
indentation_unindent_does_not: "Desindentación no coincide con ningún nivel de indentación"
unclosed_paren_in_function_arguments: "No se cerró $1 en los argumentos de la función."
unexpected_end_of_input: "Fin de entrada inesperado"
there_is_no_enemy: "No hay `$1`. Primero utiliza `$2`." # Hints start here
try_herofindnearestenemy: "Intenta `$1`"
there_is_no_function: "No hay ninguna función `$1`, pero `$2` tiene el método `$3`."
attacks_argument_enemy_has: "El argumento `$2` de `$1` tiene un problema."
is_there_an_enemy: "¿Aún hay algún enemigo en tu linea de visión?"
target_is_null_is: "El objetivo es $1. ¿Siempre hay un blanco para atacar? (Usa $2?)"
hero_has_no_method: "`$1` no tiene el método `$2`."
there_is_a_problem: "Hay un problema con tu código."
did_you_mean: "¿Quisiste decir $1? No tienes equipado un item con esa habilidad."
missing_a_quotation_mark: "Falta una commilla. "
missing_var_use_var: "Falta `$1`. Utiliza `$2` para hacer una nueva variable."
you_do_not_have: "No tienes equipado un item con la habilidad $1."
put_each_command_on: "Pon cada comando en lineas separadas"
are_you_missing_a: "¿Te falta un '$1' despues de '$2'? "
your_parentheses_must_match: "Los paréntesis deben coincidir."
apcsp:
title: "Fundamentos de Ciencias de la Computación AP | Con el respaldo del College Board"
meta_description: "El amplio plan de estudios y el programa de desarrollo profesional de CodeCombat es todo lo que necesitas para ofrecer el curso de ciencias de la computación más reciente de College Board a tus estudiantes."
syllabus: "Programa de Fundamentos de Ciencias de la Computación AP"
syllabus_description: "Usa este recurso para planificar el plan de estudios de CodeCombat para tus clases de Fundamentos de Ciencias de la Computación AP."
computational_thinking_practices: "Prácticas del Pensamiento Computacional"
learning_objectives: "Objetivos de aprendizaje"
curricular_requirements: "Requisitos curriculares"
unit_1: "Unidad 1: Tecnología creativa"
unit_1_activity_1: "Actividad de la unidad 1: Prueba de usabilidad de la tecnología"
unit_2: "Unidad 2: Pensamiento computacional"
unit_2_activity_1: "Actividad de la unidad 2: Secuencias binarias"
unit_2_activity_2: "Actividad de la unidad 2: Proyecto de lección sobre informática"
unit_3: "Unidad 3: Algoritmos"
unit_3_activity_1: "Actividad de la unidad 3: Algoritmos - Guía del viajero"
unit_3_activity_2: "Actividad de la unidad 3: Simulación - Depredador y presa"
unit_3_activity_3: "Actividad de la unidad 3: Algoritmos - Diseño y programación en pareja"
unit_4: "Unidad 4: Programación"
unit_4_activity_1: "Actividad de la unidad 4: Abstracciones"
unit_4_activity_2: "Actividad de la unidad 4: Búsqueda y ordenamiento"
unit_4_activity_3: "Actividad de la unidad 4: Refactorización"
unit_5: "Unidad 5: La Internet"
unit_5_activity_1: "Actividad de la unidad 5: Cómo funciona la Internet"
unit_5_activity_2: "Actividad de la unidad 5: Simulador de la Internet"
unit_5_activity_3: "Actividad de la unidad 5: Simulación de una sala de chat"
unit_5_activity_4: "Actividad de la unidad 5: Ciberseguridad"
unit_6: "Unidad 6: Datos"
unit_6_activity_1: "Actividad de la unidad 6: Introducción a los datos"
unit_6_activity_2: "Actividad de la unidad 6: Big data"
unit_6_activity_3: "Actividad de la unidad 6: Compresión con y sin pérdida"
unit_7: "Unidad 7: Impacto personal y global"
unit_7_activity_1: "Actividad de la unidad 7: Impacto personal y global"
unit_7_activity_2: "Actividad de la unidad 7: Crowdsourcing"
unit_8: "Unidad 8: Tareas de desempeño"
unit_8_description: "Ayuda a los estudiantes a prepararse para la tarea de creación mediante el diseño de sus propios videojuegos y el repaso de conceptos clave."
unit_8_activity_1: "Práctica 1 para la tarea de creación: Desarrollo de Juegos 1"
unit_8_activity_2: "Práctica 2 para la tarea de creación: Desarrollo de Juegos 2"
unit_8_activity_3: "Práctica 3 para la tarea de creación: Desarrollo de Juegos 3"
unit_9: "Unidad 9: Reseña de Advanced Placement (AP)"
unit_10: "Unidad 10: Después de AP"
unit_10_activity_1: "Actividad de la unidad 10: Cuestionario web"
parent_landing:
slogan_quote: "\"CodeCombat es muy vertido y te enseña muchas cosas.\""
quote_attr: "Estudiante de quinto grado, Oakland, California"
refer_teacher: "Invitar a un maestro"
focus_quote: "Desbloquea el futuro de tu hijo"
value_head1: "La forma más divertida de aprender código escrito"
value_copy1: "CodeCombat es el tutor personal del estudiante. El material de estudio, que cumple con las pautas curriculares nacionales, ayudará a tu hijo a programar algoritmos, crear sitios web e incluso diseñar sus propios videojuegos."
value_head2: "Desarrollo de habilidades esenciales para el siglo 21"
value_copy2: "Tus hijos aprenderán a navegar por el mundo digital y se convertirán en sus verdaderos ciudadanos. CodeCombat es una solución que mejora el pensamiento crítico y la capacidad de adaptación de su hijo."
value_head3: "Héroes que le encantarán a tu hijo"
value_copy3: "Sabemos lo importante que son la diversión y el interés para un cerebro en desarrollo, así que incluimos todo el aprendizaje posible en un juego que los niños amarán."
dive_head1: "No solo ingenieros de software"
dive_intro: "Las habilidades de informática tienen una amplia gama de aplicaciones. ¡Estos son solo algunos ejemplos!"
medical_flag: "Aplicaciones médicas"
medical_flag_copy: "Desde la cartografía del genoma humano hasta una máquina para hacer resonancias magnéticas, la programación nos permite entender el cuerpo de maneras nunca antes conocidas."
explore_flag: "Exploración espacial"
explore_flag_copy: "Apollo llegó a la luna gracias a computadoras humanas que trabajaron arduamente, y los científicos usan programas de computación para analizar la gravedad de los planetas y encontrar estrellas nuevas."
filmaking_flag: "Cine y animación"
filmaking_flag_copy: "Desde los robots de Parque Jurásico hasta las animaciones increíbles de Dreamworks y Pixar, las películas no serían lo que son sin los creativos digitales detrás de escena."
dive_head2: "Los videojuegos son importante para el aprendizaje"
dive_par1: "Muchos estudios descubrieron que el aprendizaje basado en juego promueve"
dive_link1: "el desarrollo cognitivo"
dive_par2: "en niños, a la vez que es"
dive_link2: "más efectivo"
dive_par3: "a la hora de ayudar a los estudiantes"
dive_link3: "a aprender y retener conocimiento"
dive_par4: ","
dive_link4: "concentrarse"
dive_par5: "y alcanzar un mayor nivel de consecución de logros."
dive_par6: "El aprendizaje basado en juego también es bueno para desarrollar"
dive_link5: "capacidad de adaptación"
dive_par7: ", razonamiento cognitivo y"
dive_par8: ". La ciencia solo nos dice lo que ya saben los estudiantes. Los niños aprenden mejor jugando."
dive_link6: "funciones ejecutivas"
dive_head3: "Trabaja en equipo con maestros"
dive_3_par1: "En el futuro, "
dive_3_link1: "programar será tan fundamental como aprender a leer y escribir"
dive_3_par2: ". Trabajamos en conjunto con docentes para diseñar y desarrollar nuestro contenido, y estamos ansiosos por que tus hijos empiecen a aprender. Los programas de tecnología educativa como CodeCombat funcionan mejor cuando los docentes los implementan con regularidad. ¡Ayúdanos a lograrlo presentándonos a los maestros de tu hijo!"
mission: "Nuestra misión: enseñar y entretener"
mission1_heading: "Código para la generación de hoy"
mission2_heading: "Prepararse para el futuro"
mission3_heading: "Con el apoyo de padres como tú"
mission1_copy: "Nuestros especialistas en educación trabajan en colaboración con docentes para adaptar el contenido al panorama educativo de los estudiantes. Los niños adquieren habilidades que pueden aplicarse fuera del juego porque aprenden a resolver problemas más allá de su estilo de aprendizaje."
mission2_copy: "Una encuesta de 2016 demostró que el 64% de las niñas de tercer a quinto grado quieren aprender a programar. En 2015, hubo siete millones de búsquedas laborales que requerían habilidades de programación. Creamos CodeCombat porque todos los niños deberían tener la oportunidad de crear su mejor futuro."
mission3_copy: "En CodeCombat somos padres. Somos programadores. Somos educadores. Pero, sobre todo, somos personas que creemos en darles a nuestros hijos la mejor oportunidad para triunfar en lo que sea que decidan hacer en el futuro."
parent_modal:
refer_teacher: "Invitar a un maestro"
name: "<NAME>"
parent_email: "Tu correo electrónico"
teacher_email: "Correo electrónico del maestro"
message: "Mensaje"
custom_message: "Acabo de enterarme de CodeCombat y creo que sería un gran programa para tu asignatura. Es una plataforma para aprender ciencias de la computación que tiene un plan de estudios que cumple con las normas educativas.\n\nLa alfabetización digital es muy importante, y creo que esta sería una gran forma de hacer que los estudiantes se interesen en aprender a programar."
send: "Enviar correo"
hoc_2019:
heading: "Hora del Código 2019"
start: "Empieza tu camino"
create_a_class: "¡Crea una clase para monitorear el progreso de los estudiantes y garantizar el guardado de sus juegos de la Hora del Código!"
choose_language: "1. ELEGIR IDIOMA"
programming_language: "Idioma"
sign_up: "2. REGISTRARSE"
already_have_account: "¿Ya tienes una cuenta de CodeCombat o de Ozaria? Inicia sesión."
download_lesson_plan: "Descarga el plan de estudios"
try_activity_without_class: "Prueba la actividad sin crear una clase"
invite_students: "Invita a los estudiantes a unirse a tu clase enviándoles"
class_code: "CÓDIGO DE CLASE"
enter_code: "Los estudiantes pueden ingresar este código en www.ozaria.com/hoc"
class_url: "URL DE CLASE"
share_url: "Comparte la URL para que los estudiantes se unan a tu clase automáticamente."
start_activity: "Empezar actividad"
save_progress_modal: "Guarda tu progreso y continúa jugando más tarde"
want_to_save: "¿Quieres guardar tu progreso del Código de Honor?"
ask_teacher_class_code: "Pídele a tu maestro tu código de clase"
dont_have: "¡No tengo, pero quiero probar la actividad!"
hoc_activity: "Actividad de la Hora del Código"
save_progress: "Guardar progreso"
err_google_exists: "Ya existe una cuenta asociada a la cuenta de Google que seleccionaste. Elige otra cuenta de Google o inicia sesión con un nombre de usuario y una contraseña."
err_username_taken: "Ya existe una cuenta asociada al nombre de usuario que ingresaste. Elige otro nombre de usuario."
enter_it_here: "Ingrésalo aquí para guardar tu progreso del juego:"
have_a_class_code: "¿Tienes un código de clase?"
create_class_and_try_activity: "Crea una clase y prueba la actividad"
hoc_2018:
banner: "¡Feliz semana de la educación en ciencias de la computación!"
page_heading: "¡Tus estudiantes aprenderán a programar diseñando su propio juego!"
step_1: "Paso 1: Ve el video informativo"
step_2: "Paso 2: Pruébalo"
step_3: "Paso 3: Descarga el plan de estudios"
try_activity: "Prueba la actividad"
download_pdf: "Descarga el PDF"
teacher_signup_heading: "Convierte la Hora del Código en un Año del Código"
teacher_signup_blurb: "Todo lo que necesitas para enseñar ciencias de la computación sin experiencia previa."
teacher_signup_input_blurb: "Consigue el primer curso gratis:"
teacher_signup_input_placeholder: "Dirección de correo electrónico del maestro"
teacher_signup_input_button: "Consigue Ciencias de la Computación 1 gratis"
activities_header: "Más actividades de la Hora del Código"
activity_label_1: "¡Escapa de las mazmorras!"
activity_label_2: " Principiante: ¡diseña un videojuego!"
activity_label_3: "Avanzado: ¡diseña un videojuego de arcade!"
activity_button_1: "Ver lección"
about: "Acerca de CodeCombat"
about_copy: "Un programa de ciencias de la computación basado en juego creado según las normas educativas que enseña a escribir Python y JavaScript de verdad."
point1: "✓ Andamiaje"
point2: "✓ Diferenciado"
point3: "✓ Evaluaciones"
point4: "✓ Cursos basados en proyectos"
point5: "✓ Seguimiento de estudiantes"
point6: "✓ Planes de estudio completos"
title: "HORA DEL CÓDIGO"
acronym: "HDC"
hoc_2018_interstitial:
welcome: "¡Te damos la bienvenida a la Hora del Código de CodeCombat!"
educator: "Soy educador"
show_resources: "¡Muéstrame los recursos para maestros!"
student: "Soy estudiante"
ready_to_code: "¡Quiero empezar a programar!"
hoc_2018_completion:
congratulations: "¡Felicitaciones por completar <b>Programa, juega y comparte</b>!"
send: "¡Envíales a tus amigos y tu familia tu juego de la Hora del Código!"
copy: "Copiar URL"
get_certificate: "¡Obtén un certificado de finalización para celebrar con tu clase!"
get_cert_btn: "Obtener certificado"
first_name: "<NAME>"
last_initial: "Inicial del apellido"
teacher_email: "Dirección de correo electrónico del maestro"
school_administrator:
title: "Panel del administrador de la escuela"
my_teachers: "Mis maestros"
last_login: "Último ingreso"
licenses_used: "licencias utilizadas"
total_students: "estudiantes en total"
active_students: "estudiantes activos"
projects_created: "proyectos creados"
other: "Otros"
notice: "Los siguientes administradores de la escuela tienen acceso de solo lectura a los datos de tu aula:"
add_additional_teacher: "¿Necesitas agregar otro maestro? Contacta a tu ejecutivo de cuenta de CodeCombat o envía un correo a <EMAIL>. "
license_stat_description: "La cantidad de licencias disponibles incluye el número total de licencias disponibles para el maestro, incluidas las licencias compartidas."
students_stat_description: "Cuentas de estudiantes totales para todos los alumnos de todas las aulas, tengan o no una licencia activa."
active_students_stat_description: "Estudiantes activos cuenta la cantidad de alumnos que han ingresado a CodeCombat en los últimos 60 días."
project_stat_description: "Proyectos creados cuenta la cantidad total de proyectos de desarrollo web y de juegos que se han creado."
no_teachers: "No administras a ningún maestro."
interactives:
phenomenal_job: "¡Gran trabajo!"
try_again: "¡Ups, vuelve a intentar!"
select_statement_left: "¡Ups! Selecciona una instrucción de código antes de presionar Enviar."
fill_boxes: "Ups, asegúrate de completar todos los campos antes de presionar \"Enviar\"."
cannot_play_video: "Lamentablemente, no es posible reproducir este video en tu zona."
console_instructions: "Entérate por qué abriendo la consola de tu navegador: 1) haz clic derecho, 2) elige \"Inspeccionar\" y 3) haz clic en la pestaña Consola."
skip_video: "Saltar video"
unavailable: "No disponible"
admin:
license_type_full: "Cursos completos"
license_type_customize: "Personalizar cursos"
teacher_dashboard:
lock: "Bloquear"
unlock: "Desbloquear"
unassign: "Anular asignación"
choose_course: "Haz clic para seleccionar una opción del menú desplegable"
teacher_locked_message: "Tu maestro bloqueó el siguiente nivel"
plan_your_class_title: "Para planificar tu primera clase:"
plan_your_class1: "Consulta la información sobre el progreso del curso"
plan_your_class2: "Previsualiza las diapositivas de la lección y las actividades de extensión"
plan_your_class3: "Prueba el primer capítulo sin cargo"
click_dismiss: "Clic para ignorar"
track_progress: "Seguir progreso"
track_progress_desc: "Haz clic en la clase que acabas de crear para ver el progreso detallado de cada estudiante."
add_classes_title: "Agregar clases aquí"
add_classes: "¡Agrega clases para que los estudiantes empiecen el capítulo gratis!"
all_classes: "Todas las clases"
my_licenses: "Mis licencias"
resource_hub: "Centro de recursos"
pd: "Desarrollo profesional"
pd_short: "DP"
curriculum_guide: "Guía curricular"
add_class: "Agregar clase nueva"
no_licenses_yet: "Aún sin licencias"
req_licenses: "Solicitar licencias"
license_ratio_used: "__totalUsedLicenses__ de __totalSpots__"
licenses_applied: "Licencias aplicadas"
student_projects: "Proyectos de estudiantes"
no_classes_yet: "Aún no hay clases"
exemplar_project: "Proyecto modelo"
capstone_proj_for: "Proyecto final de __courseName__"
project_rubric: "Guía de evaluación del proyecto"
select_chapter: "Seleccionar capítulo"
concept_flag: "Concepto difícil"
support_learning: "Ayuda de aprendizaje"
concept_flag_desc: "Más del 50% de la clase tuvo que repetir una comprobación de conceptos 3 veces o más."
concept_flag_desc2: "El estudiante tuvo que repetir una comprobación de conceptos 3 veces o más."
click_progress_dot_tip: "Consejo: Haz clic en las burbujas de progreso para más detalles."
color_code: "Código de color"
content_guide: "Guía de contenido"
story: "Historia"
cutscenes: "Escenas"
cutscenes_tooltip: "<h3>Escena</h3><p>Un video corto que explica partes de la historia épica de Ozaria.</p>"
cinematics: "Cinemáticas"
concept_checks: "Comprobaciones de conceptos"
practice_levels: "Niveles de práctica"
challenge_levels: "Niveles de desafío"
capstone_levels: "Niveles finales"
intro: "Introducción"
practice: "Practicar"
assess: "Evaluar"
view_options: "Ver opciones"
manage_class: "Administrar clase"
assign_content: "Asignar contenido"
remove_students: "Quitar estudiantes"
revoke_licenses: "Anular licencias"
remaining_licenses: "Licencias restantes: __remaining__"
start_date: "Inicio: __date__"
end_date: "Finalización: __date__"
license_questions: "¿Tienes alguna pregunta sobre aplicar o anular licencias?"
need_more_licenses: "¿Necesitas más licencias? Te ayudaremos a crear una solución que satisfaga tus necesidades."
see_also_our: "También consulta nuestra"
for_more_funding_resources: "para enterarte de cómo aprovechar las fuentes de financiación de la ley CARES, como ESSER y GEER."
support_oz: "<EMAIL>"
standards_alignment: "Cumplimiento de normas"
standards_sample: "Una muestra de las normas cubiertas en este capítulo:"
play_chapter: "Jugar capítulo"
class_time_range: "Tiempo de clase (rango):"
in_game_play_time: "Tiempo de juego:"
class_time: "Tiempo de clase"
solution_guide: "Guía de solución"
module: "Módulo"
need_licenses_tooltip: "<h3>¡Necesitas licencias para acceder a este contenido!</h3><p>Ve a la página <a href='/teachers/licenses'>Mis licencias</a> para más información.</p>"
lesson_slides_tooltip: "<h3>Diapositivas de la lección</h3><p>Diapositivas que puedes descargar para guiar paso a paso a los estudiantes por los objetivos de aprendizaje del módulo.</p>"
project_rubric_tooltip: "<h3>Guía de evaluación del proyecto</h3><p>Una guía que puedes descargar y modificar para evaluar el proyecto final.</p>"
exemplar_projects_tooltip: "<h3>Proyecto modelo</h3><p>Vista en vivo de un modelo de proyecto final.</p>"
want_to_save_tooltip: "<h3>¿Quieres guardar tu progreso?</h3><p>Crea una cuenta de estudiante y accede a ella para jugar Ozaria como estudiante si quieres guardar tu progreso.</p>"
intro_explain_tooltip: "Las <b>\"introducciones\"</b> presentan nuevos conceptos o hacen avanzar la historia de manera escalonada. En general, incluyen cinemáticas o comprobaciones de conceptos."
chapter_num: "Capítulo __num__"
# read: "View Only"
# write: "Full Access"
# read_blurb: "View Only permits the added teacher to view your class and student progress without the ability to make changes to your class."
# write_blurb: "Full Access grants the added teacher the ability to make modifications to your class (add/remove students, assign chapters, modify licensure)"
# shared_with_none: "This class is not currently shared with any other teachers."
# share_info: "To give other teachers access to the class, add their emails below."
# class_owner: "Class Owner"
# share: "Share"
# outcomes:
# outcomes_report: "Outcomes Report"
# customize_report: "Customize Report"
# done_customizing: "Done Customizing"
# start_date: "Start date"
# end_date: "End date"
# school_admin: "School Administrator"
# school_network: "School Network"
# school_subnetwork: "School Subnetwork"
# classroom: "Classroom"
# view_outcomes_report: "View Outcomes Report"
# key_concepts: "Key Concepts"
# code_languages: "Code Languages"
# using_codecombat: "Using CodeCombat's personalized learning engine..."
# wrote: "wrote..."
# across_an_estimated: "across an estimated..."
# in: "in..."
# include: "Include "
# archived: "Archived"
# max: "Max "
# multiple: "s"
# computer_program: "computer program"
# computer_programs: "computer programs"
# line_of_code: "line of code"
# lines_of_code: "lines of code"
# coding_hours: "coding hours"
# expressed_creativity: "and expressed creativity by building"
# report_content_1: "standalone game and web "
# project: "project"
# projects: "projects"
# progress_stats: "Progress stats based on sampling __sampleSize__ of __populationSize__ students."
# standards_coverage: "Standards Coverage"
# coverage_p1: "The full Ozaria curriculum covers major programming standards in several widely-adopted frameworks, including those of the International Society for Technology in Education (ISTE), the Computer Science Teacher Association (CSTA), and the K-12 Computer Science Framework."
# coverage_p2: "Ozaria is created by the CodeCombat, the game-based learning company. We believe that students will be most prepared for both real-world computing jobs and further study of computer science by using real, typed code in full programming languages, so instead of using block-based visual programming languages for beginners, we teach Python and JavaScript – the same languages used widely today by companies ranging from Google to the New York Times."
# questions: "Have questions or want more information? We'd be happy to help."
# reach_out_manager: "Reach out to your Account Manager __name__ at "
# stats_include: "stats include __number__ other __name__"
| true | module.exports = nativeDescription: "Español (América Latina)", englishDescription: "Spanish (Latin America)", translation:
ozaria_home:
subtitle: "Informática que fascina"
heading_subtitle: "Una aventura de programación para estudiantes y una solución inmediata para enseñar Ciencias de la Computación."
item_list_p: "¡Prueba hoy mismo el capítulo 1 sin costo!"
engaging_heading_corner: "Una solución para involucrar a los estudiantes y apoyar a los maestros"
engaging_row1_h2: "Implementación sencilla"
engaging_row1_p: "Incluso sin experiencia en programación, con Ozaria puedes enseñar un plan de estudios de Ciencias de la Computación completo. Nuestros planes de estudios predefinidos y el intuitivo panel te darán las herramientas necesarias para empezar a enseñar desde el primer día."
engaging_row2_h2: "Jugabilidad inmersiva"
engaging_row2_p: "Los estudiantes se sumergirán en un juego de aventura en el cual sus conocimientos sobre Ciencias de la Computación avanzarán junto con la trama. En este entorno de aprendizaje divertido, los estudiantes desarrollarán habilidades del mundo real jugando."
engaging_row3_h2: "Planes de estudio que cumplen con las normas educativas"
engaging_row3_p: "Ozaria cumple con las normas ISTE y CSTA, por lo que enseñarás contenido de calidad a tus estudiantes, quienes dominarán conceptos esenciales de Ciencias de la Computación, desarrollarán habilidades de pensamiento computacional y aprenderán sobre la importancia de estos temas en la vida cotidiana."
pd_blurb: "Aprende las habilidades necesarias para enseñar Ciencias de la Computación de manera efectiva con nuestro curso de autoaprendizaje __pd__ acreditado por la CSTA. Obtén hasta 40 horas de crédito en cualquier momento y desde cualquier dispositivo."
back_cta_1_a: "Probar el capítulo 1 sin costo"
speech_bubble_testimonial_1_blockquote: "Una vez más, el equipo creó una reliquia del entretenimiento educativo. En mi opinión, como maestro veterano de secundaria con 26 años de experiencia, no existe mejor recurso para enseñar programación."
core_curriculum_header: "Asignaturas principales de Ciencias de la Computación"
core_curriculum_p: "Hemos desarrollado nuestro modelo de enseñanza a partir de teorías comprobadas y pruebas exhaustivas sobre la mejor forma de aprender."
core_curriculum_carousel_item1_header: "Hacer conexiones"
core_curriculum_carousel_item1_p: "Al principio de cada módulo, usa las diapositivas preexistentes de la lección para que los estudiantes hagan conexiones entre los nuevos conceptos de Ciencias de la Computación y ejemplos pertinentes de la vida diaria."
core_curriculum_carousel_item2_header: "Formar un significado propio"
core_curriculum_carousel_item2_p: "Luego, guía a los estudiantes para que comprendan mejor los nuevos conceptos completando las actividades de extensión que incluyen nuestros planes de estudios."
core_curriculum_carousel_item3_header: "Aprender nuevos conceptos"
core_curriculum_carousel_item3_p: "En la tercera etapa del ciclo de aprendizaje, los estudiantes aprenderán nuevos conceptos a través de diálogos expositivos entre los personajes de la historia de Ozaria. Las voces, los gráficos y las animaciones hacen que incorporar nueva información sea aún más accesible y divertido."
core_curriculum_carousel_item4_header: "Aplicar nuevos conocimientos"
core_curriculum_carousel_item4_p: "Luego, los estudiantes pondrán en práctica lo aprendido escribiendo código real de Python y JavaScript para resolver distintos desafíos presentados en niveles escalonados. Las pistas el juego ayudan a los estudiantes a identificar y corregir errores para que desarrollen una mayor confianza a la hora de programar."
core_curriculum_carousel_item5_header: "Proyecto sumativo"
core_curriculum_carousel_item5_p: "Al final de cada capítulo, los estudiantes se enfrentarán al desafío de exhibir sus nuevas habilidades y expresar su creatividad en proyectos sumativos en los que deberán construir sus propios juegos, historias y más."
core_curriculum_scope_sequence: "Ver alcance y secuencia"
core_curriculum_sample_lesson_slides: "Ver ejemplo de diapositivas de lección"
global_community_header: "Únete a nuestra comunidad global"
global_community_row1_p: "de estudiantes"
global_community_row2_p: "de líneas de código"
global_community_row3_p: "de maestros"
global_community_row4_p: "países"
admin_dashboard_header: "Paneles completos para administradores y maestros"
admin_dashboard_p: "Ozaria está diseñado sobre la base de opiniones de nuestra comunidad de más de 140.000 educadores y brinda las herramientas y los recursos necesarios para abordar los desafíos que conlleva enseñar Ciencias de la Computación."
admin_dashboard_row1_p: "El panel para maestros es intuitivo y permite acceder a los planes de estudio que ven los estudiantes, guías didácticas, estrategias de aprendizaje a distancia y otros recursos que seguramente te servirán."
admin_dashboard_row2_p: "La página de seguimiento del progreso te permite monitorear los avances de los estudiantes en tiempo real, obtener información valiosa sobre su desempeño e identificar de inmediato si es necesario intervenir de alguna forma."
admin_dashboard_row3_a: "Solicitar una cotización"
acodus_awards_a: "Probar el capítulo 1 sin costo"
speech_bubble_testimonial_2_blockquote: "Es el sitio de programación más accesible que conozco hasta el momento. Me gusta la historia que se plantea en Ozaria porque es una misión con la que los estudiantes pueden empatizar. La verdad, me encanta. De hecho, ¡yo también lo juego más de lo que me gustaría admitir!"
shareable_resources_header: "Recursos para compartir"
shareable_resources_p: "Comparte los siguientes recursos con maestros y administradores, o con los responsables de introducir o expandir las Ciencias de la Computación en tu escuela."
shareable_resources_a: "Descargar folleto"
back_cta_2_a: "Probar el capítulo 1 sin costo"
faq_header: "Preguntas frecuentes"
faq_row1_header: "¿Cómo se relaciona Ozaria con CodeCombat?"
faq_row1_p: "Ozaria se centra en el estudiante y es la evolución de CodeCombat, uno de los juegos de programación más populares de la historia. Desarrollamos Ozaria sobre la base de los aprendizajes obtenidos por enseñar Python y JavaScript a más de 20 millones de estudiantes. Ozaria incorpora nuevos modelos pedagógicos y una narrativa con una historia inmersiva, y está diseñado para implementarse en aulas tanto presenciales como virtuales."
faq_row2_header: "¿Qué edades o grados son los más adecuados para Ozaria?"
faq_row2_p: "Ozaria cumple con las normas ISTE y CSTA para enseñar Ciencias de la Computación en escuelas secundarias, pero estudiantes tanto mayores como menores lo han disfrutado y aprovechado."
faq_row3_header: "¿Cuánto cuesta acceder a todas las unidades y recursos disponibles?"
faq_row3_p_part1: "Personalizamos soluciones para escuelas y distritos. Podemos ayudarte a entender tus necesidades, contexto y presupuesto. "
faq_row3_p_part2: " para más detalles. También ofrecemos una "
faq_row3_p_part3: "guía de recursos de financiación"
faq_row3_p_part4: " para programas de Ciencias de la Computación en escuelas y distritos."
faq_row4_header: "En Ozaria, ¿el aprendizaje está basado en proyectos?"
faq_row4_p: "Sí. Ozaria incluye proyectos al final de cada capítulo para que los estudiantes creen sus propios juegos y puedan compartirlos. Estos proyectos son evaluaciones sumativas y una buena manera de que los estudiantes se expresen y les muestren a sus compañeros, amigos y familiares todo lo aprendido."
faq_row5_header: "¿Puedo usar Ozaria como plan de estudios principal para mi clase?"
faq_row5_p: "¡Claro que sí! Ozaria tiene todo lo que necesitas para dictar una asignatura completa de Ciencias de la Computación, incluso si vienes de otro campo: desde planificaciones de clases hasta guías de soluciones, guías de evaluación y alineaciones con normas."
faq_row6_p_part1: "Si tienes más preguntas, "
# see_faq_prefix: "See more"
# see_faq_link: "frequently asked questions in our help center"
# see_faq_suffix: "."
summary: "Ozaria es un programa de ciencias de la computación, un juego de aventura y una historia de fantasía en la que los estudiantes deben dominar la magia perdida de la programación para salvar al mundo."
value_prop1_h1: "Una historia épica. Jugabilidad inmersiva."
value_prop1_h2: "Inspira una conexión más profunda con el aprendizaje"
value_prop1_p: "En Ozaria, los estudiantes se encuentran inmersos en un nuevo mundo donde deben dominar conceptos esenciales de las ciencias de la computación para avanzar en el juego. La narrativa que se desarrolla crea una gran experiencia de aprendizaje centrada en los estudiantes, en la cual el tiempo que cada alumno invierte en la historia de Ozaria equivale al tiempo que invierten en su propio camino de aprendizaje."
value_prop2_h1: "Descubre el héroe que hay en cada estudiante"
value_prop2_h2: "Desarrolla habilidades reales jugando"
value_prop2_p: "Los conceptos y las habilidades se presentan a través de contenidos diseñados cuidadosamente que incluyen niveles de juego, diálogos de enseñanza entre personajes, escenas de video y más. Los estudiantes aprenderán a programar en Python o JavaScript, a resolver problemas usando pensamiento computacional, a demostrar su comprensión mediante evaluaciones formativas y a aplicar lo que aprendieron en sus propios proyectos."
value_prop3_h1: "Empieza tu camino de manera gratuita"
value_prop3_p: "Enseña a través de la aventura con contenido gratuito que cubre conceptos introductorios de ciencias de la computación, así como acceso a guías de aplicación y planes de estudios."
projects_inspire_heading: "Proyectos que inspiran. Recursos que empoderan."
student_creativity: "Desata la creatividad de tus estudiantes"
student_creativity_paragraph: "Al final de cada unidad, para aplicar lo que han aprendido, los estudiantes crean proyectos que van desde videojuegos hasta historias con distintos desenlaces y más. Con objetivos de andamiaje que permiten desarrollar ideas sin límites, los estudiantes arman una cartera de trabajo que pueden compartir y jugar para exhibir su identidad creativa."
teach_with_support: "Enseña con apoyo"
teach_with_support_paragraph: "Ozaria está diseñado para educadores. Cada unidad del currículo incluye un plan de estudios que detalla los objetivos de aprendizaje, las confusiones más comunes, los términos clave y las normas CSTA. Además, existe un tablero de maestros muy completo para ayudarlos a supervisar el progreso de los estudiantes y corroborar el código de cada uno de ellos."
request_demo: "Solicita una demo"
im_an_educator: "Soy educador"
im_a_student: "Soy estudiante"
global_title: "Únete a nuestra comunidad mundial de estudiantes y educadores"
global_subtitle1: "Estudiantes"
global_subtitle2: "Líneas de código"
global_subtitle3: "Maestros"
global_subtitle4: "Países"
sign_up: "Registrarse"
learner_number: "12 millones"
code_line_number: "1000 millones"
new_home:
title: "CodeCombat - Juegos de Programación para aprender Python y JavaScript" # {change}
meta_keywords: "CodeCombat, Python, JavaScript, juegos de programación, programa de Ciencias de la Computación, aventura, historia épica"
meta_description: "Aprende a esciribir código a través de un juego de programación. Aprende Python, JavaScript y HTML mientras resuelves rompecabezas y aprendes a hacer tus propios juegos de código y páginas web." # {change}
become_investor: "para invertir en CodeCombat"
built_for_teachers_title: "Un Juego de programación construido teniendo en cuenta a los maestros."
built_for_teachers_blurb: "Enseñar a los niños a programar puede ser abrumador. CodeCombat ayuda a todos los educadores a enseñar a los estudiantes cómo programar en JavaScript o Python, dos de los lenguajes de programación más populares. Con un plan de estudios comprensivo que incluye seis unidades de Ciencias de la Computación, y refuerza el aprendizaje a través de unidades en el desarrollo de juegos y desarrollo web basados en proyectos, los niños progresarán en un viaje desde la sintaxis básica hasta la recursión!"
built_for_teachers_subtitle1: "Ciencias de la Computación"
built_for_teachers_subblurb1: "Comenzando con nuestro curso gratuito de Introducción a las Ciencias de la Computación, los estudiantes dominan los conceptos básicos de programación, tales como bucles de while / for, funciones y algoritmos."
built_for_teachers_subtitle2: "Desarrollo de Juegos"
built_for_teachers_subblurb2: "Los alumnos construyen laberintos y utilizan el manejo de entrada básico para programar sus propios juegos que pueden compartir con amigos y familiares."
built_for_teachers_subtitle3: "Desarrollo Web"
built_for_teachers_subblurb3: "Usando HTML, CSS y jQuery, los estudiantes ejercitan sus músculos creativos para programar sus propias páginas web con una URL personalizada para compartir con sus compañeros de clase."
century_skills_title: "Habilidades del siglo 21"
century_skills_blurb1: "Los Estudiantes No Solo Suben de Nivel a su Héroe, Sino que se Suben de Nivel Ellos Mismos"
century_skills_quote1: "Te equivocas ... entonces piensas en todas las formas posibles de solucionarlo y luego lo intentas de nuevo. No sería capaz llegar hasta aquí sin esforzarme."
century_skills_subtitle1: "Pensamiento Crítico"
century_skills_subblurb1: "Con los rompecabezas de programación que se naturalmente se organizan en niveles cada vez más desafiantes, el juego de programación de CodeCombat asegura que los niños siempre estén practicando el pensamiento crítico."
century_skills_quote2: "Todos los demás estaban haciendo laberintos, así que pensé, 'capturar la bandera' y eso es lo que hice."
century_skills_subtitle2: "Creatividad"
century_skills_subblurb2: "CodeCombat anima a los estudiantes a mostrar su creatividad construyendo y compartiendo sus propios juegos y páginas web."
century_skills_quote3: "Si me quedo atascado en un nivel. Trabajaría con la gente a mi alrededor hasta que todos pudiéramos resolverlo."
century_skills_subtitle3: "Colaboración"
century_skills_subblurb3: "A lo largo del juego hay oportunidades para que los estudiantes colaboren cuando se atasquen y trabajen juntos utilizando nuestra guía de programación en pareja."
century_skills_quote4: "Siempre he tenido aspiraciones de diseñar videojuegos y aprender a programar ... esto me está dando un gran punto de partida."
century_skills_subtitle4: "Comunicación"
century_skills_subblurb4: "La programación requiere que los niños practiquen nuevas formas de comunicación, incluida la comunicación con la computadora y la transmisión de sus ideas utilizando el código más eficiente."
classroom_in_box_title: "Nos esforzamos por:"
classroom_in_box_blurb1: "Involucre a todos los estudiantes para que confíen que la programación es para ellos."
classroom_in_box_blurb2: "Apoderar a cualquier educador para que se sienta seguro al enseñar programación."
classroom_in_box_blurb3: "Inspirar a todos los líderes escolares para crear un programa de Ciencias de la Computación de clase mundial."
click_here: "Haz clic aquí"
creativity_rigor_title: "Donde la creatividad alcanza el rigor"
creativity_rigor_subtitle1: "Haga que la programación sea divertida y enseñe habilidades del mundo real"
creativity_rigor_blurb1: "Los estudiantes escriben Python y JavaScript real mientras juegan juegos que fomentan el ensayo y error, el pensamiento crítico y la creatividad. Luego, los estudiantes aplican las habilidades de programación que han aprendido al desarrollar sus propios juegos y sitios web en cursos basados en proyectos."
creativity_rigor_subtitle2: "Alcanza a los alumnos a sus niveles"
creativity_rigor_blurb2: "Cada nivel de CodeCombat está basado en millones de puntos de datos y optimizado para adaptarse a cada alumno. Los niveles de práctica y las sugerencias ayudan a los estudiantes cuando se atascan, y los niveles de desafío evalúan el aprendizaje de los estudiantes a lo largo del juego."
creativity_rigor_subtitle3: "Construido para todos los maestros, independientemente de la experiencia"
creativity_rigor_blurb3: "El plan de estudios de CodeCombat, a ritmo propio y alineado con los estándares, hace posible la enseñanza de Ciencias de la Computación para todos. CodeCombat equipa a los maestros con capacitación, recursos de instrucción y apoyo dedicado para sentirse seguros y exitosos en el aula."
featured_partners_title1: "Presentado en"
featured_partners_title2: "Premios y socios"
featured_partners_blurb1: "Proveedor respaldado por CollegeBoard"
featured_partners_blurb2: "Mejor herramienta de creatividad para estudiantes"
featured_partners_blurb3: "La mejor opción para aprender"
featured_partners_blurb4: "Socio oficial de Code.org"
featured_partners_blurb5: "Miembro oficial de CSforAll"
featured_partners_blurb6: "Socio de Hour of Code Activity"
for_leaders_title: "Para los líderes de la escuela"
for_leaders_blurb: "Un programa de Ciencias de la Computación, comprensible y alineado con los estándares"
for_leaders_subtitle1: "Fácil implementación"
for_leaders_subblurb1: "Un programa basado en la web que no requiere soporte de TI. Comience en menos de 5 minutos con Google o el inicio de sesión único inteligente (SSO)."
for_leaders_subtitle2: "Completo plan de estudio de programación"
for_leaders_subblurb2: "Un currículo alineado con los estándares con recursos de instrucción y desarrollo profesional para permitir que cualquier maestro enseñe Ciencias de la Computación."
for_leaders_subtitle3: "Casos de uso flexibles"
for_leaders_subblurb3: "Ya sea que desee crear una clase electiva de programación de escuela intermedia, una ruta CTE o una clase de Principios de Ciencias de la Computación, CodeCombat se adapta a sus necesidades."
for_leaders_subtitle4: "Habilidades del mundo real"
for_leaders_subblurb4: "Los estudiantes construyen y desarrollan una mentalidad de crecimiento a través de los desafíos de programación que los preparan para los más de 500k trabajos informáticos abiertos."
for_teachers_title: "Para maestros"
for_teachers_blurb: "Herramientas para abrir el potencial del estudiante"
for_teachers_subtitle1: "Aprendizaje basado en proyectos"
for_teachers_subblurb1: "Promueva la creatividad, la resolución de problemas y la confianza en los cursos basados en proyectos donde los estudiantes desarrollan sus propios juegos y páginas web."
for_teachers_subtitle2: "Tablero de maestros"
for_teachers_subblurb2: "Vea datos sobre el progreso de los alumnos, descubra recursos curriculares y acceda a soporte en tiempo real para potenciar el aprendizaje."
for_teachers_subtitle3: "Evaluaciones incorporadas"
for_teachers_subblurb3: "Personalice la instrucción y asegúrese de que los alumnos comprendan los conceptos básicos con evaluaciones formativas y aditivas."
for_teachers_subtitle4: "Diferenciación automática"
for_teachers_subblurb4: "Involucre a todos los alumnos en un aula diversa con niveles de práctica que se adapten a las necesidades de aprendizaje de cada alumno."
game_based_blurb: "CodeCombat es un programa de Ciencias de la Computación basado en juegos en los que los estudiantes escriben código real y ven a sus personajes reaccionar en tiempo real."
get_started: "Empieza ahora"
global_title: "Únete a nuestra comunidad global de estudiantes y educadores"
global_subtitle1: "Alumnos"
global_subtitle2: "Líneas de código"
global_subtitle3: "Maestros"
global_subtitle4: "Países"
go_to_my_classes: "Ir a mis clases"
go_to_my_courses: "Ir a mis cursos"
quotes_quote1: "Nombra cualquier programa en línea, ya lo he intentado. Ninguno de ellos coincide con CodeCombat. Cualquier maestro que quiera que sus estudiantes aprendan a programar ... ¡comience aquí!"
quotes_quote2: " Me sorprendió lo fácil e intuitivo que CodeCombat hace que aprendan Ciencias de la Computación. Las calificaciones en el examen AP fueron mucho más altas de lo que esperaba y creo que CodeCombat es la razón por la que este fue el caso."
quotes_quote3: "CodeCombat ha sido lo más beneficioso para enseñar a mis alumnos las capacidades de programación de la vida real. Mi esposo es ingeniero de software y ha probado todos mis programas. Puso esto como su mejor opción."
quotes_quote4: "Los comentarios ... han sido tan positivos que estamos estructurando una clase de informática en torno a CodeCombat. El programa realmente involucra a los estudiantes con una plataforma estilo juego que es entretenida e instructiva al mismo tiempo. ¡Sigan con el buen trabajo, CodeCombat!"
see_example: "Ver ejemplo"
slogan: "El juego más interesante para aprender programación." # {change}
teach_cs1_free: "Enseña programación gratis"
teachers_love_codecombat_title: "A los maestros les encanta CodeCombat"
teachers_love_codecombat_blurb1: "Informan que sus estudiantes disfrutan usando CodeCombat para aprender a programar"
teachers_love_codecombat_blurb2: "Recomendarían CodeCombat a otros maestros de Ciencias de la Computación"
teachers_love_codecombat_blurb3: "Dicen que CodeCombat los ayuda a mejorar las habilidades de resolución de problemas de sus estudiantes"
teachers_love_codecombat_subblurb: "En asociación con McREL International, líder en orientación basada en investigación y evaluaciones de tecnología educativa."
top_banner_blurb: "Nuevo: ¡Únete a nuestra misión!" # {change}
top_banner_blurb_pd: "Ahora ofrecemos opciones de desarrollo profesional para educadores."
top_banner_blurb_funding: "Nuevo: Ley CARES: guía de recursos de financiación para conseguir fondos ESSER y GEER para programas de Ciencias de la Computación."
try_the_game: "Prueba el juego"
classroom_edition: "Versión para el aula:"
learn_to_code: "Aprende a programar:"
play_now: "Jugar Ahora"
im_an_educator: "Soy un Educador"
im_a_teacher: "Soy un Maestro"
im_a_student: "Soy un Estudiante"
learn_more: "Aprender más"
classroom_in_a_box: "Un aula prediseñada para enseñar Ciencias de la Computación."
codecombat_is: "CodeCombat es una plataforma para que los estudiantes aprendan Ciencias de la Computación mientras están jugando un juego de verdad." # {change}
our_courses: "Nuestros cursos fueron probados especificamente para destacarse en el aula, incluso con maestros con poca o ninguna experiencia previa en programación." # {change}
watch_how: "Observa como CodeCombat está transformando la manera en que la gente aprende Ciencias de la Computación."
top_screenshots_hint: "Los estudiantes escriben código y ven sus cambios actualizarse en tiempo real"
designed_with: "Diseñado teniendo en cuenta a los maestros"
real_code: "Escritura de código real"
from_the_first_level: "desde el primer nivel"
getting_students: "Conseguir que los estudiantes escriban código lo más pronto posible es fundamental para que aprendan la sintaxis y la estructura apropiada."
educator_resources: "Recursos para el educador"
course_guides: "y guías de curso"
teaching_computer_science: "Enseñar Ciencias de la Computación no requiere un título costoso, porque proporcionamos herramientas para ayudar a educadores con cualquier conocimiento previo."
accessible_to: "Comprensible para"
everyone: "todos"
democratizing: "Democratizar el proceso de aprender a programar es la esencia de nuestra filosofía. Todos deberían poder aprender a programar"
forgot_learning: "Creo que ellos en realidad olvidaron de que estaban aprendiendo algo." # {change}
wanted_to_do: "Programar es algo que siempre quise hacer, y que nunca pensé que sería capaz de aprenderlo en la escuela ."
builds_concepts_up: "Me gusta cómo CodeCombat construye los conceptos. Es muy fácil de entender y es divertido averiguarlo."
why_games: "¿Por qué el aprendizaje mediante juegos es importante?"
games_reward: "Los juegos recompensan el esfuerzo productivo."
encourage: "El juego es un medio que incentiva la interacción, el descubrimiento, y la prueba-error. Un buen juego desafía al jugador a dominar habilidades con el paso del tiempo, que es un proceso crítico similar al que los estudiantes atraviesan mientran aprenden"
excel: "Los juegos se destacan en recompensar el"
struggle: "esfuerzo productivo"
kind_of_struggle: "el tipo de esfuerzo que se traduce en aprendizaje que interesa y "
motivating: "que motiva"
not_tedious: "no tedioso."
gaming_is_good: "Los estudios sugieren que jugar es bueno para el cerebro de los niños (¡es verdad!)"
game_based: "Cuando los sistemas de aprendizaje basados en juegos son"
compared: "comparados"
conventional: "con los métodos de evaluación convencionales, la diferencia es clara: los juegos son mejores al ayudar a los estudiantes a retener el conocimiento, a concentrarse y"
perform_at_higher_level: "a desempeñarse con un mayor nivel de éxito"
feedback: "Los juegos también proveen retroalimentación en tiempo real que permite a los estudiantes ajustar su camino a la solución y entender conceptos de forma más holística, en lugar de estar limitados solamente a respuestas 'correctas' e 'incorrectas'"
real_game: "Un juego de verdad, jugado con código auténtico."
great_game: "Un gran juego es más que solo medallas y logros - se trata sobre una travesía del jugador, acertijos bien diseñados, y la habilidad de abordar desafios con voluntad y confianza."
agency: "CodeCombat es un juego que ofrece a los jugadores esa voluntad y confianza mediante nuestro motor de código robusto, que ayuda tanto a principiantes como a estudiantes avanzados por igual a escribir código correcto y válido."
request_demo_title: "Invita a tus estudiantes hoy!"
request_demo_subtitle: "Solicitar una demostración y empieza a jugar con tus estudiantes en menos de una hora."
get_started_title: "Configure su clase hoy"
get_started_subtitle: "Prepare su clase, agregue cuentas de estudiantes y siga su progreso a medida que aprenden a programar."
request_demo: "Solicitar un Demo"
request_quote: "Solicitar una cotización"
setup_a_class: "Configurar una Clase"
have_an_account: "¿Ya tienes una cuenta?" # {change}
logged_in_as: "Estás actualmente conectado como"
computer_science: "Cursos de Ciencias de la Computación para todas las edades" # {change}
ffa: "Gratis para todos los estudiantes"
coming_soon: "¡Proximamente!"
courses_available_in: "Los cursos están disponibles en JavaScript, Python, y Java (¡proximamente!)" # {change}
boast: "Cuenta con acertijos lo suficiente complejos como para fascinar a jugadores y programadores por igual."
winning: "Una combinación ganadora entre un juego de rol y una tarea sobre programación que consigue hacer de la educación amigable y disfrutable para los niños."
run_class: "Todo lo que necesitas para organizar una clase de Ciencias de la Computación en tu escuela hoy mismo, sin necesidad de ningún conocimiento previo de Ciencias de la Computación."
goto_classes: "Ir a mis clases" # {change}
view_profile: "Ver mi perfíl"
view_progress: "Ver mi progreso"
go_to_courses: "Ir a mis cursos"
want_coco: "¿Quisiera CodeCombat en su escuela?"
educator: "PI:NAME:<NAME>END_PI"
student: "Estudiante"
go_to_my_dashboard: "Ir a mi panel"
nav:
educators: "PI:NAME:<NAME>END_PI"
follow_us: "SPI:NAME:<NAME>END_PI"
general: "General"
map: "Mapa"
play: "Jugar" # The top nav bar entry where players choose which levels to play
community: "Comunidad"
units: "Unidades"
blog: "Blog"
forum: "Foro"
account: "Cuenta"
my_account: "Mi Cuenta"
profile: "Perfil"
home: "Inicio"
contribute: "Contribuir"
legal: "Legal"
privacy: "Privacidad"
about: "Acerca"
contact: "Contacto"
press: "Prensa"
twitter_follow: "Seguir"
my_classrooms: "Mis clases"
my_courses: "Mis cursos"
my_units: "Mis unidades"
my_teachers: "Mis maestros"
careers: "Carreras"
facebook: "Facebook"
twitter: "PI:NAME:<NAME>END_PI"
create_a_class: "Crear una Clase"
other: "Otro"
learn_to_code: "¡Aprender a programar!"
toggle_nav: "Cambia la navigación"
schools: "Escuelas"
get_involved: "Participa"
open_source: "Código Libre (GitHub)"
support: "Soporte"
faqs: "FAQs"
copyright_prefix: "Copyright"
copyright_suffix: "Todos los derechos reservados."
help_pref: "¿Necesitas ayuda? Envianos un correó electronico!"
help_suff: "y te contactaremos pronto"
resource_hub: "Centro de recursos"
apcsp: "Principios AP CS"
parent: "Padres"
faq: "Preguntas frecuentes"
return_coco: "Volver a CodeCombat"
classes: "Clases"
term_of_service: "Términos de Servicio"
esports: "Esports"
browser_recommendation: "Para una mejor experiencia, recomendamos usar la última versión de Chrome. ¡Descarga el navegador aquí!"
ozaria_classroom: "Aula de Ozaria"
codecombat_classroom: "Aula de CodeCombat"
ozaria_dashboard: "Panel de Ozaria"
codecombat_dashboard: "Panel de CodeCombat"
professional_development: "Desarrollo profesional"
new: "¡Nuevo!"
admin: "Admin"
funding_resources_guide: "Guía de recursos de financiación"
modal:
close: "Cerrar"
okay: "OK"
cancel: "Cancelar"
try_again: "Volver a intentarlo"
not_found:
page_not_found: "Página no encontrada"
diplomat_suggestion:
title: "¡Ayuda a traducir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector.
sub_heading: "Necesitamos tus habilidades de idioma."
pitch_body: "Desarrollamos CodeCombat en inglés, pero ya tenemos jugadores de todo el mundo. Muchos de ellos quieren jugar en español pero no hablan inglés, así que si puedes hablar ambos, por favor considera registrarte pare ser un Diplomático y ayudar a traducir tanto el sitio de CodeCombat como todos los niveles al español."
missing_translations: "Hasta que podamos traducir todo al español, verás inglés cuando el español no esté disponible."
learn_more: "Aprende más sobre ser un Diplomático"
subscribe_as_diplomat: "Suscríbete como un Diplomático"
play:
title: "Juega los niveles de CodeCombat - Aprende Python, JavaScript y HTML"
meta_description: "Aprende a programar con un juego para principiantes. Aprende Python o JavaScript mientras resuelves acertijos, crea tus propios videojuegos y sube de nivel. ¡Desafía a tus amigos en niveles de arena multijugador!"
level_title: "__level__ - Aprende a programar en Python, JavaScript y HTML"
video_title: "__video__ | Nivel de video"
game_development_title: "__level__ | Desarrollo de juegos"
web_development_title: "__level__ | Desarrollo web"
anon_signup_title_1: "CodeCombat tiene un"
anon_signup_title_2: "¡Versión de aula!"
anon_signup_enter_code: "Ingresa el código de la clase:"
anon_signup_ask_teacher: "¿No tienes uno? pregunta a tu maestro"
anon_signup_create_class: "¿Quieres crear una clase?"
anon_signup_setup_class: "¡Configura una clase, agrega a tus estudiantes, y monitorea el progreso!"
anon_signup_create_teacher: "Crea una cuenta de maestro gratuita"
play_as: "Jugar Como " # Ladder page
get_course_for_class: "¡Asigna desarrollo de juegos y más a tus clases!"
request_licenses: "Contacta a nuestros especialistas escolares para más detalles."
compete: "¡Competir!" # Course details page
spectate: "Observar" # Ladder page
players: "Jugadores" # Hover over a level on /play
hours_played: "horas jugadas" # Hover over a level on /play
items: "Objetos" # Tooltip on item shop button from /play
unlock: "Desbloquear" # For purchasing items and heroes
confirm: "Confirmar"
owned: "Adquirido" # For items you own
locked: "Bloqueado"
available: "Disponible"
skills_granted: "Habilidades concedidas" # Property documentation details
heroes: "Héroes" # Tooltip on hero shop button from /play
achievements: "Logros" # Tooltip on achievement list button from /play
settings: "Configuración" # Tooltip on settings button from /play
poll: "Encuestas" # Tooltip on poll button from /play
next: "Próximo" # Go from choose hero to choose inventory before playing a level
change_hero: "Cambiar héroe" # Go back from choose inventory to choose hero
change_hero_or_language: "Cambiar héroe o lenguaje"
buy_gems: "Comprar gemas"
subscribers_only: "¡Solo para suscriptores!"
subscribe_unlock: "¡Suscríbete para desbloquear!"
subscriber_heroes: "¡Suscríbete ahora para debloquear inmediatamente a Amara, Hushbaum y Hattori!"
subscriber_gems: "¡Suscríbete ahora para comprar este héroe con gemas!"
anonymous: "PI:NAME:<NAME>END_PI"
level_difficulty: "Dificultad: "
awaiting_levels_adventurer_prefix: "Nosotros liberamos nuevos niveles cada semana"
awaiting_levels_adventurer: "Registrate como un aventurero"
awaiting_levels_adventurer_suffix: "para ser el primero en jugar nuevos niveles."
adjust_volume: "Ajustar el volúmen"
campaign_multiplayer: "Arenas Multijugador"
campaign_multiplayer_description: "... en las que programas cara a cara contra otros jugadores."
brain_pop_done: "!Has derrotado a los Ogros programando! ¡Ganaste!"
brain_pop_challenge: "¡Desafiate a jugar de nuevo usando otro lenguaje de programación!"
replay: "Repetir"
back_to_classroom: "Volver al aula"
teacher_button: "Para maestros"
get_more_codecombat: "Consigue más CodeCombat"
back_to_dashboard: "Volver al panel"
back_to_ozaria: "Volver a ozaria.PI:EMAIL:<EMAIL>END_PI"
customize_hero: "Personalizar héroe"
account_settings: "Configuración de cuenta"
back_to_tutorial: "Volver al tutorial"
teacher_vega_message: "Estos mensajes de tutorial guían a los estudiantes. Para ver estos mensajes y guardar tu progreso en el juego, crea una cuenta de estudiante y accede a ella para jugar Ozaria."
code:
if: "si" # 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: "de lo contrario"
elif: "o si"
while: "mientras"
loop: "ciclo"
for: "para"
break: "interrumpir"
continue: "continuar"
pass: "pasar"
return: "regresar"
then: "entonces"
do: "hacer"
end: "fin"
function: "función"
def: "define"
var: "variable"
self: "sí mismo"
hero: "héroe"
this: "este"
or: "o"
"||": "o"
and: "y"
"&&": "y"
not: "no"
"!": "no"
"=": "asignar"
"==": "igual a"
"===": "estrictamente igual a"
"!=": "distinto a"
"!==": "estrictamente distinto a"
">": "mayor que"
">=": "mayor o igual que"
"<": "menor que"
"<=": "menor o igual que"
"*": "multiplicado por"
"/": "dividido por"
"+": "más"
"-": "menos"
"+=": "añade y asigna"
"-=": "substrae y asigna"
True: "Verdadero"
true: "verdadero"
False: "Falso"
false: "falso"
undefined: "indefinido"
null: "nulo"
nil: "nada"
None: "Ninguno"
share_progress_modal:
blurb: "¡Estás haciendo un gran progreso! Cuéntale a tus padres cuánto has aprendido con CodeCombat."
email_invalid: "Dirección de Email inválida."
form_blurb: "¡Escribe su email debajo y les enseñaremos!"
form_label: "Dirección de Email"
placeholder: "dirección de email"
title: "Excelente Trabajo, Aprendiz"
login:
auth_sign_up: "¿Primera vez en Ozaria? Crea una cuenta"
sign_up: "Crear Cuenta"
email_or_username: "Email o Nombre de usuario" # {change}
or: "o"
log_in: "Entrar"
sign_in: "Regístrate"
logging_in: "Entrando"
log_out: "Salir"
forgot_password: "PI:PASSWORD:<PASSWORD>END_PI?"
finishing: "Finalizando"
sign_in_with_facebook: "Registrarse con Facebook" # {change}
sign_in_with_gplus: "Registrarse con G+" # {change}
signup_switch: "¿Quieres crear una cuenta?"
already_have_account1: "¿Ya tienes una cuenta de maestro o estudiante de CodeCombat?"
already_have_account2: "Puedes ingresar a Ozaria.com con esa cuenta."
sign_into_ozaria: "Ingresa a Ozaria.com"
individual_users_not_supported: "¡Ozaria es solo para aulas! ¡Visita CodeCombat para seguir jugando!"
accounts_merge_confirmation: "Hay una cuenta asociada al correo electrónico de esta cuenta de Google. ¿Quieres combinar las cuentas?"
signup:
complete_subscription: "Completa Suscripción"
create_student_header: "Crear Cuenta de Estudiante"
create_teacher_header: "Crear Cuenta de Maestro"
create_individual_header: "Crear Cuenta Individual"
email_announcements: "Recibe noticias por email" # {change}
sign_in_to_continue: "Inicia sesión o crea una cuenta para continuar"
teacher_email_announcements: "Mantenme actualizado sobre nuevos recursos para maestros, currículo y cursos!"
creating: "Creando Cuenta..."
sign_up: "Registrarse"
log_in: "Inicia sesión con tu contraseña"
login: "Iniciar sesión"
required: "Necesitas entrar a tu cuenta antes de continuar."
login_switch: "¿Ya tienes una cuenta?"
optional: "opcional"
connected_gplus_header: "Te has conectado exitosamente a travez de Google+!"
connected_gplus_p: "Termina el registro para que inicies sesión con tu cuenta de Google+."
connected_facebook_header: "Te has conectado exitosamente a travez de Facebook!"
connected_facebook_p: "Termina el registro para que inicies sesión con tu cuenta de Facebook."
hey_students: "Estudiante, ingresa el coódigo de clase de tu maestro."
birthday: "Cumpleaños"
parent_email_blurb: "Nosotros sabemos que tu no puedes esperar para aprender programación — nosotros tambien estamos emocionados! Tus padres recibirán un correo electrónico con más instrucciones sobre cómo crear una cuenta para ti. Envíe un correo electrónico a {{email_link}} si tienes alguna pregunta"
classroom_not_found: "Ninguna clase existe con este código de clase. Revisa tu ortografía o pidele ayuda a tu maestro."
checking: "Comprobando..."
account_exists: "Este email ya esta en uso:"
sign_in: "Iniciar Sesión"
email_good: "Tu email se ve bien!"
name_taken: "Ese nombre de usuario ya esta en uso! Intenta {{suggestedName}}?"
name_available: "Nombre de usuario disponible!"
name_is_email: "Tu email no puede ser tu nombre de usuario"
choose_type: "Elige el tipo de cuenta:"
teacher_type_1: "Enseña como programar con CodeCombat!"
teacher_type_2: "Configura tu clase"
teacher_type_3: "Accede a guías de cursos"
teacher_type_4: "Ve el progreso del estudiante"
signup_as_teacher: "Iniciar sesión como Maestro" # {change}
student_type_1: "Aprende a programar mientras que juegas"
student_type_2: "Jugar con tu clase"
student_type_3: "Compite en arenas"
student_type_4: "Escoge tu héroe!"
student_type_5: "Ten tu código de clase listo!"
signup_as_student: "Iniciar sesión como Estudiante" # {change}
individuals_or_parents: "Independientes y Padres"
individual_type: "Para jugadores que aprenden a programar fuera de clase. Los padres deben registrar una cuenta aquí."
signup_as_individual: "Registrarse como Independiente"
enter_class_code: "Ingresa el código de tu clase"
enter_birthdate: "Ingresa tu fecha de nacimiento:"
parent_use_birthdate: "Padres, usen su propia fecha de nacimiento."
ask_teacher_1: "Pregúntale a tu maestro por el código de tu clase."
ask_teacher_2: "¿No eres parte de una clase? Crea una"
ask_teacher_3: "Cuenta Independiente"
ask_teacher_4: " en cambio."
about_to_join: "Te vas a unir a:"
enter_parent_email: "Ingresa el correo eletrónico de tus padres:"
parent_email_error: "Ha ocurrido un error al tratar de enviar el correo. Verifica la dirección de correo electrónico e intenta de nuevo."
parent_email_sent: "Hemos enviado un correo electrónico con más instrucciones sobre cómo crear una cuenta. Pide a tus padres que revisen su bandeja de entrada."
account_created: "¡Cuenta Creada!"
confirm_student_blurb: "Escribe tu información para que no la olvides. Tu maestro también puede ayudarte a restablecer tu contraseña en cualquier momento."
confirm_individual_blurb: "Escribe tu información de inicio de sesión en caso de que la necesites más adelante. Verifica tu correo electrónico para que puedas recuperar tu cuenta si alguna vez olvidas la contraseña. ¡Revisa tu bandeja de entrada!"
write_this_down: "Escribe esto:" # {change}
start_playing: "¡Empieza a jugar!"
sso_connected: "Conectado exitosamente con:"
select_your_starting_hero: "Selecciona tu héroe inicial:"
you_can_always_change_your_hero_later: "Podrás cambiar tu héroe luego."
finish: "Finalizar"
teacher_ready_to_create_class: "¡Estás listo para crear tu primera clase!"
teacher_students_can_start_now: "Sus alumnos podrán comenzar a jugar el primer curso, Introducción a las Ciencias de la Computación, inmediatamente." # {change}
teacher_list_create_class: "En la siguiente pantalla podrás crear una nueva clase."
teacher_list_add_students: "Agregue alumnos a la clase haciendo clic en el enlace Ver clase y luego envíe a sus alumnos el Código de clase o la URL. También puedes invitarlos por correo electrónico si tienen."
teacher_list_resource_hub_1: "Revisar la "
teacher_list_resource_hub_2: "Guías de curso" # {change}
teacher_list_resource_hub_3: "para soluciones a todos los niveles, y la"
teacher_list_resource_hub_4: "Centro de recursos"
teacher_list_resource_hub_5: "para guías curriculares, actividades, y más."
teacher_additional_questions: "¡Eso es todo! Si necesita ayuda adicional o tiene preguntas, comuníquese con __supportEmail__."
dont_use_our_email_silly: "¡No pongas nuestro email aquí! Pon el correo de tus padres."
want_codecombat_in_school: "¿Quieres jugar CodeCombat todo el tiempo?"
eu_confirmation: "Acepto permitir que CodeCombat almacene mis datos en servidores de los Estados Unidos."
eu_confirmation_place_of_processing: "Aprender más sobre los posibles riesgos"
eu_confirmation_student: "Si no estás seguro, pregúntale a tu maestro."
eu_confirmation_individual: "Si no deseas que almacenemos tus datos en servidores de EE. UU., Siempre puedes seguir jugando de forma anónima sin guardar tu código."
request_class_code: "¡Estudiantes, pídanle un código de clase a su docente para crear una cuenta!"
educators_create_account: "¡Docentes, creen una cuenta de maestro para acceder a la primera unidad de manera gratuita!"
looking_for_classroom: "Buscando aulas..."
create_your_educator_account: "Crea una cuenta de educador"
educator_signup_list_1_title: "Ve lo mismo que tus estudiantes:"
educator_signup_list_1_desc: "Prueba cada nivel del juego en la primera unidad"
educator_signup_list_2_title: "Ve los recursos para maestros:"
educator_signup_list_2_desc: "Accede al alcance y el orden, las lecciones y más"
educator_signup_list_3_title: "Observa el progreso de tus estudiantes:"
educator_signup_list_3_desc: "Prueba gratis la primera unidad con tu clase"
signup_with_email: "Regístrate con tu correo electrónico"
already_have_account: "Ya tienes una cuenta de Ozaria o CodeCombat"
select_your_role: "Selecciona tu rol"
select_your_state: "Selecciona tu estado"
password_requirements: "Entre 8 y 64 caracteres no repetidos"
invalid: "No válido"
invalid_password: "PI:PASSWORD:<PASSWORD>END_PIaseña no válida"
form_validation_errors:
required: "El campo es obligatorio"
invalidEmail: "Correo no válido"
invalidPhone: "Número de teléfono no válido"
emailExists: "El correo electrónico ya existe"
numberGreaterThanZero: "Debe ser un número mayor que 0"
recover:
recover_account_title: "recuperar cuenta"
send_password: "PI:PASSWORD:<PASSWORD>END_PI"
recovery_sent: "Correo de recuperación enviado."
items:
primary: "Primario"
secondary: "Secundario"
armor: "Armadura"
accessories: "Accesorios"
misc: "Misceláneo"
books: "Libros"
common:
default_title: "Ozaria - Informática que fascina"
ozaria: "Ozaria"
default_meta_description: "Ozaria es un programa de ciencias de la computación, un juego de aventura y una historia de fantasía en la que los estudiantes deben dominar la magia perdida de la programación para salvar al mundo."
back: "Atrás" # When used as an action verb, like "Navigate backward"
coming_soon: "¡Próximamente!"
continue: "Continuar" # When used as an action verb, like "Continue forward"
next: "Siguiente"
default_code: "Código predeterminado"
loading: "Cargando..."
LOADING: "CARGANDO"
overview: "Vista global"
processing: "Procesando..."
solution: "Solución"
table_of_contents: "Tabla de contenidos"
intro: "Intro"
saving: "Guardando..."
sending: "Enviando..."
send: "Enviar"
sent: "Enviado"
cancel: "Cancelar"
save: "Guardar"
publish: "Publicar"
create: "Crear"
fork: "Bifurcar"
play: "Jugar" # When used as an action verb, like "Play next level"
retry: "Reintentar"
actions: "Acciones"
info: "Info"
help: "Ayuda"
watch: "Seguir"
unwatch: "No seguir"
submit_patch: "Enviar Parche"
submit_changes: "Enviar cambios"
save_changes: "Guardar cambios"
required_field: "Requisito necesario" # {change}
submit: "Enviar"
replay: "Volver a jugar"
complete: "Completado"
continue_editing: "Continuar editando"
logout: "Cerrar sesión"
empty: "Vacío"
done: "Listo"
remove: "Quitar"
locked: "Bloqueado"
general:
and: "y"
name: "Nombre"
date: "Fecha"
body: "Cuerpo"
version: "Versión"
pending: "Pendiente"
accepted: "Aceptado"
rejected: "Rechazado"
withdrawn: "Retirado"
accept: "Aceptar"
accept_and_save: "Aceptar y Guardar"
reject: "Rechazar"
withdraw: "Retirar"
submitter: "Emisor"
submitted: "Enviado"
commit_msg: "Enviar mensaje"
version_history: "Historial de Versiones"
version_history_for: "Historial de Versiones para: "
select_changes: "Selcciona dos cambios abajo para ver la diferencia"
undo_prefix: "Deshacer"
undo_shortcut: "(Ctrl+Z)"
redo_prefix: "Rehacer"
redo_shortcut: "(Ctrl+Shift+Z)"
play_preview: "Mira el avance del nivel"
result: "Resultado"
results: "Resultados"
description: "Descripción"
or: "o"
subject: "Asunto"
email: "Email"
password: "PI:PASSWORD:<PASSWORD>END_PI"
confirm_password: "PI:PASSWORD:<PASSWORD>END_PI"
message: "Mensaje"
code: "Código"
ladder: "Escalera"
when: "Cuando"
opponent: "Oponente"
rank: "Posición"
score: "Puntuación"
win: "Ganada"
loss: "Perdida"
tie: "Empate"
easy: "Fácil"
medium: "Medio"
hard: "Difícil"
player: "PI:NAME:<NAME>END_PI"
player_level: "Nivel" # Like player level 5, not like level: Dungeons of Kithgard
warrior: "Guerrero"
ranger: "Guardabosques"
wizard: "Mago"
first_name: " PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
last_initial: "Última inicial"
username: "Nombre de usuario"
contact_us: "Contáctenos"
close_window: "Cerrar ventana"
learn_more: "Aprende Más"
more: "Más"
fewer: "Menos"
with: "con"
archived: "Archivado"
chat: "Chat"
chat_with_us: "Chatea con nosotros"
email_us: "Envíanos un correo electrónico"
sales: "Ventas"
support: "Ayuda"
units:
second: "segundo"
seconds: "segundos"
sec: "seg"
minute: "minuto"
minutes: "minutos"
hour: "hora"
hours: "horas"
day: "día"
days: "días"
week: "semana"
weeks: "semanas"
month: "mes"
months: "meses"
year: "año"
years: "años"
play_level:
back_to_map: "Volver al Mapa"
directions: "Instrucciones"
edit_level: "Editar Nivel"
keep_learning: "Sigue aprendiendo"
explore_codecombat: "Explorar CodeCombat"
finished_hoc: "He terminado con mi Hora of Código"
get_certificate: "¡Obtén tu certificado!"
level_complete: "Nivel completo"
completed_level: "Nivel Completado:"
course: "Curso:"
done: "Listo"
next_level: "Siguiente Nivel"
combo_challenge: "Desafío Combo"
concept_challenge: "Desafío de Concepto"
challenge: "Desafío"
challenge_unlocked: "Desafío Desbloqueado"
combo_challenge_unlocked: "Desafío Combo Desbloqueado"
concept_challenge_unlocked: "Desafío de Concepto Desbloqueado"
concept_challenge_complete: "Desafío de Concepto Completado!"
combo_challenge_complete: "Deasfío Combo Completado!"
combo_challenge_complete_body: "Buen trabajo, parece que te va bien entendiendo __concept__!"
replay_level: "Reiniciar nivel"
combo_concepts_used: "__complete__/__total__ Conceptos usados"
combo_all_concepts_used: "Usaste todos los conceptos posibles para resolver el desafío. ¡Buen trabajo!"
combo_not_all_concepts_used: "Usaste __complete__ de __total__ conceptos posibles para resolver el desafío. ¡Intenta obtener todos los __total__ conceptos la próxima vez!"
start_challenge: "Empezar Desafío"
next_game: "Siguiente juego"
languages: "Lenguajes"
programming_language: "Lenguajes de programación"
show_menu: "Mostrar menú de juego"
home: "Inicio" # Not used any more, will be removed soon.
level: "Nivel" # Like "Level: Dungeons of Kithgard"
skip: "Omitir"
game_menu: "Menú del Juego"
restart: "Reiniciar"
goals: "Objetivos"
goal: "Objetivo"
challenge_level_goals: "Metas del Nivel de Desafío"
challenge_level_goal: "Meta del Nivel de Desafío"
concept_challenge_goals: "Metas del Desafío de Concepto"
combo_challenge_goals: "Metas del Nivel de Desafío"
concept_challenge_goal: "Metas del Desafío de Concepto"
combo_challenge_goal: "Meta del Nivel de Desafío"
running: "Andando..."
success: "¡Éxito!"
incomplete: "Incompleto"
timed_out: "Acabó el tiempo"
failing: "Fallando"
reload: "Recargar"
reload_title: "¿Recargar Todo el Código?"
reload_really: "¿Estás seguro de que quieres empezar este nivel desde el principio?"
reload_confirm: "Recargar Todo"
restart_really: "¿Seguro que quieres reiniciar el nivel? Perderás todo el código que has escrito."
restart_confirm: "Sí, reiniciar"
test_level: "Probar Nivel"
victory: "Victoria"
victory_title_prefix: "¡"
victory_title_suffix: "¡Completo!"
victory_sign_up: "Regístrate para recibir actualizaciones"
victory_sign_up_poke: "¿Quieres recibir las últimas noticias por correo? ¡Crea una cuenta gratuita y te mantendremos informado!"
victory_rate_the_level: "¿Cómo de divertido estuvo este nivel?"
victory_return_to_ladder: "Volver a la escalera"
victory_saving_progress: "Guardando Progreso"
victory_go_home: "Ir al Inicio"
victory_review: "¡Cuéntanos más!"
victory_review_placeholder: "¿Cómo estuvo el nivel?"
victory_hour_of_code_done: "¿Has acabado?"
victory_hour_of_code_done_yes: "¡Si, he terminado con mi Hora de Código!"
victory_experience_gained: "XP Ganada"
victory_gems_gained: "Gemas Ganadas"
victory_new_item: "Objeto Nuevo"
victory_new_hero: "Nuevo Héroe"
victory_viking_code_school: "¡Changos macacos!, ¡el nivel que acabas de pasar era dificil! Si todavía no eres un desarrollador de software, deberías serlo. Acabas de conseguir una aceptación por vía rápida con la Escuela Vikinga de Có, donde tú puedes llevar tus habilidades al siguiente nivel y convertirte en un desarrollador web profesional en 14 semanas."
victory_become_a_viking: "Conviértete en un Vikingo"
victory_no_progress_for_teachers: "El progreso no es guardado para maestros. Pero puede añadir cuenta de estudiante a su aula, por su mismo."
tome_cast_button_run: "Ejecutar"
tome_cast_button_running: "Ejecutando"
tome_cast_button_ran: "Ejecutado"
tome_cast_button_update: "Actualizar"
tome_submit_button: "Enviar"
tome_reload_method: "Recargar código original para este método" # {change}
tome_available_spells: "Hechizos Disponibles"
tome_your_skills: "Tus habilidades"
hints: "Pistas"
videos: "Videos"
hints_title: "Pistas {{number}}"
code_saved: "Código Guardado"
skip_tutorial: "Saltar (esc)"
keyboard_shortcuts: "Atajos de teclado"
loading_start: "Iniciar nivel"
loading_start_combo: "Iniciar Desafío Combo"
loading_start_concept: "Iniciar Desafío de Concepto"
problem_alert_title: "Revisa tu código"
time_current: "Ahora:"
time_total: "Max:"
time_goto: "Ir a:"
non_user_code_problem_title: "No se puede cargar el nivel"
infinite_loop_title: "Ciclo infinito detectado"
infinite_loop_description: "El código inicial para construir el mundo no terminó de ejecutarse. Probablemente es muy lento o tiene un loop infinito. O puede ser un bug. Puedes tratar ejecutando este código nuevamente o reiniciar el código a su estado por defecto. Si eso no lo arregla, haznos saber."
check_dev_console: "Tú puedes también abrir la consola de desarrollo para ver que puede salir mal."
check_dev_console_link: "(instrucciones)"
infinite_loop_try_again: "Intentar nuevamente"
infinite_loop_reset_level: "Reiniciar Nivel"
infinite_loop_comment_out: "Comenta Mi Código"
tip_toggle_play: "Activa jugar/pausa con Ctrl+P."
tip_scrub_shortcut: "Ctrl+[ y Ctrl+] para rebobinar y avanzar rápido."
tip_guide_exists: "Haga click en la guía en la parte superior de la página para obtener información útil"
tip_open_source: "¡CodeCombat es 100% código abierto!" # {change}
tip_tell_friends: "¿Disfrutando de CodeCombat? ¡Cuéntale a tus amigos acerca de nosotros!"
tip_beta_launch: "CodeCombat lanzó su beta en Octubre del 2013."
tip_think_solution: "Piensa en la solución, no en el problema."
tip_theory_practice: "En teoría, no hay diferencia entre la teoría y la práctica. Pero en la práctica, si la hay. - PI:NAME:<NAME>END_PI"
tip_error_free: "Hay dos formas de escribir programas libres de errores; sólo la tercera funciona. - PI:NAME:<NAME>END_PI"
tip_debugging_program: "Si depurar es el proceso de remover errores, entonces programar debe ser el proceso de colocarlos. - PI:NAME:<NAME>END_PI"
tip_forums: "¡Dirígite a los foros y dinos lo que piensas!"
tip_baby_coders: "En el futuro, incluso los bebés serán Archimagos."
tip_morale_improves: "La carga continuará hasta que la moral mejore."
tip_all_species: "Creemos en la igualdad de oportunidades para aprender a programar para todas las especies."
tip_reticulating: "Espinas reticulantes."
tip_harry: "Eres un Hechicero, "
tip_great_responsibility: "Con una gran habilidad de hacer código viene una gran responsabilidad de depuración."
tip_munchkin: "Si no comes tus verduras, un enano vendrá por ti mientras estés dormido."
tip_binary: "Sólo hay 10 tipos de personas en el mundo: aquellas que entienden binario y las que no."
tip_commitment_yoda: "Un programador debe tener el compromiso más profundo, la mente más seria. ~ Yoda"
tip_no_try: "Haz. O no hagas. No hay intento. - Yoda"
tip_patience: "Paciencia debes tener, joven Padawan. - Yoda"
tip_documented_bug: "Un error documentado no es un error; es una característica."
tip_impossible: "Siempre parece imposible hasta que se hace. - PI:NAME:<NAME>END_PI"
tip_talk_is_cheap: "Hablar es barato. Muéstrame el código. - PI:NAME:<NAME>END_PI"
tip_first_language: "La cosa más desastrosa que puedes aprender es tu primer lenguaje de programación. - PI:NAME:<NAME>END_PI"
tip_hardware_problem: "P: ¿Cuántos programadores son necesarios para cambiar una bombilla eléctrica? R: Ninguno, es un problema de hardware."
tip_hofstadters_law: "Ley de Hofstadter: Siempre toma más tiempo del que esperas, incluso cuando tienes en cuenta la ley de Hofstadter."
tip_premature_optimization: "La optimización prematura es la raíz de la maldad. - PI:NAME:<NAME>END_PI"
tip_brute_force: "Cuando tengas duda, usa la fuerza bruta. - PI:NAME:<NAME>END_PI"
tip_extrapolation: "Solo hay dos tipos de personas: Esas que pueden extrapolar desde información incompleta..."
tip_superpower: "Programar es lo más cercano que tenemos a superpoderes."
tip_control_destiny: "En el Open Source real, tú tienes el derecho de controlar tu propio destino. - PI:NAME:<NAME>END_PI"
tip_no_code: "Ningún código es más rápido que nada de código."
tip_code_never_lies: "El código nunca miente, los comentarios a veces sí. — PI:NAME:<NAME>END_PI"
tip_reusable_software: "Antes de que el software sea reusable, primero tiene que ser usable."
tip_optimization_operator: "Cada lenguaje tiene un operador de optimización. En la mayoría de ellos, ese operador es ‘//’"
tip_lines_of_code: "Medir el progreso en la programación en líneas de código es como medir el progreso de construcción de una aeronave por su peso. — PI:NAME:<NAME>END_PI"
tip_source_code: "Quisiera cambiar el mundo, pero no me dan el código fuente."
tip_javascript_java: "Java es a Javascript lo mismo que Comer es a Comercial. - PI:NAME:<NAME>END_PI"
tip_move_forward: "Hagas lo que hagas, siempre sigue hacia delante. - PI:NAME:<NAME>END_PI Jr."
tip_google: "¿Tienes un problema que no puedes resolver? ¡Googléalo!"
tip_adding_evil: "Agregando una pizca de maldad."
tip_hate_computers: "Esa es la razón por la cual la gente piensa que odia las computadoras. Lo que ellos odian de verdad, es los pesimos programadores. - PI:NAME:<NAME>END_PI"
tip_open_source_contribute: "¡Tú puedes ayudar a CodeCombat a mejorar!"
tip_recurse: "Iterar es humano, recursar es divino. - PI:NAME:<NAME>END_PI"
tip_free_your_mind: "Tienes que dejar ir todo, Neo. Miedo, duda, e incredulidad. Libera tu mente. - Morpheus"
tip_strong_opponents: "Hasta los oponentes mas fuertes siempre tienen una debilidad. - PI:NAME:<NAME>END_PI"
tip_paper_and_pen: "Antes de comenzar a programar, siempre puedes planear con una hoja de papel y un lapicero."
tip_solve_then_write: "Primero, resuelve el problema. Entonces, escribe el código. - PI:NAME:<NAME>END_PI"
tip_compiler_ignores_comments: "A veces pienso que el compilador ignora mis comentarios."
tip_understand_recursion: "La única manera de entender la recursividad es entender la recursividad."
tip_life_and_polymorphism: "El Open Source es como una estructura heterogénea totalmente polimórfica: Todos los tipos son bienvenidos."
tip_mistakes_proof_of_trying: "Errores en tu código son solo evidencia de que estas intentando."
tip_adding_orgres: "Redondendo ogres."
tip_sharpening_swords: "Afilando las espadas."
tip_ratatouille: "No debes dejar que nadie defina tus límites a causa de donde venas. Tu único límite es tu alma. - PI:NAME:<NAME>END_PI"
tip_nemo: "¿Cuando huye la suerte, sabes que hay que hacer? Sigue nadando, sigue nadando. - PI:NAME:<NAME>END_PI"
tip_internet_weather: "Debes moverte al intenet, es genial aquí. Tenemos la oportunidad de vivir dentro donde el clima es siempre sorprendente. - PI:NAME:<NAME>END_PI"
tip_nerds: "A los Nerds se les permite amor cosas, como saltar-arriba-y-abajo-en-la-silla-no-te-puedes-controlar-tu-mismo quiérelo. - PI:NAME:<NAME>END_PI"
tip_self_taught: "Me enseñé a mí mismo el 90% de lo que he aprendido. ¡Y eso es normal! - PI:NAME:<NAME>END_PI"
tip_luna_lovegood: "No te preocupes, estas tan cuerdo como yo. - PI:NAME:<NAME>END_PI"
tip_good_idea: "La mejor forma de tener una buena idea es tener un montón de ideas. - PI:NAME:<NAME>END_PI"
tip_programming_not_about_computers: "Las Ciencias de la Computación está tan alejada de computadoras como la astronomía de telescopios. - PI:NAME:<NAME>END_PI"
tip_mulan: "Si crees que puedes, entonces lo harás. - PI:NAME:<NAME>END_PI"
project_complete: "¡Proyecto completo!"
share_this_project: "Comparte este proyecto con familia y amigos:"
ready_to_share: "¿Listo para publicar tu proyecto?"
click_publish: "Haz click en \"Publicar\" para que aparezca en la galería de la clase, a continuación ¡echa un vistazo a lo que construyeron tus compañeros! Puedes volver y seguir trabajando en este proyecto. Cualquier cambio adicional se guardará automáticamente y se compartirá con tus compañeros."
already_published_prefix: "Tus cambios se han publicado en la galería de la clase."
already_published_suffix: "¡Sigue experimentando y haciendo este proyecto aún mejor, o mira lo que el resto de la clase ha construido! Tus cambios se guardarán automáticamente y se compartirán con tus compañeros."
view_gallery: "Ver Galería"
project_published_noty: "¡Tu nivel ha sido publicado!"
keep_editing: "Continuar editando"
learn_new_concepts: "Aprende nuevos conceptos"
watch_a_video: "Mira un video de __concept_name__"
concept_unlocked: "Concepto desbloqueado"
use_at_least_one_concept: "Usa al menos un concepto: "
command_bank: "Banco de códigos"
learning_goals: "Metas de aprendizaje"
start: "Empezar"
vega_character: "Personaje Vega"
capella_character: "Personaje Capella"
octans_character: "Personaje Octans"
click_to_continue: "Haz clic para continuar"
share_your_project: "Comparte tu proyecto"
keep_editing_your_project: "Siempre puedes seguir editando tu proyecto, incluso después compartirlo."
copy_url: "Copiar URL"
level_status: "Estado"
level_status_locked: "Bloqueado"
level_status_in_progress: "En curso"
level_status_complete: "Completado"
level_type_practice: "Práctica"
level_type_challenge: "Desafío"
level_type_cutscene: "Escena"
level_type_capstone: "Final"
level_type_intro: "Introducción"
level_type_practice_level: "Nivel de práctica"
level_type_challenge_level: "Nivel de desafío"
level_type_cutscene_level: "Nivel de escena"
level_type_capstone_level: "Nivel final"
level_type_capstone_project: "Proyecto final"
level_type_intro_level: "Nivel introductorio"
content_type_avatar: "Selección de avatar"
content_type_cinematic: "Cinemática"
content_type_interactive: "Comprobación de conceptos"
feedback: "Comentarios"
apis:
methods: "Métodos"
events: "Eventos"
handlers: "Manipuladores"
properties: "Propiedades"
snippets: "Fragmentos"
spawnable: "Generable"
html: "HTML"
math: "Cálculos"
array: "Arreglo"
object: "Objeto"
string: "Cadena de texto"
function: "Función"
vector: "Vector"
date: "Fecha"
jquery: "jQuery"
json: "JSON"
number: "Número"
webjavascript: "JavaScript"
amazon_hoc:
title: "¡Sigue aprendiendo con Amazon!"
congrats: "¡Felicitaciones por conquistar esa desafiante Hora de Código!"
educate_1: "Ahora, continúa aprendiendo sobre programación y computación en la nube con AWS Educate, un programa emocionante y gratuito de Amazon para estudiantes y maestros. Con AWS Educate, puedes obtener insignias geniales a medida que aprendes sobre los conceptos básicos de la nube y las tecnologías de vanguardia, como los juegos, la realidad virtual y Alexa."
educate_2: "Aprende más y regístrate aquí"
future_eng_1: "También puedes intentar construir tu propia habilidad de datos escolares para Alexa."
future_eng_2: "aquí"
future_eng_3: "(No se requiere dispositivo). Esta actividad de Alexa es traída a ti por el"
future_eng_4: "Amazon Future Engineer"
future_eng_5: "programa que crea oportunidades de aprendizaje y trabajo para todos los estudiantes de K-12 en los Estados Unidos que desean dedicarse a Ciencias de la Computación."
play_game_dev_level:
created_by: "Creado por {{name}}"
created_during_hoc: "Creado durante Hora de Código"
restart: "Reiniciar Nivel"
play: "Iniciar Nivel"
learn_about_ozaria: "Learn About Ozaria"
default_student_instructions: "¡Haz clic para controlar a tu héroe y ganar tu juego!"
goal_survive: "Sobrevive."
goal_survive_time: "Sobrevive por __seconds__ segundos."
goal_defeat: "Derrota a todos los enemigos."
goal_defeat_amount: "Derrota __amount__ enemigos."
goal_move: "Muévete a todas las marcas X rojas."
goal_collect: "Recoge todos los objetos."
goal_collect_amount: "Recoge __amount__ objetos."
game_menu:
inventory_tab: "Inventario"
save_load_tab: "Guardar/Cargar"
options_tab: "Opciones"
guide_tab: "Guía"
guide_video_tutorial: "Guía en video"
guide_tips: "Pistas"
multiplayer_tab: "Multijugador"
auth_tab: "Entrar"
inventory_caption: "Equipar a tu héroe"
choose_hero_caption: "Elegir héroe, lenguaje"
options_caption: "Hacer ajustes"
guide_caption: "Documentos y consejos"
multiplayer_caption: "¡Jugar con amigos!"
auth_caption: "Guarda tu progreso."
leaderboard:
view_other_solutions: "Ver la Tabla de Posiciones"
scores: "Puntajes"
top_players: "Mejores jugadores"
day: "Hoy"
week: "Esta Semana"
all: "Siempre"
latest: "Mas reciente"
time: "Tiempo"
damage_taken: "Daño Recibido"
damage_dealt: "Daño Infligido"
difficulty: "Dificultad"
gold_collected: "Oro Recolectado"
survival_time: "Sobrevivido"
defeated: "Enemigos Derrotados"
code_length: "Líneas de código"
score_display: "__scoreType__: __score__"
inventory:
equipped_item: "Equipado"
required_purchase_title: "Requerido"
available_item: "Disponible"
restricted_title: "Restringido"
should_equip: "(doble-click para equipar)"
equipped: "(equipado)"
locked: "(bloqueado)"
restricted: "(restringido en este nivel)"
equip: "Equipar"
unequip: "Sacar"
warrior_only: "Sólo para Gerrero"
ranger_only: "Sólo para Arquero"
wizard_only: "Sólo para Mago"
buy_gems:
few_gems: "Pocas gemas"
pile_gems: "Pila de gemas"
chest_gems: "Cofre de gemas"
purchasing: "Comprando..."
declined: "Su tarjeta fue rechazada"
retrying: "Error del servidor, recargando."
prompt_title: "Gemas insuficientes"
prompt_body: "¿Quieres obtener más?"
prompt_button: "Entrar al mercado"
recovered: "Se recuperaron las anteriores compras de gemas. Por favor recarga la página"
price: "x{{gems}} / mes"
buy_premium: "Comprar Premium"
purchase: "Compra"
purchased: "Comprado"
subscribe_for_gems:
prompt_title: "¡Gemas suficientes!"
prompt_body: "¡Suscríbete a Premium para obtener gemas y acceso a más niveles!"
earn_gems:
prompt_title: "Gemas Insuficientes"
prompt_body: "¡Sigue jugando para ganar más!"
subscribe:
best_deal: "¡La mejor ofera!"
confirmation: "¡Felicitaciones! Ahora tienes una suscripción Premium de CodeCombat!"
premium_already_subscribed: "¡Ya tienes una suscripción Premium!"
subscribe_modal_title: "CodeCombat Premium"
comparison_blurb: "Agudiza tus habilidades con la suscripción a CodeCombat!" # {change}
must_be_logged: "Debes iniciar sesión primero. Por favor crea una cuenta o inicia sesión desde el menú superior."
subscribe_title: "Suscribirse" # Actually used in subscribe buttons, too
unsubscribe: "Cancelar suscripción"
confirm_unsubscribe: "Confirmar cancelación de suscripción"
never_mind: "Olvidalo, Te sigo queriendo"
thank_you_months_prefix: "Gracias por tu apoyo en estos últimos"
thank_you_months_suffix: "meses."
thank_you: "Gracias por apoyar CodeCombat."
sorry_to_see_you_go: "¡Sentimos que te vayas! Por favor, haznos saber lo que podríamos haber hecho mejor."
unsubscribe_feedback_placeholder: "¿Pero qué hemos hecho?"
stripe_description: "Suscripción Mensual"
buy_now: "Comprar ahora"
subscription_required_to_play: "Necesitas una suscripción para jugar este nivel."
unlock_help_videos: "Suscríbete para desbloquear todos los video tutoriales."
personal_sub: "Suscripción Personal" # Accounts Subscription View below
loading_info: "Cargando información de suscripción..."
managed_by: "Administrado por"
will_be_cancelled: "Será cancelado en"
currently_free: "Actualmente tienes una suscripción gratuita"
currently_free_until: "Actualmente tienes una suscripción gratuita hasta"
free_subscription: "Suscripción gratuita"
was_free_until: "Tuviste una suscripción gratuita hasta"
managed_subs: "Suscripciones administradas"
subscribing: "Suscribiendo..."
current_recipients: "Recipientes actuales"
unsubscribing: "Dando de baja..."
subscribe_prepaid: "Click en suscribirse para utlizar un código prepago"
using_prepaid: "Usar código prepago para una suscribción mensual"
feature_level_access: "Accede a 300+ niveles disponibles"
feature_heroes: "Desbloquea héroes y mascotas exclusivas"
feature_learn: "Aprende a crear juegos y páginas web"
month_price: "$__price__"
first_month_price: "¡Sólo $__price__ en tu primer mes!"
lifetime: "Acceso de por vida"
lifetime_price: "$__price__"
year_subscription: "Suscripción anual"
year_price: "$__price__/por año"
support_part1: "¿Necesitas ayuda con el pago o prefieres Paypal? Correo electrónico"
support_part2: "PI:EMAIL:<EMAIL>END_PI"
announcement:
now_available: "¡Ahora disponible para suscriptores!"
subscriber: "suscriptor"
cuddly_companions: "¡Compañeros de peluche!" # Pet Announcement Modal
kindling_name: "Elemental de Leña"
kindling_description: "Los Elemental de Leña sólo quieren mantenerte tibio durante la noche. Y durante el día. Todo el tiempo, realmente."
griffin_name: "PI:NAME:<NAME>END_PI"
griffin_description: "Los Grifos son mitad ágila, mitad león, son adorables."
raven_name: "PI:NAME:<NAME>END_PI"
raven_description: "Los Cuervos son excelentes para recolectar botellas brillantes llenas de salud para ti."
mimic_name: "PI:NAME:<NAME>END_PI"
mimic_description: "Los Mimos pueden recoger monedas por tí. Colócalos sobre las monedas para aumentar tu suministro de oro."
cougar_name: "PI:NAME:<NAME>END_PI"
cougar_description: "Los Pumas deberían ganar un doctorado por el ronroneo feliz de todos los días."
fox_name: "PI:NAME:<NAME>END_PI"
fox_description: "¡Los zorros azules son muy inteligentes y les encanta cavar en la tierra y la nieve!"
pugicorn_name: "PI:NAME:<NAME>END_PI"
pugicorn_description: "¡Los pugicornios son unas de las criaturas más raras y pueden lanzar hechizos!"
wolf_name: "PI:NAME:<NAME>END_PI"
wolf_description: "¡Los Lobitos son excelentes en la caza, la recolección y jugando el escondite!"
ball_name: "PI:NAME:<NAME>END_PI"
ball_description: "ball.squeak()"
collect_pets: "¡Consigue mascotas para tus héroes!"
each_pet: "¡Cada mascota tiene una habilidad de ayuda única!"
upgrade_to_premium: "Vuélvete un {{subscriber}} para usar mascotas."
play_second_kithmaze: "Juega {{the_second_kithmaze}} para desbloquear al Lobito!"
the_second_kithmaze: "El segundo Kithmaze"
keep_playing: "¡Sigue jugando para descubrir la primera mascota!"
coming_soon: "Muy pronto"
ritic: "Ritic el frío" # Ritic Announcement Modal
ritic_description: "Ritic elfrío. Atrapado en el glaciar PI:NAME:<NAME>END_PI durante incontables edades, finalmente libre y listo para atender a los ogros que lo encarcelaron."
ice_block: "Un bloque de hielo"
ice_description: "Parece que hay algo atrapado adentro..."
blink_name: "Parpadeo"
blink_description: "Ritic desaparece y aparece en un abrir y cerrar de ojos, dejando nada más que una sombra."
shadowStep_name: "Pasombra"
shadowStep_description: "Un asesino maestro sabe como caminar entre las sombras."
tornado_name: "Tornado"
tornado_description: "Es bueno tener un botón de reinicio cuando la tapa está quemada."
wallOfDarkness_name: "Pared de la Oscuridad"
wallOfDarkness_description: "Se oculta detrás de un muro de sombras para evitar las miradas indiscretas."
avatar_selection:
pick_an_avatar: "Elige un avatar que te representará como jugador"
select_avatar_title: "Elige un avatar de jugador"
premium_features:
get_premium: "Obtén<br>CodeCombat<br>Premium" # Fit into the banner on the /features page
master_coder: "¡Conviértete en un programador experto suscribiéndote hoy!"
paypal_redirect: "Serás redirigido a PayPal para completar el proceso de suscripción."
subscribe_now: "Suscríbete ahora"
hero_blurb_1: "Accede a __premiumHeroesCount__ héroes super cargados sólo para suscriptores! Aprovecha el poder imparable de Okar Stompfoot, la precisión mortal de Naria of the Leaf, o invoca esqueletos \"adorables\" con Nalfar Cryptor."
hero_blurb_2: "Los Guerreros Premium desbloquean impresionantes habilidades marciales como Llanto de guerra, Paso firme y Lanzar enemigo. O, ¡juega como un arquero, usando sigilo y arcos, lanzando cuchillos y trampas! ¡Prueba tu habilidad como un verdadero mago programador, y ¡libera una poderosa variedad de magia Primordial, Nigromántica o Elemental!"
hero_caption: "¡Nuevos héroes emocionantes!"
pet_blurb_1: "Las mascotas no son solo compañeros adorables, sino que también proporcionan una funcionalidad y métodos únicos. El Grifo Bebé puede transportar unidades por el aire, el Lobito juega con las flechas del enemigo, al Puma le gusta perseguir a los ogros, ¡y el Mimo atrae monedas como un imán!"
pet_blurb_2: "¡Consigue todas las mascotas para descubrir sus habilidades únicas!"
pet_caption: "¡Adopta mascotas para que acompañen a tu héroe!"
game_dev_blurb: "¡Aprende scripts de juegos y crea nuevos niveles para compartir con tus amigos! Coloca los elementos que desees, escribe el código para la lógica y el comportamiento de la unidad, ¡y mira si tus amigos pueden superar el nivel!"
game_dev_caption: "¡Diseña tus propios juegos para desafiar a tus amigos!"
everything_in_premium: "Todo lo que obtienes en CodeCombat Premium:"
list_gems: "Recibe gemas de bonificación para comprar equipo, mascotas y héroes."
list_levels: "Obtén acceso a otros __premiumLevelsCount__ niveles"
list_heroes: "Desbloquea héroes exclusivos, incluye las clases Arquero y Mago"
list_game_dev: "Crea y comparte juegos con tus amigos"
list_web_dev: "Crea páginas web y aplicaciones interactivas"
list_items: "Equipa elementos únicos para Premium, como mascotas"
list_support: "Obtén soporte Premium para ayudarte a depurar código complicado"
list_clans: "Crea clanes privados para invitar a tus amigos y competir en una tabla de clasificación de grupo."
choose_hero:
choose_hero: "Elige tu héroe"
programming_language: "Lenguaje de programación"
programming_language_description: "¿Qué lenguaje de programación vas a elegir?"
default: "por Defecto"
experimental: "Experimental"
python_blurb: "Simple pero poderoso."
javascript_blurb: "El lenguaje de la web (no es Java)."
coffeescript_blurb: "JavaScript pero más bonito."
lua_blurb: "Lenguaje para Juegos."
java_blurb: "(Sólo para Suscriptiores) Android y Empresarial."
status: "Estado"
weapons: "Armas"
weapons_warrior: "Espada - Corto Alcance, Sin Magia"
weapons_ranger: "Ballestas, Armas - Largo Alcance, Sin Magia"
weapons_wizard: "Barita, - Largo Alcance, Mágico"
attack: "Daño" # Can also translate as "Attack"
health: "Salud"
speed: "Velocidad"
regeneration: "Regeneración"
range: "Rango" # As in "attack or visual range"
blocks: "Bloqueo" # As in "this shield blocks this much damage"
backstab: "Apuñala" # As in "this dagger does this much backstab damage"
skills: "Habilidades"
attack_1: "Ofertas"
attack_2: "de la lista"
attack_3: "daño de arma."
health_1: "Gana"
health_2: "de la lista"
health_3: "salud de la armadura."
speed_1: "Se mueve a"
speed_2: "metros por segundo."
available_for_purchase: "Disponible para Comprar" # Shows up when you have unlocked, but not purchased, a hero in the hero store
level_to_unlock: "Nivel para desbloquear:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see)
restricted_to_certain_heroes: "Sólo ciertos héroes pueden jugar este nivel."
char_customization_modal:
heading: "Personaliza a tu héroe"
body: "Cuerpo"
name_label: "Nombre del héroe"
hair_label: "Color de pelo"
skin_label: "Color de piel"
skill_docs:
function: "función" # skill types
method: "método"
snippet: "fragmento"
number: "número"
array: "arreglo"
object: "objeto"
string: "cadena"
writable: "escribible" # Hover over "attack" in Your Skills while playing a level to see most of this
read_only: "Sólo Lectura"
action: "Acción"
spell: "Conjuro"
action_name: "nombre"
action_cooldown: "Toma"
action_specific_cooldown: "Enfriamiento"
action_damage: "Daño"
action_range: "Rango"
action_radius: "Radio"
action_duration: "Duración"
example: "Ejemplo"
ex: "ej" # Abbreviation of "example"
current_value: "Valor actual"
default_value: "Valor por defecto"
parameters: "Parámetros"
required_parameters: "Parámetros Requeridos"
optional_parameters: "Parámetros Opcionales"
returns: "Devoluciones"
granted_by: "Concedido por"
description_coming_soon: "Descripción próximamente"
save_load:
granularity_saved_games: "Guardado"
granularity_change_history: "Historia"
options:
general_options: "Opciones Generales" # Check out the Options tab in the Game Menu while playing a level
volume_label: "Volúmen"
music_label: "Música"
music_description: "Música encendida/apagada."
editor_config_title: "Configuración del Editor" # {change}
editor_config_livecompletion_label: "Autocompletado automático" # {change}
editor_config_livecompletion_description: "Despliega sugerencias de autocompletado mientras escribes."
editor_config_invisibles_label: "Mostrar Invisibles"
editor_config_invisibles_description: "Visualiza invisibles tales como espacios o tabulaciones."
editor_config_indentguides_label: "Mostrar guías de indentación"
editor_config_indentguides_description: "Visualiza líneas verticales para ver mejor la indentación."
editor_config_behaviors_label: "Comportamientos Inteligentes" # {change}
editor_config_behaviors_description: "Autocompleta corchetes, llaves y comillas."
# editor_config_screen_reader_mode_label: "Enable Screen Reader Mode"
# editor_config_screen_reader_mode_description: "Display levels in text rather than visually."
about:
title: "Acerca de CodeCombat - Involucrar a estudiantes, empoderar a docentes, inspirar la creación"
meta_description: "Nuestra misión es equilibrar los niveles de informática mediante el aprendizaje basado en juego y hacer que la programación sea accesible para todo el que quiera aprender. Creemos que la programación es magia y queremos que los estudiantes tengan la capacidad de crear lo que quieran con solo imaginarlo."
learn_more: "Aprende más"
main_title: "Si queres aprender a programar, necesitas escribir (un montón de) código."
main_description: "En CodeCombat, nuestro trabajo es asegurarnos que estás haciendo eso con una sonrisa en tu cara."
mission_link: "Misión"
team_link: "Equipo"
story_link: "Historia"
press_link: "Prensa"
mission_title: "Nuestra misión: hacer accesible la programación para cada estudiante en la Tierra." # {change}
mission_teach: "Enseña a través de la aventura"
mission_desc_1: "En el mundo de hoy, los niños están bombardeados con entretenimiento que cada año se vuelve más atrapante. Cada aplicación, video, juego y publicidad se crea con el objetivo de captar y retener su atención. Para competir con esa situación, la educación debe encontrar maneras de retener la atención de los estudiantes y capturar su imaginación."
mission_desc_2: "Creemos que aprender ciencias de la computación puede ser fascinante. Debe parecer mágico. Después de todo, la programación le da a cualquiera la posibilidad de explorar nuevas ideas, construir algo a partir de la imaginación e interactuar con otros de nuevas maneras. Nuestra meta es inspirar una conexión con la creatividad y la imaginación inherentes de las ciencias de la computación creando videojuegos educativos que sean creativos e imaginativos."
mission_desc_3: "A lo largo de los últimos cinco años, más de doce millones de personas han aprendido a programar en Python y JavaScript con CodeCombat, lo que lo convirtió en uno de los juegos de programación más populares de la historia. Ahora nos complace anunciar Ozaria y ampliar nuestro compromiso de inspirar a una nueva generación de estudiantes a aprender ciencias de la computación. Ozaria es un juego de aventura que pone a cada estudiante en el centro de una historia legendaria en la que, para salvar al planeta Ozaria de la oscuridad inminente, deben dominar la magia perdida de la programación. A medida que la narrativa se desarrolla, se crea una gran experiencia de aprendizaje centrada en los estudiantes, en la cual el tiempo que cada alumno invierte en la historia de Ozaria equivale al tiempo que invierten en su propio camino de aprendizaje." # {change}
team_title: "Conoce al equipo de CodeCombat"
team_values: "Valoramos el diálogo abierto y respetuoso, donde gana la mejor idea. Nuestras decisiones se basan en la investigación del cliente y nuestro método se centra en obtener resultados tangibles para ellas. Todos están echando una mano, desde nuestro CEO hasta nuestros contribuidores en GitHub, porque en nuestro equipo valoramos el crecimiento y el aprendizaje. " # {change}
nick_title: "PI:NAME:<NAME>END_PI"
csm_title: "Gerente de relaciones comerciales"
scsm_title: "Gerente de relaciones comerciales senior"
ae_title: "Ejecutivo de cuentas"
sae_title: "Ejecutivo de cuentas senior"
sism_title: "Gerente de ventas internas senior"
shan_title: "Encargada principal de establecimiento de asociaciones, China"
run_title: "Jefe de operaciones, China"
lance_title: "Pasante de ingeniería de software, China"
zhiran_title: "Jefa de planes de estudio, China"
yuqiang_title: "Jefe de innovación, China"
swe_title: "Ingeniero de software"
sswe_title: "Ingeniero de software senior"
css_title: "Especialista en atención al cliente"
css_qa_title: "Especialista en atención al cliente / control de calidad"
maya_title: "Desarrolladora de planes de estudio senior"
bill_title: "Gerente general, China"
pvd_title: "Diseñador visual y de productos"
spvd_title: "Diseñador visual y de productos senior"
daniela_title: "Gerente de marketing"
bobby_title: "Diseñador de juegos"
brian_title: "Diseñador de juegos principal" # {change}
stephanie_title: "Especialista en atención al cliente"
sdr_title: "Representante de desarrollo de ventas"
retrostyle_title: "Ilustración"
retrostyle_blurb: "Juegos con estilo Retro"
community_title: "...y nuestra comunidad open-source"
bryukh_title: "Desarrollador de jugabilidad senior"
oa_title: "Asistente de operaciones"
ac_title: "Coordinador administrativo"
ea_title: "Asistente ejecutivo"
om_title: "Gerente de operaciones"
mo_title: "Gerente de operaciones"
smo_title: "Gerente de operaciones senior"
scd_title: "Desarrollador de planes de estudio senior"
lcd_title: "Desarrollador de planes de estudio principal"
vpm_title: "Vicepresidente de marketing"
community_subtitle: "¡Más de 450 contribuidores que ayudaron a contruir CodeCombat, y más uniendose cada semana!" # {change}
community_description_3: "CodeCombat es un"
community_description_link_2: "proyecto comunitario"
community_description_1: "CodeCombat es un proyecto comunitario, con cientos de jugadores haciendo trabajo voluntario al crear niveles, contribuir a nuestro código para añadir características, arreglar bugs, testear, e incluso traducir el juego a 50 idiomas hasta ahora. Empleados, contribuidores y la página ganan al compartir las ideas Echa un vistazo a nuestra" # {change}
community_description_link: "página de contribución"
community_description_2: "para más información."
number_contributors: "Más de 450 contribuidores dieron su apoyo y tiempo a este proyecto."
story_title: "Nuestra historia hasta ahora"
story_subtitle: "Desde 2013, CodeCombat creció desde un mero conjunto de bocetos hasta un juego próspero, vivo."
story_statistic_1a: "+5,000,000" # {change}
story_statistic_1b: "jugadores totales"
story_statistic_1c: "comenzaron su viaje en la programación mediante CodeCombat" # {change}
story_statistic_2a: "We’ve been translated into over 50 languages — nuestros jugadores son de"
story_statistic_2b: "+200 países" # {change}
story_statistic_3a: "Juntos, escribieron"
story_statistic_3b: "1 mil millones de líneas de código, y contando"
story_statistic_3c: "en seis lenguajes de programación distintos" # {change}
story_long_way_1: "Aunque hemos recorrido un largo camino..."
story_sketch_caption: "El primer boceto de Nick representando un juego de programación en acción."
story_long_way_2: "todavía nos queda mucho por hacer antes de que completemos nuestra misión, asi que..."
jobs_title: "¡Ven a trabajar con nosotros y ayuda a escribir la historia de CodeCombat!" # {change}
jobs_subtitle: "¿No encontras una buena opción pero estás interesado en mantener el contacto? Mirá nuestra entrada \"Crear Tu Propio\"."
jobs_benefits: "Beneficios del empleado"
jobs_benefit_4: "Días personales/enfermo ilimitados" # {change}
jobs_benefit_5: "Desarrollo profesional y soporte de formación continua" # {change}
jobs_benefit_6: "Seguro médico/dental/vista" # {change}
jobs_benefit_9: "Ventana opcional de ejercicio por 10 años"
jobs_benefit_10: "Permiso de maternidad: 12 semanas pagadas, luego 6 @ 55% del salario"
jobs_benefit_11: "Permiso de paternidad: 12 semanas pagadas"
jobs_custom_title: "Crear Tu Propio"
jobs_custom_description: "¿Te apasiona CodeCombat pero nos ves un puesto de trabajo que coincida con tus cualificaciones? Escríbenos y muestrenos como cree que puede contribuir a nuestro equipo. ¡Nos encantaría saber de vos!"
jobs_custom_contact_1: "¡Envíanos una nota a"
jobs_custom_contact_2: "presentándote y ¡podremos estar en contacto en el futuro!"
contact_title: "Prensa & Contacto"
contact_subtitle: "¿Necesitas más información? Contáctanos en"
press_subtitle: "o visita nuestro sitio de prensa en"
screenshots_title: "Capturas de pantalla del Juego"
screenshots_hint: "(click para ver en tamaño completo)"
downloads_title: "Descargar Recursos & Información"
about_codecombat: "Acerca de CodeCombat"
logo: "Logo"
screenshots: "Capturas de pantalla"
character_art: "Arte de Personajes"
download_all: "Descargar Todo"
previous: "Anterior"
location_title: "Nos encontramos en el centro de SF:"
teachers:
licenses_needed: "Licencias necesarias"
google_classroom_disabled_text: "Para vincular Google Classroom, inicia sesión con el SSO de Google"
select_class: "Selecciona una clase"
programming_language: "Lenguaje de programación"
programming_language_edit_desc: "No es posible cambiar el lenguaje una vez que ya hay estudiantes en la clase. Recomendamos crear una nueva clase para los mismos estudiantes."
add_a_class: "Agregar una clase nueva"
select_desired_lang: "Seleccionar el idioma de la clase"
elementary: "Primaria (elementary school)"
middle: "Intermedia (middle school)"
high_school: "Secundaria (high school)"
class_name: "Nombre de la clase"
grades: "Grados"
select_all_that_apply: "Selecciona las opciones que correspondan"
class_info_modal_sub_title: "Para invitar a los estudiantes a que se unan a tu clase, envíales lo siguiente:"
class_url: "Enlace de la clase"
class_url_desc: "Comparte el enlace para que los estudiantes se unan a tu clase tras registrarse"
class_code: "Código de la clase"
class_code_desc: "Los estudiantes pueden ingresar este código al registrarse en www.ozaria.com"
invite_by_email: "Invitación por correo electrónico"
# regenerate_class_code: "Regenerate"
invite_modal_sub_title: "Separa cada dirección de correo con un salto de línea o una coma"
no_new_students_imported: "No se importó ningún estudiante nuevo"
error_in_importing_classrooms: "Error al importar aulas"
error_in_importing_students: "Error al importar estudiantes"
no_licenses_page:
are_your_students_ready: "¿Tus estudiantes están entusiasmados por aprender más?"
once_students_have_completed: "Una vez que los estudiantes hayan completado el capítulo 1, necesitarán licencias para continuar aprendiendo con los próximos capítulos."
get_licenses: "Conseguir licencias"
get_full_access_to_ozaria: "Obtener acceso completo a Ozaria"
unlock_all: "Desbloquea todo lo anterior y recibe apoyo para maestros"
unlock_all_dsa: "Desbloquea todo lo anterior y todo el apoyo que necesitan los maestros"
comprehensive_dashboards: "Paneles muy completos para maestros y administradores"
lesson_plans_rubrics_guides: "Planes de estudios, guías de evaluación, guías de soluciones y más"
dedicated_customer_success_manager: "Un gerente exclusivo de satisfacción del cliente"
automatic_access: "Acceso automático a nuevas funciones y contenido"
license_quote: "\"En mi opinión, como maestro veterano de secundaria con 26 años de experiencia, no existe mejor recurso para enseñar programación\"."
join_our_community: "Únete a nuestra comunidad"
join_our_community_desc: "Más de 12 millones de personas han aprendido a escribir en Python y JavaScript con CodeCombat. Ahora te invitamos a unirte a nuestra comunidad de más de 82 000 educadores y 25 000 escuelas que usan Ozaria, un programa diseñado para docentes que quieren inspirar a la nueva generación de estudiantes a aprender Ciencias de la Computación."
teach_real_typed_code: "Enseña código real y práctico"
teach_real_typed_code_desc: "Los estudiantes aprenden Python y JavaScript, los dos lenguajes de programación más populares, y desarrollan habilidades del siglo XXI que les servirán para cualquier carrera."
support_student_progress: "Ayuda a los estudiantes a progresar"
support_student_progress_desc: "Obtén datos de evaluaciones formativas y sumativas a partir de comprobaciones de conceptos, niveles y proyectos finales para ayudar a los estudiantes a progresar."
creative_projects: "Proyectos creativos"
creative_projects_desc: "Despierta la imaginación y desata la creatividad de tus estudiantes con los proyectos finales. Por ejemplo, en el capítulo 2, deben diseñar su propio juego narrativo, que luego pueden compartir con quien quieran. "
looking_for_engaging: "¿Estás buscando un plan de estudios de Ciencias de la Computación interesante?"
licenses_are_required: "Para que los estudiantes continúen su camino después del capítulo 1, necesitarán licencias."
real_world_skills: "Habilidades del mundo real"
real_world_skills_desc: "Los estudiantes aprenden a escribir Python y JavaScript, los dos lenguajes de programación más populares, y perfeccionan sus habilidades de pensamiento crítico, su creatividad y su resiliencia, lo que les servirá para cualquier carrera."
personalized_learning: "Aprendizaje personalizado y enseñanza escalonada"
personalized_learning_desc: "Los estudiantes aprenden conceptos a su propio ritmo. Los niveles aumentan de dificultad a la vez que dan pistas predefinidas para fomentar la persistencia y la determinación."
flexible_curriculum: "Planes de estudio flexibles y alineados con estándares"
flexible_curriculum_desc: "Planes de estudio 100% alineados con la norma CSTA que se pueden adaptar con facilidad a cualquier cronograma, situación o entorno."
resources_to_support: "Recursos para ayudar a los maestros"
resources_to_support_desc: "Planificaciones de clases, actividades de extensión, guías curriculares y más recursos educativos diseñados para funcionar en entornos remotos e híbridos."
actionable_insights: "Información útil para maestros"
actionable_insights_desc: "Empodera a los educadores con datos intuitivos sobre el progreso y las evaluaciones de los estudiantes que posibilitan la enseñanza diferenciada."
special_offer:
special_offer: "Oferta Especial"
project_based_title: "Cursos basados en proyectos"
project_based_description: "Los cursos de desarrollo web y de juegos presentan proyectos finales compartibles."
great_for_clubs_title: "Ideal para clubes y clases electivas"
great_for_clubs_description: "Los maestros pueden comprar hasta __maxQuantityStarterLicenses__ Licencias de Principiante."
low_price_title: "Sólo __starterLicensePrice__ por estudiante"
low_price_description: "Las Licencias de Principiante se mantienen activas por for __starterLicenseLengthMonths__ meses desde la compra."
three_great_courses: "Tres grandes cursos incluidos en la Licencia de Principiante:"
license_limit_description: "Los maestros pueden comprar hasta __maxQuantityStarterLicenses__ Licencias de Principiante. Ya has comprado __quantityAlreadyPurchased__. Si necesitas más, contacta a __supportEmail__. Las Licencias de Principiante son válidas por __starterLicenseLengthMonths__ meses."
student_starter_license: "Licencia de Estudiante Principiante"
purchase_starter_licenses: "Comprar Licencias de Principiante"
purchase_starter_licenses_to_grant: "Compra Licencias de Principiante para acceder a __starterLicenseCourseList__"
starter_licenses_can_be_used: "Licencias de Principiante pueden usarse para agregar cursos adicionales inmediatamente luego de la compra."
pay_now: "Paga Ahora"
we_accept_all_major_credit_cards: "Aceptamos las principales tarjetas de crédito."
cs2_description: "se basa en la base de Introducción a las Ciencias de la Computación, adentrándose en declaraciones if, funciones, eventos y más."
wd1_description: "presenta los conceptos básicos de HTML y CSS al tiempo que enseña las habilidades necesarias para que los estudiantes construyan su primera página web."
gd1_description: "usa la sintaxis con la que los estudiantes ya están familiarizados para mostrarles cómo construir y compartir sus propios niveles de juego."
see_an_example_project: "mira un proyecto de ejemplo"
get_started_today: "¡Comienza Hoy!"
want_all_the_courses: "¿Quieres todos los cursos? Solicita información de nuestras Licencias Completas."
compare_license_types: "Compara los Typos de Licencia:"
cs: "Ciencias de la Computación"
wd: "Desarrollo Web"
wd1: "Desarrollo Web 1"
gd: "Desarrollo de Videojuegos"
gd1: "Desarrollo de Videojuegos 1"
maximum_students: "# Máximo de Estudiantes"
unlimited: "Ilimitado"
priority_support: "Apoyo prioritario"
yes: "Si"
price_per_student: "__price__ por estudiante "
pricing: "Precios"
free: "Gratis"
purchase: "Comprar"
courses_prefix: "Cursos"
courses_suffix: ""
course_prefix: "Curso"
course_suffix: ""
teachers_quote:
subtitle: "¡Obtén CodeCombat en tu clase, club, escuela o distrito!" # {change}
email_exists: "Existe un usuario con este email."
phone_number: "Teléfono"
phone_number_help: "¿Dónde podemos contactarte durante el horario de trabajo ?"
primary_role_label: "Tu Rol Primario"
role_default: "Seleccione Rol"
primary_role_default: "Seleccione Rol Primario"
purchaser_role_default: "Seleccione Rol de Comprador"
teacher: "PI:NAME:<NAME>END_PI"
tech_coordinator: "Coordinador de tecnología"
advisor: "PI:NAME:<NAME>END_PI" # {change}
principal: "PI:NAME:<NAME>END_PI"
superintendent: "PI:NAME:<NAME>END_PI"
parent: "Padre"
purchaser_role_label: "Tu Rol de Comprador"
influence_advocate: "Influencia/Partidario"
evaluate_recommend: "Evaluar/Recomendar"
approve_funds: "Aprobar Fondos"
no_purchaser_role: "Ningún papel en las decisiones de compra"
district_label: "Distrito"
district_name: "Nombre del Distrito"
district_na: "Ingresa N/A si no aplica"
organization_label: "Escuela / Distrito" # {change}
school_name: "Nombre de la Escuela"
city: "Ciudad"
state: "Estado" # {change}
country: "País"
num_students_help: "¿Cuántos prevees inscribir en CodeCombat?" # {change}
num_students_default: "Seleccionar Rango"
education_level_label: "Nivel Educativo de los Estudiantes"
education_level_help: "Elegí todas las que correspondan."
elementary_school: "Escuela Primaria"
high_school: "Escuela Secundaria"
please_explain: "(describa, por favor)"
middle_school: "Escuela Intermedia"
college_plus: "Universidad o superior"
referrer: "¿Cómo supiste de nosotros?"
referrer_help: "Por ejemplo: por otro maestro, una conferencia, tus estudiantes, Code.org, etc."
referrer_default: "Selecciona Una"
referrer_conference: "Conferencia (p. ej. ISTE)"
referrer_hoc: "Code.org/Hour of Code"
referrer_teacher: "Un Maestro"
referrer_admin: "Un Administrador"
referrer_student: "Un Estudiante"
referrer_pd: "Capacitaciones/Talleres Profesionales"
referrer_web: "Google"
referrer_other: "Otro"
anything_else: "¿Algo más que deberíamos saber?" # {change}
thanks_header: "¡Gracias por solicitar un presupuesto!" # {change}
thanks_sub_header: "Gracias por el interés de su institución en CodeCombat" # {change}
thanks_p: "Estaremos en contacto pronto. ¿Preguntas? Escríbenos:" # {change}
back_to_classes: "Volver a las clases"
finish_signup: "Termine la creación de su cuenta de maestro:"
finish_signup_p: "Crear una cuenta para configurar la clase, agregar estudiante y monitorear su progreso a medida que aprenden programacioón"
signup_with: "Registrarse con:"
connect_with: "Conectar con:"
conversion_warning: "ADVERTENCIA: Su cuenta actual es de tipo <em>Estudiante</em>. Una vez que envie este formulario, su cuenta será actualizada como cuenta de maestro."
learn_more_modal: "Cuentas de maestro en CodeCombat tienen la ventaja de monitorear el progreso del estudiante, asignar inscripciónes y administrar salones de clases. Cuentas de maestro no pueden ser parte de los salones de clases. Si usted está registrado en una clase utilizando una cuenta de estudiante, no podrá acceder hasta que tenga una Cuenta de maestro." # {change}
create_account: "Crear una Cuenta de maestro"
create_account_subtitle: "Obtenga acceso a herramientas exclusivas para maestros de CodeCombat. <strong>Configurar una clase</strong>, agregar estudiantes, y <strong>monitorear su progreso</strong>!"
convert_account_title: "Actualizar mi perfil a Cuenta de maestro"
not: "No"
full_name_required: "Nombre y apellido requeridos"
versions:
save_version_title: "Guardar nueva versión"
new_major_version: "Nueva Gran Versión"
submitting_patch: "Publicando Parche..."
cla_prefix: "Para guardar los cambios, primero debes estar de acuerdo con nuestro"
cla_url: "CLA"
cla_suffix: "."
cla_agree: "ACEPTO"
owner_approve: "Necesita la aprobación de un propietario para que los cambios sean visibles."
contact:
contact_us: "Contacta a CodeCombat"
welcome: "¡Qué bueno es escuchar algo de ti! Usa este formulario para enviarnos un mensaje"
forum_prefix: "Para cualquier cosa pública, por favor prueba "
forum_page: "nuestro foro "
forum_suffix: "en su lugar."
faq_prefix: "También hay un"
faq: "FAQ"
subscribe_prefix: "Si necesitas ayuda para resolver un nivel, por favor"
subscribe: "compra una suscripción de CodeCombat"
subscribe_suffix: "y nosotros estaremos felices de ayudarte con tu código."
subscriber_support: "Como estás suscrito a CodeCombat, tu email tendrá prioridad."
screenshot_included: "Captura de pantalla incluida."
where_reply: "¿A dónde deberíamos responder?"
send: "Enviar Comentario"
account_settings:
title: "Configuración de la Cuenta"
not_logged_in: "Inicia sesión o crea una cuenta para cambiar tu configuración."
me_tab: "Yo"
picture_tab: "Imagen"
delete_account_tab: "Borra tu cuenta"
wrong_email: "Mail Incorrecto"
wrong_password: "PI:PASSWORD:<PASSWORD>END_PI"
delete_this_account: "Borrar esta cuenta permanentemente"
reset_progress_tab: "Reiniciar Todo Progreso"
reset_your_progress: "Limpiar todo tu progreso y comenzar de nuevo"
god_mode: "Modo Dios"
emails_tab: "Correos"
admin: "Admin"
manage_subscription: "Click aquí para administrar tu subscripción"
new_password: "PI:PASSWORD:<PASSWORD>END_PI"
new_password_verify: "Verificar"
type_in_email: "Ingrese su correo electrónico para confirmar la eliminación de su cuenta." # {change}
type_in_email_progress: "Ingrese su correo para confirmar la eliminación de su progreso."
type_in_password: "PI:PASSWORD:<PASSWORD>END_PI, ingrese su contraseña."
email_subscriptions: "Suscripciones de Email"
email_subscriptions_none: "No tienes suscripciones."
email_announcements: "Noticias"
email_announcements_description: "Recibe correos electrónicos con las últimas noticias y desarrollos de CodeCombat."
email_notifications: "Notificaciones"
email_notifications_summary: "Controles para tus notificaciones por correo electrónico automáticas y personalizadas relativas a tu actividad en CodeCombat."
email_any_notes: "Algunas notificaciones"
email_any_notes_description: "Desactiva para detener toda la actividad de correos de notificaciones."
email_news: "Noticias"
email_recruit_notes: "Oportunidades Laborales"
email_recruit_notes_description: "Si juegas realmente bien podríamos contactarte para ofrecerte un (mejor) trabajo."
contributor_emails: "Emails Clase Contribuyente"
contribute_prefix: "¡Estamos buscando gente que se una a nuestro grupo! Echa un vistazo a la "
contribute_page: "página de contribución"
contribute_suffix: "para averiguar más."
email_toggle: "Activar Todo"
error_saving: "Error al Guardar"
saved: "Cambios Guardados"
password_mismatch: "La contraseña no coincide."
password_repeat: "Por favor repita su contraseña."
keyboard_shortcuts:
keyboard_shortcuts: "Atajos de teclado"
space: "Barra espaciadora"
enter: "Enter"
press_enter: "Toca enter"
escape: "Escape"
shift: "Shift"
run_code: "Ejecutar el código."
run_real_time: "Ejecutar en tiempo real."
continue_script: "Continuar hasta finalizado el script."
skip_scripts: "Omitir todos los scripts omitibles."
toggle_playback: "Aplicar ejecutar/pausar."
scrub_playback: "Devolverse y avanzar en el tiempo."
single_scrub_playback: "Devolverse y avanzar en el tiempo de a un cuadro."
scrub_execution: "Scrub through la ejecución del hechizo actual."
toggle_debug: "Mostrar/ocultar depuración."
toggle_grid: "Mostrar/ocultar rejilla."
toggle_pathfinding: "Mostrar/ocultar buscador de rutas."
beautify: "Hacer bello tu código estandarizando formato."
maximize_editor: "Maximizar/minimizar editor de código."
cinematic:
click_anywhere_continue: "haz clic en cualquier lado para continuar" # {change}
instructional_tooltip: "Haz clic en los botones de flechas para avanzar o retroceder. También puedes usar las teclas de dirección del teclado."
community:
main_title: "Comunidad CodeCombat"
introduction: "Mira las maneras en las que puedes involucrarte adelante y decide qué es más divertido. ¡Queremos trabajar contigo!"
level_editor_prefix: "Usar CodeCombat"
level_editor_suffix: "para crear y editar niveles. Los han creado niveles para sus clases, amigos, hackatones, estudiantes, familiares. Si crear un nuevo juego luce intimidante puedes ¡comenzar con base en uno nuestro!"
thang_editor_prefix: "Nosotros llamamos a las unidades del juego 'Tiliches'. Usa el"
thang_editor_suffix: "para modificar el arte de CodeCombat. Permite a las unidades lanzar proyectiles, altera la dirección de una animación, cambia los puntos de vida de una unidad o sube tu propio sprite de vectores."
article_editor_prefix: "¿Ves algún error en nuestros documentos? ¿Quieres hacer algunas instrucciones para tus propias creaciones? Revisa el"
article_editor_suffix: "y ayuda a los jugadores de CodeCombat conseguir lo más posible de su tiempo jugando."
find_us: "Encuentranos en etsos sitios"
social_github: "Revisa todo nuestro código en GitHub"
social_blog: "Lee el blog de CodeCombat en Sett"
social_discource: "Únete a la discusión en nuestro foro"
social_facebook: "Me Gusta CodeCombat en Facebook"
social_twitter: "Sigue a CodeCombat en Twitter"
social_gplus: "Únete a CodeCombat con Google+"
social_slack: "Conversa con nosotros en nuestro canal de Slack"
contribute_to_the_project: "Contribuir al proyecto"
clans:
title: "Únete a los clanes de CodeCombat - Aprende a programar en Python, JavaScript y HTML"
clan_title: "__clan__ - Únete a los clanes de CodeCombat y aprende a programar"
meta_description: "Únete a un clan o crea tu propia comunidad de programadores. Juega en niveles de arena multijugador y mejora tu héroe y tus habilidades de programación."
clan: "Clan"
clans: "Clanes"
new_name: "Nuevo nombre de clan"
new_description: "descripción del clan"
make_private: "Hacer clan privado"
subs_only: "solo suscriptores"
create_clan: "Crear nuevo clan"
private_preview: "Vista previa"
private_clans: "Clanes Privados"
public_clans: "Clanes publicos"
my_clans: "Mis Clanes"
clan_name: "Nombre del clan"
name: "PI:NAME:<NAME>END_PI"
chieftain: "Líder del Clan"
edit_clan_name: "Editar el nombre del Clan"
edit_clan_description: "Editar descripción del clan"
edit_name: "editar nombre"
edit_description: "editar descripción"
private: "(privado)"
summary: "Resumen"
average_level: "Nivel Promedio"
average_achievements: "Logros Promedio"
delete_clan: "Borrar Clan"
leave_clan: "Abandonar Clan"
join_clan: "Ingresar Clan"
invite_1: "Invitar:"
invite_2: "*Invitar jugadores al clan, mandandoles este link."
members: "PI:NAME:<NAME>END_PI"
progress: "Progreso"
not_started_1: "no iniciado"
started_1: "iniciado"
complete_1: "completo"
exp_levels: "Expand levels"
rem_hero: "Remover Heróe"
status: "Estado"
complete_2: "Completo"
started_2: "Iniciado"
not_started_2: "No iniciado"
view_solution: "Click para ver la solución."
view_attempt: "Click para ver intento."
latest_achievement: "último logro"
playtime: "Tiempo de juego"
last_played: "Último jugado"
leagues_explanation: "Juega en una liga contra otros miembros del clan en estas instancias de arena multijugador."
track_concepts1: "Haga un seguimiento de los conceptos"
track_concepts2a: "aprendidos por cada estudiante"
track_concepts2b: "aprendidos por cada miembro"
track_concepts3a: "Haga un seguimiento de los niveles completados por cada estudiante"
track_concepts3b: "Haga un seguimiento de los niveles completados por cada miembro"
track_concepts4a: "Ve a tus estudiantes'"
track_concepts4b: "Ve a tus miembros'"
track_concepts5: "soluciones"
track_concepts6a: "Ordene a sus estudiantes por nombre o progreso"
track_concepts6b: "Ordene a sus miembros por nombre o progreso"
track_concepts7: "Requiere invitación"
track_concepts8: "para unirse"
private_require_sub: "Los clanes privados requieren una suscripción para crearlos o unírseles."
courses:
create_new_class: "Crear Nueva Clase"
hoc_blurb1: "Intenta"
hoc_blurb2: "Programa, Juega, Comparte"
hoc_blurb3: "¡actividad! Construye cuatro minijuegos diferentes para aprender los conceptos básicos del desarrollo de juegos, ¡luego crea los tuyos!"
solutions_require_licenses: "Las soluciones de nivel están disponibles para los maestros que tienen licencias."
unnamed_class: "Grupo Anónimo"
edit_settings1: "Editar Configuraciónes de Grupos"
add_students: "Agregar Estudiantes"
stats: "Estadísticas"
student_email_invite_blurb: "Sus estudiantes también pueden usar el código de clase <strong> __classCode__ </strong> al crear una Cuenta de Estudiante, no se requiere correo electrónico."
total_students: "Total de Estudiantes:"
average_time: "Tiempo Promedio de juego por nivel:"
total_time: "Tiempo total de juego:"
average_levels: "Niveles Promedio completados:"
total_levels: "Total de niveles completados:"
students: "Estudiantes"
concepts: "Con ceptos"
play_time: "Tiempo de Juego:"
completed: "Completados:"
enter_emails: "Introducir los emails de los estudiantes a invitar, uno por línea" # {change}
send_invites: "¿Mandar Invitaciones?" # {change}
number_programming_students: "Número de Estudiantes"
number_total_students: "Total de Estudiantes en Escuela/Distrito/Facultad"
enroll: "Inscribirse"
enroll_paid: "Anotar estudiantes en cursos pagos."
get_enrollments: "Obtener Más Matrículas"
change_language: "Cambiar idioma del curso"
keep_using: "Seguir Usando"
switch_to: "Cambiar a"
greetings: "Saludos!"
back_classrooms: "Volver a mis aulas"
back_classroom: "Volver a mi aula" # {change}
back_courses: "Volver a mis cursos" # {change}
edit_details: "Editar detalles de clase"
purchase_enrollments: "Comprar Matrículas" # {change}
remove_student: "Eliminar alumno"
assign: "Asignar"
to_assign: "para asignar cursos pagos."
student: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
teacher: "PI:NAME:<NAME>END_PI"
arena: "Arena"
available_levels: "Niveles Disponibles"
started: "iniciado"
complete: "completado"
practice: "práctica"
required: "obligatorio"
welcome_to_courses: "Aventureros, Bienvenidos a los Cursos!"
ready_to_play: "¿Estás listo?"
start_new_game: "Iniciar un Nuevo Juego"
play_now_learn_header: "Juega y Aprende"
play_now_learn_1: "Sintaxis básica para controlar a tu personaje"
play_now_learn_2: "bucles while para resolver rompecabezas molestos"
play_now_learn_3: "cadenas y variables para personalizar acciones"
play_now_learn_4: "como vencer a un ogro (¡habilidades importantes en la vida!)"
welcome_to_page: "¡Bienvenido a tu página de cursos!" # {change}
my_classes: "Mis Clases" # {change}
class_added: "¡Clase añadida satisfactoriamente!"
view_map: "ver mapa"
view_videos: "ver videos"
view_project_gallery: "ver proyectos de mis compañeros"
join_class: "Unirse a clase" # {change}
join_class_2: "Unirse a clase"
ask_teacher_for_code: "Preguntalé a tu maestro si tu tienes un código de CodeCombat! Si lo tiene, ingresalo debajo:" # {change}
enter_c_code: "<Ingresar Código de la Clase>" # {change}
join: "Unirse"
joining: "Uniéndose a clase __claseJoining__ "
unit_complete: "Unidad completada"
play_arena: "Jugar Arena"
view_project: "Ver Proyecto"
start: "Iniciar"
last_level: "Último nivel" # {change}
not_you: "¿No eres tú?"
continue_playing: "Seguir jugando"
option1_header: "Opción 1: Invitar estudiantes vía email" # {change}
remove_student1: "Quitar alumno"
are_you_sure: "¿Estás seguro que quieres eliminar a este alumno de tu clase?"
remove_description1: "El estudiante perderá acceso a esta aula y a sus clases asignadas. El progreso y la experiencia del juego NO se pierde, y el estudiante puede ser agregado de vuelta al aula en cualquier momento."
remove_description2: "La matrícula paga activada no será devuelta."
license_will_revoke: "La licencia paga de este estudiante será revocada y estará disponible para asignarla a otro estudiante."
keep_student: "Mantener alumno"
removing_user: "Eliminando usuario"
subtitle: "Revisar guías del curso, soluciones y niveles." # {change}
changelog: "Ver los últimos cambios en los niveles del curso."
select_language: "Seleccionar lenguaje"
select_level: "Seleccionar nivel"
play_level: "Jugar Nivel"
concepts_covered: "Conceptos Cubiertos"
view_guide_online: "Ver Guía En Línea(PDF)" # {change}
grants_lifetime_access: "Otorgar derecho de acceso a todos los cursos."
enrollment_credits_available: "Créditos de Inscripción Disponibles :" # {change}
language_select: "Seleccionar Lenguaje" # ClassroomSettingsModal
language_cannot_change: "El lenguaje no puede ser cambiado una vez que el estudiante ingreso a la clase."
avg_student_exp_label: "Promedio de la experiencia en programación del estudiante"
avg_student_exp_desc: "Esto nos ayudará a entender como llevar el ritmo de los cursos."
avg_student_exp_select: "Selecciona la mejor opción"
avg_student_exp_none: "Sin experiencia - poca o ninguna experiencia"
avg_student_exp_beginner: "Principiante - cierto grado de exposición o basado en bloque"
avg_student_exp_intermediate: "Intermedio - un poco de experiencia con código escrito"
avg_student_exp_advanced: "Avanzado - amplia experiencia con código escrito"
avg_student_exp_varied: "Niveles Variados de Experiencia"
student_age_range_label: "Rango de Edad del Estudiante"
student_age_range_younger: "Menor que 6"
student_age_range_older: "Mayor que 18"
student_age_range_to: "a"
estimated_class_dates_label: "Fechas Estimadas de Clase"
estimated_class_frequency_label: "Frecuencia Estimada de Clase"
classes_per_week: "clases por semana"
minutes_per_class: "minutos por clase"
create_class: "Crear Grupo"
class_name: "Nombre de clase"
teacher_account_restricted: "Tu cuenta es una cuenta de maestro, y no puedes acceder al contenido del estudiante." # {change}
account_restricted: "Necesitas una cuenta de Estudiante para acceder a esta pagina."
update_account_login_title: "Inicia sesión para actualizar tu cuenta"
update_account_title: "¡Tu cuenta necesita atención!"
update_account_blurb: "Antes de acceder a tus clases, selecciona como quieres usar esta cuenta."
update_account_current_type: "Tipo de Cuenta Actual:"
update_account_account_email: "Nombre/Correo electrónico de la Cuenta:"
update_account_am_teacher: "Soy un Maestro"
update_account_keep_access: "Mantener el acceso a las clases que he creado"
update_account_teachers_can: "Las cuentas de maestro pueden:"
update_account_teachers_can1: "Crear/administrar/agregar clases"
update_account_teachers_can2: "Asignar/inscribir estudiantes en cursos"
update_account_teachers_can3: "Desbloquea todos los niveles del curso para probar"
update_account_teachers_can4: "Accede a las nuevas funciones solo para maestros a medida que las lanzamos"
update_account_teachers_warning: "Advertencia: se lo eliminará de todas las clases a las que se haya unido anteriormente y no podrá jugar como estudiante."
update_account_remain_teacher: "Mantener Maestro"
update_account_update_teacher: "Actualizar Maestro"
update_account_am_student: "Soy un estudiante"
update_account_remove_access: "Eliminar acceso a las clases que he creado"
update_account_students_can: "Las cuentas de Estudiante pueden:"
update_account_students_can1: "Unirse a classes"
update_account_students_can2: "Juega a través de cursos como estudiante y sigue tu propio progreso"
update_account_students_can3: "Compite contra otros compañeros en arenas"
update_account_students_can4: "Accede a nuevas funciones solo para estudiantes a medida que las lanzamos"
update_account_students_warning: "Advertencia: No podrá administrar ninguna clase que haya creado anteriormente o crear nuevas clases."
unsubscribe_warning: "Advertencia: Se le dará de baja de su suscripción mensual."
update_account_remain_student: "Manener Estudiante"
update_account_update_student: "Actualizar Estudiante"
need_a_class_code: "Necesitarás un Código de Clase para la clase a la que te estás uniendo:"
update_account_not_sure: "¿No sabes cuál elegir? Correo electrónico"
update_account_confirm_update_student: "¿Estás seguro de que deseas actualizar tu cuenta a una experiencia de estudiante?"
update_account_confirm_update_student2: "No podrás administrar ninguna clase que hayas creado anteriormente o crear nuevas clases. Las clases creadas anteriormente se eliminarán de CodeCombat y no se podrán restaurar."
instructor: "Instructor: "
youve_been_invited_1: "Has sido invitado para unirte "
youve_been_invited_2: ", donde aprenderás "
youve_been_invited_3: " con tus compañeros en CodeCombat."
by_joining_1: "UniéPI:NAME:<NAME>END_PI "
by_joining_2: "podrás ayudar a restablecer tu contraseña si la olvidas o la pierdes. También puedes verificar tu dirección de correo electrónico para que puedas restablecer la contraseña tu mismo."
sent_verification: "Hemos enviado un correo electrónico de verificación a:"
you_can_edit: "Puedes editar tu dirección de correo electrónico en "
account_settings: "Configuración de Cuenta"
select_your_hero: "Selecciona tu Héroe"
select_your_hero_description: "Siempre puedes cambiar tu héroe entrando en tu página de Cursos y haciendo click en \"Cambiar Héroe\""
select_this_hero: "Seleccionar este Héroe"
current_hero: "Héroe Actual:"
current_hero_female: "Heroína Actual:"
web_dev_language_transition: "Todas las clases programan en HTML / JavaScript para este curso. Las clases que han estado usando Python comenzarán con niveles de introducción de JavaScript adicionales para facilitar la transición. Las clases que ya están usando JavaScript omitirán los niveles de introducción."
course_membership_required_to_play: "Deberás unirte a un curso para jugar a este nivel."
license_required_to_play: "¡Pídele a tu maestro que te asigne una licencia para que puedas continuar jugando CodeCombat!" # {change}
update_old_classroom: "¡Nuevo año escolar, nuevos niveles!"
update_old_classroom_detail: "Para asegurarte de que estás obteniendo los niveles más actualizados, asegúrate de crear una nueva clase para este semestre haciendo clic en Crear una Nueva Clase en su"
teacher_dashboard: "tablero de maestros"
update_old_classroom_detail_2: "y entregando a los estudiantes el nuevo Código de Clase que aparecerá."
view_assessments: "Ver evaluaciones"
view_challenges: "ver niveles de desafío"
challenge: "Desafío:"
challenge_level: "Nivel de Desafío:"
status: "Estado:"
assessments: "Evaluaciones"
challenges: "Desafíos"
level_name: "Nombre del Nivel:"
keep_trying: "Sigue Intentando"
start_challenge: "Iniciar Desafío"
locked: "Bloqueado"
concepts_used: "Conceptos Usados:"
show_change_log: "Mostrar cambios a los niveles de este curso"
hide_change_log: "Ocultar cambios a los niveles de este curso"
concept_videos: "Videos de Concepto"
concept: "Concepto:"
basic_syntax: "Sintaxis Básica"
while_loops: "Bucles While"
variables: "Variables"
basic_syntax_desc: "La sintaxis es cómo escribimos código. Al igual que la ortografía y la gramática son importantes para escribir narraciones y ensayos, la sintaxis es importante al escribir código. Los humanos son buenos para entender lo que significa algo, incluso si no es exactamente correcto, pero las computadoras no son tan inteligentes, y necesitan que escribas con mucha precisión."
while_loops_desc: "Un bucle es una forma de repetir acciones en un programa. Puedes usarlos para no tener que seguir escribiendo códigos repetitivos, y cuando no sepas exactamente cuántas veces tendrá que ocurrir una acción para completar una tarea."
variables_desc: "Trabajar con variables es como organizar cosas en cajas de zapatos. Le das un nombre a la caja de zapatos, como \"Útiles escolares \", y luego pones las cosas dentro. El contenido exacto de la caja puede cambiar con el tiempo, pero todo lo que haya dentro siempre se llamará \"Útiles escolares \". En la programación, las variables son símbolos utilizados para almacenar datos que cambiarán a lo largo del programa. Las variables pueden contener una variedad de tipos de datos, incluidos números y cadenas de texto."
locked_videos_desc: "Sigue jugando para desbloquear el video del concepto __concept_name__."
unlocked_videos_desc: "Revisa el video del concepto __concept_name__."
video_shown_before: "mostrado antes de __level__"
link_google_classroom: "Enlace a Google Classroom"
select_your_classroom: "Selecciona tu Aula"
no_classrooms_found: "No se encontraron sulas"
create_classroom_manually: "Crear un aula manualmente"
classes: "Clases"
certificate_btn_print: "Imprimir"
certificate_btn_toggle: "Alternar"
module_coming_soon: "¡Próximamente, se vienen los módulos 4 a 6 del capítulo 1!"
error_in_creating_data: "Error al crear datos para el nivel introductorio."
project_gallery:
no_projects_published: "¡Sé el primero en publicar un proyecto en este curso!"
view_project: "Ver Proyecto"
edit_project: "Editar Proyecto"
teacher:
assigning_course: "Asignando curso"
back_to_top: "Volver arriba"
click_student_code: "Haz clic en cualquier nivel que el estudiante haya comenzado o completado para ver el código que escribió."
code: "Código de __name__"
complete_solution: "Solución completa"
course_not_started: "El estudiante todavía no ha completado este curso."
appreciation_week_blurb1: "¡Por la <strong>semana de apreciación al maestro de 2019</strong>, ofrecemos licencias gratuitas de una semana!<br />Debes escribirle a PI:NAME:<NAME>END_PI (<a href=\"mailto:PI:EMAIL:<EMAIL>END_PI?subject=Teacher Appreciation Week\">PI:EMAIL:<EMAIL>END_PI</a>) con el asunto \"<strong>Semana de apreciación al maestro</strong>\" e incluir:"
appreciation_week_blurb2: "la cantidad de licencias de una semana que quieres (una por estudiante)"
appreciation_week_blurb3: "la dirección de correo electrónico de tu cuenta de maestro de CodeCombat"
appreciation_week_blurb4: "si quieres licencias para la semana 1 (6 a 10 de mayo) o para la semana 2 (13 a 17 de mayo)"
hoc_happy_ed_week: "¡Feliz semana de la educación en ciencias de la computación!"
hoc_blurb1: "¡Entérate de la actividad gratuita"
hoc_blurb2: "Programa, juega y comparte,"
hoc_blurb3: "descarga un nuevo plan de estudios para maestros y dile a tus estudiantes que ingresen a jugar!"
hoc_button_text: "Ver actividad"
no_code_yet: "El estudiante aún no ha escrito nada de código para este nivel."
open_ended_level: "Nivel abierto"
partial_solution: "Solución parcial"
capstone_solution: "Solución final"
removing_course: "Quitando curso"
solution_arena_blurb: "Se alienta a los estudiantes a solucionar los niveles de arena con creatividad. La siguiente solución cumple con los requisitos del nivel."
solution_challenge_blurb: "Se alienta a los estudiantes a resolver los niveles abiertos con creatividad. La siguiente es una solución posible."
solution_project_blurb: "Se alienta a los estudiantes a crear un proyecto creativo en este nivel. Consulta las guías curriculares del centro de recursos para más información sobre cómo evaluar estos proyectos."
feedback_capstone: "El estudiante creará un proyecto básico en la parte 1 y hará actualizaciones creativas a partir de los comentarios de sus compañeros en la parte 2. Puedes compartir esta <a target=\"_blank\" rel=\"noopener\" href=\"https://docs.google.com/document/d/1u8LtMHlWnpEgLZQtZomPfe82s-Swden7iIacCzdYYxk\">plantilla de comentarios</a> con tus estudiantes."
students_code_blurb: "Cuando corresponde, se ofrece una solución correcta para el nivel. En algunos casos, es posible que el estudiante lo resuelva con un código distinto. No se muestran las soluciones de los niveles que el estudiante no ha comenzado."
course_solution: "Solución del curso"
level_overview_solutions: "Resumen del nivel y soluciones"
no_student_assigned: "No hay ningún estudiante asignado a este curso."
paren_new: "(nuevo)"
student_code: "Código del estudiante __name__"
teacher_dashboard: "Tablero del maestro" # Navbar
my_classes: "Mis Clases" # {change}
courses: "Cursos" # {change}
enrollments: "Recursos"
resources: "Resources"
help: "Ayuda"
language: "Lenguaje"
edit_class_settings: "editar configuración de la clase"
access_restricted: "Se requiere Actualización de la Cuenta"
teacher_account_required: "Una cuenta de Maestro es requerida para acceder a este contenido."
create_teacher_account: "Crear Cuenta de Maestro" # {change}
what_is_a_teacher_account: "Qué es una Cuenta de Maestro?"
teacher_account_explanation: "Una Cuenta de Maestro en CodeCombat da permiso a crear salones de clases, monitorear el progreso de los estudiantes mientras ellos trabajan a través de los cursos, manejar inscripciones y acceder a recursos para la creación de su plan de estudio." # {change}
current_classes: "Clases Recientes"
archived_classes: "Clases Archivadas"
# shared_classes: "Shared Classes"
archived_classes_blurb: "Las Clases pueden ser archivadas para futuras referencias. Desarchiva una Clase para verla en la lista de Clases Recientes de nuevo."
view_class: "ver clase"
archive_class: "almacenar clase"
unarchive_class: "desarchivar clase"
unarchive_this_class: "desarchivar esta clase"
no_students_yet: "Esta clase no tienes estudiantes todavía."
no_students_yet_view_class: "Ver clase para agregar estudiantes."
try_refreshing: "(Necesitarás recargar la página)"
create_new_class: "Crear una Nueva Clase"
class_overview: "Resumen de la Clase" # View Class page
avg_playtime: "Nivel medio de tiempo de juego"
total_playtime: "Tiempo Total de juego"
avg_completed: "Promedio de niveles completados"
total_completed: "Total de niveles completados"
created: "Creado"
concepts_covered: "Conceptos cubiertos"
earliest_incomplete: "Nivel incompleto más Reciente"
latest_complete: "Último nivel completado"
enroll_student: "Inscribir estudiante"
apply_modal_subtitle: "Se te redirigirá a la página Mis clases, donde podrás aplicar licencias a tus estudiantes de las siguientes formas:"
apply_modal_list_item_1: "Seleccionando o creando una clase"
apply_modal_list_item_2: "Seleccionando a los estudiantes a los que quieres aplicar licencias"
apply_modal_list_item_3: "Haciendo clic en el botón “Aplicar licencias”"
apply_license: "Aplicar Licencia"
revoke_license: "Eliminar Licencia"
revoke_licenses: "ELiminar Todas las Licencias"
course_progress: "Progreso del curso"
unit_progress: "Progreso de la unidad"
not_applicable: "N/A"
edit: "editar"
edit_2: "Editar"
remove: "eliminar"
latest_completed: "Último Completado" # {change}
sort_by: "Ordenado por"
progress: "Progreso"
concepts_used: "Conceptos usados por el Estudiante:"
concept_checked: "Concepto verificado:"
completed: "Completado"
practice: "Práctica"
started: "Iniciado"
no_progress: "Sin progreso"
not_required: "No requerido"
view_student_code: "Haz clic para ver el código de estudiante"
select_course: "Selecciona el curso a ver" # {change}
progress_color_key: "Color clave de Progreso:"
level_in_progress: "Nivel en Progreso"
level_not_started: "Nivel no Iniciado"
project_or_arena: "Proyecto o Arena"
students_not_assigned: "Estudiantes que no han sido asignados {{courseName}}"
course_overview: "Resumen del Curso"
copy_class_code: "Copiar código de la Clase"
class_code_blurb: "Nuevos estudiantes pueden entrar a este código de la clase en su tablero o visitar codecombat.com/courses para unirse a la clase." # {change}
copy_class_url: "Copia la URL de la Clase"
class_join_url_blurb: "Nuevos estudiantes pueden visitar esta URL mientras esten logeados para unirse a la clase." # {change}
add_students_manually: "Agregar Estudiantes Manualmente" # {change}
bulk_assign: "Mayor a asignar" # {change}
assigned_msg_1: "Se asignaron {{numberAssigned}} estudiantes a {{courseName}}."
assigned_msg_2: "Se aplicaron {{numberEnrolled}} licencias."
assigned_msg_3: "Tienes {{remainingSpots}} licencias disponibles restantes."
assign_course: "Asignar unidad"
removed_course_msg: "Se quitaron {{numberRemoved}} estudiantes de {{courseName}}."
remove_course: "Quitar unidad"
not_assigned_modal_title: "No se asignaron unidades"
not_assigned_modal_starter_body_1: "Este curso requiere una licencia de principiante. No tienes suficientes licencias de ese tipo para asignar este curso a los __selected__ estudiantes seleccionados."
not_assigned_modal_starter_body_2: "Compra licencias de principiante para brindar acceso a este curso."
not_assigned_modal_full_body_1: "Esta unidad requiere una licencia completa. No tienes suficientes licencias de ese tipo para asignar este curso a los __selected__ estudiantes seleccionados."
not_assigned_modal_full_body_2: "Solo tienes __numFullLicensesAvailable__ licencias completas disponibles (hay __numStudentsWithoutFullLicenses__ estudiantes que actualmente no tienen una licencia completa activa)."
not_assigned_modal_full_body_3: "Selecciona a menos estudiantes o escribe a __supportEmail__ para recibir asistencia."
assigned: "Asignado"
enroll_selected_students: "Inscribir Estudiantes Seleccionados"
no_students_selected: "No fueron seleccionados estudiantes."
show_students_from: "Muestra estudiantes de" # Enroll students modal
apply_licenses_to_the_following_students: "Aplicar licencias a los siguientes estudiantes"
students_have_licenses: "Los siguientes estudiantes ya tienen licencias aplicadas:"
all_students: "Todos los estudiantes"
apply_licenses: "Aplicar licencias"
not_enough_enrollments: "No tienes suficientes Inscripciones disponibles." # {change}
enrollments_blurb: "Los estudiantes deben tener una licencia para acceder al contenido luego de la primera unidad."
how_to_apply_licenses: "Cómo aplicar licencias"
export_student_progress: "Exportar el Progreso del Estudiante(CSV)"
send_email_to: "Enviar correo de recuperación de contraseña a:"
email_sent: "Correo enviado"
send_recovery_email: "Enviar correo de recuperación"
enter_new_password_below: "Ingresa la nueva contraseña:"
change_password: "PI:PASSWORD:<PASSWORD>END_PI"
changed: "Modificada"
available_credits: "Licencias disponibles"
pending_credits: "Licencias pendientes"
empty_credits: "Licencias vencidas"
license_remaining: "licencia restante"
licenses_remaining: "licencias restantes"
one_license_used: "Se ha utilizado 1 licencia de __totalLicenses__"
num_licenses_used: "Se han utilizado __numLicensesUsed__ licencias de __totalLicenses__"
starter_licenses: "licencias de principiante"
start_date: "fecha de inicio:"
end_date: "fecha de finalización:"
get_enrollments_blurb: " Te ayudaremos a crear una solución que satisfaga las necesidades de tu clase, escuela o distrito."
how_to_apply_licenses_blurb_1: "Cuando un maestro le asigna una unidad a un estudiante por primera vez, aplicaremos la licencia automáticamente. Utiliza la lista desplegable Seleccionar unidad en tu aula para asignar una unidad a los estudiantes seleccionados:"
how_to_apply_licenses_blurb_2: "¿Puedo aplicar una licencia sin asignar una unidad?"
how_to_apply_licenses_blurb_3: "Sí. Ve a la pestaña Estado de licencia en tu aula y haz clic en \"Aplicar licencia\" sobre todo estudiante que no tenga una licencia activa."
request_sent: "¡Solicitud enviada!"
assessments: "Evaluaciones"
license_status: "Estado de licencia"
status_expired: "Vencida el {{date}}"
status_not_enrolled: "No inscripto"
status_enrolled: "Vence el {{date}}"
select_all: "Seleccionar todo"
project: "Proyecto"
project_gallery: "Galería de proyectos"
view_project: "Ver proyecto"
unpublished: "(sin publicar)"
view_arena_ladder: "Ver clasificación de arena"
resource_hub: "Centro de recursos"
pacing_guides: "Guías didácticas de aula virtual"
pacing_guides_desc: "¡Aprende a incorporar todos los recursos de CodeCombat para planificar tu año académico!"
pacing_guides_elem: "Guía didáctica para primaria (Elementary School)"
pacing_guides_middle: "Guía didáctica para secundaria (Middle School)"
pacing_guides_high: "Guía didáctica para preparatoria (High School)"
getting_started: "Primeros pasos"
# student_resources: "Student Resources"
# lesson_slides: "Lesson Slides"
# section: "Section"
educator_faq: "Preguntas frecuentes de educadores"
educator_faq_desc: "Preguntas frecuentes sobre el uso de Ozaria en el aula o la escuela."
teacher_getting_started: "Guía introductoria para maestros"
teacher_getting_started_desc: "¿Primera vez en Ozaria? Descarga la guía introductoria para maestros para configurar tu cuenta, crear tu primera clase e invitar a tus estudiantes a trabajar en la primera unidad."
student_getting_started: "Guía de inicio rápido para estudiantes"
student_getting_started_desc: "Puedes compartir esta guía con tus estudiantes antes de empezar a jugar CodeCombat para que se familiaricen con el editor de código. Esta guía sirve para aulas de Python y JavaScript."
ap_cs_principles: "Fundamentos de Ciencias de la Computación AP"
ap_cs_principles_desc: "Con Fundamentos de Ciencias de la Computación AP, los estudiantes reciben una amplia introducción sobre la potencia, el impacto y las posibilidades de la informática. Este curso hace énfasis en el pensamiento computacional y la resolución de problemas a la vez que enseña conceptos básicos de programación."
cs1: "Introducción a las Ciencias de la Computación"
cs2: "Ciencias de la Computación 2"
cs3: "Ciencias de la Computación 3"
cs4: "Ciencias de la Computación 4"
cs5: "Ciencias de la Computación 5"
cs1_syntax_python: "Guía de sintaxis para el curso 1 de Python"
cs1_syntax_python_desc: "Apunte con referencias a la sintaxis habitual de Python que los estudiantes aprenderán en Introducción a las Ciencias de la Computación."
cs1_syntax_javascript: "Guía de sintaxis para el curso 1 de JavaScript"
cs1_syntax_javascript_desc: "Apunte con referencias a la sintaxis habitual de JavaScript que los estudiantes aprenderán en Introducción a las Ciencias de la Computación."
coming_soon: "¡Próximamente más guías!"
engineering_cycle_worksheet: "Hoja de ejercicios sobre el ciclo de ingeniería"
engineering_cycle_worksheet_desc: "Usa esta hoja de ejercicios para enseñarles a los estudiantes las bases del ciclo de ingeniería: análisis, diseño, implementación y depuración. Consulta la hoja de ejemplo completada como guía."
engineering_cycle_worksheet_link: "Ver ejemplo"
progress_journal: "Diario de progreso"
progress_journal_desc: "Alienta a los estudiantes a mantener un registro de sus avances en su diario de progreso."
cs1_curriculum: "Introducción a las Ciencias de la Computación - Guía curricular"
cs1_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 1."
arenas_curriculum: "Niveles de arena - Guía para maestros"
arenas_curriculum_desc: "Instrucciones sobre cómo jugar las arenas multijugador PI:NAME:<NAME>END_PI de PI:NAME:<NAME>END_PIakka, Huesos cruzados y Pico de poder con tu clase."
assessments_curriculum: "Niveles de evaluación - Guía para maestros"
assessments_curriculum_desc: "Aprende a usar los niveles de desafío y los niveles de desafío combo para evaluar el aprendizaje de los estudiantes."
cs2_curriculum: "Ciencias de la Computación 2 - Guía curricular"
cs2_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 2."
cs3_curriculum: "Ciencias de la Computación 3 - Guía curricular"
cs3_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 3."
cs4_curriculum: "Ciencias de la Computación 4 - Guía curricular"
cs4_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para el curso 4."
cs5_curriculum_js: "Ciencias de la Computación 5 - Guía curricular (JavaScript)"
cs5_curriculum_desc_js: "Alcance y orden, planes de estudio, actividades y más para las clases del curso 5 sobre JavaScript."
cs5_curriculum_py: "Ciencias de la Computación 5 - Guía curricular (Python)"
cs5_curriculum_desc_py: "Alcance y orden, planes de estudio, actividades y más para las clases del curso 5 sobre Python."
cs1_pairprogramming: "Actividad de programación en pareja"
cs1_pairprogramming_desc: "Enfrenta a los estudiantes a un ejercicio de programación en pareja que los ayudará a escuchar y comunicar mejor."
gd1: "Desarrollo de Juegos 1"
gd1_guide: "Desarrollo de Juegos 1 - Guía de proyecto"
gd1_guide_desc: "Usa esta guía para orientar a tus estudiantes mientras crean su primer proyecto de videojuego para compartir en cinco días."
gd1_rubric: "Desarrollo de Juegos 1 - Guía de evaluación del proyecto"
gd1_rubric_desc: "Usa esta guía de evaluación al finalizar Desarrollo de Juegos 1."
gd2: "Desarrollo de Juegos 2"
gd2_curriculum: "Desarrollo de Juegos 2 - Guía curricular"
gd2_curriculum_desc: "Planes de estudio para Desarrollo de Juegos 2."
gd3: "Desarrollo de Juegos 3"
gd3_curriculum: "Desarrollo de Juegos 3 - Guía curricular"
gd3_curriculum_desc: "Planes de estudio para Desarrollo de Juegos 3."
wd1: "Desarrollo Web 1"
wd1_curriculum: "Desarrollo Web 1 - Guía curricular"
wd1_curriculum_desc: "Alcance y orden, planes de estudio, actividades y más para Desarrollo Web 1."
wd1_headlines: "Actividad sobre títulos y encabezados"
wd1_headlines_example: "Ver ejemplo de solución"
wd1_headlines_desc: "¿Por qué son importantes las etiquetas de párrafo y encabezado? Usa esta actividad para demostrar que elegir bien los encabezados facilita la lectura de un sitio web. ¡Existen muchas soluciones correctas!"
wd1_html_syntax: "Guía de sintaxis HTML"
wd1_html_syntax_desc: "Hoja de referencia sobre los estilos de HTML que los estudiantes aprenderán en Desarrollo Web 1."
wd1_css_syntax: "Guía de sintaxis CSS"
wd1_css_syntax_desc: "Hoja de referencia sobre la sintaxis de CSS y de estilos que los estudiantes aprenderán en Desarrollo Web 1."
wd2: "Desarrollo Web 2"
wd2_jquery_syntax: "Guía de sintaxis para las funciones jQuery"
wd2_jquery_syntax_desc: "Hoja de referencia sobre las funciones jQuery que los estudiantes aprenderán en Desarrollo Web 2."
wd2_quizlet_worksheet: "Hoja de ejercicios para planificar el cuestionario"
wd2_quizlet_worksheet_instructions: "Ver instrucciones y ejemplos"
wd2_quizlet_worksheet_desc: "Antes de que tus estudiantes armen su proyecto de cuestionario de personalidad al finalizar Desarrollo Web 2, deben planificar las preguntas, los resultados y las respuestas con esta hoja de trabajo. Los maestros pueden distribuir las instrucciones y los ejemplos para consulta de los estudiantes."
student_overview: "Resumen"
student_details: "Detalles del estudiante"
student_name: "Nombre del estudiante"
no_name: "No ingresó nombre."
no_username: "No ingresó nombre de usuario."
no_email: "El estudiante no asignó ningún correo electrónico."
student_profile: "Perfil del estudiante"
playtime_detail: "Tiempo de juego detallado"
student_completed: "Completado por estudiante"
student_in_progress: "Estudiante en curso"
class_average: "Promedio de la clase"
not_assigned: "no cuenta con los siguientes cursos asignados"
playtime_axis: "Tiempo de juego en segundos"
levels_axis: "Niveles en"
student_state: "¿Cómo viene"
student_state_2: "en sus cursos?"
student_good: "viene bien en"
student_good_detail: "Este estudiante está a la par de la clase."
student_warn: "tal vez necesite ayuda con"
student_warn_detail: "Este estudiante tal vez necesite ayuda con nuevos conceptos que se han presentado en este curso."
student_great: "viene muy bien en"
student_great_detail: "Este estudiante tal vez pueda ayudar a otros alumnos de este curso."
full_license: "Licencia full"
starter_license: "Licencia de principiante"
trial: "Prueba"
hoc_welcome: "Feliz semana de la educación en ciencias de la computación"
hoc_title: "Juegos de la Hora del Código - Actividades gratuitas para aprender lenguajes de programación reales"
hoc_meta_description: "¡Crea tu propio juego o escapa de la mazmorra programando! CodeCombat tiene cuatro actividades de la Hora del Código y más de 60 niveles para jugar, crear y aprender a programar."
hoc_intro: "Hay tres maneras en las que tu clase puede participar de la Hora del Código con CodeCombat"
hoc_self_led: "Juego individual"
hoc_self_led_desc: "Los estudiantes pueden jugar dos tutoriales de la Hora del Código de CodeCombat por sí solos"
hoc_game_dev: "Desarrollo de juegos"
hoc_and: "y"
hoc_programming: "programación en JavaScript/Python"
hoc_teacher_led: "Lecciones dirigidas por el docente"
hoc_teacher_led_desc1: "Descarga nuestros"
hoc_teacher_led_link: "planes de estudio de Introducción a las Ciencias de la Computación"
hoc_teacher_led_desc2: "para que tus estudiantes aprendan conceptos de programación con actividades sin conexión"
hoc_group: "Juego grupal"
hoc_group_desc_1: "Los maestros pueden combinar las lecciones con nuestro curso de Introducción a las Ciencias de la Computación para supervisar el progreso de los estudiantes. Consulta nuestra"
hoc_group_link: "guía de inicio"
hoc_group_desc_2: "para más detalles"
hoc_additional_desc1: "Para acceder a más recursos y actividades de CodeCombat, consulta nuestras"
hoc_additional_desc2: "Preguntas"
hoc_additional_contact: "Contáctanos"
revoke_confirm: "¿Seguro quieres anular la licencia completa de {{student_name}}? La licencia estará disponible para asignársela a otro estudiante."
revoke_all_confirm: "¿Seguro quieres anular las licencias completas de todos los estudiantes de esta clase?"
revoking: "Anulando..."
unused_licenses: "¡Tienes licencias sin usar que te permiten asignar cursos pagos a estudiantes cuando estén listos para seguir aprendiendo!"
remember_new_courses: "¡Recuerda asignar cursos nuevos!"
more_info: "Más información"
how_to_assign_courses: "Cómo asignar cursos"
select_students: "Seleccionar Estudiantes"
select_instructions: "Haz clic en la casilla de verificación junto a cada estudiante para asignarle un curso."
choose_course: "Elegir curso"
choose_instructions: "Selecciona de la lista desplegable el curso que quieres asignar y luego haz clic en Asignar a los estudiantes seleccionados."
push_projects: "Recomendamos asignar Desarrollo Web 1 o Desarrollo de Juegos 1 una vez que los estudiantes hayan completado Introducción a las Ciencias de la Computación. Consulta nuestro {{resource_hub}} para más información sobre esos cursos."
teacher_quest: "El camino del maestro hacia el éxito"
quests_complete: "Misiones completadas"
teacher_quest_create_classroom: "Crear aula"
teacher_quest_add_students: "Agregar estudiantes"
teacher_quest_teach_methods: "Ayuda a tus estudiantes a aprender a `llamar métodos`."
teacher_quest_teach_methods_step1: "Consigue que el 75% de al menos una clase supere el primer nivel, __Mazmorras de Kithgard__"
teacher_quest_teach_methods_step2: "Imprime la [guía de inicio rápido para estudiantes](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) del centro de recursos."
teacher_quest_teach_strings: "Suéltales la cadena a tus estudiantes. Enséñales qué son las `cadenas`."
teacher_quest_teach_strings_step1: "Consigue que el 75% de al menos una clase supere __Nombres verdaderos__"
teacher_quest_teach_strings_step2: "Usa el selector de niveles para maestros que hay en la página [Guías de curso](/teachers/units) para previsualizar __Nombres verdaderos__."
teacher_quest_teach_loops: "Repíteles a tus estudiantes una y otra vez el concepto de `bucle`."
teacher_quest_teach_loops_step1: "Consigue que el 75% de al menos una clase supere __Danza con fuego__."
teacher_quest_teach_loops_step2: "Usa la __actividad sobre bucles__ de la [Guía curricular CS1](/teachers/resources/cs1) para reforzar este concepto."
teacher_quest_teach_variables: "Varía los conceptos con las `variables`."
teacher_quest_teach_variables_step1: "Consigue que el 75% de al menos una clase supere __Enemigo reconocido__."
teacher_quest_teach_variables_step2: "Fomenta la colaboración usando la [actividad de programación en pareja](/teachers/resources/pair-programming)."
teacher_quest_kithgard_gates_100: "Escapa por las Puertas de Kithgard con tu clase."
teacher_quest_kithgard_gates_100_step1: "Consigue el 75% de al menos una clase supere __Puertas de Kithgard__."
teacher_quest_kithgard_gates_100_step2: "Orienta a los estudiantes para que resuelvan problemas difíciles usando la [hoja de ejercicios sobre el ciclo de ingeniería](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)."
teacher_quest_wakka_maul_100: "Prepárate para un duelo en la Batalla de Wakka."
teacher_quest_wakka_maul_100_step1: "Consigue que el 75% de al menos una clase supere __Batalla de Wakka__."
teacher_quest_wakka_maul_100_step2: "Consulta la [guía de arenas](/teachers/resources/arenas) del [centro de recursos](/teachers/resources) para recibir sugerencias sobre cómo organizar un día de arena."
teacher_quest_reach_gamedev: "¡Explora nuevos mundos!"
teacher_quest_reach_gamedev_step1: "¡[Consigue licencias](/teachers/licenses) para que tus estudiantes exploren nuevos mundos, como el desarrollo web o de videojuegos!"
teacher_quest_done: "¿Quieres que tus estudiantes aprendan aún más sobre programación? ¡Ponte en contacto con nuestros [especialistas escolares](mailto:PI:EMAIL:<EMAIL>END_PI) de inmediato!"
teacher_quest_keep_going: "¡Sigue avanzando! Esto es lo que puedes hacer ahora:"
teacher_quest_more: "Ver todas las misiones"
teacher_quest_less: "Ver menos misiones"
refresh_to_update: "(actualiza la página para ver actualizaciones)"
view_project_gallery: "Ver galería de proyectos" # {change}
office_hours: "Seminarios web para maestros"
office_hours_detail: "Aprende a seguir el ritmo de tus estudiantes mientras crean juegos y transitan el camino de la programación. Asiste a nuestros"
office_hours_link: "seminarios web"
office_hours_detail_2: "para maestros."
success: "Éxito"
in_progress: "En curso"
not_started: "Sin comenzar"
mid_course: "Mitad de curso"
end_course: "Fin de curso"
none: "Aún sin detectar"
explain_open_ended: "Nota: Se alienta a los estudiantes a resolver este nivel con creatividad. La siguiente es una solución posible."
level_label: "Nivel:"
time_played_label: "Tiempo jugado:" # {change}
back_to_resource_hub: "Volver al centro de recursos"
back_to_course_guides: "Volver a las guías de curso"
print_guide: "Imprimir esta guía"
combo: "Combo"
combo_explanation: "Los estudiantes superan los niveles de desafío combo si utilizan al menos uno de los conceptos enumerados. Puedes revisar el código de los estudiantes haciendo clic en el punto de progreso."
concept: "Concepto"
sync_google_classroom: "Sincronizar Google Classroom"
unit_overview: "Resumen de la unidad"
module_overview: "Resumen del módulo"
chapter1_unit_overview_desc: "Resumen de la experiencia del estudiante que incluye escenas de video, niveles de práctica, introducciones y el proyecto final del capítulo 1."
lesson_plan: "Plan de estudios"
chapter1_lesson_plan_desc: "Guía detallada que incluye objetivos de aprendizaje, normas CSTA, actividades de reflexión, sugerencias de facilitación y más."
capstone_rubric: "Guía de evaluación del proyecto final"
chapter1_capstone_rubric_desc: "Guía para evaluar los proyectos finales y las actividades de reflexión de los estudiantes al final de la unidad."
chapter1: "Capítulo 1: Bailarines de la luna" # {change}
chapter2: "Capítulo 2: Bailarines de la luna"
chapter3: "Capítulo 3: Tierras de Phoenix"
module1: "Módulo 1" # {change}
module2: "Módulo 2" # {change}
module3: "Módulo 3" # {change}
module4: "Módulo 4" # {change}
module5: "Módulo 5" # {change}
module6: "Módulo 6" # {change}
algorithms_and_syntax: "Algoritmos y sintaxis"
debugging: "Depuración"
variables: "Variables"
conditionals: "Condicionales"
capstone_intro: "Inicio del proyecto final"
capstone_project: "Proyecto final"
level_code: "Código de nivel"
review_needed: "Repaso necesario"
review_tooltip_heading: "¿Qué significa esto?"
review_tooltip_text: "Aparecerán señales de advertencia junto a las comprobaciones de conceptos en caso de que al menos un estudiante haya intentando responder la pregunta tres veces o más. En la sección <strong>Resumen del curso</strong>, aparecerán señales de advertencia junto a las comprobaciones de conceptos si al menos el 50% de los estudiantes que han comenzado o completado la comprobación lo intentaron tres veces o más."
scroll_to_see_more: "Desplázate para más información"
click_to_view_concept_check: "Haz clic para ver la comprobación de conceptos"
click_to_view_project_gallery: "Haz clic para ver la galería de proyectos"
review_learning_goal: "Repasar \"Meta de aprendizaje: __learningGoal__\" con los estudiantes."
view_capstone_project: "Ver proyecto final"
ozaria_dashboard_guide: "Guía de panel para maestros"
dashboard_guide_desc: "Un recorrido por las funciones del panel para maestros de Ozaria que te ayudará a supervisar el progreso y el trabajo de los estudiantes."
review: "Repaso"
for_loops: "Bucles for"
peer_feedback: "Formulario de comentarios"
presentation_checklist: "Lista de verificación para presentaciones"
teacher_licenses:
active_licenses: "Licencias activas"
expired_licenses: "Licencias vencidas"
share_licenses:
share_licenses: "Compartir licencias"
shared_by: "Compartido por:"
add_teacher_label: "Ingresar el correo electrónico del maestro:"
add_teacher_button: "Agregar maestro"
modal_subtitle: "Puedes compartir tus licencias con otros maestros de tu conjunto compartido."
modal_list_item_1: "Cada licencia puede utilizarse solamente para un estudiante a la vez."
modal_list_item_2: "Cuando los maestros anulan la licencia de algún estudiante, esa licencia regresa al conjunto compartido para que puedan usarla otros maestros del grupo."
subheader: "Puedes compartir tus licencias con otros maestros de tu institución. Cada licencia puede utilizarse solamente para un estudiante a la vez."
teacher_not_found: "Maestro no encontrado. Asegúrate de que el maestro ya tenga creada una cuenta de maestro."
teacher_not_valid: "Esta no es una cuenta de maestro válida. Solo los maestros pueden compartir licencias desde sus cuentas."
already_shared: "Ya has compartido estas licencias con ese maestro."
teachers_using_these: "Maestros que pueden acceder a estas licencias:"
footer: "Cuando los maestros anulan la licencia de algún estudiante, esa licencia regresa al conjunto compartido para que puedan usarla otros maestros del grupo."
you: "(tú)"
one_license_used: "(1 licencia utilizada)"
licenses_used: "(__licensesUsed__ licencias utilizadas)"
licenses_used_no_braces: "__licensesUsed__ licencias utilizadas"
more_info: "Más información"
shared_pool_label: "Maestros en tu conjunto compartido:"
sharing:
game: "Juego"
webpage: "Sitio web"
your_students_preview: "Tus estudiantes harán clic aquí para ver sus proyectos finalizados. No disponible en la vista previa del maestro."
unavailable: "No es posible compartir enlaces en la vista previa del maestro."
share_game: "Compartir este juego"
share_web: "Compartir este sitio web"
victory_share_prefix: "Comparte este enlace para invitar a tus amigos y familia a"
victory_share_prefix_short: "Invita a otras personas a"
victory_share_game: "jugar tu nivel del juego"
victory_share_web: "ver tu página web"
victory_share_suffix: "."
victory_course_share_prefix: "Este enlace les permitirá a tus amigos y familia"
victory_course_share_game: "jugar el videojuego"
victory_course_share_web: "ver la página web"
victory_course_share_suffix: "que has creado."
copy_url: "Copiar URL"
share_with_teacher_email: "Enviar a tu maestro"
game_dev:
creator: "PI:NAME:<NAME>END_PI"
web_dev:
image_gallery_title: "Galería de imágenes"
select_an_image: "Selecciona la imagen que quieres usar"
scroll_down_for_more_images: "(Desplazar hacia abajo para ver más imágenes)"
copy_the_url: "Copiar la URL de abajo"
copy_the_url_description: "Útil si quieres reemplazar una imagen existente."
copy_the_img_tag: "Copiar la etiqueta <img>"
copy_the_img_tag_description: "Útil si quieres insertar una nueva imagen."
copy_url: "Copiar URL"
copy_img: "Copiar <img>"
how_to_copy_paste: "Cómo copiar y pegar"
copy: "Copiar"
paste: "Pegar"
back_to_editing: "Volver a editar"
classes:
archmage_title: "Archimago"
archmage_title_description: "(Desarrollador)"
archmage_summary: "Si eres un programador interesado en juegos educativos, conviértete en un archimago y ayúdanos a construir CodeCombat!"
artisan_title: "Artesano"
artisan_title_description: "(Constructor de Niveles)"
artisan_summary: "Construye y comparte niveles para que tú y tus amigos jueguen. Conviértete en un Artesano y aprende el arte the enseñar a los demás a programar."
adventurer_title: "Aventurero"
adventurer_title_description: "(Probador de Niveles)"
adventurer_summary: "Consigue nuestros nuevos niveles| (even our subscriber content) for free one week early and help us work out bugs before our public release."
scribe_title: "PI:NAME:<NAME>END_PI"
scribe_title_description: "(Editor de Artículos)"
scribe_summary: "Buen código necesita buena documentación. Escribe, edita y mejora los documentos leídos por millones de jugadores en el mundo."
diplomat_title: "Diplomático"
diplomat_title_description: "(Traductor)"
diplomat_summary: "CodeCombat está traducido a más de 45 idiomas por nuestros diplomáticos. Ayúdanos y contribuye con las traducciones."
ambassador_title: "Embajador"
ambassador_title_description: "(Soporte)"
ambassador_summary: "Ayuda a responder las preguntas de los usuarios del foro. Nuestros Embajadores representan CodeCombat en todo el mundo."
teacher_title: "Maestro"
editor:
main_title: "Editor de CodeCombat"
article_title: "Editor de Artículo"
thang_title: "Editor de Tiliches"
level_title: "Editor de Nivel"
course_title: "Editor de Curso"
achievement_title: "Editor de logros"
poll_title: "Editor de Encuesta"
# resource_title: "Resource Editor"
back: "Atrás"
revert: "Revertir"
revert_models: "Revertir Modelos"
pick_a_terrain: "Elije un Terreno"
dungeon: "Calabozo"
indoor: "Interior"
desert: "Desierto"
grassy: "Herboso"
mountain: "Montaña"
glacier: "Glaciar"
small: "Pequeño"
large: "Grande"
fork_title: "Fork de Nueva Versión"
fork_creating: "Creando Fork..."
generate_terrain: "Generar terreno"
more: "Más"
wiki: "Wiki"
live_chat: "Chat en vivo"
thang_main: "Principal"
thang_spritesheets: "Hojas de figuras( para animaciones )"
thang_colors: "Colores"
level_some_options: "¿Algunas opciones?"
level_tab_thangs: "Tiliches"
level_tab_scripts: "Scripts"
level_tab_components: "Componentes"
level_tab_systems: "Sistemas"
level_tab_docs: "Documentación"
level_tab_thangs_title: "Tiliches Actuales"
level_tab_thangs_all: "Todo"
level_tab_thangs_conditions: "Condiciones Iniciales"
level_tab_thangs_add: "Agregar Thangs"
level_tab_thangs_search: "Buscar Thangs"
add_components: "Agregar Componentes"
component_configs: "Configuraciones del Componente"
config_thang: "Doble clic para configurar un Tiliche"
delete: "Borrar"
duplicate: "Duplicar"
stop_duplicate: "Parar de Duplicar"
rotate: "Rotar"
level_component_tab_title: "Componentes Actuales"
level_component_btn_new: "Crear Nuevo Componente"
level_systems_tab_title: "Sistemas Actuales"
level_systems_btn_new: "Crear Nuevo Sistema"
level_systems_btn_add: "Agregar Sistema"
level_components_title: "Regresar a todos los Tiliches"
level_components_type: "Tipo"
level_component_edit_title: "Editar Componente"
level_component_config_schema: "Config Schema"
level_system_edit_title: "Editar Sistema"
# course_edit_title: "Edit Course"
# resource_edit_title: "Edit Resource"
create_system_title: "Crear Nuevo Sistema"
new_component_title: "Crear Nuevo Componente"
new_component_field_system: "Sistema"
new_article_title: "Crear un Nuevo Artículo"
new_thang_title: "Crear un Nuevo tipo de Tiliche"
new_level_title: "Crear un Nuevo Nivel"
new_article_title_login: "Ingresa para Crear un Nuevo Artículo"
new_thang_title_login: "Ingresa para crear un nuevo tipo de Tiliche"
new_level_title_login: "Ingresa para Crear un Nuevo Nivel"
new_achievement_title: "Crear un Nuevo Logro"
new_achievement_title_login: "Ingresa para Crear un Nuevo Logro"
new_poll_title: "Crear una nueva encuesta"
new_poll_title_login: "Ingresa para crear una nueva encuesta"
# new_course_title: "Create a New Course"
# new_course_title_login: "Log In to Create a New Course"
# new_resource_title: "Create a New Resource"
# new_resource_title_login: "Log In to Create a New Resource"
article_search_title: "Buscar Artículos aquí"
thang_search_title: "Buscar tipos de Tiliche aquí"
level_search_title: "Buscar Niveles aquí"
achievement_search_title: "Buscar logros"
poll_search_title: "Buscar Encuesta"
# course_search_title: "Search Courses"
# resource_search_title: "Search Resources"
read_only_warning2: "Nota: no puedes guardar ediciones aquí, porque no estas logueado."
no_achievements: "No hay logros agregados en este nivel por ahora."
achievement_query_misc: "Objetivo clave de misceláneo"
achievement_query_goals: "Objetivo clave de los objetivos de nivel"
level_completion: "Nivel Completado"
pop_i18n: "Poblar I18N"
tasks: "Tareas"
clear_storage: "Borrar tus cambios locales"
add_system_title: "Agregar Sistemas al Nivel"
done_adding: "Finalizar"
# product: "Product"
# link: "Link"
article:
edit_btn_preview: "Vista previa"
edit_article_title: "Editar Artículo"
polls:
priority: "Prioridad"
contribute:
page_title: "Contribuyendo"
intro_blurb: "CodeCombat es 100% open source! Cientos de jugadores dedicados nos han ayudado a contruir el juego. Únete y escribe el siguiente capítulo de la misión de CodeCombat de enseñar al mundo a programar!" # {change}
alert_account_message_intro: "¡Hola!"
alert_account_message: "Para suscribirte para los correos, necesitas ingresar primero."
archmage_introduction: "Una de las mejores partes de hacer juegos es que sintetizan muchas cosas diferentes. Gráficas, sonido, redes, redes sociales y muchos aspectos comunes de programación, desde manejo de bases de datos y administración de servidores, hasta trabajar en el diseño y construcción de interfaces. Hay mucho para hacer, y si eres un programador con experiencia con el deseo de ingresar en el meollo del asunto de CodeCombat, esta clase puede ser para ti. Nos encantaría contar con tu ayuda para construir el mejor juego de programación."
class_attributes: "Atributos de Clase"
archmage_attribute_1_pref: "Conocimiento en "
archmage_attribute_1_suf: ", o un deseo de aprender. La mayor parte de nuestro código está en este lenguaje. Si eres un fan de Python o Ruby, te sentirás en casa. Es Javascript, pero con un mejor syntax."
archmage_attribute_2: "Alguna experiencia programando e iniciativa personal. Te ayudaremos a orientarte, pero no podemos perder mucho tiempo entrenando."
how_to_join: "Unirse:"
join_desc_1: "¡Cualquiera puede unirse! Sólo checa nuestro "
join_desc_2: "para comenzar, y pon un check abajo para marcarte como un valiente Archimago y conseguir las últimas noticias por email. ¿Quieres chatear sobre qué hacer o cómo involucrarte más? "
join_desc_3: ", o encuéntranos en "
join_desc_4: "y ahí empezaremos!"
join_url_email: "Escríbenos"
join_url_slack: "Canal de Slack"
archmage_subscribe_desc: "Obten correos de nuevas oportunidades y anuncios."
artisan_introduction_pref: "¡Debemos construir niveles adicionales! La gente ruega por más contenido, y podemos hacer tanto por nosotros mismos. De momento tu estación de trabajo es nivel 1 ; Nuestro editor de niveles es apenas útil incluso para sus creadores, así que sea cauteloso. Si tuviera visiones de campañas apareciendo para ciclos for"
artisan_introduction_suf: ", entonces esta lase es ideal para ti."
artisan_attribute_1: "Cualquier experiencia creando contenido similar estaría bien, como por ejemplo el editor de niveles de Blizzard. ¡Aunque no es necesaria!"
artisan_attribute_2: "Un anhelo de hacer un montón de pruebas e iteraciones. Para hacer buenos niveles necesitas mostrárselos a otros y mirar como juegan, además de estar preparado para encontrar los fallos a reparar."
artisan_attribute_3: "Por el momento, la resistencia va a la par con el Aventurero. Nuestro editor de niveles está a un nivel de desarrollo temprano y puede ser muy frustrante usarlo. ¡Estás advertido!"
artisan_join_desc: "Sigue las siguientes indicaciones para usar el editor de niveles. Tómalo o déjalo:"
artisan_join_step1: "Lee la documentación."
artisan_join_step2: "Crea un nuevo nivel y explora los niveles existentes."
artisan_join_step3: "Busca nuestra sala pública de Slack en busca de ayuda."
artisan_join_step4: "Publica tus niveles en el foro para recibir comentarios críticos."
artisan_subscribe_desc: "Recibe correos sobre actualizaciones del editor de niveles y anuncios."
adventurer_introduction: "Hablemos claro sobre tu papel: eres el tanque. Vas a recibir fuertes daños. Necesitamos gente para probar nuestros flamantes niveles y ayudar a mejorarlos. El dolor será enorme; hacer buenos juegos es un proceso largo y nadie lo consigue a la primera. Si puedes resistir y tener una puntuación alta en resistencia, entonces esta clase es para ti."
adventurer_attribute_1: "Estar sediento de conocimientos. Quieres aprender a programar y nosotros queremos enseñarte a hacerlo. Aunque en este caso es más probable que seas tú el que esté haciendo la mayor parte de la enseñanza."
adventurer_attribute_2: "Carismático. Se amable pero claro a la hora de desglosar qué necesita ser mejorado y sugiere de qué formas podría hacerse."
adventurer_join_pref: "Reúnete con (¡o recluta!) un Artesano y trabaja con ellos, o marca la casilla de abajo para recibir un correo cuando haya nuevos niveles para probar. También publicaremos en nuestras redes nuevos niveles para revisar"
adventurer_forum_url: "nuestro foro"
adventurer_join_suf: "así que si prefieres estar informado en esa forma, ¡crea una cuenta allí!"
adventurer_subscribe_desc: "Recibe correos cuando haya nuevos niveles para testar."
scribe_introduction_pref: "CodeCombat no será solo un montón de niveles. También será una fuente de conocimientos, una wiki de conceptos de programación a la que los niveles se engancharan. De esa forma, en lugar de que cada Artesano tenga que describir en detalle qué es un operador de comparación, podrá simplemente enlazar el nivel al Artículo que los describe y que ya ha sido escrito para edificación del jugador. Algo en la línea de lo que la "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: " ha construido. Si tu idea de diversión es articular los conceptos de la programación de una forma sencilla, entonces esta clase es para ti."
scribe_attribute_1: "Habilidad a la hora de escribir es casi todo lo que necesitas. No solo dominar la gramática y la ortografía sino también expresar ideas complicadas a los demás de forma sencilla."
contact_us_url: "Escribenos un correo electrónico" # {change}
scribe_join_description: "cuéntanos más sobre ti, tu experiencia en el mundo de la programación y sobre qué cosas te gustaría escribir. ¡Y continuaremos a partir de ahí!"
scribe_subscribe_desc: "Recibe correos sobre anuncios de redacción de Artículos."
diplomat_introduction_pref: "Hemos aprendido algo gracias a la "
diplomat_introduction_url: "comunidad de código abierto:"
diplomat_introduction_suf: "hay un interés considerable en CodeCombat en otros paises, ¡especialmente Brasil! Estamos formando un cuerpo de traductores con ganas de traducir un grupo de palabras tras otro para hacer CodeCombat tan accesible para todo el mundo como sea posible. Si quieres recibir avances de próximos contenidos y quieres poner esos niveles a disposición de los que comparten tu idioma tan pronto como sea posible, entonces esta Clase es para ti."
diplomat_attribute_1: "Fluidez con el ingles y el lenguaje al que quieras traducir. Cuando de transmitir ideas complejas se trata, ¡es importante tener grandes conocimientos de ambas!"
diplomat_i18n_page_prefix: "Puedes traducir nuestros niveles yendo a nuestra"
diplomat_i18n_page: "página de traducciones"
diplomat_i18n_page_suffix: ", o en nuestra interfaz y sitio web en GitHub."
diplomat_join_pref_github: "Encuentra el fichero local de tu idioma "
diplomat_github_url: "en GitHub"
diplomat_join_suf_github: ", edítalo online, y solicita que sea revisado. Además, marca la casilla de abajo para mantenerte informado en nuevos progresos en Internacionalización."
diplomat_subscribe_desc: "Recibe correos sobre nuevos niveles y desarrollos para traducir."
ambassador_introduction: "Esta es una comunidad en construcción y tú eres parte de las conexiones. Tenemos chat PI:NAME:<NAME>END_PI, correos electrónicos y las redes sociales con una gran cantidad de personas con quienes hablar, ayudar a familiarizarse con el juego y aprender. Si quieres ayudar a la gente a que se involucre, se divierta, y tenga buenas sensaciones sobre CodeCombat y hacia dónde vamos, entonces esta clase es para ti."
ambassador_attribute_1: "Habilidades de comunicación. Ser capaz de identificar los problemas que los jugadores están teniendo y ayudarles a resolverlos. Además, mantener al resto de nosotros informados sobre lo que los jugadores están diciendo, lo que les gusta, lo que no ¡y de lo que quieren más!"
ambassador_join_desc: "cuéntanos más sobre ti, que has hecho y qué estarías interesado en hacer. ¡Y continuaremos a partir de ahí!"
ambassador_subscribe_desc: "Recibe correos sobre actualizaciones de soporte y desarrollo del multijugador."
teacher_subscribe_desc: "Obtener actulizaciones y anuncios para maestros en su correo electrónico."
changes_auto_save: "Los cambios son guardados automáticamente cuando marcas las casillas de verificación."
diligent_scribes: "Nuestros diligentes Escribas:"
powerful_archmages: "Nuestros poderosos Archimagos:"
creative_artisans: "Nuestros creativos Artesanos:"
brave_adventurers: "Nuestros bravos Aventureros:"
translating_diplomats: "Nuestros políglotas Diplomáticos:"
helpful_ambassadors: "Nuestros amables Embajadores:"
ladder:
title: "Arenas multijugador"
arena_title: "__arena__ | Arenas multijugador"
my_matches: "Mis Partidas"
simulate: "Simular"
simulation_explanation: "¡Simulando tus juegos puedes mejorar tu posición más rápido!"
simulation_explanation_leagues: "Principalmente ayudarás a simular juegos para jugadores aliados en tus clanes y cursos."
simulate_games: "¡Simular Juegos!"
games_simulated_by: "Juegos simulados por ti:"
games_simulated_for: "Juegos simulados para ti:"
games_in_queue: "Juegos actualmente en cola:"
games_simulated: "Juegos simulados"
games_played: "Juegos jugados"
ratio: "Proporción"
leaderboard: "Tabla de Posiciones"
battle_as: "Combate como "
summary_your: "Tus "
summary_matches: "Partidas - "
summary_wins: " Ganadas, "
summary_losses: " Perdidas"
rank_no_code: "Sin Código Nuevo para Clasificar"
rank_my_game: "¡Clasifica Mi Juego!"
rank_submitting: "Enviando..."
rank_submitted: "Enviado para Clasificación"
rank_failed: "Fallo al Clasificar"
rank_being_ranked: "Juego Siendo Clasificado"
rank_last_submitted: "Presentado"
help_simulate: "¿Ayudar simulando juego?"
code_being_simulated: "Tu nuevo código está siendo simulado por otros jugadores para clasificación. Esto se refrescará a medida que vengan nuevas partidas."
no_ranked_matches_pre: "Sin partidas clasificadas para el "
no_ranked_matches_post: " equipo! Juega en contra de algunos competidores y luego vuelve aquí para ver tu juego clasificado."
choose_opponent: "Escoge un Oponente"
select_your_language: "Selecciona tu idioma"
tutorial_play: "Juega el Tutorial"
tutorial_recommended: "Recomendado si nunca has jugado antes"
tutorial_skip: "Saltar Tutorial"
tutorial_not_sure: "¿No estás seguro de que sucede?"
tutorial_play_first: "Juega el Tutorial primero."
simple_ai: "IA Simple"
warmup: "Calentamiento"
friends_playing: "Amigos Jugando"
log_in_for_friends: "Ingresa para jugar con tus amigos!"
social_connect_blurb: "Conectate y juega contra tus amigos!"
invite_friends_to_battle: "Invita a tus amigos para que se unan a la Batalla!"
fight: "Pelea!"
watch_victory: "Observa tu Victoria"
defeat_the: "Derrota a"
watch_battle: "Mirar la batalla"
tournament_started: ", iniciado"
tournament_ends: "Final de Torneo"
tournament_ended: "Finalizó el Torneo"
tournament_rules: "Reglas del Torneo"
tournament_blurb: "Escribe código, recolecta oro, arma ejercitos, aplasta adversarios, gana premios, y asciende en tu carrera por $40,000 en el Torneo Codicia! Echa un vistazo a los detalles"
tournament_blurb_criss_cross: "Gana apuestas, construye caminos, burla tus oponentes, agarra gemas, y asciende tu perfil en nuestro torneo Cruzado! Echa un vistazo a los detalles"
tournament_blurb_zero_sum: "Suelta tus habilidades de código en recolección de oro y tácticas de batalla en este partido espejo alpino entre el hechicero rojo y el hechicero azul. El torneo comenzó el Viernes, 27 de Marzo y se extenderá hasta el Lunes, 6 de Abril a las 5PM PDT. Compite por la diversión y la gloria ! Echa un vistazo a los detalles:"
tournament_blurb_ace_of_coders: "¡Lucha en el glaciar congelado en este encuentro con estilo dominación en espejo! El torneo comienza el Miércoles 16 de Septiembre, y se ejecutará hasta el Miércoles 14 de Octubre hasta las 5PM PDT. Revisa los detalles"
tournament_blurb_blog: "en nuestro blog"
rules: "Reglas"
winners: "PI:NAME:<NAME>END_PI"
league: "Liga"
red_ai: "IA Roja" # "Red AI Wins", at end of multiplayer match playback
blue_ai: "PI:NAME:<NAME>END_PI"
wins: "Gana" # At end of multiplayer match playback
humans: "PI:NAME:<NAME>END_PI" # Ladder page display team name
ogres: "Azul"
live_tournament: "Torneo en vivo"
awaiting_tournament_title: "Torneo inactivo"
awaiting_tournament_blurb: "La arena de torneos no se encuentra activa en este momento."
tournament_end_desc: "El torneo ha terminado. ¡Gracias por jugar!"
age: "Edad"
bracket_0_11: "0-11"
bracket_11_14: "11-14"
bracket_14_18: "14-18"
# bracket_11_18: "11-18"
bracket_open: "Abierto"
user:
user_title: "__name__ - Aprende a programar con CodeCombat"
stats: "Estados"
singleplayer_title: "Nivel un jugador"
multiplayer_title: "Niveles multijugador"
achievements_title: "Logros"
last_played: "Último jugado"
status: "Estado"
status_completed: "Completo"
status_unfinished: "Incompleto"
no_singleplayer: "No hay juegos para un jugador todavía."
no_multiplayer: "No hay juegos multijugador todavía."
no_achievements: "Sin Logros todavía."
favorite_prefix: "Idioma favorito "
favorite_postfix: "."
not_member_of_clans: "No eres miembro de ningún clan todavía."
certificate_view: "ver certificado"
certificate_click_to_view: "haz clic para ver certificado"
certificate_course_incomplete: "curso incompleto"
certificate_of_completion: "Certificado de Aprobación"
certificate_endorsed_by: "Avalado por"
certificate_stats: "Estadísticas de Curso"
certificate_lines_of: "líneas de"
certificate_levels_completed: "niveles completados"
certificate_for: "Por"
certificate_number: "No."
achievements:
last_earned: "Último Ganado"
amount_achieved: "Cantidad"
achievement: "Logros"
current_xp_prefix: ""
current_xp_postfix: " en total"
new_xp_prefix: ""
new_xp_postfix: " ganado"
left_xp_prefix: ""
left_xp_infix: " hasta el nivel "
left_xp_postfix: ""
account:
title: "Cuenta"
settings_title: "Configuración de cuenta"
unsubscribe_title: "Cancelar suscripción"
payments_title: "Pagos"
subscription_title: "Suscripción"
invoices_title: "Facturas"
prepaids_title: "Prepagados"
payments: "Pagos"
prepaid_codes: "Códigos Prepagados"
purchased: "Comprado"
subscribe_for_gems: "Suscríbete para obtener gemas"
subscription: "Suscripción"
invoices: "Facturas"
service_apple: "Apple"
service_web: "Web"
paid_on: "Pagado en"
service: "Servicio"
price: "Precio"
gems: "Gemas"
active: "Activo"
subscribed: "Suscrito"
unsubscribed: "Desuscrito"
active_until: "Activo Hasta"
cost: "Costo"
next_payment: "Próximo Pago"
card: "Tarjeta"
status_unsubscribed_active: "No estas suscrito y no se te cobrará, pero tu cuenta está activa por ahora."
status_unsubscribed: "¡Obtén acceso a nuevos niveles, héroes, items y gemas extras con la suscripción a CodeCombat!"
not_yet_verified: "No verificado todavía."
resend_email: "Reenviar email"
email_sent: "¡Email enviado! Revisa tu casilla."
verifying_email: "Verificando tu email..."
successfully_verified: "¡Has verificado tu email con exito!"
verify_error: "Algo salio mal al verificar tu email :("
unsubscribe_from_marketing: "¿Cancelar suscripción de __email__ de todos los correos de marketing de CodeCombat?"
unsubscribe_button: "Si, cancelar suscripción"
unsubscribe_failed: "Error"
unsubscribe_success: "¡Éxito!"
account_invoices:
amount: "Cantidad en dólares."
declined: "La tarjeta fue rechazada."
invalid_amount: "Por favor ingrese cantidad en dólares."
not_logged_in: "Ingresate o crea una cuenta para acceder a las facturas."
pay: "Pagar Factura"
purchasing: "Comprando..."
retrying: "Error de Servidor, reintentando..."
success: "Listo, fue cobrado. Gracias!"
account_prepaid:
purchase_code: "Adquirir un Código de Suscripción"
purchase_code1: "Los códigos de suscripción pueden ser canjeados para agregar tiempo de suscripción premium para una o más cuentas CodeCombat." # {change}
purchase_code2: "Cada cuenta CodeCombat puede canjear una sola vez un Código de Suscripción en particular."
purchase_code3: "Los meses del Código de Suscripción serán agregados al final de la suscripción existente de la cuenta."
purchase_code4: "Los códigos de suscripción son para las cuentas que juegan la versión doméstica de CodeCombat, no se pueden usar en lugar de las licencias de estudiante para la versión de aula."
purchase_code5: "Para obtener más información sobre licencias de estudiantes, comunícate con"
users: "Usuarios"
months: "Meses"
purchase_total: "Total"
purchase_button: "Enviar Adquisición"
your_codes: "Tus Códigos:"
redeem_codes: "Reclamar un Código de Suscripción"
prepaid_code: "Código Prepagado"
lookup_code: "Buscar código prepagado"
apply_account: "Aplicara tu cuenta"
copy_link: "Puedes copiarl el enlace del código y enviarlo a alguien."
quantity: "Cantidad"
redeemed: "Reclamado"
no_codes: "¡Aún sin códigos!"
you_can1: "Puedes"
you_can2: "comprar un código prepagado"
you_can3: "que puede ser aplicado a tu propia cuenta o regalado a otros."
ozaria_chrome:
sound_off: "Sonido apagado"
sound_on: "Sonido encendido"
back_to_map: "Volver al mapa"
level_options: "Opciones de nivel"
restart_level: "Reiniciar nivel"
max_browser: "Maximizar navegador"
loading_error:
could_not_load: "Error cargando del servidor" # {change}
connection_failure: "Fallo de conexión."
connection_failure_desc: "Al parecer no estás conectado a internet! Revisa tu conección de red y actualiza la página."
login_required: "Login Requerido"
login_required_desc: "Necesitas iniciar sesión para acceder a esta página."
unauthorized: "Necesitas acceder. ¿Tienes desabilitadas las cookies?"
forbidden: "No tienes los permisos."
forbidden_desc: "Oh no, no hay nada que podemos mostrarte aquí! Asegurate que has iniciado sesión en la cuenta correcta, o visita uno de los siguientes enlaces para regresar a programar!"
not_found: "No encontrado."
not_found_desc: "Mmm, no hay nada aquí. Visita uno de los siguientes enlaces para regresar a programar!"
not_allowed: "Método no permitido."
timeout: "Expiró el tiempo del servidor." # {change}
conflict: "Conflicto de recurso."
bad_input: "Mala entrada."
server_error: "Error de servidor."
unknown: "Error desconocido." # {change}
error: "ERROR"
general_desc: "Ocurrió un errór, probablemente es tu culpa. Espera un poco y luego refresca la página, o visíta uno de los siguientes enlaces para regresar a programar!"
too_many_login_failures: "Hubo demasiados intentos de acceso fallidos. Vuelve a intentarlo más tarde."
something_went_wrong: "¡Ups! Hubo un error."
resources:
level: "Nivel"
patch: "Parche"
patches: "Parches"
system: "Sistema"
systems: "Sistemas"
component: "Componente"
components: "Componentes"
hero: "Heróe"
campaigns: "Campañas"
concepts:
advanced_css_rules: "Reglas CSS Avanzadas"
advanced_css_selectors: "Selectores CSS Avanzados"
advanced_html_attributes: "Atributos HTML Avanzados"
advanced_html_tags: "Etiquetas HTML Avanzados"
algorithm_average: "Algoritmo Promedio"
algorithm_find_minmax: "Algoritmo Buscar Min/Max"
algorithm_search_binary: "Algoritmo Búsqueda Binaria"
algorithm_search_graph: "Algoritmo Búsqueda Grafica"
algorithm_sort: "Algoritmo Ordenar"
algorithm_sum: "Algoritmo Suma"
arguments: "Argumentos"
arithmetic: "Aritmética"
array_2d: "Matrices Bidimencionales"
array_index: "Indexando Matrices"
array_iterating: "Iterando Sobre Matrices"
array_literals: "Matrices Literales"
array_searching: "Buscando en Matrices"
array_sorting: "Array Sorting"
arrays: "Arreglos"
basic_css_rules: "Reglas CSS Básicas"
basic_css_selectors: "Selectores CSS Básicos"
basic_html_attributes: "Atributos HTML Básicos"
basic_html_tags: "Etiquetas HTML Básicas"
basic_syntax: "Sintaxis Básica"
binary: "Binario"
boolean_and: "Booleanos Y"
boolean_inequality: "Desigualdad Booleana"
boolean_equality: "Booleano Equidad"
boolean_greater_less: "Booleano Mayor/Menor que"
boolean_logic_shortcircuit: "Booleano Cortocircuito Lógico"
boolean_not: "Booleano Negación"
boolean_operator_precedence: "Booleano Precedencia de Operadores"
boolean_or: "Booleano O"
boolean_with_xycoordinates: "Comparación de Coordenadas"
bootstrap: "Bootstrap"
break_statements: "Declaraciones Break"
classes: "Clases"
conditionals: "Condicionales"
continue_statements: "Declaraciones Continue"
debugging: "Depuración"
dom_events: "Eventos de DOM"
dynamic_styling: "Estilos Dinámicos"
events: "Eventos"
event_concurrency: "Concurrencia de Eventos"
event_data: "Datos de Evento"
event_handlers: "Manejadores de Evento"
event_spawn: "Generador de Eventos"
for_loops: "Bucle For"
for_loops_nested: "Bucles For Anidados"
for_loops_range: "Bucle For en Rangos"
functions: "Funciones"
functions_parameters: "Parámetros"
functions_multiple_parameters: "Múltiples Parámetros"
game_ai: "IA de Juego"
game_design: "Diseño de juegos"
game_goals: "Objetivos del Juego"
game_spawn: "Generador del Juego"
graphics: "Gráficos"
graphs: "Gráfico"
heaps: "Montículos"
if_condition: "Declaraciones Condicionales If"
if_else_if: "Declaraciones If/Else If"
if_else_statements: "Declaraciones If/Else"
if_statements: "Declaraciones If"
if_statements_nested: "Declaraciones If Anidadas" # {change}
indexing: "Indexado de Arreglos"
input_handling_flags: "Manejo de Entradas - Flags"
input_handling_keyboard: "Manejo de Entradas - Keyboard"
input_handling_mouse: "Manejo de Entradas - Mouse"
intermediate_css_rules: "Reglas CSS Intermedias"
intermediate_css_selectors: "Selectores CSS Intermedios"
intermediate_html_attributes: "Atributos HTML Intermedios"
intermediate_html_tags: "Etiquetas HTML Intermedias"
jquery: "jQuery"
jquery_animations: "Animaciones jQuery"
jquery_filtering: "Filtrado de Elementos jQuery"
jquery_selectors: "Selectores jQuery"
length: "Longitud de Matrices"
math_coordinates: "Coordenadas Matemáticas"
math_geometry: "Geometría"
math_operations: "Operaciones Matemáticas"
math_proportions: "Proporciones Matemáticas"
math_trigonometry: "Trigonometría"
object_literals: "Objetos Literales"
parameters: "Parámetros"
problem_solving: "Solución de problemas"
programs: "Programas"
properties: "Propiedades"
property_access: "Acceso a Propiedades"
property_assignment: "Asignación de Propiedades"
property_coordinate: "Coordinación de Propiedades"
queues: "Estructuras de Datos - Colas"
reading_docs: "Leyendo Documentos"
recursion: "Recursividad"
return_statements: "declaraciones de Return"
sequences_algorithms: "Secuencias y algoritmos"
stacks: "Estructuras de Datos - Pilas"
strings: "Cadenas"
strings_concatenation: "Concatenación de Cadenas"
strings_substrings: "Subcadenas"
student_code: "Código de estudiante"
syntax: "Sintaxis"
trees: "Estructuras de Datos - Arboles"
variables: "Variables"
vectors: "Vectores"
while_condition_loops: "Bucles While con Condicionales"
while_loops_simple: "Bucles While"
while_loops_nested: "Bucles While Anidados"
xy_coordinates: "Coordenadas Cartesianas"
advanced_strings: "Cadenas - Avanzado" # Rest of concepts are deprecated
algorithms: "Algoritmos"
boolean_logic: "Lógica Booleana"
basic_html: "HTML Básico"
basic_css: "CSS Básico"
basic_web_scripting: "Web Scripting Básico"
intermediate_html: "HTML Intermedio"
intermediate_css: "CSS Intermedio"
intermediate_web_scripting: "Web Scripting Intermedio"
advanced_html: "HTML Avanzado"
advanced_css: "CSS Avanzado"
advanced_web_scripting: "Web Scripting Avanzado"
input_handling: "Manejo de Entradas"
while_loops: "Bucles"
place_game_objects: "Poner objetos en el juego"
construct_mazes: "Construir laberintos"
create_playable_game: "Crear un proyecto de juego jugable y compartible"
alter_existing_web_pages: "Editar página web existente"
create_sharable_web_page: "Crear página web compartible"
basic_input_handling: "Manejo de Entradas Básico"
basic_game_ai: "IA de Juego Básico"
basic_javascript: "JavaScript Básico"
basic_event_handling: "Manejo de Eventos Básico"
create_sharable_interactive_web_page: "Crear página web interactiva compartible"
iteration: "Iteración"
nesting: "Anidamiento"
data_types: "Tipos de datos"
objects: "Objetos"
methods: "Métodos"
compound_conditionals: "Condicionales compuestos"
comparators: "Comparadores"
data_and_analysis: "Datos y análisis"
anonymous_teacher:
notify_teacher: "Notificar al Maestro"
create_teacher_account: "Crear una cuenta de maestro gratuita"
enter_student_name: "Tu nombre:"
enter_teacher_email: "Correo electrónico de tu maestro:"
teacher_email_placeholder: "PI:EMAIL:<EMAIL>END_PI"
student_name_placeholder: "escribe tu nombre aquí"
teachers_section: "Maestros:"
students_section: "Estudiantes:"
teacher_notified: "¡Hemos notificado a tu maestro que quieres jugar más CodeCombat en tu clase!"
delta:
added: "Agregado"
modified: "Modificado"
not_modified: "No Modificado"
deleted: "Borrado"
moved_index: "Índice movido"
text_diff: "Diferir Texto"
merge_conflict_with: "UNIR CONFLICTO CON"
no_changes: "Sin cambios"
legal:
page_title: "Información legal"
opensource_introduction: "CodeCombat es parte de la comunidad open source."
opensource_description_prefix: "Echa un vistazo a "
github_url: "nuestro GitHub"
opensource_description_center: "y ayudanos si quieres! CodeCombat esta construido por docenas de proyectos open source, y los amamos. Mira "
archmage_wiki_url: "nuestra wiki de Archimago"
opensource_description_suffix: "Para la lista de softwares que hacen al juego posible."
practices_title: "Mejores prácticas respetuosas"
practices_description: "Estas son nuestras promesas hacia ti, el jugador, en términos menos legales."
privacy_title: "Privacidad"
privacy_description: "No vederemos nada sobre tu información personalWe will not sell any of your personal information."
security_title: "Seguridad"
security_description: "Queremos mantener tu información personal privada. Como un proyecto open source, cualquiera puede revisar y mejorar nuestros sistemas de seguridad."
email_title: "Mail"
email_description_prefix: "No te vamos a inundar de Spam. Mediante"
email_settings_url: "tus opciones de mail"
email_description_suffix: "o mediante links en los mails que mandamos, tu puedas cambiar tus preferencias y fácilmente desuscribirte en cualquier momento."
cost_title: "Costo"
cost_description: "CodeCombat es gratuito para todos sus niveles principales, con una suscripción de ${{price}} USD/mes con acceso a niveles adicionales y un bonus de {{gems}} gemas cada mes. Puedes cancelar con un click y ofrecemos una garantía del 100%."
copyrights_title: "Derechos y Licencias"
contributor_title: "Contributor License Agreement"
contributor_description_prefix: "Todas las Contribuciones, tanto en el website como en nuestro Repositorio GitHub, estan sujetos a nuestra aprobación."
cla_url: "CLA"
contributor_description_suffix: "A lo que debes de estar de acuerdo antes de contribuir."
code_title: "Código - MIT" # {change}
client_code_description_prefix: "Todo el código del lado del cliente para codecombat.com en el repositorio público de GitHub y en la base de datos de codecombat.com, está bajo la "
mit_license_url: "Licencia MIT"
code_description_suffix: "Esto incluye todo el código en Systems and Components that are made available by CodeCombat for the purpose of creating levels."
art_title: "Arte/Música - Comunas Creativas "
art_description_prefix: "Todo el Contenido Comunal está disponible bajo la"
cc_license_url: "Licencia Internacional de Atribución Comunas Creativas (CC) 4.0"
art_description_suffix: "Contenido Comunal es cualquiera hecho por CodeCombat y disponile con el propósito de crear niveles. Esto incluye:"
art_music: "Música"
art_sound: "Sonido"
art_artwork: "Trabajo Artístico"
art_sprites: "Sprites"
art_other: "Cualquier otro trabajo creativo (no necesariamente código) que están disponibles cuando se crean niveles."
art_access: "Actualmente no hay un sistema fácil y universal para obtener estos activos. En general, obtenlos de los URLs tal y como son usados por el sitio, contáctanos si necesitas ayuda, o ayúdanos extendiendo el sitio para hacer estos activos accesibles más fácilmente."
art_paragraph_1: "Para atribución, por favor nombre y enlace a codecombat.com cerca de donde esta fuente sea usada o donde sea apropiado en el medio usado. Por ejemplo:"
use_list_1: "Si es usado en una película o en otro juego, incluya codecombat.com en los créditos."
use_list_2: "Si es usado en un website, incluya un link cerca donde es usado, por ejemplo debajo de una imagen, o en las atribuciones generales de la página, donde pueda mencionar también otros trabajos bajo Creative Commons o de código abierto que sean usados en el sitio web. Cualquier otro website que haga clara referencia a CodeCombat, tal como un blog post mencionando a CodeCombat, no necesita una atribución separada."
art_paragraph_2: "Si el contenido usado no fue creado por CodeCombat, sino por un usuario de codecombat.com, atribuya al usuario y siga las directivas de atribución provistas en la descripción del recurso, en caso las haya."
rights_title: "Derechos Reservados"
rights_desc: "Todos los derechos estan reservados para los niveles mismos. Esto incluye."
rights_scripts: "Scripts"
rights_unit: "Configuración de la unidad"
rights_writings: "Escritos"
rights_media: "Media (sonidos, música) y cualquier otro contenido creativo hecho específicamente para un nivel y que no haya sido hecho disponible al público cuando se crearon los niveles."
rights_clarification: "Aclarando, todo contenido puesto a disposición en el Editor de Niveles con el propósito de hacer más niveles se encuentra bajo licencia CC, mientras todo contenido creado con el Editor de Niveles o cargado durante la creación de Niveles no lo está."
nutshell_title: "En una palabra"
nutshell_description: "Cualquier recurso que te proveamos en el Editor de Niveles es gratis de usar como te plazca para la creación de Niveles. Sin embargo, nos reservamos el derecho de restringir la distribución de los niveles por sí mismos (aquellos creados en codecombat.com) para así poder cobrar por ellos en el futuro, si es que eso es lo que termina pasando."
nutshell_see_also: "Mira También:"
canonical: "La versión en inglés de este documento es la versión canónica y definitiva. Si hay alguna discrepancia entre las traducciones, la versión en inglés toma precedencia."
third_party_title: "Servicios de Terceros"
third_party_description: "CodeCombat utiliza los siguientes servicios de terceros (entre otros):"
cookies_message: "CodeCombat utiliza algunas cookies esenciales y no esenciales."
cookies_deny: "Rechazar las cookies no esenciales"
cookies_allow: "Permitir cookies"
ladder_prizes:
title: "Premios de Torneos" # This section was for an old tournament and doesn't need new translations now.
blurb_1: "Estos premios seran dados de acuerdo a "
blurb_2: "las reglas del torneo"
blurb_3: "a los mejores jugadores humanos y ogros."
blurb_4: "Dos equipos significan el doble de premios!"
blurb_5: "(Habrán dos ganadores en el primer puesto, dos en el segundo puesto, etc.)"
rank: "Ranking"
prizes: "Premios"
total_value: "Valor Total"
in_cash: "en dinero"
custom_wizard: "CodeCombat Mago Personalizado"
custom_avatar: " CodeCombat Avatar Personalizado"
heap: "Por seis meses acceso \"Startup\"."
credits: "creditos"
one_month_coupon: "Cupón: elige entre Rails o HTML."
one_month_discount: "descuento del 30%: elige entre Rails o HTML"
license: "licencia"
oreilly: "ebook de su elección"
calendar:
year: "Año"
day: "Día"
month: "Mes"
january: "Enero"
february: "Febrero"
march: "Marzo"
april: "Abril"
may: "Mayo"
june: "Junio"
july: "Julio"
august: "Agosto"
september: "Septiembre"
october: "Octubre"
november: "Noviembre"
december: "Diciembre"
code_play_create_account_modal:
title: "¡LO LOGRASTE!" # This section is only needed in US, UK, Mexico, India, and Germany
body: "Pronto serás un programador experto. Regístrate para recibir <strong>100 GEMAS</strong> adicionales y participar en un sorteo donde podrás <strong>GANAR $50,000 Y OTROS PREMIOS DE LENOVO</strong>."
sign_up: "REGÍSTRATE Y SIGUE PROGRAMANDO ▶"
victory_sign_up_poke: "¡ABRE UNA CUENTA GRATUITA PARA GUARDAR TU CÓDIGO Y PARTICIPAR EN UN SORTEO DONDE PODRÁS GANAR PREAMIOS!"
victory_sign_up: "REGÍSTRATE PARA PODER <strong>GANAR $50,000</strong>"
server_error:
email_taken: "Email ya utilizado"
username_taken: "El nombre de usuario ya existe"
esper:
line_no: "Linea $1: "
uncaught: "$1 no detectado" # $1 will be an error type, eg "Uncaught SyntaxError"
reference_error: "Referencia Errónea: "
argument_error: "Argumento Erróneo: "
type_error: "Tipo Erróneo: "
syntax_error: "Sintaxis Errónea: "
error: "Error: "
x_not_a_function: "$1 no es una función"
x_not_defined: "$1 no está definido"
spelling_issues: "Corrige la ortografía: ¿quisiste decir `$1` en lugar de `$2`?"
capitalization_issues: "Cuidado con las mayúsculas: `$1` debe ser `$2`."
py_empty_block: "$1 vacío. Adelanta 4 espacios las declaraciones dentro del bloque $2."
fx_missing_paren: "Si deseas llamar `$1` como función, pon paréntesis `()` al final"
unmatched_token: "`$1` no coincide. Cada apertura de `$2` necesita un cierre de `$3` para coincidir."
unterminated_string: "Cadena sin terminar. Agrega `\"` al final de la cadena."
missing_semicolon: "Falta punto y coma."
missing_quotes: "Faltan comillas. Intenta `$1`"
argument_type: "El argumento `$2` de `$1` debe tener un tipo `$3`, pero tiene `$4`: `$5`."
argument_type2: "El argumento `$2` de `$1` debe tener un tipo `$3`, pero tiene `$4`."
target_a_unit: "Apuntar a una unidad."
attack_capitalization: "Ataca a $1, no a $2. (Mayúsculas son importantes.)"
empty_while: "Sentencia while vacía. Adelanta 4 espacios las declaraciones dentro del bloque while."
line_of_site: "El argumento `$2` de `$1` tiene un problema. ¿Hay algún enemigo en la línea de visión?"
need_a_after_while: "Necesitas un `$1` después de `$2`."
too_much_indentation: "Demasiada indentación al inicio de esta línea."
missing_hero: "Falta la palabra clave `$1`; debe ser `$2`."
takes_no_arguments: "`$1` no acepta argumentos."
no_one_named: "No se puede apuntar a \"$1\" porque nadie se llama así."
separated_by_comma: "Al llamar una función los parámetros deben estar separados con `,`"
protected_property: "No se puede leer propiedad protegida: $1"
need_parens_to_call: "Si deseas llamar `$1` como función, pon paréntesis `()` al final"
expected_an_identifier: "Se esperaba un identificador y en su lugar se recibió '$1'."
unexpected_identifier: "Identificador inesperado"
unexpected_end_of: "Fin de entrada inesperado"
unnecessary_semicolon: "Punto y coma innecesario."
unexpected_token_expected: "Símbolo inesperado: se esperaba $1 pero se encontró $2 mientras se analizaba $3"
unexpected_token: "Símbolo $1 inesperado"
unexpected_token2: "Símbolo inesperado"
unexpected_number: "Número inesperado"
unexpected: "No se esperaba '$1'."
escape_pressed_code: "Escape presionado; código anulado."
target_an_enemy: "Apunta a un enemigo por su nombre, como `$1`, no la cadena `$2`."
target_an_enemy_2: "Apunta a un enemigo por su nombre, como $1."
cannot_read_property: "No se puede leer la propiedad '$1' de indefinido"
attempted_to_assign: "Se intentó asignar una propiedad de solo lectura."
unexpected_early_end: "Fin del programa antes de lo esperado."
you_need_a_string: "Necesitas una cadena para construir; una de $1"
unable_to_get_property: "No se puede obtener la propiedad '$1' de una referencia nula o indefinida" # TODO: Do we translate undefined/null?
code_never_finished_its: "El código no finalizo. Es demasiado lento o tiene un bucle infinito."
unclosed_string: "Cadena sin cerrar."
unmatched: "No coincide '$1'."
error_you_said_achoo: "Dijiste: $1, pero la contraseña es: $2. (Mayúsculas y minúsculas son importantes.)"
indentation_error_unindent_does: "Error de Indentación: no coincide con ningun nivel de indentación"
indentation_error: "Error de Indentación."
need_a_on_the: "Necesitas un `:` al final de la linea seguido de `$1`."
attempt_to_call_undefined: "se intento llamar '$1' (un valor nulo)"
unterminated: "`$1` sin terminar"
target_an_enemy_variable: "Apunta a la variable $1, y no al string $2. (Intenta usar $3.)"
error_use_the_variable: "Usa el nombre de la variable como `$1` en lugar de la cadena como `$2`"
indentation_unindent_does_not: "Desindentación no coincide con ningún nivel de indentación"
unclosed_paren_in_function_arguments: "No se cerró $1 en los argumentos de la función."
unexpected_end_of_input: "Fin de entrada inesperado"
there_is_no_enemy: "No hay `$1`. Primero utiliza `$2`." # Hints start here
try_herofindnearestenemy: "Intenta `$1`"
there_is_no_function: "No hay ninguna función `$1`, pero `$2` tiene el método `$3`."
attacks_argument_enemy_has: "El argumento `$2` de `$1` tiene un problema."
is_there_an_enemy: "¿Aún hay algún enemigo en tu linea de visión?"
target_is_null_is: "El objetivo es $1. ¿Siempre hay un blanco para atacar? (Usa $2?)"
hero_has_no_method: "`$1` no tiene el método `$2`."
there_is_a_problem: "Hay un problema con tu código."
did_you_mean: "¿Quisiste decir $1? No tienes equipado un item con esa habilidad."
missing_a_quotation_mark: "Falta una commilla. "
missing_var_use_var: "Falta `$1`. Utiliza `$2` para hacer una nueva variable."
you_do_not_have: "No tienes equipado un item con la habilidad $1."
put_each_command_on: "Pon cada comando en lineas separadas"
are_you_missing_a: "¿Te falta un '$1' despues de '$2'? "
your_parentheses_must_match: "Los paréntesis deben coincidir."
apcsp:
title: "Fundamentos de Ciencias de la Computación AP | Con el respaldo del College Board"
meta_description: "El amplio plan de estudios y el programa de desarrollo profesional de CodeCombat es todo lo que necesitas para ofrecer el curso de ciencias de la computación más reciente de College Board a tus estudiantes."
syllabus: "Programa de Fundamentos de Ciencias de la Computación AP"
syllabus_description: "Usa este recurso para planificar el plan de estudios de CodeCombat para tus clases de Fundamentos de Ciencias de la Computación AP."
computational_thinking_practices: "Prácticas del Pensamiento Computacional"
learning_objectives: "Objetivos de aprendizaje"
curricular_requirements: "Requisitos curriculares"
unit_1: "Unidad 1: Tecnología creativa"
unit_1_activity_1: "Actividad de la unidad 1: Prueba de usabilidad de la tecnología"
unit_2: "Unidad 2: Pensamiento computacional"
unit_2_activity_1: "Actividad de la unidad 2: Secuencias binarias"
unit_2_activity_2: "Actividad de la unidad 2: Proyecto de lección sobre informática"
unit_3: "Unidad 3: Algoritmos"
unit_3_activity_1: "Actividad de la unidad 3: Algoritmos - Guía del viajero"
unit_3_activity_2: "Actividad de la unidad 3: Simulación - Depredador y presa"
unit_3_activity_3: "Actividad de la unidad 3: Algoritmos - Diseño y programación en pareja"
unit_4: "Unidad 4: Programación"
unit_4_activity_1: "Actividad de la unidad 4: Abstracciones"
unit_4_activity_2: "Actividad de la unidad 4: Búsqueda y ordenamiento"
unit_4_activity_3: "Actividad de la unidad 4: Refactorización"
unit_5: "Unidad 5: La Internet"
unit_5_activity_1: "Actividad de la unidad 5: Cómo funciona la Internet"
unit_5_activity_2: "Actividad de la unidad 5: Simulador de la Internet"
unit_5_activity_3: "Actividad de la unidad 5: Simulación de una sala de chat"
unit_5_activity_4: "Actividad de la unidad 5: Ciberseguridad"
unit_6: "Unidad 6: Datos"
unit_6_activity_1: "Actividad de la unidad 6: Introducción a los datos"
unit_6_activity_2: "Actividad de la unidad 6: Big data"
unit_6_activity_3: "Actividad de la unidad 6: Compresión con y sin pérdida"
unit_7: "Unidad 7: Impacto personal y global"
unit_7_activity_1: "Actividad de la unidad 7: Impacto personal y global"
unit_7_activity_2: "Actividad de la unidad 7: Crowdsourcing"
unit_8: "Unidad 8: Tareas de desempeño"
unit_8_description: "Ayuda a los estudiantes a prepararse para la tarea de creación mediante el diseño de sus propios videojuegos y el repaso de conceptos clave."
unit_8_activity_1: "Práctica 1 para la tarea de creación: Desarrollo de Juegos 1"
unit_8_activity_2: "Práctica 2 para la tarea de creación: Desarrollo de Juegos 2"
unit_8_activity_3: "Práctica 3 para la tarea de creación: Desarrollo de Juegos 3"
unit_9: "Unidad 9: Reseña de Advanced Placement (AP)"
unit_10: "Unidad 10: Después de AP"
unit_10_activity_1: "Actividad de la unidad 10: Cuestionario web"
parent_landing:
slogan_quote: "\"CodeCombat es muy vertido y te enseña muchas cosas.\""
quote_attr: "Estudiante de quinto grado, Oakland, California"
refer_teacher: "Invitar a un maestro"
focus_quote: "Desbloquea el futuro de tu hijo"
value_head1: "La forma más divertida de aprender código escrito"
value_copy1: "CodeCombat es el tutor personal del estudiante. El material de estudio, que cumple con las pautas curriculares nacionales, ayudará a tu hijo a programar algoritmos, crear sitios web e incluso diseñar sus propios videojuegos."
value_head2: "Desarrollo de habilidades esenciales para el siglo 21"
value_copy2: "Tus hijos aprenderán a navegar por el mundo digital y se convertirán en sus verdaderos ciudadanos. CodeCombat es una solución que mejora el pensamiento crítico y la capacidad de adaptación de su hijo."
value_head3: "Héroes que le encantarán a tu hijo"
value_copy3: "Sabemos lo importante que son la diversión y el interés para un cerebro en desarrollo, así que incluimos todo el aprendizaje posible en un juego que los niños amarán."
dive_head1: "No solo ingenieros de software"
dive_intro: "Las habilidades de informática tienen una amplia gama de aplicaciones. ¡Estos son solo algunos ejemplos!"
medical_flag: "Aplicaciones médicas"
medical_flag_copy: "Desde la cartografía del genoma humano hasta una máquina para hacer resonancias magnéticas, la programación nos permite entender el cuerpo de maneras nunca antes conocidas."
explore_flag: "Exploración espacial"
explore_flag_copy: "Apollo llegó a la luna gracias a computadoras humanas que trabajaron arduamente, y los científicos usan programas de computación para analizar la gravedad de los planetas y encontrar estrellas nuevas."
filmaking_flag: "Cine y animación"
filmaking_flag_copy: "Desde los robots de Parque Jurásico hasta las animaciones increíbles de Dreamworks y Pixar, las películas no serían lo que son sin los creativos digitales detrás de escena."
dive_head2: "Los videojuegos son importante para el aprendizaje"
dive_par1: "Muchos estudios descubrieron que el aprendizaje basado en juego promueve"
dive_link1: "el desarrollo cognitivo"
dive_par2: "en niños, a la vez que es"
dive_link2: "más efectivo"
dive_par3: "a la hora de ayudar a los estudiantes"
dive_link3: "a aprender y retener conocimiento"
dive_par4: ","
dive_link4: "concentrarse"
dive_par5: "y alcanzar un mayor nivel de consecución de logros."
dive_par6: "El aprendizaje basado en juego también es bueno para desarrollar"
dive_link5: "capacidad de adaptación"
dive_par7: ", razonamiento cognitivo y"
dive_par8: ". La ciencia solo nos dice lo que ya saben los estudiantes. Los niños aprenden mejor jugando."
dive_link6: "funciones ejecutivas"
dive_head3: "Trabaja en equipo con maestros"
dive_3_par1: "En el futuro, "
dive_3_link1: "programar será tan fundamental como aprender a leer y escribir"
dive_3_par2: ". Trabajamos en conjunto con docentes para diseñar y desarrollar nuestro contenido, y estamos ansiosos por que tus hijos empiecen a aprender. Los programas de tecnología educativa como CodeCombat funcionan mejor cuando los docentes los implementan con regularidad. ¡Ayúdanos a lograrlo presentándonos a los maestros de tu hijo!"
mission: "Nuestra misión: enseñar y entretener"
mission1_heading: "Código para la generación de hoy"
mission2_heading: "Prepararse para el futuro"
mission3_heading: "Con el apoyo de padres como tú"
mission1_copy: "Nuestros especialistas en educación trabajan en colaboración con docentes para adaptar el contenido al panorama educativo de los estudiantes. Los niños adquieren habilidades que pueden aplicarse fuera del juego porque aprenden a resolver problemas más allá de su estilo de aprendizaje."
mission2_copy: "Una encuesta de 2016 demostró que el 64% de las niñas de tercer a quinto grado quieren aprender a programar. En 2015, hubo siete millones de búsquedas laborales que requerían habilidades de programación. Creamos CodeCombat porque todos los niños deberían tener la oportunidad de crear su mejor futuro."
mission3_copy: "En CodeCombat somos padres. Somos programadores. Somos educadores. Pero, sobre todo, somos personas que creemos en darles a nuestros hijos la mejor oportunidad para triunfar en lo que sea que decidan hacer en el futuro."
parent_modal:
refer_teacher: "Invitar a un maestro"
name: "PI:NAME:<NAME>END_PI"
parent_email: "Tu correo electrónico"
teacher_email: "Correo electrónico del maestro"
message: "Mensaje"
custom_message: "Acabo de enterarme de CodeCombat y creo que sería un gran programa para tu asignatura. Es una plataforma para aprender ciencias de la computación que tiene un plan de estudios que cumple con las normas educativas.\n\nLa alfabetización digital es muy importante, y creo que esta sería una gran forma de hacer que los estudiantes se interesen en aprender a programar."
send: "Enviar correo"
hoc_2019:
heading: "Hora del Código 2019"
start: "Empieza tu camino"
create_a_class: "¡Crea una clase para monitorear el progreso de los estudiantes y garantizar el guardado de sus juegos de la Hora del Código!"
choose_language: "1. ELEGIR IDIOMA"
programming_language: "Idioma"
sign_up: "2. REGISTRARSE"
already_have_account: "¿Ya tienes una cuenta de CodeCombat o de Ozaria? Inicia sesión."
download_lesson_plan: "Descarga el plan de estudios"
try_activity_without_class: "Prueba la actividad sin crear una clase"
invite_students: "Invita a los estudiantes a unirse a tu clase enviándoles"
class_code: "CÓDIGO DE CLASE"
enter_code: "Los estudiantes pueden ingresar este código en www.ozaria.com/hoc"
class_url: "URL DE CLASE"
share_url: "Comparte la URL para que los estudiantes se unan a tu clase automáticamente."
start_activity: "Empezar actividad"
save_progress_modal: "Guarda tu progreso y continúa jugando más tarde"
want_to_save: "¿Quieres guardar tu progreso del Código de Honor?"
ask_teacher_class_code: "Pídele a tu maestro tu código de clase"
dont_have: "¡No tengo, pero quiero probar la actividad!"
hoc_activity: "Actividad de la Hora del Código"
save_progress: "Guardar progreso"
err_google_exists: "Ya existe una cuenta asociada a la cuenta de Google que seleccionaste. Elige otra cuenta de Google o inicia sesión con un nombre de usuario y una contraseña."
err_username_taken: "Ya existe una cuenta asociada al nombre de usuario que ingresaste. Elige otro nombre de usuario."
enter_it_here: "Ingrésalo aquí para guardar tu progreso del juego:"
have_a_class_code: "¿Tienes un código de clase?"
create_class_and_try_activity: "Crea una clase y prueba la actividad"
hoc_2018:
banner: "¡Feliz semana de la educación en ciencias de la computación!"
page_heading: "¡Tus estudiantes aprenderán a programar diseñando su propio juego!"
step_1: "Paso 1: Ve el video informativo"
step_2: "Paso 2: Pruébalo"
step_3: "Paso 3: Descarga el plan de estudios"
try_activity: "Prueba la actividad"
download_pdf: "Descarga el PDF"
teacher_signup_heading: "Convierte la Hora del Código en un Año del Código"
teacher_signup_blurb: "Todo lo que necesitas para enseñar ciencias de la computación sin experiencia previa."
teacher_signup_input_blurb: "Consigue el primer curso gratis:"
teacher_signup_input_placeholder: "Dirección de correo electrónico del maestro"
teacher_signup_input_button: "Consigue Ciencias de la Computación 1 gratis"
activities_header: "Más actividades de la Hora del Código"
activity_label_1: "¡Escapa de las mazmorras!"
activity_label_2: " Principiante: ¡diseña un videojuego!"
activity_label_3: "Avanzado: ¡diseña un videojuego de arcade!"
activity_button_1: "Ver lección"
about: "Acerca de CodeCombat"
about_copy: "Un programa de ciencias de la computación basado en juego creado según las normas educativas que enseña a escribir Python y JavaScript de verdad."
point1: "✓ Andamiaje"
point2: "✓ Diferenciado"
point3: "✓ Evaluaciones"
point4: "✓ Cursos basados en proyectos"
point5: "✓ Seguimiento de estudiantes"
point6: "✓ Planes de estudio completos"
title: "HORA DEL CÓDIGO"
acronym: "HDC"
hoc_2018_interstitial:
welcome: "¡Te damos la bienvenida a la Hora del Código de CodeCombat!"
educator: "Soy educador"
show_resources: "¡Muéstrame los recursos para maestros!"
student: "Soy estudiante"
ready_to_code: "¡Quiero empezar a programar!"
hoc_2018_completion:
congratulations: "¡Felicitaciones por completar <b>Programa, juega y comparte</b>!"
send: "¡Envíales a tus amigos y tu familia tu juego de la Hora del Código!"
copy: "Copiar URL"
get_certificate: "¡Obtén un certificado de finalización para celebrar con tu clase!"
get_cert_btn: "Obtener certificado"
first_name: "PI:NAME:<NAME>END_PI"
last_initial: "Inicial del apellido"
teacher_email: "Dirección de correo electrónico del maestro"
school_administrator:
title: "Panel del administrador de la escuela"
my_teachers: "Mis maestros"
last_login: "Último ingreso"
licenses_used: "licencias utilizadas"
total_students: "estudiantes en total"
active_students: "estudiantes activos"
projects_created: "proyectos creados"
other: "Otros"
notice: "Los siguientes administradores de la escuela tienen acceso de solo lectura a los datos de tu aula:"
add_additional_teacher: "¿Necesitas agregar otro maestro? Contacta a tu ejecutivo de cuenta de CodeCombat o envía un correo a PI:EMAIL:<EMAIL>END_PI. "
license_stat_description: "La cantidad de licencias disponibles incluye el número total de licencias disponibles para el maestro, incluidas las licencias compartidas."
students_stat_description: "Cuentas de estudiantes totales para todos los alumnos de todas las aulas, tengan o no una licencia activa."
active_students_stat_description: "Estudiantes activos cuenta la cantidad de alumnos que han ingresado a CodeCombat en los últimos 60 días."
project_stat_description: "Proyectos creados cuenta la cantidad total de proyectos de desarrollo web y de juegos que se han creado."
no_teachers: "No administras a ningún maestro."
interactives:
phenomenal_job: "¡Gran trabajo!"
try_again: "¡Ups, vuelve a intentar!"
select_statement_left: "¡Ups! Selecciona una instrucción de código antes de presionar Enviar."
fill_boxes: "Ups, asegúrate de completar todos los campos antes de presionar \"Enviar\"."
cannot_play_video: "Lamentablemente, no es posible reproducir este video en tu zona."
console_instructions: "Entérate por qué abriendo la consola de tu navegador: 1) haz clic derecho, 2) elige \"Inspeccionar\" y 3) haz clic en la pestaña Consola."
skip_video: "Saltar video"
unavailable: "No disponible"
admin:
license_type_full: "Cursos completos"
license_type_customize: "Personalizar cursos"
teacher_dashboard:
lock: "Bloquear"
unlock: "Desbloquear"
unassign: "Anular asignación"
choose_course: "Haz clic para seleccionar una opción del menú desplegable"
teacher_locked_message: "Tu maestro bloqueó el siguiente nivel"
plan_your_class_title: "Para planificar tu primera clase:"
plan_your_class1: "Consulta la información sobre el progreso del curso"
plan_your_class2: "Previsualiza las diapositivas de la lección y las actividades de extensión"
plan_your_class3: "Prueba el primer capítulo sin cargo"
click_dismiss: "Clic para ignorar"
track_progress: "Seguir progreso"
track_progress_desc: "Haz clic en la clase que acabas de crear para ver el progreso detallado de cada estudiante."
add_classes_title: "Agregar clases aquí"
add_classes: "¡Agrega clases para que los estudiantes empiecen el capítulo gratis!"
all_classes: "Todas las clases"
my_licenses: "Mis licencias"
resource_hub: "Centro de recursos"
pd: "Desarrollo profesional"
pd_short: "DP"
curriculum_guide: "Guía curricular"
add_class: "Agregar clase nueva"
no_licenses_yet: "Aún sin licencias"
req_licenses: "Solicitar licencias"
license_ratio_used: "__totalUsedLicenses__ de __totalSpots__"
licenses_applied: "Licencias aplicadas"
student_projects: "Proyectos de estudiantes"
no_classes_yet: "Aún no hay clases"
exemplar_project: "Proyecto modelo"
capstone_proj_for: "Proyecto final de __courseName__"
project_rubric: "Guía de evaluación del proyecto"
select_chapter: "Seleccionar capítulo"
concept_flag: "Concepto difícil"
support_learning: "Ayuda de aprendizaje"
concept_flag_desc: "Más del 50% de la clase tuvo que repetir una comprobación de conceptos 3 veces o más."
concept_flag_desc2: "El estudiante tuvo que repetir una comprobación de conceptos 3 veces o más."
click_progress_dot_tip: "Consejo: Haz clic en las burbujas de progreso para más detalles."
color_code: "Código de color"
content_guide: "Guía de contenido"
story: "Historia"
cutscenes: "Escenas"
cutscenes_tooltip: "<h3>Escena</h3><p>Un video corto que explica partes de la historia épica de Ozaria.</p>"
cinematics: "Cinemáticas"
concept_checks: "Comprobaciones de conceptos"
practice_levels: "Niveles de práctica"
challenge_levels: "Niveles de desafío"
capstone_levels: "Niveles finales"
intro: "Introducción"
practice: "Practicar"
assess: "Evaluar"
view_options: "Ver opciones"
manage_class: "Administrar clase"
assign_content: "Asignar contenido"
remove_students: "Quitar estudiantes"
revoke_licenses: "Anular licencias"
remaining_licenses: "Licencias restantes: __remaining__"
start_date: "Inicio: __date__"
end_date: "Finalización: __date__"
license_questions: "¿Tienes alguna pregunta sobre aplicar o anular licencias?"
need_more_licenses: "¿Necesitas más licencias? Te ayudaremos a crear una solución que satisfaga tus necesidades."
see_also_our: "También consulta nuestra"
for_more_funding_resources: "para enterarte de cómo aprovechar las fuentes de financiación de la ley CARES, como ESSER y GEER."
support_oz: "PI:EMAIL:<EMAIL>END_PI"
standards_alignment: "Cumplimiento de normas"
standards_sample: "Una muestra de las normas cubiertas en este capítulo:"
play_chapter: "Jugar capítulo"
class_time_range: "Tiempo de clase (rango):"
in_game_play_time: "Tiempo de juego:"
class_time: "Tiempo de clase"
solution_guide: "Guía de solución"
module: "Módulo"
need_licenses_tooltip: "<h3>¡Necesitas licencias para acceder a este contenido!</h3><p>Ve a la página <a href='/teachers/licenses'>Mis licencias</a> para más información.</p>"
lesson_slides_tooltip: "<h3>Diapositivas de la lección</h3><p>Diapositivas que puedes descargar para guiar paso a paso a los estudiantes por los objetivos de aprendizaje del módulo.</p>"
project_rubric_tooltip: "<h3>Guía de evaluación del proyecto</h3><p>Una guía que puedes descargar y modificar para evaluar el proyecto final.</p>"
exemplar_projects_tooltip: "<h3>Proyecto modelo</h3><p>Vista en vivo de un modelo de proyecto final.</p>"
want_to_save_tooltip: "<h3>¿Quieres guardar tu progreso?</h3><p>Crea una cuenta de estudiante y accede a ella para jugar Ozaria como estudiante si quieres guardar tu progreso.</p>"
intro_explain_tooltip: "Las <b>\"introducciones\"</b> presentan nuevos conceptos o hacen avanzar la historia de manera escalonada. En general, incluyen cinemáticas o comprobaciones de conceptos."
chapter_num: "Capítulo __num__"
# read: "View Only"
# write: "Full Access"
# read_blurb: "View Only permits the added teacher to view your class and student progress without the ability to make changes to your class."
# write_blurb: "Full Access grants the added teacher the ability to make modifications to your class (add/remove students, assign chapters, modify licensure)"
# shared_with_none: "This class is not currently shared with any other teachers."
# share_info: "To give other teachers access to the class, add their emails below."
# class_owner: "Class Owner"
# share: "Share"
# outcomes:
# outcomes_report: "Outcomes Report"
# customize_report: "Customize Report"
# done_customizing: "Done Customizing"
# start_date: "Start date"
# end_date: "End date"
# school_admin: "School Administrator"
# school_network: "School Network"
# school_subnetwork: "School Subnetwork"
# classroom: "Classroom"
# view_outcomes_report: "View Outcomes Report"
# key_concepts: "Key Concepts"
# code_languages: "Code Languages"
# using_codecombat: "Using CodeCombat's personalized learning engine..."
# wrote: "wrote..."
# across_an_estimated: "across an estimated..."
# in: "in..."
# include: "Include "
# archived: "Archived"
# max: "Max "
# multiple: "s"
# computer_program: "computer program"
# computer_programs: "computer programs"
# line_of_code: "line of code"
# lines_of_code: "lines of code"
# coding_hours: "coding hours"
# expressed_creativity: "and expressed creativity by building"
# report_content_1: "standalone game and web "
# project: "project"
# projects: "projects"
# progress_stats: "Progress stats based on sampling __sampleSize__ of __populationSize__ students."
# standards_coverage: "Standards Coverage"
# coverage_p1: "The full Ozaria curriculum covers major programming standards in several widely-adopted frameworks, including those of the International Society for Technology in Education (ISTE), the Computer Science Teacher Association (CSTA), and the K-12 Computer Science Framework."
# coverage_p2: "Ozaria is created by the CodeCombat, the game-based learning company. We believe that students will be most prepared for both real-world computing jobs and further study of computer science by using real, typed code in full programming languages, so instead of using block-based visual programming languages for beginners, we teach Python and JavaScript – the same languages used widely today by companies ranging from Google to the New York Times."
# questions: "Have questions or want more information? We'd be happy to help."
# reach_out_manager: "Reach out to your Account Manager __name__ at "
# stats_include: "stats include __number__ other __name__"
|
[
{
"context": "console.log msg_info\n if msg_info.nick is \"bingbot\" and s.match /^http\\:\\/\\/(.+)*(jpg|png)/i\n ",
"end": 669,
"score": 0.9990345239639282,
"start": 662,
"tag": "USERNAME",
"value": "bingbot"
},
{
"context": "'./irc_config'\n\nunless bot.connect\n # b... | imgo.coffee | mrluc/node-dbp-irctweet | 1 | fs = require 'fs'
ResponderBot = require './responderbot'
# get disposables via https://imgur.com/register/api_anon
client_id = "879200d6e95a899c7b1453ed6a31dd37"
imgur = require "imgur"
imgur.setKey client_id
{Facer} = require './cv/facer.coffee'
{OverlayImage} = require './cv/dl_overlay'
class Imgo extends ResponderBot
constructor: (config) ->
config.name = "imgo"
config.connect = yes
super config
@patterns = [
recognize: @re /^hamsnap (.+)*\?*/i
respond: ([first,matched,s...], o, say) ->
say "camsnap #{ matched }"
,
recognize: (s,msg_info) =>
console.log msg_info
if msg_info.nick is "bingbot" and s.match /^http\:\/\/(.+)*(jpg|png)/i
#if s.match /^http\:\/\/\w+.mm.bing.net\//i
console.log "wow it matched"
return s
no
respond: (m, o, say) =>
console.log m
@onImage m, say
]
should_ignore: -> no
rand: (n)-> parseInt Math.random() * n
onImage: (url, say) =>
facer = new Facer {
url,
dir: "./cv/tmp"
faceplant: "./cv/ham#{ @rand 3 }.png"
}
overlay = new OverlayImage {
url,
dir: "./cv/tmp"
overlay: "./cv/ham#{ @rand 3 }.png"
}
facer.go (file_path, cleanup) =>
@upload file_path, (link) =>
if link
say "More like #{ link }"
else
say "Something went wrong."
upload: (file_path, next) =>
fs.stat file_path, (err, stats) ->
throw err if err
if stats.size
console.log stats.size
imgur.upload file_path, (response)->
if response.error
console.log(response.error);
return next( no )
console.log response
next response.links.original
else
throw "onoz"
bot = new Imgo require './irc_config'
unless bot.connect
# bot.match "hamsnap rafael correa"
bot.match "http://ts1.mm.bing.net/th?id=H.4605008969401592&pid=1.7&w=228&h=149&c=7&rs=1.jpg"
bot.match "http://i.telegraph.co.uk/multimedia/archive/02206/spain-protest_2206735b.jpg"
bot.match "tots" | 82273 | fs = require 'fs'
ResponderBot = require './responderbot'
# get disposables via https://imgur.com/register/api_anon
client_id = "879200d6e95a899c7b1453ed6a31dd37"
imgur = require "imgur"
imgur.setKey client_id
{Facer} = require './cv/facer.coffee'
{OverlayImage} = require './cv/dl_overlay'
class Imgo extends ResponderBot
constructor: (config) ->
config.name = "imgo"
config.connect = yes
super config
@patterns = [
recognize: @re /^hamsnap (.+)*\?*/i
respond: ([first,matched,s...], o, say) ->
say "camsnap #{ matched }"
,
recognize: (s,msg_info) =>
console.log msg_info
if msg_info.nick is "bingbot" and s.match /^http\:\/\/(.+)*(jpg|png)/i
#if s.match /^http\:\/\/\w+.mm.bing.net\//i
console.log "wow it matched"
return s
no
respond: (m, o, say) =>
console.log m
@onImage m, say
]
should_ignore: -> no
rand: (n)-> parseInt Math.random() * n
onImage: (url, say) =>
facer = new Facer {
url,
dir: "./cv/tmp"
faceplant: "./cv/ham#{ @rand 3 }.png"
}
overlay = new OverlayImage {
url,
dir: "./cv/tmp"
overlay: "./cv/ham#{ @rand 3 }.png"
}
facer.go (file_path, cleanup) =>
@upload file_path, (link) =>
if link
say "More like #{ link }"
else
say "Something went wrong."
upload: (file_path, next) =>
fs.stat file_path, (err, stats) ->
throw err if err
if stats.size
console.log stats.size
imgur.upload file_path, (response)->
if response.error
console.log(response.error);
return next( no )
console.log response
next response.links.original
else
throw "onoz"
bot = new Imgo require './irc_config'
unless bot.connect
# bot.match "hamsnap <NAME>"
bot.match "http://ts1.mm.bing.net/th?id=H.4605008969401592&pid=1.7&w=228&h=149&c=7&rs=1.jpg"
bot.match "http://i.telegraph.co.uk/multimedia/archive/02206/spain-protest_2206735b.jpg"
bot.match "tots" | true | fs = require 'fs'
ResponderBot = require './responderbot'
# get disposables via https://imgur.com/register/api_anon
client_id = "879200d6e95a899c7b1453ed6a31dd37"
imgur = require "imgur"
imgur.setKey client_id
{Facer} = require './cv/facer.coffee'
{OverlayImage} = require './cv/dl_overlay'
class Imgo extends ResponderBot
constructor: (config) ->
config.name = "imgo"
config.connect = yes
super config
@patterns = [
recognize: @re /^hamsnap (.+)*\?*/i
respond: ([first,matched,s...], o, say) ->
say "camsnap #{ matched }"
,
recognize: (s,msg_info) =>
console.log msg_info
if msg_info.nick is "bingbot" and s.match /^http\:\/\/(.+)*(jpg|png)/i
#if s.match /^http\:\/\/\w+.mm.bing.net\//i
console.log "wow it matched"
return s
no
respond: (m, o, say) =>
console.log m
@onImage m, say
]
should_ignore: -> no
rand: (n)-> parseInt Math.random() * n
onImage: (url, say) =>
facer = new Facer {
url,
dir: "./cv/tmp"
faceplant: "./cv/ham#{ @rand 3 }.png"
}
overlay = new OverlayImage {
url,
dir: "./cv/tmp"
overlay: "./cv/ham#{ @rand 3 }.png"
}
facer.go (file_path, cleanup) =>
@upload file_path, (link) =>
if link
say "More like #{ link }"
else
say "Something went wrong."
upload: (file_path, next) =>
fs.stat file_path, (err, stats) ->
throw err if err
if stats.size
console.log stats.size
imgur.upload file_path, (response)->
if response.error
console.log(response.error);
return next( no )
console.log response
next response.links.original
else
throw "onoz"
bot = new Imgo require './irc_config'
unless bot.connect
# bot.match "hamsnap PI:NAME:<NAME>END_PI"
bot.match "http://ts1.mm.bing.net/th?id=H.4605008969401592&pid=1.7&w=228&h=149&c=7&rs=1.jpg"
bot.match "http://i.telegraph.co.uk/multimedia/archive/02206/spain-protest_2206735b.jpg"
bot.match "tots" |
[
{
"context": "sword_field.val() == ''\n password_field.val(@generatePassword())\n\n @attribute('ticket_message').val(",
"end": 1074,
"score": 0.708336591720581,
"start": 1066,
"tag": "PASSWORD",
"value": "generate"
}
] | app/assets/javascripts/pigeon/qst-server-wizard.js.coffee | instedd/pigeon | 1 | #= require pigeon/wizard
class QstServerWizard extends PigeonWizard
onPhoneType: (type) ->
@pages.each (index, page) ->
page_phone_type = $(page).data('phone-type')
if page_phone_type
page.disabled = page_phone_type != type
true
@attribute('phone_type').val(type)
@updateNavigation()
initPhoneType: (type) ->
@phone_type_radios.each (index, radio) ->
$(radio).attr('checked', radio.value == type)
@onPhoneType type
initWizard: ->
self = this
@navigation.show()
@pages[0].disabled = true
@ticket_code_fields = $('.ticket_code', @div)
@phone_type_radios = $('.phone_type', @div)
@initPhoneType @attribute('phone_type').val()
@phone_type_radios.click ->
self.onPhoneType @value
@ticket_code_fields.change ->
# update both ticket_code fields to make sure the current value gets
# posted
self.attribute('ticket_code').val(@value)
password_field = @attribute('configuration[password]')
if password_field.val() == ''
password_field.val(@generatePassword())
@attribute('ticket_message').val("This phone will be used for #{@app_name}.")
@attribute('use_ticket').val(true)
initPersisted: ->
$('#qst-reconfigure', @div).click =>
@initWizard()
@selectPage 1
@navigation.hide()
@selectPage 0
run: ->
if @persisted
@initPersisted()
else
@initWizard()
@selectDefaultPage()
PigeonWizard.registerClass 'qst-server', QstServerWizard
| 175424 | #= require pigeon/wizard
class QstServerWizard extends PigeonWizard
onPhoneType: (type) ->
@pages.each (index, page) ->
page_phone_type = $(page).data('phone-type')
if page_phone_type
page.disabled = page_phone_type != type
true
@attribute('phone_type').val(type)
@updateNavigation()
initPhoneType: (type) ->
@phone_type_radios.each (index, radio) ->
$(radio).attr('checked', radio.value == type)
@onPhoneType type
initWizard: ->
self = this
@navigation.show()
@pages[0].disabled = true
@ticket_code_fields = $('.ticket_code', @div)
@phone_type_radios = $('.phone_type', @div)
@initPhoneType @attribute('phone_type').val()
@phone_type_radios.click ->
self.onPhoneType @value
@ticket_code_fields.change ->
# update both ticket_code fields to make sure the current value gets
# posted
self.attribute('ticket_code').val(@value)
password_field = @attribute('configuration[password]')
if password_field.val() == ''
password_field.val(@<PASSWORD>Password())
@attribute('ticket_message').val("This phone will be used for #{@app_name}.")
@attribute('use_ticket').val(true)
initPersisted: ->
$('#qst-reconfigure', @div).click =>
@initWizard()
@selectPage 1
@navigation.hide()
@selectPage 0
run: ->
if @persisted
@initPersisted()
else
@initWizard()
@selectDefaultPage()
PigeonWizard.registerClass 'qst-server', QstServerWizard
| true | #= require pigeon/wizard
class QstServerWizard extends PigeonWizard
onPhoneType: (type) ->
@pages.each (index, page) ->
page_phone_type = $(page).data('phone-type')
if page_phone_type
page.disabled = page_phone_type != type
true
@attribute('phone_type').val(type)
@updateNavigation()
initPhoneType: (type) ->
@phone_type_radios.each (index, radio) ->
$(radio).attr('checked', radio.value == type)
@onPhoneType type
initWizard: ->
self = this
@navigation.show()
@pages[0].disabled = true
@ticket_code_fields = $('.ticket_code', @div)
@phone_type_radios = $('.phone_type', @div)
@initPhoneType @attribute('phone_type').val()
@phone_type_radios.click ->
self.onPhoneType @value
@ticket_code_fields.change ->
# update both ticket_code fields to make sure the current value gets
# posted
self.attribute('ticket_code').val(@value)
password_field = @attribute('configuration[password]')
if password_field.val() == ''
password_field.val(@PI:PASSWORD:<PASSWORD>END_PIPassword())
@attribute('ticket_message').val("This phone will be used for #{@app_name}.")
@attribute('use_ticket').val(true)
initPersisted: ->
$('#qst-reconfigure', @div).click =>
@initWizard()
@selectPage 1
@navigation.hide()
@selectPage 0
run: ->
if @persisted
@initPersisted()
else
@initWizard()
@selectDefaultPage()
PigeonWizard.registerClass 'qst-server', QstServerWizard
|
[
{
"context": "llers.find().count() == 0\n _.shuffle([\n {name: \"Francesco Totti\", team: \"Roma\", role: \"F\"},\n {name: \"Mauro Icar",
"end": 94,
"score": 0.9998282790184021,
"start": 79,
"tag": "NAME",
"value": "Francesco Totti"
},
{
"context": "esco Totti\", team: \"Roma\", ... | server/fixtures.coffee | dfucci/fantasybid | 0 | Current.remove({})
if Footballers.find().count() == 0
_.shuffle([
{name: "Francesco Totti", team: "Roma", role: "F"},
{name: "Mauro Icardi", team: "Inter", role: "F"},
{name: "Marco Materazzi", team: "Inter", role: "D"},
{name: "Ale Nesta", team: "Milan", role: "D"},
{name: "Daniele DeRossi", team: "Roma", role: "M"},
{name: "Darko Kuzmanovic", team: "Inter", role: "M"},
{name: "Gigi Buffon", team: "Juventus", role: "G"},
{name: "Sergio Romero", team: "Sampdoria", role: "G"}
]).forEach (data) ->
Footballers.insert data
| 139385 | Current.remove({})
if Footballers.find().count() == 0
_.shuffle([
{name: "<NAME>", team: "Roma", role: "F"},
{name: "<NAME>", team: "Inter", role: "F"},
{name: "<NAME>", team: "Inter", role: "D"},
{name: "<NAME>", team: "Milan", role: "D"},
{name: "<NAME>", team: "Roma", role: "M"},
{name: "<NAME>", team: "Inter", role: "M"},
{name: "<NAME>", team: "Juventus", role: "G"},
{name: "<NAME>", team: "Sampdoria", role: "G"}
]).forEach (data) ->
Footballers.insert data
| true | Current.remove({})
if Footballers.find().count() == 0
_.shuffle([
{name: "PI:NAME:<NAME>END_PI", team: "Roma", role: "F"},
{name: "PI:NAME:<NAME>END_PI", team: "Inter", role: "F"},
{name: "PI:NAME:<NAME>END_PI", team: "Inter", role: "D"},
{name: "PI:NAME:<NAME>END_PI", team: "Milan", role: "D"},
{name: "PI:NAME:<NAME>END_PI", team: "Roma", role: "M"},
{name: "PI:NAME:<NAME>END_PI", team: "Inter", role: "M"},
{name: "PI:NAME:<NAME>END_PI", team: "Juventus", role: "G"},
{name: "PI:NAME:<NAME>END_PI", team: "Sampdoria", role: "G"}
]).forEach (data) ->
Footballers.insert data
|
[
{
"context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\nmongo = r",
"end": 44,
"score": 0.999849796295166,
"start": 36,
"tag": "NAME",
"value": "Jae Kwon"
},
{
"context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.c... | logic/sessions.coffee | jaekwon/YCatalyst | 3 | ###
# YCatalyst
# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)
# MIT Licensed
###
mongo = require '../mongo'
# a global hash from record id to {username: {timestamp}}
all_sessions = undefined
mongo.after_open 'app', ->
mongo.app.findOne({_id: 'all_sessions'}, (err, stuff) ->
all_sessions = stuff or {_id: 'all_sessions'}
)
# clear old sessions after 60 secondsish
setInterval (->
now = new Date()
num_cleared = 0
num_seen = 0
for key, sessions of all_sessions
continue if key == '_id'
# we count the number of sessions per key, cuz javascript has no suitable object.length
num_seen_for_key = 0
for username, session of sessions
# TODO this is stupid. replace with a better dict implementation with length
continue if username == '_fake_length'
num_seen_for_key += 1
if now - session.timestamp > 60*1000
num_cleared += 1
delete sessions[username]
sessions._fake_length = num_seen_for_key
# if there are zero sessions on a key, then remove that session
if sessions._fake_length == 0
delete all_sessions[key]
# other
num_seen += num_seen_for_key
if num_cleared > 0
console.log "cleared #{num_cleared} of #{num_seen} in #{new Date() - now} sessions"
# every interval save the sessions object
mongo.app.save all_sessions, (err, stuff) ->
if err?
console.log "error saving all_sessions: " + err
), 15000
# create or update the session for key/username
exports.touch_session = (key, username) ->
sessions = all_sessions[key]
if not sessions?
sessions = all_sessions[key] = {}
s = sessions[username]
if not s?
s = sessions[username] = {}
s.timestamp = new Date()
# get sorted list of [record_id, num views]
exports.get_viewers = ->
views = [] # list of [record id, num viewers]
for key, sessions of all_sessions
continue if key == '_id'
if key != '_fake_length' # not sure why i put this here
views.push( [key, sessions._fake_length] )
views.sort( (a, b) -> b[1] - a[1] )
return views
# get list of usernames watching an item
exports.get_watching = (rid) ->
watching = if all_sessions[rid]? then (username for username, session of (all_sessions[rid] or {})) else []
return watching
| 96268 | ###
# YCatalyst
# Copyright(c) 2011 <NAME> (<EMAIL>)
# MIT Licensed
###
mongo = require '../mongo'
# a global hash from record id to {username: {timestamp}}
all_sessions = undefined
mongo.after_open 'app', ->
mongo.app.findOne({_id: 'all_sessions'}, (err, stuff) ->
all_sessions = stuff or {_id: 'all_sessions'}
)
# clear old sessions after 60 secondsish
setInterval (->
now = new Date()
num_cleared = 0
num_seen = 0
for key, sessions of all_sessions
continue if key == '_id'
# we count the number of sessions per key, cuz javascript has no suitable object.length
num_seen_for_key = 0
for username, session of sessions
# TODO this is stupid. replace with a better dict implementation with length
continue if username == '_fake_length'
num_seen_for_key += 1
if now - session.timestamp > 60*1000
num_cleared += 1
delete sessions[username]
sessions._fake_length = num_seen_for_key
# if there are zero sessions on a key, then remove that session
if sessions._fake_length == 0
delete all_sessions[key]
# other
num_seen += num_seen_for_key
if num_cleared > 0
console.log "cleared #{num_cleared} of #{num_seen} in #{new Date() - now} sessions"
# every interval save the sessions object
mongo.app.save all_sessions, (err, stuff) ->
if err?
console.log "error saving all_sessions: " + err
), 15000
# create or update the session for key/username
exports.touch_session = (key, username) ->
sessions = all_sessions[key]
if not sessions?
sessions = all_sessions[key] = {}
s = sessions[username]
if not s?
s = sessions[username] = {}
s.timestamp = new Date()
# get sorted list of [record_id, num views]
exports.get_viewers = ->
views = [] # list of [record id, num viewers]
for key, sessions of all_sessions
continue if key == <KEY>'
if key != <KEY>' # not sure why i put this here
views.push( [key, sessions._fake_length] )
views.sort( (a, b) -> b[1] - a[1] )
return views
# get list of usernames watching an item
exports.get_watching = (rid) ->
watching = if all_sessions[rid]? then (username for username, session of (all_sessions[rid] or {})) else []
return watching
| true | ###
# YCatalyst
# Copyright(c) 2011 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# MIT Licensed
###
mongo = require '../mongo'
# a global hash from record id to {username: {timestamp}}
all_sessions = undefined
mongo.after_open 'app', ->
mongo.app.findOne({_id: 'all_sessions'}, (err, stuff) ->
all_sessions = stuff or {_id: 'all_sessions'}
)
# clear old sessions after 60 secondsish
setInterval (->
now = new Date()
num_cleared = 0
num_seen = 0
for key, sessions of all_sessions
continue if key == '_id'
# we count the number of sessions per key, cuz javascript has no suitable object.length
num_seen_for_key = 0
for username, session of sessions
# TODO this is stupid. replace with a better dict implementation with length
continue if username == '_fake_length'
num_seen_for_key += 1
if now - session.timestamp > 60*1000
num_cleared += 1
delete sessions[username]
sessions._fake_length = num_seen_for_key
# if there are zero sessions on a key, then remove that session
if sessions._fake_length == 0
delete all_sessions[key]
# other
num_seen += num_seen_for_key
if num_cleared > 0
console.log "cleared #{num_cleared} of #{num_seen} in #{new Date() - now} sessions"
# every interval save the sessions object
mongo.app.save all_sessions, (err, stuff) ->
if err?
console.log "error saving all_sessions: " + err
), 15000
# create or update the session for key/username
exports.touch_session = (key, username) ->
sessions = all_sessions[key]
if not sessions?
sessions = all_sessions[key] = {}
s = sessions[username]
if not s?
s = sessions[username] = {}
s.timestamp = new Date()
# get sorted list of [record_id, num views]
exports.get_viewers = ->
views = [] # list of [record id, num viewers]
for key, sessions of all_sessions
continue if key == PI:KEY:<KEY>END_PI'
if key != PI:KEY:<KEY>END_PI' # not sure why i put this here
views.push( [key, sessions._fake_length] )
views.sort( (a, b) -> b[1] - a[1] )
return views
# get list of usernames watching an item
exports.get_watching = (rid) ->
watching = if all_sessions[rid]? then (username for username, session of (all_sessions[rid] or {})) else []
return watching
|
[
{
"context": "ntainer',\n modules:\n authorship: { authorId: 'basic' }\n toolbar: { container: '.basic-wrapper .too",
"end": 134,
"score": 0.5651406049728394,
"start": 129,
"tag": "NAME",
"value": "basic"
}
] | examples/scripts/advanced.coffee | philschatz/quill | 0 | _ = Quill.require('lodash')
basicEditor = new Quill('.basic-wrapper .editor-container',
modules:
authorship: { authorId: 'basic' }
toolbar: { container: '.basic-wrapper .toolbar-container' }
styles: false
)
advancedEditor = new Quill('.advanced-wrapper .editor-container',
modules:
'authorship': { authorId: 'advanced', enabled: true }
'toolbar': { container: '.advanced-wrapper .toolbar-container' }
'link-tooltip': true
'image-tooltip': true
'multi-cursor': true
styles: false
theme: 'snow'
)
authorship = advancedEditor.getModule('authorship')
authorship.addAuthor('basic', 'rgba(255,153,51,0.4)')
cursorManager = advancedEditor.getModule('multi-cursor')
cursorManager.setCursor('basic', 0, 'basic', 'rgba(255,153,51,0.9)')
basicEditor.on('selection-change', (range) ->
console.info 'basic', 'selection', range
cursorManager.moveCursor('basic', range.end) if range?
)
basicEditor.on('text-change', (delta, source) ->
return if source == 'api'
console.info 'basic', 'text', delta, source
advancedEditor.updateContents(delta)
sourceDelta = basicEditor.getContents()
targetDelta = advancedEditor.getContents()
console.assert(_.isEqual(sourceDelta, targetDelta), "Editor diversion!", sourceDelta.ops, targetDelta.ops)
)
advancedEditor.on('selection-change', (range) ->
console.info 'advanced', 'selection', range
)
advancedEditor.on('text-change', (delta, source) ->
return if source == 'api'
console.info 'advanced', 'text', delta, source
basicEditor.updateContents(delta)
sourceDelta = advancedEditor.getContents()
targetDelta = basicEditor.getContents()
console.assert(_.isEqual(sourceDelta, targetDelta), "Editor diversion!", sourceDelta.ops, targetDelta.ops)
)
| 29906 | _ = Quill.require('lodash')
basicEditor = new Quill('.basic-wrapper .editor-container',
modules:
authorship: { authorId: '<NAME>' }
toolbar: { container: '.basic-wrapper .toolbar-container' }
styles: false
)
advancedEditor = new Quill('.advanced-wrapper .editor-container',
modules:
'authorship': { authorId: 'advanced', enabled: true }
'toolbar': { container: '.advanced-wrapper .toolbar-container' }
'link-tooltip': true
'image-tooltip': true
'multi-cursor': true
styles: false
theme: 'snow'
)
authorship = advancedEditor.getModule('authorship')
authorship.addAuthor('basic', 'rgba(255,153,51,0.4)')
cursorManager = advancedEditor.getModule('multi-cursor')
cursorManager.setCursor('basic', 0, 'basic', 'rgba(255,153,51,0.9)')
basicEditor.on('selection-change', (range) ->
console.info 'basic', 'selection', range
cursorManager.moveCursor('basic', range.end) if range?
)
basicEditor.on('text-change', (delta, source) ->
return if source == 'api'
console.info 'basic', 'text', delta, source
advancedEditor.updateContents(delta)
sourceDelta = basicEditor.getContents()
targetDelta = advancedEditor.getContents()
console.assert(_.isEqual(sourceDelta, targetDelta), "Editor diversion!", sourceDelta.ops, targetDelta.ops)
)
advancedEditor.on('selection-change', (range) ->
console.info 'advanced', 'selection', range
)
advancedEditor.on('text-change', (delta, source) ->
return if source == 'api'
console.info 'advanced', 'text', delta, source
basicEditor.updateContents(delta)
sourceDelta = advancedEditor.getContents()
targetDelta = basicEditor.getContents()
console.assert(_.isEqual(sourceDelta, targetDelta), "Editor diversion!", sourceDelta.ops, targetDelta.ops)
)
| true | _ = Quill.require('lodash')
basicEditor = new Quill('.basic-wrapper .editor-container',
modules:
authorship: { authorId: 'PI:NAME:<NAME>END_PI' }
toolbar: { container: '.basic-wrapper .toolbar-container' }
styles: false
)
advancedEditor = new Quill('.advanced-wrapper .editor-container',
modules:
'authorship': { authorId: 'advanced', enabled: true }
'toolbar': { container: '.advanced-wrapper .toolbar-container' }
'link-tooltip': true
'image-tooltip': true
'multi-cursor': true
styles: false
theme: 'snow'
)
authorship = advancedEditor.getModule('authorship')
authorship.addAuthor('basic', 'rgba(255,153,51,0.4)')
cursorManager = advancedEditor.getModule('multi-cursor')
cursorManager.setCursor('basic', 0, 'basic', 'rgba(255,153,51,0.9)')
basicEditor.on('selection-change', (range) ->
console.info 'basic', 'selection', range
cursorManager.moveCursor('basic', range.end) if range?
)
basicEditor.on('text-change', (delta, source) ->
return if source == 'api'
console.info 'basic', 'text', delta, source
advancedEditor.updateContents(delta)
sourceDelta = basicEditor.getContents()
targetDelta = advancedEditor.getContents()
console.assert(_.isEqual(sourceDelta, targetDelta), "Editor diversion!", sourceDelta.ops, targetDelta.ops)
)
advancedEditor.on('selection-change', (range) ->
console.info 'advanced', 'selection', range
)
advancedEditor.on('text-change', (delta, source) ->
return if source == 'api'
console.info 'advanced', 'text', delta, source
basicEditor.updateContents(delta)
sourceDelta = advancedEditor.getContents()
targetDelta = basicEditor.getContents()
console.assert(_.isEqual(sourceDelta, targetDelta), "Editor diversion!", sourceDelta.ops, targetDelta.ops)
)
|
[
{
"context": "#\n# Ethan Mick\n# 2015\n#\n\nmongoose = require('mongoose-q')()\nSche",
"end": 14,
"score": 0.9997891187667847,
"start": 4,
"tag": "NAME",
"value": "Ethan Mick"
}
] | lib/models/solar_system.coffee | ethanmick/mustached-octo-dubstep | 0 | #
# Ethan Mick
# 2015
#
mongoose = require('mongoose-q')()
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
SolarSystem = new Schema
name:
type: String
location: Number
slots: Number
planets: [
{
type: ObjectId
ref: 'Planet'
}
]
galaxy:
type: ObjectId
ref: 'Galaxy'
module.exports = mongoose.model 'SolarSystem', SolarSystem
| 112403 | #
# <NAME>
# 2015
#
mongoose = require('mongoose-q')()
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
SolarSystem = new Schema
name:
type: String
location: Number
slots: Number
planets: [
{
type: ObjectId
ref: 'Planet'
}
]
galaxy:
type: ObjectId
ref: 'Galaxy'
module.exports = mongoose.model 'SolarSystem', SolarSystem
| true | #
# PI:NAME:<NAME>END_PI
# 2015
#
mongoose = require('mongoose-q')()
Schema = mongoose.Schema
ObjectId = Schema.Types.ObjectId
SolarSystem = new Schema
name:
type: String
location: Number
slots: Number
planets: [
{
type: ObjectId
ref: 'Planet'
}
]
galaxy:
type: ObjectId
ref: 'Galaxy'
module.exports = mongoose.model 'SolarSystem', SolarSystem
|
[
{
"context": "\n localStorage = _localStorage_\n key = 'test.memory.key'\n\n it 'sets/gets Item', ->\n value = 'What",
"end": 632,
"score": 0.9199728965759277,
"start": 617,
"tag": "KEY",
"value": "test.memory.key"
},
{
"context": "torage functions to handle data', ... | h/static/scripts/test/local-storage-test.coffee | noscripter/h | 0 | {module, inject} = angular.mock
describe 'localStorage', ->
fakeWindow = null
sandbox = null
before ->
angular.module('h', [])
.service('localStorage', require('../local-storage'))
beforeEach module('h')
describe 'memory fallback', ->
localStorage = null
key = null
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeWindow = {
localStorage: {}
}
$provide.value '$window', fakeWindow
return
afterEach ->
sandbox.restore()
beforeEach inject (_localStorage_) ->
localStorage = _localStorage_
key = 'test.memory.key'
it 'sets/gets Item', ->
value = 'What shall we do with a drunken sailor?'
localStorage.setItem key, value
actual = localStorage.getItem key
assert.equal value, actual
it 'removes item', ->
localStorage.setItem key, ''
localStorage.removeItem key
result = localStorage.getItem key
assert.isNull result
it 'sets/gets Object', ->
data = {'foo': 'bar'}
localStorage.setObject key, data
stringified = localStorage.getItem key
assert.equal stringified, JSON.stringify data
actual = localStorage.getObject key
assert.deepEqual actual, data
describe 'browser localStorage', ->
localStorage = null
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeWindow = {
localStorage: {
getItem: sandbox.stub()
setItem: sandbox.stub()
removeItem: sandbox.stub()
}
}
$provide.value '$window', fakeWindow
return
afterEach ->
sandbox.restore()
beforeEach inject (_localStorage_) ->
localStorage = _localStorage_
it 'uses window.localStorage functions to handle data', ->
key = 'test.storage.key'
data = 'test data'
localStorage.setItem key, data
assert.calledWith fakeWindow.localStorage.setItem, key, data
| 32815 | {module, inject} = angular.mock
describe 'localStorage', ->
fakeWindow = null
sandbox = null
before ->
angular.module('h', [])
.service('localStorage', require('../local-storage'))
beforeEach module('h')
describe 'memory fallback', ->
localStorage = null
key = null
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeWindow = {
localStorage: {}
}
$provide.value '$window', fakeWindow
return
afterEach ->
sandbox.restore()
beforeEach inject (_localStorage_) ->
localStorage = _localStorage_
key = '<KEY>'
it 'sets/gets Item', ->
value = 'What shall we do with a drunken sailor?'
localStorage.setItem key, value
actual = localStorage.getItem key
assert.equal value, actual
it 'removes item', ->
localStorage.setItem key, ''
localStorage.removeItem key
result = localStorage.getItem key
assert.isNull result
it 'sets/gets Object', ->
data = {'foo': 'bar'}
localStorage.setObject key, data
stringified = localStorage.getItem key
assert.equal stringified, JSON.stringify data
actual = localStorage.getObject key
assert.deepEqual actual, data
describe 'browser localStorage', ->
localStorage = null
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeWindow = {
localStorage: {
getItem: sandbox.stub()
setItem: sandbox.stub()
removeItem: sandbox.stub()
}
}
$provide.value '$window', fakeWindow
return
afterEach ->
sandbox.restore()
beforeEach inject (_localStorage_) ->
localStorage = _localStorage_
it 'uses window.localStorage functions to handle data', ->
key = '<KEY>'
data = 'test data'
localStorage.setItem key, data
assert.calledWith fakeWindow.localStorage.setItem, key, data
| true | {module, inject} = angular.mock
describe 'localStorage', ->
fakeWindow = null
sandbox = null
before ->
angular.module('h', [])
.service('localStorage', require('../local-storage'))
beforeEach module('h')
describe 'memory fallback', ->
localStorage = null
key = null
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeWindow = {
localStorage: {}
}
$provide.value '$window', fakeWindow
return
afterEach ->
sandbox.restore()
beforeEach inject (_localStorage_) ->
localStorage = _localStorage_
key = 'PI:KEY:<KEY>END_PI'
it 'sets/gets Item', ->
value = 'What shall we do with a drunken sailor?'
localStorage.setItem key, value
actual = localStorage.getItem key
assert.equal value, actual
it 'removes item', ->
localStorage.setItem key, ''
localStorage.removeItem key
result = localStorage.getItem key
assert.isNull result
it 'sets/gets Object', ->
data = {'foo': 'bar'}
localStorage.setObject key, data
stringified = localStorage.getItem key
assert.equal stringified, JSON.stringify data
actual = localStorage.getObject key
assert.deepEqual actual, data
describe 'browser localStorage', ->
localStorage = null
beforeEach module ($provide) ->
sandbox = sinon.sandbox.create()
fakeWindow = {
localStorage: {
getItem: sandbox.stub()
setItem: sandbox.stub()
removeItem: sandbox.stub()
}
}
$provide.value '$window', fakeWindow
return
afterEach ->
sandbox.restore()
beforeEach inject (_localStorage_) ->
localStorage = _localStorage_
it 'uses window.localStorage functions to handle data', ->
key = 'PI:KEY:<KEY>END_PI'
data = 'test data'
localStorage.setItem key, data
assert.calledWith fakeWindow.localStorage.setItem, key, data
|
[
{
"context": "nce.pdf\n# http://yihui.name/knitr/options/\n\nkey: 'rmarkdown'\npatterns: [\n {\n begin: '(?x)\n (```)(\n ",
"end": 185,
"score": 0.7625868916511536,
"start": 176,
"tag": "KEY",
"value": "rmarkdown"
}
] | grammars/repositories/flavors/rmarkdown.cson | wesleyem/language-markdown | 0 | # http://rmarkdown.rstudio.com/authoring_rcodechunks.html
# http://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf
# http://yihui.name/knitr/options/
key: 'rmarkdown'
patterns: [
{
begin: '(?x)
(```)(
(\\{)(r)(?:\\s)?
(?:([a-zA-Z0-9|_|-]*)(?=[\\s|,|}])\\s?)?
([^\\}]*)?
(\\})
)
'
end: '^(\\1)$'
name: 'fenced.code.md'
contentName: 'source.embedded.r'
patterns: [{ include: 'source.r' }]
beginCaptures:
1: name: 'punctuation.md'
3: name: 'punctuation.md'
4: name: 'language.constant.md'
5: name: 'label.string.md'
6: patterns: [{ include: '#rmarkdown-attributes' }]
7: name: 'punctuation.md'
endCaptures:
1: name: 'punctuation.md'
}
]
| 41820 | # http://rmarkdown.rstudio.com/authoring_rcodechunks.html
# http://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf
# http://yihui.name/knitr/options/
key: '<KEY>'
patterns: [
{
begin: '(?x)
(```)(
(\\{)(r)(?:\\s)?
(?:([a-zA-Z0-9|_|-]*)(?=[\\s|,|}])\\s?)?
([^\\}]*)?
(\\})
)
'
end: '^(\\1)$'
name: 'fenced.code.md'
contentName: 'source.embedded.r'
patterns: [{ include: 'source.r' }]
beginCaptures:
1: name: 'punctuation.md'
3: name: 'punctuation.md'
4: name: 'language.constant.md'
5: name: 'label.string.md'
6: patterns: [{ include: '#rmarkdown-attributes' }]
7: name: 'punctuation.md'
endCaptures:
1: name: 'punctuation.md'
}
]
| true | # http://rmarkdown.rstudio.com/authoring_rcodechunks.html
# http://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf
# http://yihui.name/knitr/options/
key: 'PI:KEY:<KEY>END_PI'
patterns: [
{
begin: '(?x)
(```)(
(\\{)(r)(?:\\s)?
(?:([a-zA-Z0-9|_|-]*)(?=[\\s|,|}])\\s?)?
([^\\}]*)?
(\\})
)
'
end: '^(\\1)$'
name: 'fenced.code.md'
contentName: 'source.embedded.r'
patterns: [{ include: 'source.r' }]
beginCaptures:
1: name: 'punctuation.md'
3: name: 'punctuation.md'
4: name: 'language.constant.md'
5: name: 'label.string.md'
6: patterns: [{ include: '#rmarkdown-attributes' }]
7: name: 'punctuation.md'
endCaptures:
1: name: 'punctuation.md'
}
]
|
[
{
"context": "entry\n\n unless result\n result = {name: name, data: []}\n series.push result\n retur",
"end": 2059,
"score": 0.6281265616416931,
"start": 2055,
"tag": "NAME",
"value": "name"
}
] | server/sales-force/adapters/grouper.coffee | JSSolutions/Dataforce | 2 | #todo: update this adapter for new data structures
class DataGrouper
constructor: (@chart, data) ->
@series = {}
getDimension2Value = (entry) =>
if @_is2Dimensional() then entry[@chart.axis.dimension2] else @chart.axis.dimension
data.forEach (entry) =>
dimensionValue = entry[@chart.axis.dimension]
dimension2Value = getDimension2Value(entry)
value = entry[@chart.axis.metrics]
@_updateValue(dimension2Value, dimensionValue, value)
_is2Dimensional: () -> !!@chart.axis.dimension2
_isAverageValueFunction: () -> @chart.valueFunction is 'average'
_getSeriesEntry: (functionArguments) -> @series[functionArguments[0]][functionArguments[1]]
_updateValue: (dimension2Value, dimensionValue, value) ->
unless @series[dimension2Value] then @series[dimension2Value] = {}
unless @series[dimension2Value][dimensionValue]
@series[dimension2Value][dimensionValue] =
value: if @_isAverageValueFunction() then 1 else 0
#dispatch value function
@["_#{@chart.valueFunction}"].apply(@, arguments)
_sum: (dimension2Value, dimensionValue, value) ->
seriesEntry = @_getSeriesEntry(arguments)
seriesEntry.value += value
_multiply: (dimension2Value, dimensionValue, value) ->
@_getSeriesEntry(arguments).value *= value
_average: (dimension2Value, dimensionValue, value) ->
seriesEntry = @_getSeriesEntry(arguments)
if seriesEntry.count
seriesEntry.count++
else
seriesEntry.count = 1
seriesEntry.value += value
_getValue: (dimension2Value, dimensionValue) ->
seriesEntry = @_getSeriesEntry(arguments)
value = if @_isAverageValueFunction() then seriesEntry.value / seriesEntry.count else seriesEntry.value
#round value up to 2 digits after dot
Math.round(value * 100) / 100
getConvertedSeriesForHighchart: ->
categories = []
series = []
seriesByName = (name) ->
result = false
for entry in series
if entry.name is name then result = entry
unless result
result = {name: name, data: []}
series.push result
return result
Object.keys(@series).forEach (dimension2Value) =>
Object.keys(@series[dimension2Value]).forEach (dimensionValue) =>
value = @_getValue dimension2Value, dimensionValue
unless dimension2Value in categories then categories.push dimension2Value
categoryIndex = categories.indexOf(dimension2Value)
seriesEntry = seriesByName(dimensionValue)
seriesEntry.data[categoryIndex] = value
#process series data (replace all undefined to 0)
series.forEach (seriesEntry) ->
for i in [0..categories.length - 1]
value = seriesEntry.data[i]
seriesEntry.data[i] = unless value then 0 else value
#return chart data
categories: categories
series: series
_.extend App.SalesForce, {
DataGrouper: DataGrouper
} | 55641 | #todo: update this adapter for new data structures
class DataGrouper
constructor: (@chart, data) ->
@series = {}
getDimension2Value = (entry) =>
if @_is2Dimensional() then entry[@chart.axis.dimension2] else @chart.axis.dimension
data.forEach (entry) =>
dimensionValue = entry[@chart.axis.dimension]
dimension2Value = getDimension2Value(entry)
value = entry[@chart.axis.metrics]
@_updateValue(dimension2Value, dimensionValue, value)
_is2Dimensional: () -> !!@chart.axis.dimension2
_isAverageValueFunction: () -> @chart.valueFunction is 'average'
_getSeriesEntry: (functionArguments) -> @series[functionArguments[0]][functionArguments[1]]
_updateValue: (dimension2Value, dimensionValue, value) ->
unless @series[dimension2Value] then @series[dimension2Value] = {}
unless @series[dimension2Value][dimensionValue]
@series[dimension2Value][dimensionValue] =
value: if @_isAverageValueFunction() then 1 else 0
#dispatch value function
@["_#{@chart.valueFunction}"].apply(@, arguments)
_sum: (dimension2Value, dimensionValue, value) ->
seriesEntry = @_getSeriesEntry(arguments)
seriesEntry.value += value
_multiply: (dimension2Value, dimensionValue, value) ->
@_getSeriesEntry(arguments).value *= value
_average: (dimension2Value, dimensionValue, value) ->
seriesEntry = @_getSeriesEntry(arguments)
if seriesEntry.count
seriesEntry.count++
else
seriesEntry.count = 1
seriesEntry.value += value
_getValue: (dimension2Value, dimensionValue) ->
seriesEntry = @_getSeriesEntry(arguments)
value = if @_isAverageValueFunction() then seriesEntry.value / seriesEntry.count else seriesEntry.value
#round value up to 2 digits after dot
Math.round(value * 100) / 100
getConvertedSeriesForHighchart: ->
categories = []
series = []
seriesByName = (name) ->
result = false
for entry in series
if entry.name is name then result = entry
unless result
result = {name: <NAME>, data: []}
series.push result
return result
Object.keys(@series).forEach (dimension2Value) =>
Object.keys(@series[dimension2Value]).forEach (dimensionValue) =>
value = @_getValue dimension2Value, dimensionValue
unless dimension2Value in categories then categories.push dimension2Value
categoryIndex = categories.indexOf(dimension2Value)
seriesEntry = seriesByName(dimensionValue)
seriesEntry.data[categoryIndex] = value
#process series data (replace all undefined to 0)
series.forEach (seriesEntry) ->
for i in [0..categories.length - 1]
value = seriesEntry.data[i]
seriesEntry.data[i] = unless value then 0 else value
#return chart data
categories: categories
series: series
_.extend App.SalesForce, {
DataGrouper: DataGrouper
} | true | #todo: update this adapter for new data structures
class DataGrouper
constructor: (@chart, data) ->
@series = {}
getDimension2Value = (entry) =>
if @_is2Dimensional() then entry[@chart.axis.dimension2] else @chart.axis.dimension
data.forEach (entry) =>
dimensionValue = entry[@chart.axis.dimension]
dimension2Value = getDimension2Value(entry)
value = entry[@chart.axis.metrics]
@_updateValue(dimension2Value, dimensionValue, value)
_is2Dimensional: () -> !!@chart.axis.dimension2
_isAverageValueFunction: () -> @chart.valueFunction is 'average'
_getSeriesEntry: (functionArguments) -> @series[functionArguments[0]][functionArguments[1]]
_updateValue: (dimension2Value, dimensionValue, value) ->
unless @series[dimension2Value] then @series[dimension2Value] = {}
unless @series[dimension2Value][dimensionValue]
@series[dimension2Value][dimensionValue] =
value: if @_isAverageValueFunction() then 1 else 0
#dispatch value function
@["_#{@chart.valueFunction}"].apply(@, arguments)
_sum: (dimension2Value, dimensionValue, value) ->
seriesEntry = @_getSeriesEntry(arguments)
seriesEntry.value += value
_multiply: (dimension2Value, dimensionValue, value) ->
@_getSeriesEntry(arguments).value *= value
_average: (dimension2Value, dimensionValue, value) ->
seriesEntry = @_getSeriesEntry(arguments)
if seriesEntry.count
seriesEntry.count++
else
seriesEntry.count = 1
seriesEntry.value += value
_getValue: (dimension2Value, dimensionValue) ->
seriesEntry = @_getSeriesEntry(arguments)
value = if @_isAverageValueFunction() then seriesEntry.value / seriesEntry.count else seriesEntry.value
#round value up to 2 digits after dot
Math.round(value * 100) / 100
getConvertedSeriesForHighchart: ->
categories = []
series = []
seriesByName = (name) ->
result = false
for entry in series
if entry.name is name then result = entry
unless result
result = {name: PI:NAME:<NAME>END_PI, data: []}
series.push result
return result
Object.keys(@series).forEach (dimension2Value) =>
Object.keys(@series[dimension2Value]).forEach (dimensionValue) =>
value = @_getValue dimension2Value, dimensionValue
unless dimension2Value in categories then categories.push dimension2Value
categoryIndex = categories.indexOf(dimension2Value)
seriesEntry = seriesByName(dimensionValue)
seriesEntry.data[categoryIndex] = value
#process series data (replace all undefined to 0)
series.forEach (seriesEntry) ->
for i in [0..categories.length - 1]
value = seriesEntry.data[i]
seriesEntry.data[i] = unless value then 0 else value
#return chart data
categories: categories
series: series
_.extend App.SalesForce, {
DataGrouper: DataGrouper
} |
[
{
"context": "onsole.log goats\n\n goat = find(propEq('name', 'Jade'), goats)\n\n should.exist goats\n goats.shoul",
"end": 737,
"score": 0.8205804824829102,
"start": 733,
"tag": "NAME",
"value": "Jade"
},
{
"context": "goat.should.have.property('name').which.is.equal('Dolly... | test/server/livestockService/test.coffee | blakeschwartz/rowdyranchtx-3.1 | 0 | #
# This is a file of template tests.
#
#
chai = require 'chai'
ramda = require 'ramda'
assert = chai.assert
should = chai.should()
find = ramda.find
propEq = ramda.propEq
Service = require('../../../dist/server/service/livestock/service').default
describe 'LivestockService Test', ->
service = null
before ->
#service = new Service()
service = Service.getInstance()
it 'it should exist', ->
should.exist service
it 'it should query all', ->
goats = await service.getGoats()
should.exist goats
goats.should.be.instanceOf Array
.timeout 3000
it 'it should contain an instance by name', ->
goats = await service.getGoats()
#console.log goats
goat = find(propEq('name', 'Jade'), goats)
should.exist goats
goats.should.be.instanceOf Array
it 'it should contain an instance by id', ->
goat = await service.getGoatById('gt000018')
#console.log goat
should.exist goat
goat.should.have.property('name').which.is.equal('Dolly')
| 68689 | #
# This is a file of template tests.
#
#
chai = require 'chai'
ramda = require 'ramda'
assert = chai.assert
should = chai.should()
find = ramda.find
propEq = ramda.propEq
Service = require('../../../dist/server/service/livestock/service').default
describe 'LivestockService Test', ->
service = null
before ->
#service = new Service()
service = Service.getInstance()
it 'it should exist', ->
should.exist service
it 'it should query all', ->
goats = await service.getGoats()
should.exist goats
goats.should.be.instanceOf Array
.timeout 3000
it 'it should contain an instance by name', ->
goats = await service.getGoats()
#console.log goats
goat = find(propEq('name', '<NAME>'), goats)
should.exist goats
goats.should.be.instanceOf Array
it 'it should contain an instance by id', ->
goat = await service.getGoatById('gt000018')
#console.log goat
should.exist goat
goat.should.have.property('name').which.is.equal('<NAME>')
| true | #
# This is a file of template tests.
#
#
chai = require 'chai'
ramda = require 'ramda'
assert = chai.assert
should = chai.should()
find = ramda.find
propEq = ramda.propEq
Service = require('../../../dist/server/service/livestock/service').default
describe 'LivestockService Test', ->
service = null
before ->
#service = new Service()
service = Service.getInstance()
it 'it should exist', ->
should.exist service
it 'it should query all', ->
goats = await service.getGoats()
should.exist goats
goats.should.be.instanceOf Array
.timeout 3000
it 'it should contain an instance by name', ->
goats = await service.getGoats()
#console.log goats
goat = find(propEq('name', 'PI:NAME:<NAME>END_PI'), goats)
should.exist goats
goats.should.be.instanceOf Array
it 'it should contain an instance by id', ->
goat = await service.getGoatById('gt000018')
#console.log goat
should.exist goat
goat.should.have.property('name').which.is.equal('PI:NAME:<NAME>END_PI')
|
[
{
"context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed under the Apach",
"end": 35,
"score": 0.9998136162757874,
"start": 24,
"tag": "NAME",
"value": "Dan Elliott"
},
{
"context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed ... | clients/www/src/coffee/isadore_graphs/TimeGraph.coffee | bluthen/isadore_server | 0 | # Copyright 2010-2019 Dan Elliott, Russell Valentine
#
# 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.
#begin_datetime=2013-09-11T19:31:00.000Z
#end_datetime=2013-09-14T12:30:00.000Z
#Test Queries
###
query =
{
time: {begin_datetime: '2013-09-11T19:31:00.000Z', end_datetime: '2013-09-14T12:30:00.000Z', sample_period: 5},
labels: {title: 'Test graph', y0label: 'y 0 label', y1label: 'y 1 label'},
data: [
{
value: 'Bin 1.Top.Temp',
display: {
label: 'T',
color: '#FFFF00',
pattern: null,
axis: 0
}
},
{
value: 'Bin 1.Bottom.Temp',
display: {
label: 'B',
color: '#FF0000',
pattern: [2,2],
axis: 1
}
}
]
};
query2 =
{
time: {begin_datetime: '2013-09-11T19:31:00.000Z', end_datetime: '2013-09-14T12:30:00.000Z', sample_period: 5},
labels: {y0label: 'y 0 label', y1label: 'y 1 label'},
data: [
{
value: 'Bin 1.Top.Temp',
display: {
label: 'T',
color: '#000000',
pattern: null,
axis: 0
}
}
]
}
$('body').empty(); a = new TimeGraph($('body'), query, {}, {width: '600px', height: '400px', showRangeSelector: false});
b = new TimeGraph($('body'), query2, {}, {width: '600px', height: '200px', showRangeSelector: false});
a.linkGraph(b);
b.linkGraph(a);
###
#QUERY SYNTAX
#{
# time: {begin_datetime: 'ISO8601'|Date(), end_datetime: 'ISO8601'|Date(), sample_period: int_valid_sample_period_minutes, time_display: null_or_'timestamp'_or_'hours'},
# labels: {title: 'title', xlabel: null, y0label: 'F (°F)', y1label: '%'},
# initial_options: {y0range: [60, 130], y1range: [30, 100], minmax: true|false},
# data: [
# {value: 'Bin Name.Bin Section Name.Short Name Sensor Type', vname: 'bin1_top_temp', display: {label: 'Top Temp (° F)', color: '#FF0000', pattern: [2, 2], axis: 0}}, ...
# ],
# calc: [
# {value: 'js_code', SAME_AS_data, options: {all_rows: true}}
# ]
#}
# Instead of 'Bin Section', can use 'inlet|outlet|maxtemp'
#Query to Request logic
#in data sort by bin name in data
#group by bin name
#For each group
# get bin_id from Bin Name
# get bin_section_id from 'Bin Section Name' or leaves as inlet|outlet|maxtemp
# Make REST Query for data
# {bin_id: bin_id, query: [ [TYPE_STR, [OPTS]], ...], sample_period: int, begin_datetime: 'ISO8601', end_datetime: 'ISO8601'}
#
#Process calc, if variable is needed process data
#Merge data info dygraph form keeping track of indexes
#Use indexes to make dygraph options
#otherOptions
# width: '600px'
# height: '400px'
# showRangeSelector: true,
class window.TimeGraph
@RIGHT_GAP: 60
constructor: ($parent, query, ourvars, otherOpts) ->
@_$parent = $parent
@_$selfdiv = $('<div><img src="./imgs/ajax-loader-big.gif" alt="loading spinner"/></div>')
@_$parent.append(@_$selfdiv)
@_query = _.cloneDeep(query)
@_ourvars = ourvars
@_dygraph = null
@_dygraphOptions = null
@_dygraphData = null
@_otherOpts = otherOpts
@_linkedGraphs = []
if @_otherOpts?.height?
@_$selfdiv.css('height', @_otherOpts.height)
if @_otherOpts?.width?
@_$selfdiv.css('width', @_otherOpts.width)
@_timeVariableReplace()
@_generate()
_timeVariableReplace: () ->
#Replace variables in datetime
if _.isString(@_query.time.begin_datetime) && @_ourvars.hasOwnProperty(@_query.time.begin_datetime)
@_query.time.begin_datetime = @_ourvars[@_query.time.begin_datetime]
if _.isString(@_query.time.end_datetime) && @_ourvars.hasOwnProperty(@_query.time.end_datetime)
@_query.time.end_datetime = @_ourvars[@_query.time.end_datetime]
if @_query.time.begin_datetime instanceof Date
@_query.time.begin_datetime = HTMLHelper.dateToParamString(@_query.time.begin_datetime)
if @_query.time.end_datetime instanceof Date
@_query.time.end_datetime = HTMLHelper.dateToParamString(@_query.time.end_datetime)
_groupVariableReplaceBins: () ->
#Group by Bin Name
binGroups = {}
for d in @_query.data
vsplit = d.value.split('.')
binName = vsplit[0]
if @_ourvars.hasOwnProperty(binName)
binName = @_ourvars[binName]
if binGroups.hasOwnProperty(binName)
binGroups[binName].push(d)
else
binGroups[binName] = []
binGroups[binName].push(d)
return binGroups
_restQueries: (binGroups) ->
allRestQueries = []
for binName, groupArray of binGroups
bin = _.find(IsadoreData.bins, (b) ->
return b.name == binName
)
if bin
binId = bin.id
restQuery = {bin_id: binId, sample_period: @_query.time.sample_period, begin_datetime: @_query.time.begin_datetime, end_datetime: @_query.time.end_datetime, query: []}
restQueryIdxMap = []
for d in groupArray
vsplit = d.value.split('.')
binSectionName = vsplit[1]
if binSectionName == 'maxtemp'
restQuery.query.push(['maxtemp', []])
restQueryIdxMap.push(d)
else
readTypeName = vsplit[2]
readTypeId = null
readType = _.findWhere(IsadoreData.readTypes, {'short_name': readTypeName})
if readType
readTypeId = readType.id
if binSectionName == 'inlet' || binSectionName == 'outlet'
restQuery.query.push([binSectionName, [readTypeId]])
restQueryIdxMap.push(d)
else
binSection = _.find(IsadoreData.binSections, (b) ->
return b.name == binSectionName
)
if binSection
binSectionId = binSection.id
restQuery.query.push(['sensor', [binSectionId, readTypeId]])
restQueryIdxMap.push(d)
if restQuery.query.length > 0
restQuery.query = JSON.stringify(restQuery.query)
allRestQueries.push([restQueryIdxMap, restQuery])
return allRestQueries
_generate: () ->
#TODO: Add Spinner
binGroups = @_groupVariableReplaceBins()
allRestQueries = @_restQueries(binGroups)
#Fetch data
queryFuncGen = (ourMap, ourQuery) ->
return (callback) ->
$.ajax({
url: '../resources/data/graph/data'
type: 'GET'
dataType: 'json'
data: ourQuery
success: (d) =>
callback(null, [ourMap, d])
error: (jqXHR, textStatus) =>
console?.error('Error getting graph data: '+textStatus)
callback(textStatus, [ourMap, null])
})
#Get data
tasks=[]
for rquery in allRestQueries
tasks.push(queryFuncGen(rquery[0], rquery[1]))
console.log(tasks)
async.parallel(
tasks,
(err, results) =>
@_generate2(err, results)
)
_highlights: (canvas, area, g) ->
if @_otherOpts.highlights?
for hl in @_otherOpts.highlights
start = hl.start
end = hl.end
if _.isString(start)
start = new Date(hl.start)
if _.isString(end)
end = new Date(end)
if @_query.time.time_display == 'hours'
start = (start.getTime() - @_firstDate) / (3600000.0)
end = (end.getTime() - @_firstDate) / (3600000.0)
bl = g.toDomCoords(start, -20)
tr = g.toDomCoords(end, 20)
canvas.fillStyle = hl.color
canvas.fillRect(bl[0], area.y, tr[0] - bl[0], area.h)
_generate2: (err, results) ->
#Go through results
console.log("_generate2")
console.log(err)
console.log(results)
data=[]
dataVars = {}
dataMap = []
#If any errors set to display
@_dataErrors = []
if err
if err instanceof Array
for er in err
if er
@_dataErrors.push(er)
else
@_dataErrors.push(err)
if @_dataErrors.length > 0
@_$selfdiv.html(@_dataErrors.join('</br>'))
return
for r in results
if not r[1] or r[1].length == 0
continue
#zip
zr = _.zip(r[1])
#merge
if data.length == 0
data.push(zr[0])
if data[0].length != zr[0].length
console?.warn('Different lengths')
if zr.length-1 != r[0].length
console?.warn('Map and data lengths differ')
for i in [1...zr.length]
data.push(zr[i])
#Set new index data map
dataMap.push(r[0][i-1])
#Set variable map
if r[0][i-1].vname?
dataVars[r[0][i-1].vname] = zr[i]
#Go through calc in query
if @_query.calc?
for c in @_query.calc
try
#process calc using math.eval http://mathjs.org
res = math.eval(c.value, dataVars)
data.push(res)
dataMap.push(c)
if c.vname?
dataVars[c.vname] = res
catch er
console?.error(er)
@_dataErrors.push(er)
if @_dataErrors.length > 0
@_$selfdiv.html(@_dataErrors.join('</br>'))
return
if data.length == 0
@_$selfdiv.html('No results found.')
return
#Make dygraph options using index map
dygraphOptions = {
legend: 'always'
labels: ['Time']
series: {}
yAxisLabelWidth: 70
customBars: true
labelsSeparateLines: true,
underlayCallback: (canvas, area, g) =>
@_highlights(canvas, area, g)
zoomCallback: (minX, maxX, yRanges) =>
@_zoomCB(minX, maxX, yRanges)
}
if @_otherOpts?.showRangeSelector?
dygraphOptions.showRangeSelector = @_otherOpts.showRangeSelector
if @_query.labels?.title?
title = @_query.labels.title
if @_ourvars.hasOwnProperty(title)
title = @_ourvars[title]
dygraphOptions.title = title
if @_query.labels?.y0label?
dygraphOptions.ylabel = @_query.labels?.y0label
if @_query.labels?.y1label?
dygraphOptions.y2label = @_query.labels?.y1label
if @_query.initial_options?.y0range?
dygraphOptions.axes = {y: @_query.initial_options.y0range}
if @_query.initial_options?.y1range?
if not dygraphOptions.axes?
dygraphOptions.axes = {}
dygraphOptions.axes.y2 = @_query.initial_options.y1range
if @_query.time.time_display? and @_query.time.time_display == 'hours'
if not dygraphOptions.axes?
dygraphOptions.axes = {}
if not dygraphOptions.axes.x
dygraphOptions.axes.x = {}
dygraphOptions.axes.x.valueFormatter = (hrs) ->
hours = Math.floor(hrs)
mins = Math.floor((hrs - hours)*60.0)
seconds = Math.floor(((hrs - hours)*60.0 - mins)*60)
return "#{hours}h#{mins}m#{seconds}s"
hasY2 = false
dygraphOptions.series = {}
for i in [0...dataMap.length]
m = dataMap[i]
if m.display?
if m.display.label?
label = m.display.label
dygraphOptions.labels.push(label)
else
label = uuid.v4()
dygraphOptions.labels.push(label)
dygraphOptions.series[label] = {}
if m.display.axis? and m.display.axis == 1
dygraphOptions.series[label].axis = 'y2'
hasY2 = true
if m.display.color?
dygraphOptions.series[label].color = m.display.color
if m.display.pattern?
dygraphOptions.series[label].strokePattern = m.display.pattern
else
# Was just used as a variable
data.splice(i, 1)
if !hasY2
dygraphOptions.rightGap = TimeGraph.RIGHT_GAP
#unzip
#First column needs to be date objects
for i in [0...data[0].length]
data[0][i] = new Date(data[0][i])
if @_query.time.time_display? and @_query.time.time_display == 'hours'
if ! @_firstDate
@_firstDate = new Date(data[0][i]).getTime()
data[0][i] = (new Date(data[0][i]).getTime() - @_firstDate) / (3600000.0)
dygraphData = _.unzip(data)
#Make dygraph
# dygraphOptions = {
# legend: 'follow',
# animatedZooms: true,
# title: 'dygraphs chart template',
# customBars: true,
# labels: ['Xdog', 'Y', 'Z'],
# series: {
# 'Z': { color: 'green'},
# 'Y': {
# strokePattern: [5,5],
# color: '#FF0000'
# }
# }
# }
@_dygraphOptions = dygraphOptions
console.log('Data length = '+dygraphData.length)
# dygraphData = [
# [1,[0, 0, 0],[1, 2, 3]],
# [2,[2, 2, 2],[6, 6, 6]],
# [3,[4, 4, 4],[8, 8, 8]],
# [4,[6, 6, 6],[9, 9, 9]],
# [5,[8, 8, 8],[9, 9, 9]],
# [6,[10, 10, 10],[8, 8, 8]],
# [7,[12, 12, 12],[6, 6, 6]],
# [8,[14, 14, 14],[3, 3, 3]]]
@_dygraphData = dygraphData
checkData = false
#Lets check the data
if checkData
if not @_debugData(dygraphData)
console.error('Aborting bad data.')
@_$selfdiv.empty()
@_dygraph = new Dygraph(@_$selfdiv[0], dygraphData, dygraphOptions)
_debugData: (dygraphData) ->
oursize = 0
for i in [0...dygraphData.length]
if i == 0
oursize = dygraphData[i].length
if dygraphData[i].length != oursize
console.error('Column wrong size, '+oursize+" != "+dygraphData[i].length);
return false
for j in [0...dygraphData[i].length]
if j == 0
if not dygraphData[i][j] instanceof Date
console.error('First column is not date '+i+" "+j)
return false
else
if not _.isArray(dygraphData[i][j])
console.error('column is not array '+i+" "+j)
return false
if dygraphData[i][j].length != 3
console.error('in column not size 3: '+i+" "+j)
return false
for k in [0...3]
if not _.isNumber(dygraphData[i][j][k])
console.error('in column not number'+i+" "+j+' '+k)
return false
return true
_zoomCB: (minX, maxX, yRanges) ->
console.log(minX)
console.log(maxX)
console.log(yRanges)
for g in @_linkedGraphs
g.update({dateWindow: [minX, maxX]})
delete: () ->
if @_dygraph
@_dygraph.destroy()
@_dygraph = null
@_$selfdiv.remove()
update: (opts) ->
if @_dygraph
@_dygraph.updateOptions(opts)
linkGraph: (graph) ->
if graph
@_linkedGraphs.push(graph)
unlinkGraph: (graph) ->
idx = _.indexOf(@_linkedGraphs, graph)
if idx > -1
@_linkedGraphs.splice(idx, 1)
| 59106 | # Copyright 2010-2019 <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#begin_datetime=2013-09-11T19:31:00.000Z
#end_datetime=2013-09-14T12:30:00.000Z
#Test Queries
###
query =
{
time: {begin_datetime: '2013-09-11T19:31:00.000Z', end_datetime: '2013-09-14T12:30:00.000Z', sample_period: 5},
labels: {title: 'Test graph', y0label: 'y 0 label', y1label: 'y 1 label'},
data: [
{
value: 'Bin 1.Top.Temp',
display: {
label: 'T',
color: '#FFFF00',
pattern: null,
axis: 0
}
},
{
value: 'Bin 1.Bottom.Temp',
display: {
label: 'B',
color: '#FF0000',
pattern: [2,2],
axis: 1
}
}
]
};
query2 =
{
time: {begin_datetime: '2013-09-11T19:31:00.000Z', end_datetime: '2013-09-14T12:30:00.000Z', sample_period: 5},
labels: {y0label: 'y 0 label', y1label: 'y 1 label'},
data: [
{
value: 'Bin 1.Top.Temp',
display: {
label: 'T',
color: '#000000',
pattern: null,
axis: 0
}
}
]
}
$('body').empty(); a = new TimeGraph($('body'), query, {}, {width: '600px', height: '400px', showRangeSelector: false});
b = new TimeGraph($('body'), query2, {}, {width: '600px', height: '200px', showRangeSelector: false});
a.linkGraph(b);
b.linkGraph(a);
###
#QUERY SYNTAX
#{
# time: {begin_datetime: 'ISO8601'|Date(), end_datetime: 'ISO8601'|Date(), sample_period: int_valid_sample_period_minutes, time_display: null_or_'timestamp'_or_'hours'},
# labels: {title: 'title', xlabel: null, y0label: 'F (°F)', y1label: '%'},
# initial_options: {y0range: [60, 130], y1range: [30, 100], minmax: true|false},
# data: [
# {value: 'Bin Name.Bin Section Name.Short Name Sensor Type', vname: 'bin1_top_temp', display: {label: 'Top Temp (° F)', color: '#FF0000', pattern: [2, 2], axis: 0}}, ...
# ],
# calc: [
# {value: 'js_code', SAME_AS_data, options: {all_rows: true}}
# ]
#}
# Instead of 'Bin Section', can use 'inlet|outlet|maxtemp'
#Query to Request logic
#in data sort by bin name in data
#group by bin name
#For each group
# get bin_id from Bin Name
# get bin_section_id from 'Bin Section Name' or leaves as inlet|outlet|maxtemp
# Make REST Query for data
# {bin_id: bin_id, query: [ [TYPE_STR, [OPTS]], ...], sample_period: int, begin_datetime: 'ISO8601', end_datetime: 'ISO8601'}
#
#Process calc, if variable is needed process data
#Merge data info dygraph form keeping track of indexes
#Use indexes to make dygraph options
#otherOptions
# width: '600px'
# height: '400px'
# showRangeSelector: true,
class window.TimeGraph
@RIGHT_GAP: 60
constructor: ($parent, query, ourvars, otherOpts) ->
@_$parent = $parent
@_$selfdiv = $('<div><img src="./imgs/ajax-loader-big.gif" alt="loading spinner"/></div>')
@_$parent.append(@_$selfdiv)
@_query = _.cloneDeep(query)
@_ourvars = ourvars
@_dygraph = null
@_dygraphOptions = null
@_dygraphData = null
@_otherOpts = otherOpts
@_linkedGraphs = []
if @_otherOpts?.height?
@_$selfdiv.css('height', @_otherOpts.height)
if @_otherOpts?.width?
@_$selfdiv.css('width', @_otherOpts.width)
@_timeVariableReplace()
@_generate()
_timeVariableReplace: () ->
#Replace variables in datetime
if _.isString(@_query.time.begin_datetime) && @_ourvars.hasOwnProperty(@_query.time.begin_datetime)
@_query.time.begin_datetime = @_ourvars[@_query.time.begin_datetime]
if _.isString(@_query.time.end_datetime) && @_ourvars.hasOwnProperty(@_query.time.end_datetime)
@_query.time.end_datetime = @_ourvars[@_query.time.end_datetime]
if @_query.time.begin_datetime instanceof Date
@_query.time.begin_datetime = HTMLHelper.dateToParamString(@_query.time.begin_datetime)
if @_query.time.end_datetime instanceof Date
@_query.time.end_datetime = HTMLHelper.dateToParamString(@_query.time.end_datetime)
_groupVariableReplaceBins: () ->
#Group by Bin Name
binGroups = {}
for d in @_query.data
vsplit = d.value.split('.')
binName = vsplit[0]
if @_ourvars.hasOwnProperty(binName)
binName = @_ourvars[binName]
if binGroups.hasOwnProperty(binName)
binGroups[binName].push(d)
else
binGroups[binName] = []
binGroups[binName].push(d)
return binGroups
_restQueries: (binGroups) ->
allRestQueries = []
for binName, groupArray of binGroups
bin = _.find(IsadoreData.bins, (b) ->
return b.name == binName
)
if bin
binId = bin.id
restQuery = {bin_id: binId, sample_period: @_query.time.sample_period, begin_datetime: @_query.time.begin_datetime, end_datetime: @_query.time.end_datetime, query: []}
restQueryIdxMap = []
for d in groupArray
vsplit = d.value.split('.')
binSectionName = vsplit[1]
if binSectionName == 'maxtemp'
restQuery.query.push(['maxtemp', []])
restQueryIdxMap.push(d)
else
readTypeName = vsplit[2]
readTypeId = null
readType = _.findWhere(IsadoreData.readTypes, {'short_name': readTypeName})
if readType
readTypeId = readType.id
if binSectionName == 'inlet' || binSectionName == 'outlet'
restQuery.query.push([binSectionName, [readTypeId]])
restQueryIdxMap.push(d)
else
binSection = _.find(IsadoreData.binSections, (b) ->
return b.name == binSectionName
)
if binSection
binSectionId = binSection.id
restQuery.query.push(['sensor', [binSectionId, readTypeId]])
restQueryIdxMap.push(d)
if restQuery.query.length > 0
restQuery.query = JSON.stringify(restQuery.query)
allRestQueries.push([restQueryIdxMap, restQuery])
return allRestQueries
_generate: () ->
#TODO: Add Spinner
binGroups = @_groupVariableReplaceBins()
allRestQueries = @_restQueries(binGroups)
#Fetch data
queryFuncGen = (ourMap, ourQuery) ->
return (callback) ->
$.ajax({
url: '../resources/data/graph/data'
type: 'GET'
dataType: 'json'
data: ourQuery
success: (d) =>
callback(null, [ourMap, d])
error: (jqXHR, textStatus) =>
console?.error('Error getting graph data: '+textStatus)
callback(textStatus, [ourMap, null])
})
#Get data
tasks=[]
for rquery in allRestQueries
tasks.push(queryFuncGen(rquery[0], rquery[1]))
console.log(tasks)
async.parallel(
tasks,
(err, results) =>
@_generate2(err, results)
)
_highlights: (canvas, area, g) ->
if @_otherOpts.highlights?
for hl in @_otherOpts.highlights
start = hl.start
end = hl.end
if _.isString(start)
start = new Date(hl.start)
if _.isString(end)
end = new Date(end)
if @_query.time.time_display == 'hours'
start = (start.getTime() - @_firstDate) / (3600000.0)
end = (end.getTime() - @_firstDate) / (3600000.0)
bl = g.toDomCoords(start, -20)
tr = g.toDomCoords(end, 20)
canvas.fillStyle = hl.color
canvas.fillRect(bl[0], area.y, tr[0] - bl[0], area.h)
_generate2: (err, results) ->
#Go through results
console.log("_generate2")
console.log(err)
console.log(results)
data=[]
dataVars = {}
dataMap = []
#If any errors set to display
@_dataErrors = []
if err
if err instanceof Array
for er in err
if er
@_dataErrors.push(er)
else
@_dataErrors.push(err)
if @_dataErrors.length > 0
@_$selfdiv.html(@_dataErrors.join('</br>'))
return
for r in results
if not r[1] or r[1].length == 0
continue
#zip
zr = _.zip(r[1])
#merge
if data.length == 0
data.push(zr[0])
if data[0].length != zr[0].length
console?.warn('Different lengths')
if zr.length-1 != r[0].length
console?.warn('Map and data lengths differ')
for i in [1...zr.length]
data.push(zr[i])
#Set new index data map
dataMap.push(r[0][i-1])
#Set variable map
if r[0][i-1].vname?
dataVars[r[0][i-1].vname] = zr[i]
#Go through calc in query
if @_query.calc?
for c in @_query.calc
try
#process calc using math.eval http://mathjs.org
res = math.eval(c.value, dataVars)
data.push(res)
dataMap.push(c)
if c.vname?
dataVars[c.vname] = res
catch er
console?.error(er)
@_dataErrors.push(er)
if @_dataErrors.length > 0
@_$selfdiv.html(@_dataErrors.join('</br>'))
return
if data.length == 0
@_$selfdiv.html('No results found.')
return
#Make dygraph options using index map
dygraphOptions = {
legend: 'always'
labels: ['Time']
series: {}
yAxisLabelWidth: 70
customBars: true
labelsSeparateLines: true,
underlayCallback: (canvas, area, g) =>
@_highlights(canvas, area, g)
zoomCallback: (minX, maxX, yRanges) =>
@_zoomCB(minX, maxX, yRanges)
}
if @_otherOpts?.showRangeSelector?
dygraphOptions.showRangeSelector = @_otherOpts.showRangeSelector
if @_query.labels?.title?
title = @_query.labels.title
if @_ourvars.hasOwnProperty(title)
title = @_ourvars[title]
dygraphOptions.title = title
if @_query.labels?.y0label?
dygraphOptions.ylabel = @_query.labels?.y0label
if @_query.labels?.y1label?
dygraphOptions.y2label = @_query.labels?.y1label
if @_query.initial_options?.y0range?
dygraphOptions.axes = {y: @_query.initial_options.y0range}
if @_query.initial_options?.y1range?
if not dygraphOptions.axes?
dygraphOptions.axes = {}
dygraphOptions.axes.y2 = @_query.initial_options.y1range
if @_query.time.time_display? and @_query.time.time_display == 'hours'
if not dygraphOptions.axes?
dygraphOptions.axes = {}
if not dygraphOptions.axes.x
dygraphOptions.axes.x = {}
dygraphOptions.axes.x.valueFormatter = (hrs) ->
hours = Math.floor(hrs)
mins = Math.floor((hrs - hours)*60.0)
seconds = Math.floor(((hrs - hours)*60.0 - mins)*60)
return "#{hours}h#{mins}m#{seconds}s"
hasY2 = false
dygraphOptions.series = {}
for i in [0...dataMap.length]
m = dataMap[i]
if m.display?
if m.display.label?
label = m.display.label
dygraphOptions.labels.push(label)
else
label = uuid.v4()
dygraphOptions.labels.push(label)
dygraphOptions.series[label] = {}
if m.display.axis? and m.display.axis == 1
dygraphOptions.series[label].axis = 'y2'
hasY2 = true
if m.display.color?
dygraphOptions.series[label].color = m.display.color
if m.display.pattern?
dygraphOptions.series[label].strokePattern = m.display.pattern
else
# Was just used as a variable
data.splice(i, 1)
if !hasY2
dygraphOptions.rightGap = TimeGraph.RIGHT_GAP
#unzip
#First column needs to be date objects
for i in [0...data[0].length]
data[0][i] = new Date(data[0][i])
if @_query.time.time_display? and @_query.time.time_display == 'hours'
if ! @_firstDate
@_firstDate = new Date(data[0][i]).getTime()
data[0][i] = (new Date(data[0][i]).getTime() - @_firstDate) / (3600000.0)
dygraphData = _.unzip(data)
#Make dygraph
# dygraphOptions = {
# legend: 'follow',
# animatedZooms: true,
# title: 'dygraphs chart template',
# customBars: true,
# labels: ['Xdog', 'Y', 'Z'],
# series: {
# 'Z': { color: 'green'},
# 'Y': {
# strokePattern: [5,5],
# color: '#FF0000'
# }
# }
# }
@_dygraphOptions = dygraphOptions
console.log('Data length = '+dygraphData.length)
# dygraphData = [
# [1,[0, 0, 0],[1, 2, 3]],
# [2,[2, 2, 2],[6, 6, 6]],
# [3,[4, 4, 4],[8, 8, 8]],
# [4,[6, 6, 6],[9, 9, 9]],
# [5,[8, 8, 8],[9, 9, 9]],
# [6,[10, 10, 10],[8, 8, 8]],
# [7,[12, 12, 12],[6, 6, 6]],
# [8,[14, 14, 14],[3, 3, 3]]]
@_dygraphData = dygraphData
checkData = false
#Lets check the data
if checkData
if not @_debugData(dygraphData)
console.error('Aborting bad data.')
@_$selfdiv.empty()
@_dygraph = new Dygraph(@_$selfdiv[0], dygraphData, dygraphOptions)
_debugData: (dygraphData) ->
oursize = 0
for i in [0...dygraphData.length]
if i == 0
oursize = dygraphData[i].length
if dygraphData[i].length != oursize
console.error('Column wrong size, '+oursize+" != "+dygraphData[i].length);
return false
for j in [0...dygraphData[i].length]
if j == 0
if not dygraphData[i][j] instanceof Date
console.error('First column is not date '+i+" "+j)
return false
else
if not _.isArray(dygraphData[i][j])
console.error('column is not array '+i+" "+j)
return false
if dygraphData[i][j].length != 3
console.error('in column not size 3: '+i+" "+j)
return false
for k in [0...3]
if not _.isNumber(dygraphData[i][j][k])
console.error('in column not number'+i+" "+j+' '+k)
return false
return true
_zoomCB: (minX, maxX, yRanges) ->
console.log(minX)
console.log(maxX)
console.log(yRanges)
for g in @_linkedGraphs
g.update({dateWindow: [minX, maxX]})
delete: () ->
if @_dygraph
@_dygraph.destroy()
@_dygraph = null
@_$selfdiv.remove()
update: (opts) ->
if @_dygraph
@_dygraph.updateOptions(opts)
linkGraph: (graph) ->
if graph
@_linkedGraphs.push(graph)
unlinkGraph: (graph) ->
idx = _.indexOf(@_linkedGraphs, graph)
if idx > -1
@_linkedGraphs.splice(idx, 1)
| true | # Copyright 2010-2019 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#begin_datetime=2013-09-11T19:31:00.000Z
#end_datetime=2013-09-14T12:30:00.000Z
#Test Queries
###
query =
{
time: {begin_datetime: '2013-09-11T19:31:00.000Z', end_datetime: '2013-09-14T12:30:00.000Z', sample_period: 5},
labels: {title: 'Test graph', y0label: 'y 0 label', y1label: 'y 1 label'},
data: [
{
value: 'Bin 1.Top.Temp',
display: {
label: 'T',
color: '#FFFF00',
pattern: null,
axis: 0
}
},
{
value: 'Bin 1.Bottom.Temp',
display: {
label: 'B',
color: '#FF0000',
pattern: [2,2],
axis: 1
}
}
]
};
query2 =
{
time: {begin_datetime: '2013-09-11T19:31:00.000Z', end_datetime: '2013-09-14T12:30:00.000Z', sample_period: 5},
labels: {y0label: 'y 0 label', y1label: 'y 1 label'},
data: [
{
value: 'Bin 1.Top.Temp',
display: {
label: 'T',
color: '#000000',
pattern: null,
axis: 0
}
}
]
}
$('body').empty(); a = new TimeGraph($('body'), query, {}, {width: '600px', height: '400px', showRangeSelector: false});
b = new TimeGraph($('body'), query2, {}, {width: '600px', height: '200px', showRangeSelector: false});
a.linkGraph(b);
b.linkGraph(a);
###
#QUERY SYNTAX
#{
# time: {begin_datetime: 'ISO8601'|Date(), end_datetime: 'ISO8601'|Date(), sample_period: int_valid_sample_period_minutes, time_display: null_or_'timestamp'_or_'hours'},
# labels: {title: 'title', xlabel: null, y0label: 'F (°F)', y1label: '%'},
# initial_options: {y0range: [60, 130], y1range: [30, 100], minmax: true|false},
# data: [
# {value: 'Bin Name.Bin Section Name.Short Name Sensor Type', vname: 'bin1_top_temp', display: {label: 'Top Temp (° F)', color: '#FF0000', pattern: [2, 2], axis: 0}}, ...
# ],
# calc: [
# {value: 'js_code', SAME_AS_data, options: {all_rows: true}}
# ]
#}
# Instead of 'Bin Section', can use 'inlet|outlet|maxtemp'
#Query to Request logic
#in data sort by bin name in data
#group by bin name
#For each group
# get bin_id from Bin Name
# get bin_section_id from 'Bin Section Name' or leaves as inlet|outlet|maxtemp
# Make REST Query for data
# {bin_id: bin_id, query: [ [TYPE_STR, [OPTS]], ...], sample_period: int, begin_datetime: 'ISO8601', end_datetime: 'ISO8601'}
#
#Process calc, if variable is needed process data
#Merge data info dygraph form keeping track of indexes
#Use indexes to make dygraph options
#otherOptions
# width: '600px'
# height: '400px'
# showRangeSelector: true,
class window.TimeGraph
@RIGHT_GAP: 60
constructor: ($parent, query, ourvars, otherOpts) ->
@_$parent = $parent
@_$selfdiv = $('<div><img src="./imgs/ajax-loader-big.gif" alt="loading spinner"/></div>')
@_$parent.append(@_$selfdiv)
@_query = _.cloneDeep(query)
@_ourvars = ourvars
@_dygraph = null
@_dygraphOptions = null
@_dygraphData = null
@_otherOpts = otherOpts
@_linkedGraphs = []
if @_otherOpts?.height?
@_$selfdiv.css('height', @_otherOpts.height)
if @_otherOpts?.width?
@_$selfdiv.css('width', @_otherOpts.width)
@_timeVariableReplace()
@_generate()
_timeVariableReplace: () ->
#Replace variables in datetime
if _.isString(@_query.time.begin_datetime) && @_ourvars.hasOwnProperty(@_query.time.begin_datetime)
@_query.time.begin_datetime = @_ourvars[@_query.time.begin_datetime]
if _.isString(@_query.time.end_datetime) && @_ourvars.hasOwnProperty(@_query.time.end_datetime)
@_query.time.end_datetime = @_ourvars[@_query.time.end_datetime]
if @_query.time.begin_datetime instanceof Date
@_query.time.begin_datetime = HTMLHelper.dateToParamString(@_query.time.begin_datetime)
if @_query.time.end_datetime instanceof Date
@_query.time.end_datetime = HTMLHelper.dateToParamString(@_query.time.end_datetime)
_groupVariableReplaceBins: () ->
#Group by Bin Name
binGroups = {}
for d in @_query.data
vsplit = d.value.split('.')
binName = vsplit[0]
if @_ourvars.hasOwnProperty(binName)
binName = @_ourvars[binName]
if binGroups.hasOwnProperty(binName)
binGroups[binName].push(d)
else
binGroups[binName] = []
binGroups[binName].push(d)
return binGroups
_restQueries: (binGroups) ->
allRestQueries = []
for binName, groupArray of binGroups
bin = _.find(IsadoreData.bins, (b) ->
return b.name == binName
)
if bin
binId = bin.id
restQuery = {bin_id: binId, sample_period: @_query.time.sample_period, begin_datetime: @_query.time.begin_datetime, end_datetime: @_query.time.end_datetime, query: []}
restQueryIdxMap = []
for d in groupArray
vsplit = d.value.split('.')
binSectionName = vsplit[1]
if binSectionName == 'maxtemp'
restQuery.query.push(['maxtemp', []])
restQueryIdxMap.push(d)
else
readTypeName = vsplit[2]
readTypeId = null
readType = _.findWhere(IsadoreData.readTypes, {'short_name': readTypeName})
if readType
readTypeId = readType.id
if binSectionName == 'inlet' || binSectionName == 'outlet'
restQuery.query.push([binSectionName, [readTypeId]])
restQueryIdxMap.push(d)
else
binSection = _.find(IsadoreData.binSections, (b) ->
return b.name == binSectionName
)
if binSection
binSectionId = binSection.id
restQuery.query.push(['sensor', [binSectionId, readTypeId]])
restQueryIdxMap.push(d)
if restQuery.query.length > 0
restQuery.query = JSON.stringify(restQuery.query)
allRestQueries.push([restQueryIdxMap, restQuery])
return allRestQueries
_generate: () ->
#TODO: Add Spinner
binGroups = @_groupVariableReplaceBins()
allRestQueries = @_restQueries(binGroups)
#Fetch data
queryFuncGen = (ourMap, ourQuery) ->
return (callback) ->
$.ajax({
url: '../resources/data/graph/data'
type: 'GET'
dataType: 'json'
data: ourQuery
success: (d) =>
callback(null, [ourMap, d])
error: (jqXHR, textStatus) =>
console?.error('Error getting graph data: '+textStatus)
callback(textStatus, [ourMap, null])
})
#Get data
tasks=[]
for rquery in allRestQueries
tasks.push(queryFuncGen(rquery[0], rquery[1]))
console.log(tasks)
async.parallel(
tasks,
(err, results) =>
@_generate2(err, results)
)
_highlights: (canvas, area, g) ->
if @_otherOpts.highlights?
for hl in @_otherOpts.highlights
start = hl.start
end = hl.end
if _.isString(start)
start = new Date(hl.start)
if _.isString(end)
end = new Date(end)
if @_query.time.time_display == 'hours'
start = (start.getTime() - @_firstDate) / (3600000.0)
end = (end.getTime() - @_firstDate) / (3600000.0)
bl = g.toDomCoords(start, -20)
tr = g.toDomCoords(end, 20)
canvas.fillStyle = hl.color
canvas.fillRect(bl[0], area.y, tr[0] - bl[0], area.h)
_generate2: (err, results) ->
#Go through results
console.log("_generate2")
console.log(err)
console.log(results)
data=[]
dataVars = {}
dataMap = []
#If any errors set to display
@_dataErrors = []
if err
if err instanceof Array
for er in err
if er
@_dataErrors.push(er)
else
@_dataErrors.push(err)
if @_dataErrors.length > 0
@_$selfdiv.html(@_dataErrors.join('</br>'))
return
for r in results
if not r[1] or r[1].length == 0
continue
#zip
zr = _.zip(r[1])
#merge
if data.length == 0
data.push(zr[0])
if data[0].length != zr[0].length
console?.warn('Different lengths')
if zr.length-1 != r[0].length
console?.warn('Map and data lengths differ')
for i in [1...zr.length]
data.push(zr[i])
#Set new index data map
dataMap.push(r[0][i-1])
#Set variable map
if r[0][i-1].vname?
dataVars[r[0][i-1].vname] = zr[i]
#Go through calc in query
if @_query.calc?
for c in @_query.calc
try
#process calc using math.eval http://mathjs.org
res = math.eval(c.value, dataVars)
data.push(res)
dataMap.push(c)
if c.vname?
dataVars[c.vname] = res
catch er
console?.error(er)
@_dataErrors.push(er)
if @_dataErrors.length > 0
@_$selfdiv.html(@_dataErrors.join('</br>'))
return
if data.length == 0
@_$selfdiv.html('No results found.')
return
#Make dygraph options using index map
dygraphOptions = {
legend: 'always'
labels: ['Time']
series: {}
yAxisLabelWidth: 70
customBars: true
labelsSeparateLines: true,
underlayCallback: (canvas, area, g) =>
@_highlights(canvas, area, g)
zoomCallback: (minX, maxX, yRanges) =>
@_zoomCB(minX, maxX, yRanges)
}
if @_otherOpts?.showRangeSelector?
dygraphOptions.showRangeSelector = @_otherOpts.showRangeSelector
if @_query.labels?.title?
title = @_query.labels.title
if @_ourvars.hasOwnProperty(title)
title = @_ourvars[title]
dygraphOptions.title = title
if @_query.labels?.y0label?
dygraphOptions.ylabel = @_query.labels?.y0label
if @_query.labels?.y1label?
dygraphOptions.y2label = @_query.labels?.y1label
if @_query.initial_options?.y0range?
dygraphOptions.axes = {y: @_query.initial_options.y0range}
if @_query.initial_options?.y1range?
if not dygraphOptions.axes?
dygraphOptions.axes = {}
dygraphOptions.axes.y2 = @_query.initial_options.y1range
if @_query.time.time_display? and @_query.time.time_display == 'hours'
if not dygraphOptions.axes?
dygraphOptions.axes = {}
if not dygraphOptions.axes.x
dygraphOptions.axes.x = {}
dygraphOptions.axes.x.valueFormatter = (hrs) ->
hours = Math.floor(hrs)
mins = Math.floor((hrs - hours)*60.0)
seconds = Math.floor(((hrs - hours)*60.0 - mins)*60)
return "#{hours}h#{mins}m#{seconds}s"
hasY2 = false
dygraphOptions.series = {}
for i in [0...dataMap.length]
m = dataMap[i]
if m.display?
if m.display.label?
label = m.display.label
dygraphOptions.labels.push(label)
else
label = uuid.v4()
dygraphOptions.labels.push(label)
dygraphOptions.series[label] = {}
if m.display.axis? and m.display.axis == 1
dygraphOptions.series[label].axis = 'y2'
hasY2 = true
if m.display.color?
dygraphOptions.series[label].color = m.display.color
if m.display.pattern?
dygraphOptions.series[label].strokePattern = m.display.pattern
else
# Was just used as a variable
data.splice(i, 1)
if !hasY2
dygraphOptions.rightGap = TimeGraph.RIGHT_GAP
#unzip
#First column needs to be date objects
for i in [0...data[0].length]
data[0][i] = new Date(data[0][i])
if @_query.time.time_display? and @_query.time.time_display == 'hours'
if ! @_firstDate
@_firstDate = new Date(data[0][i]).getTime()
data[0][i] = (new Date(data[0][i]).getTime() - @_firstDate) / (3600000.0)
dygraphData = _.unzip(data)
#Make dygraph
# dygraphOptions = {
# legend: 'follow',
# animatedZooms: true,
# title: 'dygraphs chart template',
# customBars: true,
# labels: ['Xdog', 'Y', 'Z'],
# series: {
# 'Z': { color: 'green'},
# 'Y': {
# strokePattern: [5,5],
# color: '#FF0000'
# }
# }
# }
@_dygraphOptions = dygraphOptions
console.log('Data length = '+dygraphData.length)
# dygraphData = [
# [1,[0, 0, 0],[1, 2, 3]],
# [2,[2, 2, 2],[6, 6, 6]],
# [3,[4, 4, 4],[8, 8, 8]],
# [4,[6, 6, 6],[9, 9, 9]],
# [5,[8, 8, 8],[9, 9, 9]],
# [6,[10, 10, 10],[8, 8, 8]],
# [7,[12, 12, 12],[6, 6, 6]],
# [8,[14, 14, 14],[3, 3, 3]]]
@_dygraphData = dygraphData
checkData = false
#Lets check the data
if checkData
if not @_debugData(dygraphData)
console.error('Aborting bad data.')
@_$selfdiv.empty()
@_dygraph = new Dygraph(@_$selfdiv[0], dygraphData, dygraphOptions)
_debugData: (dygraphData) ->
oursize = 0
for i in [0...dygraphData.length]
if i == 0
oursize = dygraphData[i].length
if dygraphData[i].length != oursize
console.error('Column wrong size, '+oursize+" != "+dygraphData[i].length);
return false
for j in [0...dygraphData[i].length]
if j == 0
if not dygraphData[i][j] instanceof Date
console.error('First column is not date '+i+" "+j)
return false
else
if not _.isArray(dygraphData[i][j])
console.error('column is not array '+i+" "+j)
return false
if dygraphData[i][j].length != 3
console.error('in column not size 3: '+i+" "+j)
return false
for k in [0...3]
if not _.isNumber(dygraphData[i][j][k])
console.error('in column not number'+i+" "+j+' '+k)
return false
return true
_zoomCB: (minX, maxX, yRanges) ->
console.log(minX)
console.log(maxX)
console.log(yRanges)
for g in @_linkedGraphs
g.update({dateWindow: [minX, maxX]})
delete: () ->
if @_dygraph
@_dygraph.destroy()
@_dygraph = null
@_$selfdiv.remove()
update: (opts) ->
if @_dygraph
@_dygraph.updateOptions(opts)
linkGraph: (graph) ->
if graph
@_linkedGraphs.push(graph)
unlinkGraph: (graph) ->
idx = _.indexOf(@_linkedGraphs, graph)
if idx > -1
@_linkedGraphs.splice(idx, 1)
|
[
{
"context": "e = QUnit.module\n\n\tdataOrig = [\n\t {id: 1, name: 'John'},\n\t {id: 2, name: 'Sarah'}\n\t]\n\n\tcompareData = (",
"end": 98,
"score": 0.9998253583908081,
"start": 94,
"tag": "NAME",
"value": "John"
},
{
"context": "g = [\n\t {id: 1, name: 'John'},\n\t {id: 2, nam... | tests/backend/memory-test.coffee | dundalek/warehouse | 74 |
@run_tests_memory = (constructor) ->
module = QUnit.module
dataOrig = [
{id: 1, name: 'John'},
{id: 2, name: 'Sarah'}
]
compareData = (data) ->
data.sort (a, b) -> a.id - b.id
deepEqual data, dataOrig
testData = (data) ->
backend = new constructor()
store = backend.objectStore('item', {json: data})
store.query().then (qdata) ->
compareData qdata
store.fromJSON({})
store.query().then (qdata) ->
deepEqual qdata, []
store.fromJSON(data)
store.query().then (qdata) ->
compareData(qdata);
start()
module "MemoryStore"
asyncTest 'json parameter in constructor: Array', 3, ->
data = [
{id: 1, name: 'John'},
{id: 2, name: 'Sarah'}
]
testData data
asyncTest 'json parameter in constructor: Array in JSON', 3, ->
data = '[{"id":1,"name":"John"},{"id":2,"name":"Sarah"}]'
testData data
asyncTest 'json parameter in constructor: Object', 3, ->
data = {
1: {id: 1, name: 'John'},
2: {id: 2, name: 'Sarah'}
}
testData data
asyncTest 'json parameter in constructor: Object in JSON', 3, ->
data = {"1":{"id":1,"name":"John"},"2":{"id":2,"name":"Sarah"}}
testData data
if typeof require != 'undefined'
@run_tests_memory(require('../../backend/memory')) | 74222 |
@run_tests_memory = (constructor) ->
module = QUnit.module
dataOrig = [
{id: 1, name: '<NAME>'},
{id: 2, name: '<NAME>'}
]
compareData = (data) ->
data.sort (a, b) -> a.id - b.id
deepEqual data, dataOrig
testData = (data) ->
backend = new constructor()
store = backend.objectStore('item', {json: data})
store.query().then (qdata) ->
compareData qdata
store.fromJSON({})
store.query().then (qdata) ->
deepEqual qdata, []
store.fromJSON(data)
store.query().then (qdata) ->
compareData(qdata);
start()
module "MemoryStore"
asyncTest 'json parameter in constructor: Array', 3, ->
data = [
{id: 1, name: '<NAME>'},
{id: 2, name: '<NAME>'}
]
testData data
asyncTest 'json parameter in constructor: Array in JSON', 3, ->
data = '[{"id":1,"name":"<NAME>"},{"id":2,"name":"<NAME>"}]'
testData data
asyncTest 'json parameter in constructor: Object', 3, ->
data = {
1: {id: 1, name: '<NAME>'},
2: {id: 2, name: '<NAME>'}
}
testData data
asyncTest 'json parameter in constructor: Object in JSON', 3, ->
data = {"1":{"id":1,"name":"<NAME>"},"2":{"id":2,"name":"<NAME>"}}
testData data
if typeof require != 'undefined'
@run_tests_memory(require('../../backend/memory')) | true |
@run_tests_memory = (constructor) ->
module = QUnit.module
dataOrig = [
{id: 1, name: 'PI:NAME:<NAME>END_PI'},
{id: 2, name: 'PI:NAME:<NAME>END_PI'}
]
compareData = (data) ->
data.sort (a, b) -> a.id - b.id
deepEqual data, dataOrig
testData = (data) ->
backend = new constructor()
store = backend.objectStore('item', {json: data})
store.query().then (qdata) ->
compareData qdata
store.fromJSON({})
store.query().then (qdata) ->
deepEqual qdata, []
store.fromJSON(data)
store.query().then (qdata) ->
compareData(qdata);
start()
module "MemoryStore"
asyncTest 'json parameter in constructor: Array', 3, ->
data = [
{id: 1, name: 'PI:NAME:<NAME>END_PI'},
{id: 2, name: 'PI:NAME:<NAME>END_PI'}
]
testData data
asyncTest 'json parameter in constructor: Array in JSON', 3, ->
data = '[{"id":1,"name":"PI:NAME:<NAME>END_PI"},{"id":2,"name":"PI:NAME:<NAME>END_PI"}]'
testData data
asyncTest 'json parameter in constructor: Object', 3, ->
data = {
1: {id: 1, name: 'PI:NAME:<NAME>END_PI'},
2: {id: 2, name: 'PI:NAME:<NAME>END_PI'}
}
testData data
asyncTest 'json parameter in constructor: Object in JSON', 3, ->
data = {"1":{"id":1,"name":"PI:NAME:<NAME>END_PI"},"2":{"id":2,"name":"PI:NAME:<NAME>END_PI"}}
testData data
if typeof require != 'undefined'
@run_tests_memory(require('../../backend/memory')) |
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998440742492676,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/membrane/linkage.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
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 OWNER 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.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
{Barebones} = require "./skeleton"
{Extending} = require "../nucleus/extends"
{Composition} = require "../nucleus/compose"
{BowerSupport} = require "../applied/bower"
{Archetype} = require "../nucleus/arche"
# A complementary part of the preflight procedures that provides the
# ability to create and emit arbitrary linkage in the contexts that
# are going to be assembled within the current preflight hierarchy.
# The facilities of this toolkit should typically be used when you
# need to link to a static asset file, within any domain or path.
module.exports.LinksToolkit = class LinksToolkit extends Barebones
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: jscripts: 1, stsheets: 1, metatags: 1
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
identify = try @constructor.identify().underline
message = "Flushing out the JS/CSS linkage in %s"
assert _.isString(symbol), "cannot found symbol"
assert _.isObject(context), "located no context"
assert _.isObject(request), "located no request"
assert _.isFunction(next), "got no next function"
logger.debug message.yellow, identify.toString()
gx = (key) => this.constructor[key] or Array()
sx = (key, s) => context[key].push v for v in s
fx = (inp, out) => try sx out, _.unique(gx(inp))
ax = (mapping) => fx(k, v) for k, v of mapping
ax metatags: "metatag" # map metatags to context
ax jscripts: "scripts" # map scripts to context
ax stsheets: "sheets" # map styles to context
return do => next.call this # asynchronous
# This is a preflight directive that can be used to generate and
# emit meta tags for the client browser. The directive expects a
# aggregate definition (an object) whose key/value pairs will be
# diretly corellated as parameter name and value for a meta tag
# definition. Any number of pairs (parameters) may be supplied.
@metatag: (aggregate) ->
assert identify = this.identify().toString()
failed = "argument has to be the plain object"
message = "Setting metatags information in %s"
noPrevious = "found invalid previous metatags"
assert _.all(_.values(aggregate), _.isString)
assert previous = this.metatags or new Array()
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isPlainObject(aggregate or 0), failed
format = (val, key) -> "#{key}=\x22#{val}\x22"
_.map aggregate, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join " "
@metatags = previous.concat joined.toString()
logger.debug message.grey, identify.underline
return aggregate # return the object back
# This is a preflight directive that can be used to link any
# arbitrary JavaScript file source. Is important do understand
# that this directive only compiles the appropriate statement
# to be transferred to the server and it is up to you to ensure
# the existence of that file and its ability to be downloaded.
@javascript: (xparameter, xdirection) ->
assert previous = this.jscripts or Array()
assert identify = this.identify().toString()
parameter = _.find arguments or [], _.isObject
direction = _.find arguments or [], _.isString
message = "Adding JavaScript information in %s"
indirect = "an inalid direction have supplied"
noPrevious = "found invalid previous jscripts"
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isString(direction or null), indirect
format = (val, key) -> return "#{key}=#{val}"
_.map parameter, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join "&"
logger.debug message.grey, identify.underline
direction += "?#{joined}" unless _.isEmpty a
assert @jscripts = previous.concat direction
assert @jscripts = _.unique this.jscripts
# This is a preflight directive that can be used to link any
# arbitrary CSS style file source. Is important do understand
# that this directive only compiles the appropriate statement
# to be transferred to the server and it is up to you to ensure
# the existence of that file and its ability to be downloaded.
@stylesheet: (xoptions, xdirection) ->
assert previous = this.stsheets or Array()
assert identify = this.identify().toString()
parameter = _.find arguments or [], _.isObject
direction = _.find arguments or [], _.isString
message = "Adding Stylesheet information in %s"
indirect = "an inalid direction have supplied"
noPrevious = "found invalid previous stsheets"
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isString(direction or null), indirect
format = (val, key) -> return "#{key}=#{val}"
_.map parameter, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join "&"
logger.debug message.grey, identify.underline
direction += "?#{joined}" unless _.isEmpty a
assert @stsheets = previous.concat direction
assert @stsheets = _.unique this.stsheets
| 78466 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
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 OWNER 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.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
{Barebones} = require "./skeleton"
{Extending} = require "../nucleus/extends"
{Composition} = require "../nucleus/compose"
{BowerSupport} = require "../applied/bower"
{Archetype} = require "../nucleus/arche"
# A complementary part of the preflight procedures that provides the
# ability to create and emit arbitrary linkage in the contexts that
# are going to be assembled within the current preflight hierarchy.
# The facilities of this toolkit should typically be used when you
# need to link to a static asset file, within any domain or path.
module.exports.LinksToolkit = class LinksToolkit extends Barebones
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: jscripts: 1, stsheets: 1, metatags: 1
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
identify = try @constructor.identify().underline
message = "Flushing out the JS/CSS linkage in %s"
assert _.isString(symbol), "cannot found symbol"
assert _.isObject(context), "located no context"
assert _.isObject(request), "located no request"
assert _.isFunction(next), "got no next function"
logger.debug message.yellow, identify.toString()
gx = (key) => this.constructor[key] or Array()
sx = (key, s) => context[key].push v for v in s
fx = (inp, out) => try sx out, _.unique(gx(inp))
ax = (mapping) => fx(k, v) for k, v of mapping
ax metatags: "metatag" # map metatags to context
ax jscripts: "scripts" # map scripts to context
ax stsheets: "sheets" # map styles to context
return do => next.call this # asynchronous
# This is a preflight directive that can be used to generate and
# emit meta tags for the client browser. The directive expects a
# aggregate definition (an object) whose key/value pairs will be
# diretly corellated as parameter name and value for a meta tag
# definition. Any number of pairs (parameters) may be supplied.
@metatag: (aggregate) ->
assert identify = this.identify().toString()
failed = "argument has to be the plain object"
message = "Setting metatags information in %s"
noPrevious = "found invalid previous metatags"
assert _.all(_.values(aggregate), _.isString)
assert previous = this.metatags or new Array()
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isPlainObject(aggregate or 0), failed
format = (val, key) -> "#{key}=\x22#{val}\x22"
_.map aggregate, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join " "
@metatags = previous.concat joined.toString()
logger.debug message.grey, identify.underline
return aggregate # return the object back
# This is a preflight directive that can be used to link any
# arbitrary JavaScript file source. Is important do understand
# that this directive only compiles the appropriate statement
# to be transferred to the server and it is up to you to ensure
# the existence of that file and its ability to be downloaded.
@javascript: (xparameter, xdirection) ->
assert previous = this.jscripts or Array()
assert identify = this.identify().toString()
parameter = _.find arguments or [], _.isObject
direction = _.find arguments or [], _.isString
message = "Adding JavaScript information in %s"
indirect = "an inalid direction have supplied"
noPrevious = "found invalid previous jscripts"
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isString(direction or null), indirect
format = (val, key) -> return "#{key}=#{val}"
_.map parameter, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join "&"
logger.debug message.grey, identify.underline
direction += "?#{joined}" unless _.isEmpty a
assert @jscripts = previous.concat direction
assert @jscripts = _.unique this.jscripts
# This is a preflight directive that can be used to link any
# arbitrary CSS style file source. Is important do understand
# that this directive only compiles the appropriate statement
# to be transferred to the server and it is up to you to ensure
# the existence of that file and its ability to be downloaded.
@stylesheet: (xoptions, xdirection) ->
assert previous = this.stsheets or Array()
assert identify = this.identify().toString()
parameter = _.find arguments or [], _.isObject
direction = _.find arguments or [], _.isString
message = "Adding Stylesheet information in %s"
indirect = "an inalid direction have supplied"
noPrevious = "found invalid previous stsheets"
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isString(direction or null), indirect
format = (val, key) -> return "#{key}=#{val}"
_.map parameter, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join "&"
logger.debug message.grey, identify.underline
direction += "?#{joined}" unless _.isEmpty a
assert @stsheets = previous.concat direction
assert @stsheets = _.unique this.stsheets
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
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 OWNER 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.
###
_ = require "lodash"
bower = require "bower"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
events = require "eventemitter2"
assert = require "assert"
colors = require "colors"
crypto = require "crypto"
nconf = require "nconf"
https = require "https"
path = require "path"
http = require "http"
util = require "util"
{Barebones} = require "./skeleton"
{Extending} = require "../nucleus/extends"
{Composition} = require "../nucleus/compose"
{BowerSupport} = require "../applied/bower"
{Archetype} = require "../nucleus/arche"
# A complementary part of the preflight procedures that provides the
# ability to create and emit arbitrary linkage in the contexts that
# are going to be assembled within the current preflight hierarchy.
# The facilities of this toolkit should typically be used when you
# need to link to a static asset file, within any domain or path.
module.exports.LinksToolkit = class LinksToolkit extends Barebones
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: jscripts: 1, stsheets: 1, metatags: 1
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an asynchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
identify = try @constructor.identify().underline
message = "Flushing out the JS/CSS linkage in %s"
assert _.isString(symbol), "cannot found symbol"
assert _.isObject(context), "located no context"
assert _.isObject(request), "located no request"
assert _.isFunction(next), "got no next function"
logger.debug message.yellow, identify.toString()
gx = (key) => this.constructor[key] or Array()
sx = (key, s) => context[key].push v for v in s
fx = (inp, out) => try sx out, _.unique(gx(inp))
ax = (mapping) => fx(k, v) for k, v of mapping
ax metatags: "metatag" # map metatags to context
ax jscripts: "scripts" # map scripts to context
ax stsheets: "sheets" # map styles to context
return do => next.call this # asynchronous
# This is a preflight directive that can be used to generate and
# emit meta tags for the client browser. The directive expects a
# aggregate definition (an object) whose key/value pairs will be
# diretly corellated as parameter name and value for a meta tag
# definition. Any number of pairs (parameters) may be supplied.
@metatag: (aggregate) ->
assert identify = this.identify().toString()
failed = "argument has to be the plain object"
message = "Setting metatags information in %s"
noPrevious = "found invalid previous metatags"
assert _.all(_.values(aggregate), _.isString)
assert previous = this.metatags or new Array()
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isPlainObject(aggregate or 0), failed
format = (val, key) -> "#{key}=\x22#{val}\x22"
_.map aggregate, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join " "
@metatags = previous.concat joined.toString()
logger.debug message.grey, identify.underline
return aggregate # return the object back
# This is a preflight directive that can be used to link any
# arbitrary JavaScript file source. Is important do understand
# that this directive only compiles the appropriate statement
# to be transferred to the server and it is up to you to ensure
# the existence of that file and its ability to be downloaded.
@javascript: (xparameter, xdirection) ->
assert previous = this.jscripts or Array()
assert identify = this.identify().toString()
parameter = _.find arguments or [], _.isObject
direction = _.find arguments or [], _.isString
message = "Adding JavaScript information in %s"
indirect = "an inalid direction have supplied"
noPrevious = "found invalid previous jscripts"
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isString(direction or null), indirect
format = (val, key) -> return "#{key}=#{val}"
_.map parameter, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join "&"
logger.debug message.grey, identify.underline
direction += "?#{joined}" unless _.isEmpty a
assert @jscripts = previous.concat direction
assert @jscripts = _.unique this.jscripts
# This is a preflight directive that can be used to link any
# arbitrary CSS style file source. Is important do understand
# that this directive only compiles the appropriate statement
# to be transferred to the server and it is up to you to ensure
# the existence of that file and its ability to be downloaded.
@stylesheet: (xoptions, xdirection) ->
assert previous = this.stsheets or Array()
assert identify = this.identify().toString()
parameter = _.find arguments or [], _.isObject
direction = _.find arguments or [], _.isString
message = "Adding Stylesheet information in %s"
indirect = "an inalid direction have supplied"
noPrevious = "found invalid previous stsheets"
assert _.isEmpty a = accumulate = new Array()
assert _.isArray(previous or null), noPrevious
assert _.isString(direction or null), indirect
format = (val, key) -> return "#{key}=#{val}"
_.map parameter, (v, k) -> a.push format(v, k)
assert _.isString joined = accumulate.join "&"
logger.debug message.grey, identify.underline
direction += "?#{joined}" unless _.isEmpty a
assert @stsheets = previous.concat direction
assert @stsheets = _.unique this.stsheets
|
[
{
"context": "align correctly\", ->\n editor.setText \"a::a::a:1\\nbbb::bbb=ccc:1\"\n editor.selectAll()",
"end": 2566,
"score": 0.7463645339012146,
"start": 2562,
"tag": "IP_ADDRESS",
"value": "a::a"
},
{
"context": " expect(editor.lineTextForBufferRow 0).toEq... | spec/atom-alignment-spec.coffee | papermoon1978/atom-alignment-fork | 0 | Aligner = require '../lib/aligner.coffee'
# Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
#
# To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
# or `fdescribe`). Remove the `f` to unfocus the block.
describe "atom-alignment", ->
leftSpaceChars = ['=>', ':=', '=']
rightSpaceChars = ['=>', ':=', '=', ':']
matcher = ['=>', ':=', ':', '=']
ignoreChars = ['===', '==', '!==', '!=', '::']
editor = null
align = (callback) ->
runs(callback)
beforeEach ->
waitsForPromise ->
atom.workspace.open()
runs ->
editor = atom.workspace.getActiveTextEditor()
editorView = atom.views.getView(editor)
return
describe "when aligner is called on one line only", ->
it "has to break the line", ->
editor.setText "var a = 1; var b = 2;"
editor.setCursorScreenPosition([1, 1])
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var b = 2;"
describe "when aligner is called on multiple lines with only one matcher", ->
it "should align correctly", ->
editor.setText "var a = 1;\nvar bbb = 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = 2;"
describe "when aligner is called on multiple lines with different matchers", ->
it "should align correctly", ->
editor.setText "var a = 1; b:2; c:3;d=4\nvar bbb : 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb : 2;"
describe "when aligner is called on lines with multiple char matchers", ->
it "should align correctly", ->
editor.setText "var a => 1; b = 2;\nvar bbb => 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb => 2;"
describe "when aligner is called on lines with ignore chars", ->
it "should align correctly", ->
editor.setText "a::a::a:1\nbbb::bbb=ccc:1"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a::a::a : 1"
describe "when there is everything put together (1)", ->
it "should align correctly", ->
editor.setText "a::a=b=c=>d\naaaaa=b=>a\nfffffffffff=ffffffff=>h"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a::a = b = c => d"
expect(editor.lineTextForBufferRow 1).toEqual "aaaaa = b => a"
expect(editor.lineTextForBufferRow 2).toEqual "fffffffffff = ffffffff => h"
describe "when there is everything put together (2)", ->
it "should align correctly", ->
editor.setText "a=b=>c\naa=bb=>cc\nb=>c=a\nbb=>cc=aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = b => c"
expect(editor.lineTextForBufferRow 1).toEqual "aa = bb => cc"
expect(editor.lineTextForBufferRow 2).toEqual "b=>c = a"
expect(editor.lineTextForBufferRow 3).toEqual "bb=>cc = aa"
describe "when indentation is mixed with spaces and tabs", ->
it "should align correctly", ->
editor.setText "aa = 4\na = 1\nb = 2\nc::3=4"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "aa = 4"
expect(editor.lineTextForBufferRow(1).replace(/\t/g,"t")).toEqual "at = 1" #specs cannot handle tabs ... wtf?
expect(editor.lineTextForBufferRow 2).toEqual "b = 2"
expect(editor.lineTextForBufferRow 3).toEqual "c::3 = 4"
describe "when matcher with left and right space prefix are mixed", ->
it "should align correctly", ->
editor.setText "a=1a : 1\nb = 2c::ab :2"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1a : 1"
expect(editor.lineTextForBufferRow 1).toEqual "b = 2c::ab: 2"
describe "when there are some matcher to ignore", ->
it "should align correctly", ->
editor.setText "a = a = b => c\na => a = b => c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = a = b => c"
expect(editor.lineTextForBufferRow 1).toEqual "a => a = b => c"
describe "when matcher is the first character on the line", ->
it "should align correctly", ->
editor.setText "a=a\n=c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = a"
expect(editor.lineTextForBufferRow 1).toEqual " = c"
describe "when there is nothing to do", ->
it "should keep the intendation and remove duplicate blanks", ->
editor.setText " a::a::b a\nb::b::c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual " a::a::b a"
expect(editor.lineTextForBufferRow 1).toEqual "b::b::c"
describe "when there are multiple separators, but we only want to align the first one", ->
it "should align the first one, but in any case remove duplicate blanks", ->
editor.setText "a=1 b=2\na =2 b =1"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(false)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1 b=2"
expect(editor.lineTextForBufferRow 1).toEqual "a = 2 b =1"
leftSpaceChars2 = ['=', ':']
rightSpaceChars2 = ['=', ':']
matcher2 = [':', '=', '|']
ignoreChars2 = ['===', '==', '!==', '!=']
describe "run 2 when aligner is called on one line only", ->
it "has to break the line", ->
editor.setText "var a = 1; var b = 2;"
editor.setCursorScreenPosition([1, 1])
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var b = 2;"
describe "run 2 when aligner is called on multiple lines with only one matcher", ->
it "should align correctly", ->
editor.setText "var a = 1;\nvar bbb = 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = 2;"
describe "run 2 when aligner is called on multiple lines with different matchers", ->
it "should align correctly", ->
editor.setText "var a = 1; b:2; c:3;d=4\nvar bbb : 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb : 2;"
describe "run 2 when aligner is called on lines with multiple char matchers", ->
it "should align correctly", ->
editor.setText "var a => 1; b = 2;\nvar bbb => 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = > 2;"
describe "run 2 when aligner is called on lines with ignore chars", ->
it "should align correctly", ->
editor.setText "a==a::a:1\nbbb::bbb=ccc:1"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a==a : : a : 1"
describe "run 2 when there is everything put together (1)", ->
it "should align correctly", ->
editor.setText "a::a=b=c=>d\naaaaa=b=>a\nfffffffffff=ffffffff=>h"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a : : a = b = c = >d"
expect(editor.lineTextForBufferRow 1).toEqual "aaaaa = b = >a"
expect(editor.lineTextForBufferRow 2).toEqual "fffffffffff = ffffffff = >h"
describe "run 2 when there is everything put together (2)", ->
it "should align correctly", ->
editor.setText "a=b=>c\naa=bb=>cc\nb=>c=a\nbb=>cc=aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = b = >c"
expect(editor.lineTextForBufferRow 1).toEqual "aa = bb = >cc"
expect(editor.lineTextForBufferRow 2).toEqual "b = >c = a"
expect(editor.lineTextForBufferRow 3).toEqual "bb = >cc = aa"
describe "run 2 when indentation is mixed with spaces and tabs", ->
it "should align correctly", ->
editor.setText "aa = 4\na = 1\nb = 2\nc::3=4"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "aa = 4"
expect(editor.lineTextForBufferRow(1).replace(/\t/g,"t")).toEqual "at = 1" #specs cannot handle tabs ... wtf?
expect(editor.lineTextForBufferRow 2).toEqual "b = 2"
expect(editor.lineTextForBufferRow 3).toEqual "c : : 3 = 4"
describe "run 2 when matcher with left and right space prefix are mixed", ->
it "should align correctly", ->
editor.setText "a=1a : 1\nb = 2c::ab :2"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1a : 1"
expect(editor.lineTextForBufferRow 1).toEqual "b = 2c : : ab : 2"
describe "run 2 when there are some matcher to ignore", ->
it "should align correctly", ->
editor.setText "a== = a = b => c\na => ==a = b => c"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a== = a = b = > c"
expect(editor.lineTextForBufferRow 1).toEqual "a = > ==a = b = > c"
describe "when character | (pipe) should be aligned", ->
it "should align correctly", ->
editor.setText "a|1|a\naa|1|aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a |1|a"
| 139309 | Aligner = require '../lib/aligner.coffee'
# Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
#
# To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
# or `fdescribe`). Remove the `f` to unfocus the block.
describe "atom-alignment", ->
leftSpaceChars = ['=>', ':=', '=']
rightSpaceChars = ['=>', ':=', '=', ':']
matcher = ['=>', ':=', ':', '=']
ignoreChars = ['===', '==', '!==', '!=', '::']
editor = null
align = (callback) ->
runs(callback)
beforeEach ->
waitsForPromise ->
atom.workspace.open()
runs ->
editor = atom.workspace.getActiveTextEditor()
editorView = atom.views.getView(editor)
return
describe "when aligner is called on one line only", ->
it "has to break the line", ->
editor.setText "var a = 1; var b = 2;"
editor.setCursorScreenPosition([1, 1])
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var b = 2;"
describe "when aligner is called on multiple lines with only one matcher", ->
it "should align correctly", ->
editor.setText "var a = 1;\nvar bbb = 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = 2;"
describe "when aligner is called on multiple lines with different matchers", ->
it "should align correctly", ->
editor.setText "var a = 1; b:2; c:3;d=4\nvar bbb : 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb : 2;"
describe "when aligner is called on lines with multiple char matchers", ->
it "should align correctly", ->
editor.setText "var a => 1; b = 2;\nvar bbb => 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb => 2;"
describe "when aligner is called on lines with ignore chars", ->
it "should align correctly", ->
editor.setText "a::fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:1\nbbb::bbb=ccc:1"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a::fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b : 1"
describe "when there is everything put together (1)", ->
it "should align correctly", ->
editor.setText "a::a=b=c=>d\naaaaa=b=>a\nfffffffffff=ffffffff=>h"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a::a = b = c => d"
expect(editor.lineTextForBufferRow 1).toEqual "aaaaa = b => a"
expect(editor.lineTextForBufferRow 2).toEqual "fffffffffff = ffffffff => h"
describe "when there is everything put together (2)", ->
it "should align correctly", ->
editor.setText "a=b=>c\naa=bb=>cc\nb=>c=a\nbb=>cc=aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = b => c"
expect(editor.lineTextForBufferRow 1).toEqual "aa = bb => cc"
expect(editor.lineTextForBufferRow 2).toEqual "b=>c = a"
expect(editor.lineTextForBufferRow 3).toEqual "bb=>cc = aa"
describe "when indentation is mixed with spaces and tabs", ->
it "should align correctly", ->
editor.setText "aa = 4\na = 1\nb = 2\nc::3=4"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "aa = 4"
expect(editor.lineTextForBufferRow(1).replace(/\t/g,"t")).toEqual "at = 1" #specs cannot handle tabs ... wtf?
expect(editor.lineTextForBufferRow 2).toEqual "b = 2"
expect(editor.lineTextForBufferRow 3).toEqual "c::3 = 4"
describe "when matcher with left and right space prefix are mixed", ->
it "should align correctly", ->
editor.setText "a=1a : 1\nb = fc00:db20:35b:7399::5 :2"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1a : 1"
expect(editor.lineTextForBufferRow 1).toEqual "b = fc00:db20:35b:7399::5: 2"
describe "when there are some matcher to ignore", ->
it "should align correctly", ->
editor.setText "a = a = b => c\na => a = b => c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = a = b => c"
expect(editor.lineTextForBufferRow 1).toEqual "a => a = b => c"
describe "when matcher is the first character on the line", ->
it "should align correctly", ->
editor.setText "a=a\n=c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = a"
expect(editor.lineTextForBufferRow 1).toEqual " = c"
describe "when there is nothing to do", ->
it "should keep the intendation and remove duplicate blanks", ->
editor.setText " a::a::b a\nb::b::c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual " a::a::b a"
expect(editor.lineTextForBufferRow 1).toEqual "b::b::c"
describe "when there are multiple separators, but we only want to align the first one", ->
it "should align the first one, but in any case remove duplicate blanks", ->
editor.setText "a=1 b=2\na =2 b =1"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(false)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1 b=2"
expect(editor.lineTextForBufferRow 1).toEqual "a = 2 b =1"
leftSpaceChars2 = ['=', ':']
rightSpaceChars2 = ['=', ':']
matcher2 = [':', '=', '|']
ignoreChars2 = ['===', '==', '!==', '!=']
describe "run 2 when aligner is called on one line only", ->
it "has to break the line", ->
editor.setText "var a = 1; var b = 2;"
editor.setCursorScreenPosition([1, 1])
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var b = 2;"
describe "run 2 when aligner is called on multiple lines with only one matcher", ->
it "should align correctly", ->
editor.setText "var a = 1;\nvar bbb = 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = 2;"
describe "run 2 when aligner is called on multiple lines with different matchers", ->
it "should align correctly", ->
editor.setText "var a = 1; b:2; c:3;d=4\nvar bbb : 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb : 2;"
describe "run 2 when aligner is called on lines with multiple char matchers", ->
it "should align correctly", ->
editor.setText "var a => 1; b = 2;\nvar bbb => 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = > 2;"
describe "run 2 when aligner is called on lines with ignore chars", ->
it "should align correctly", ->
editor.setText "a==a::a:1\nbbb::bbb=ccc:1"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a==a : : a : 1"
describe "run 2 when there is everything put together (1)", ->
it "should align correctly", ->
editor.setText "a::a=b=c=>d\naaaaa=b=>a\nfffffffffff=ffffffff=>h"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a : : a = b = c = >d"
expect(editor.lineTextForBufferRow 1).toEqual "aaaaa = b = >a"
expect(editor.lineTextForBufferRow 2).toEqual "fffffffffff = ffffffff = >h"
describe "run 2 when there is everything put together (2)", ->
it "should align correctly", ->
editor.setText "a=b=>c\naa=bb=>cc\nb=>c=a\nbb=>cc=aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = b = >c"
expect(editor.lineTextForBufferRow 1).toEqual "aa = bb = >cc"
expect(editor.lineTextForBufferRow 2).toEqual "b = >c = a"
expect(editor.lineTextForBufferRow 3).toEqual "bb = >cc = aa"
describe "run 2 when indentation is mixed with spaces and tabs", ->
it "should align correctly", ->
editor.setText "aa = 4\na = 1\nb = 2\nc::3=4"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "aa = 4"
expect(editor.lineTextForBufferRow(1).replace(/\t/g,"t")).toEqual "at = 1" #specs cannot handle tabs ... wtf?
expect(editor.lineTextForBufferRow 2).toEqual "b = 2"
expect(editor.lineTextForBufferRow 3).toEqual "c : : 3 = 4"
describe "run 2 when matcher with left and right space prefix are mixed", ->
it "should align correctly", ->
editor.setText "a=1a : 1\nb = 2fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b :2"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1a : 1"
expect(editor.lineTextForBufferRow 1).toEqual "b = 2c : : ab : 2"
describe "run 2 when there are some matcher to ignore", ->
it "should align correctly", ->
editor.setText "a== = a = b => c\na => ==a = b => c"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a== = a = b = > c"
expect(editor.lineTextForBufferRow 1).toEqual "a = > ==a = b = > c"
describe "when character | (pipe) should be aligned", ->
it "should align correctly", ->
editor.setText "a|1|a\naa|1|aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a |1|a"
| true | Aligner = require '../lib/aligner.coffee'
# Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
#
# To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
# or `fdescribe`). Remove the `f` to unfocus the block.
describe "atom-alignment", ->
leftSpaceChars = ['=>', ':=', '=']
rightSpaceChars = ['=>', ':=', '=', ':']
matcher = ['=>', ':=', ':', '=']
ignoreChars = ['===', '==', '!==', '!=', '::']
editor = null
align = (callback) ->
runs(callback)
beforeEach ->
waitsForPromise ->
atom.workspace.open()
runs ->
editor = atom.workspace.getActiveTextEditor()
editorView = atom.views.getView(editor)
return
describe "when aligner is called on one line only", ->
it "has to break the line", ->
editor.setText "var a = 1; var b = 2;"
editor.setCursorScreenPosition([1, 1])
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var b = 2;"
describe "when aligner is called on multiple lines with only one matcher", ->
it "should align correctly", ->
editor.setText "var a = 1;\nvar bbb = 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = 2;"
describe "when aligner is called on multiple lines with different matchers", ->
it "should align correctly", ->
editor.setText "var a = 1; b:2; c:3;d=4\nvar bbb : 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb : 2;"
describe "when aligner is called on lines with multiple char matchers", ->
it "should align correctly", ->
editor.setText "var a => 1; b = 2;\nvar bbb => 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb => 2;"
describe "when aligner is called on lines with ignore chars", ->
it "should align correctly", ->
editor.setText "a::PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI:1\nbbb::bbb=ccc:1"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a::PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI : 1"
describe "when there is everything put together (1)", ->
it "should align correctly", ->
editor.setText "a::a=b=c=>d\naaaaa=b=>a\nfffffffffff=ffffffff=>h"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a::a = b = c => d"
expect(editor.lineTextForBufferRow 1).toEqual "aaaaa = b => a"
expect(editor.lineTextForBufferRow 2).toEqual "fffffffffff = ffffffff => h"
describe "when there is everything put together (2)", ->
it "should align correctly", ->
editor.setText "a=b=>c\naa=bb=>cc\nb=>c=a\nbb=>cc=aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = b => c"
expect(editor.lineTextForBufferRow 1).toEqual "aa = bb => cc"
expect(editor.lineTextForBufferRow 2).toEqual "b=>c = a"
expect(editor.lineTextForBufferRow 3).toEqual "bb=>cc = aa"
describe "when indentation is mixed with spaces and tabs", ->
it "should align correctly", ->
editor.setText "aa = 4\na = 1\nb = 2\nc::3=4"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "aa = 4"
expect(editor.lineTextForBufferRow(1).replace(/\t/g,"t")).toEqual "at = 1" #specs cannot handle tabs ... wtf?
expect(editor.lineTextForBufferRow 2).toEqual "b = 2"
expect(editor.lineTextForBufferRow 3).toEqual "c::3 = 4"
describe "when matcher with left and right space prefix are mixed", ->
it "should align correctly", ->
editor.setText "a=1a : 1\nb = PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI :2"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1a : 1"
expect(editor.lineTextForBufferRow 1).toEqual "b = PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI: 2"
describe "when there are some matcher to ignore", ->
it "should align correctly", ->
editor.setText "a = a = b => c\na => a = b => c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = a = b => c"
expect(editor.lineTextForBufferRow 1).toEqual "a => a = b => c"
describe "when matcher is the first character on the line", ->
it "should align correctly", ->
editor.setText "a=a\n=c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = a"
expect(editor.lineTextForBufferRow 1).toEqual " = c"
describe "when there is nothing to do", ->
it "should keep the intendation and remove duplicate blanks", ->
editor.setText " a::a::b a\nb::b::c"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual " a::a::b a"
expect(editor.lineTextForBufferRow 1).toEqual "b::b::c"
describe "when there are multiple separators, but we only want to align the first one", ->
it "should align the first one, but in any case remove duplicate blanks", ->
editor.setText "a=1 b=2\na =2 b =1"
editor.selectAll()
new Aligner(editor, leftSpaceChars, rightSpaceChars, matcher, ignoreChars).align(false)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1 b=2"
expect(editor.lineTextForBufferRow 1).toEqual "a = 2 b =1"
leftSpaceChars2 = ['=', ':']
rightSpaceChars2 = ['=', ':']
matcher2 = [':', '=', '|']
ignoreChars2 = ['===', '==', '!==', '!=']
describe "run 2 when aligner is called on one line only", ->
it "has to break the line", ->
editor.setText "var a = 1; var b = 2;"
editor.setCursorScreenPosition([1, 1])
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var b = 2;"
describe "run 2 when aligner is called on multiple lines with only one matcher", ->
it "should align correctly", ->
editor.setText "var a = 1;\nvar bbb = 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = 2;"
describe "run 2 when aligner is called on multiple lines with different matchers", ->
it "should align correctly", ->
editor.setText "var a = 1; b:2; c:3;d=4\nvar bbb : 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb : 2;"
describe "run 2 when aligner is called on lines with multiple char matchers", ->
it "should align correctly", ->
editor.setText "var a => 1; b = 2;\nvar bbb => 2;"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 1).toEqual "var bbb = > 2;"
describe "run 2 when aligner is called on lines with ignore chars", ->
it "should align correctly", ->
editor.setText "a==a::a:1\nbbb::bbb=ccc:1"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a==a : : a : 1"
describe "run 2 when there is everything put together (1)", ->
it "should align correctly", ->
editor.setText "a::a=b=c=>d\naaaaa=b=>a\nfffffffffff=ffffffff=>h"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a : : a = b = c = >d"
expect(editor.lineTextForBufferRow 1).toEqual "aaaaa = b = >a"
expect(editor.lineTextForBufferRow 2).toEqual "fffffffffff = ffffffff = >h"
describe "run 2 when there is everything put together (2)", ->
it "should align correctly", ->
editor.setText "a=b=>c\naa=bb=>cc\nb=>c=a\nbb=>cc=aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = b = >c"
expect(editor.lineTextForBufferRow 1).toEqual "aa = bb = >cc"
expect(editor.lineTextForBufferRow 2).toEqual "b = >c = a"
expect(editor.lineTextForBufferRow 3).toEqual "bb = >cc = aa"
describe "run 2 when indentation is mixed with spaces and tabs", ->
it "should align correctly", ->
editor.setText "aa = 4\na = 1\nb = 2\nc::3=4"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "aa = 4"
expect(editor.lineTextForBufferRow(1).replace(/\t/g,"t")).toEqual "at = 1" #specs cannot handle tabs ... wtf?
expect(editor.lineTextForBufferRow 2).toEqual "b = 2"
expect(editor.lineTextForBufferRow 3).toEqual "c : : 3 = 4"
describe "run 2 when matcher with left and right space prefix are mixed", ->
it "should align correctly", ->
editor.setText "a=1a : 1\nb = 2PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI :2"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a = 1a : 1"
expect(editor.lineTextForBufferRow 1).toEqual "b = 2c : : ab : 2"
describe "run 2 when there are some matcher to ignore", ->
it "should align correctly", ->
editor.setText "a== = a = b => c\na => ==a = b => c"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a== = a = b = > c"
expect(editor.lineTextForBufferRow 1).toEqual "a = > ==a = b = > c"
describe "when character | (pipe) should be aligned", ->
it "should align correctly", ->
editor.setText "a|1|a\naa|1|aa"
editor.selectAll()
new Aligner(editor, leftSpaceChars2, rightSpaceChars2, matcher2, ignoreChars2).align(true)
align ->
expect(editor.lineTextForBufferRow 0).toEqual "a |1|a"
|
[
{
"context": "lcome. Do not hesitate to contact me, my email is: jetic@me.com\n# Refreshing Frequency is set to once every 3000m",
"end": 522,
"score": 0.9999270439147949,
"start": 510,
"tag": "EMAIL",
"value": "jetic@me.com"
},
{
"context": "oard.widget.zip https://raw.githubusercon... | Eva.widget/index.coffee | viridityzhu/Evangelion-Uebersicht-Widget | 0 | Version = "0.X14.4a"
config = {
Magnification: 1.0
BatteryAlertLevel: 20
CPUAlertLevel: 90
Opacity: 0.5
Voice: false
colourIdle: "rgba(50,50,50,1)" # 10,10,10 black
colourWarn: "rgba(256,0,0,1)"
colourDNDS: "rgba(256,96,0,1)"
colourWhit: "rgba(256,256,256,1)"
colourIdleHover: "rgba(128,128,128,1)"
colourWarnHover: "rgba(128,0,0,1)"
ShowUpdates: true
remoteBranch: "dev"
}
## Any advise or new idea is welcome. Do not hesitate to contact me, my email is: jetic@me.com
# Refreshing Frequency is set to once every 3000ms
refreshFrequency: 30000
# Information on cells Cells consists of three parts. A main body(nav), a top and a bottom(s and b). Cells are rotated 90 degrees to the current position.
# For special cells (Battery cell, iTunes cell), the toppings and bottoms are slightly different, for example s1, s2, b1, b2, these are modified to cover the gaps between the originally seperated cells.
# Almost all the elements in the cells are positioned manually, this is to ensure that the UI looks exactly the same on different environments.
# Übersicht is using the safari engine to render the widgets, therefore the UI under different versions of Safari could be different.
# classes like a0, a1, a2, battCells, a4 act as collective cell controlls allowing me to change the output of all related cells when necessary.
# ai cells are initially hidden;
# a1 and a2 are used to adjust the lines so that the cells won't crash into each other;
# battCells is the battery cell;
# a4 is the console output cell;
# ax hasn't been used.
# Contents in the cells can use the classes content of bigger text or contents for smaller text, although most of the time it might be better to adjust the font-size manually.
# It is obvious that some of the cells are hidden(ai), these can be easily modified to display new contents as you like.
# You can change the size through adjusting the font-size under style. Default is 1px
style: """
font-size: #{config.Magnification}px
top: -25em
font-family: Futura
text-transform: uppercase
position:relative
opacity: #{config.Opacity}
margin:0
text-align:center
text-decoration:none
.left
position: fixed
bottom: -25em
left:-100em
width: 800em
float:left
vertical-align : bottom
.right
float:right
margin-right:-60em
.nav
text-decoration: none
transform:rotate(90deg)
width:100em;height:58em
background:#{config.colourIdle}
display:inline-block
position:relative
line-height:58em
color:#ffffff
float:right
margin-top:-5em
margin-left:45em
margin-right:45em
.nav d
width:0;height:0
display:block
overflow:hidden
position:absolute
border-left:0.4em dotted transparent
border-right:0.4em dotted transparent
border-bottom:0.8em solid #{config.colourWhit}
bottom:3.33333em
right: 2.93333em
.nav u
width:0;height:0
display:block
overflow:hidden
position:absolute
border-left:0.4em dotted transparent
border-right:0.4em dotted transparent
border-top:0.8em solid #{config.colourWhit}
top:3.33333em
right:2.93333em
.nav o
display:block
overflow:hidden
position:absolute
border-right:2em solid #{config.colourWhit}
border-left:2em solid #{config.colourWhit}
padding-right:88em
padding-top:52em
left:4em
top:3em
.nav s
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:50em dotted transparent
border-left:50em dotted transparent
border-bottom:30em solid #{config.colourIdle}
right:0em
top:-30em
.nav b
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:50em dotted transparent
border-left:50em dotted transparent
border-top:30em solid #{config.colourIdle}
bottom:-30em
right:0em
.nav b1
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:0em dotted transparent
border-left:100em dotted transparent
border-top:60em solid #{config.colourIdle}
bottom:-60em
right:0em
.nav b2
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:100em dotted transparent
border-left:0em dotted transparent
border-top:60em solid #{config.colourIdle}
bottom:-60em
right:0em
.nav b3
margin-left:10em
width:100em
height:0
display:block
position:absolute
background-color: #{config.colourIdle}
border-top:95em solid #{config.colourIdle}
right:0em
bottom:-95em
.nav s1
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:0em dotted transparent
border-left:100em dotted transparent
border-bottom:60em solid #{config.colourIdle}
right:0em
top:-60em
.nav s2
margin-left:10em
width:100em
height:0
display:block
position:absolute
background-color: #{config.colourIdle}
border-bottom:95em solid #{config.colourIdle}
right:0em
top:-95em
.a0, .a0 s, .a0 b
@keyframes meow { from { opacity:1; } to { opacity:0.6; } }
.a1
margin-right:140em
.ai
/* visibility: hidden */
.a4
background:rgba(0,0,0,0)
.nav:hover a0 s
border-top-color:#{config.colourIdleHover}
.nav:hover a0 b
border-top-color:#{config.colourIdleHover}
.a4 s, .a4 s2, .a4 b, .a4 b1, .a4 b2, .a4 b3
border-bottom-color:rgba(10,10,10,0)
border-top-color:rgba(10,10,10,0)
border-left-color:rgba(10,10,10,0)
border-right-color:rgba(10,10,10,0)
background-color:rgba(10,10,10,0)
.ax
height:200em
.a1:hover, .a2:hover, .battCells:hover
background-color:#{config.colourIdleHover}
.a1:hover s, .a2:hover s, .battCells:hover s
border-bottom-color:#{config.colourIdleHover}
.a1:hover b, .a2:hover b, .battCells:hover b
border-top-color:#{config.colourIdleHover}
.output
padding: 5em 10em
font-size: 30em
font-weight: 100
text-shadow: 0 0em 5em #000000
background-color: rgba(0,0,0,0.2)
border: 1em solid #fff
.content
transform:rotate(-90deg)
font-style: Black
z-index:99999
.clock
font-size: 30em
.sal
font-family: Songti SC
font-style: Black
font-size:40em
.Wcontent
transform:rotate(-90deg)
font-style: Black
font-size: 15em
z-index:99999
visibility:hidden
.contentS
transform:rotate(-90deg)
font-style: Black
z-index:99999
.Bat
font-weight: bold
font-size: 15em
text-transform: uppercase
.id
font-size:20em
font-family:Futura
font-style:normal
.BatStatus
font-weight: bold
font-size: 20em
text-transform: uppercase
.Rotate
transform:rotate(-90deg)
width:200em
.iTunesPre
width:0;height:0
position:relative
border-right:11em dotted transparent
border-left:11em dotted transparent
border-top:20em solid #{config.colourWhit}
right:-40em
top:-10em
.iTunesNext
width:0;height:0
position:relative
border-right:11em dotted transparent
border-left:11em dotted transparent
border-bottom:20em solid #{config.colourWhit}
right:-40em
top:-260em
.iTunesPause
width:30em;height:8em
position:relative
border-top:8em solid #{config.colourWhit}
border-bottom:8em solid #{config.colourWhit}
right:-37em
top:-100em
.iTunesPlay
width:0;height:0
position:relative
border-right:17em dotted transparent
border-left:17em dotted transparent
border-bottom:30em solid #{config.colourWhit}
right:-35em
top:-170em
.iTunesPlay:active
border-bottom-color: #{config.colourIdleHover}
.iTunesPause:active
border-top-color: #{config.colourIdleHover}
border-bottom-color: #{config.colourIdleHover}
.iTunesNext:active
border-bottom-color: #{config.colourIdleHover}
.iTunesPre:active
border-top-color: #{config.colourIdleHover}
.Disk
background-color: rgba(226,161,54,1)
position: relative
font-size: 10em
left: 1em; top:0.7em
width:5em;height:4em
border:0.2em solid #{config.colourWhit}
border-right: 0.5em solid #{config.colourWhit}
z-index:99999
.DiskN
width: 9em; height:4em
margin-left:2em;
margin-top:-3.5em;
text-overflow:ellipsis;
overflow:hidden;
font-size:10em
transform:rotate(-90deg)
font-style: Black
z-index:99999
.iTunesCover
position: fixed;
left:410em; bottom:500em;
width:200em; height:200em;
background-color: #{config.colourIdle};
z-index:99999
.iTunesCoverMask
color:white
position: fixed;
margin-left:5em; margin-top:5em;
width: 190em; height: 190em;
background-color: rgba(10,10,10,0.75);
.iTunesRatingBlock
width:33em;height:10em;
margin-left:1em;margin-right:1em;
background-color: rgba(256,256,256,0.5);
display:inline-block;
"""
render: -> """
<div class="left" style="float:left">
<div class="iTunesCover CoverCell">
<div class="iTunesCoverMask">
<div style="font-size:30em;font-family:IMPACT">SEELE</div>
<div style="font-size:70em;font-family:IMPACT" id="iTunesTrack">00</div>
<div style="font-size:30em;font-family:IMPACT">SOUND</div>
<div style="font-size:30em;font-family:IMPACT">ONLY</div>
</div>
<div style="width:190em;height:190em;margin-top:5em" id="iTunesCoverImg"></div>
<div class="iTunesRatingBlock" id="rate1"></div>
<div class="iTunesRatingBlock" id="rate2"></div>
<div class="iTunesRatingBlock" id="rate3"></div>
<div class="iTunesRatingBlock" id="rate4"></div>
<div class="iTunesRatingBlock" id="rate5"></div>
</div>
<div class="nav a2 CoverCell" target="_blank" href="#" id="44"><s></s><b1></b1></div>
<div class="nav a2 CoverCell" target="_blank" href="#" id="45"><s1></s1><b></b></div>
<div class="nav a0" target="_blank" href="#" id="46"><s></s><b></b>
<div class="id">46</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="47"><s></s><b></b>
<div class="id">47</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 CoverCell" target="_blank" href="#" id="48"><s></s><b2></b2></div>
<div class="nav a0" target="_blank" href="#" id="49"><s></s><b></b>
<div class="id">49</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="50"><s></s><b></b>
<div class="id">50</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav ai" target="_blank" href="#" id="51"></div>
<div class="nav a2 NetCell" target="_blank" href="#" style="z-index:9999"><s1></s1><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">Ibytes/s</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-70em;font-family:Futura;font-style:normal">
<span class="NetU" style="font-size:25em">Fehler</span>
</div>
<div class="contentS" style="position:absolute;left:55em;top:-95em;">
<span style="font-size:15em">Obytes/s</span>
</div>
</div>
<div class="nav a5" target="_blank" href="#" id="53"><s1></s1><b1></b1></div>
<div class="nav a0" target="_blank" href="#" id="54"><s></s><b></b>
<div class="id">54</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a2 NetCell" target="_blank" href="#"><s></s><b2></b2>
<div class="content" style="margin-left:30em;margin-top:-4em;font-family:Futura;font-style:normal">
<span class="NetD" style="font-size:25em">Fehler</span>
</div></div>
<div class="nav a5" target="_blank" href="#" id="56"><s></s><b3></b3></div>
<div class="nav a5" target="_blank" href="#" id="57" style="z-index:99999"><s2></s2><b></b>
<div class="Rotate" style="text-overflow:ellipsis;
overflow:hidden;
position:absolute;
top:-85em;left:-20em;
text-align:center;height:40em;width:200em">
<span id="iTunesArtist" style="font-size:12em"></span>
</div>
<div class="Rotate" style="text-overflow:ellipsis;
overflow:hidden;
position:absolute;
top:-85em;left:-92em;
text-align:center;height:40em;width:200em">
<span id="iTunesTitle" style="font-size:12em"></span>
</div>
<div class="iTunesPre"></div><div class="iTunesPre"></div>
<div class="iTunesPause"></div><div class="iTunesPlay"></div>
<div class="iTunesNext"></div><div class="iTunesNext"></div></div>
<div class="nav ai" target="_blank" href="#" id="58"><s></s><b></b></div>
<div class="nav a0" target="_blank" href="#" id="59"><s></s><b></b>
<div class="id">59</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a5" target="_blank" href="#" id="60"><s></s><b2></b2></div>
<div class="nav a0" target="_blank" href="#" id="61"><s></s><b></b>
<div class="id">61</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a2" target="_blank" href="#" id="62" style="margin-right:140em"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="62content"></div></div>
<div class="nav a0" target="_blank" href="#" id="63"><s></s><b></b>
<div class="id">63</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="64"><s></s><b></b>
<div class="id">64</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="65"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="65content"></div></div>
<div class="nav a2" target="_blank" href="#" id="66"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="66content"></div></div>
<div class="nav a0" target="_blank" href="#" id="67"><s></s><b></b>
<div class="id">67</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="68"><s></s><b></b>
<div class="id">68</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a2" target="_blank" href="#" id="69" style="margin-right:140em"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="69content"></div></div>
<div class="nav a0" target="_blank" href="#" id="70"><s></s><b></b>
<div class="id">70</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="71"><s></s><b></b>
<div class="id">71</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="72"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="72content"></div></div>
<div class="nav a0" target="_blank" href="#" id="73"><s></s><b></b>
<div class="id">73</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="74"><s></s><b></b>
<div class="id">74</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="75"><s></s><b></b>
<div class="id">75</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="76"><s></s><b></b>
<div class="id">76</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="77"><s></s><b></b>
<div class="id">77</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="78"><s></s><b></b>
<div class="id">78</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="79"><s></s><b></b>
<div class="id">79</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="80"><s></s><b></b>
<div class="id">80</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="81"><s></s><b></b>
<div class="id">81</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="82"><s></s><b></b>
<div class="id">82</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
</div>
<div class="right">
<div class="nav a0" target="_blank" href="#" id="0"><s></s><b></b>
<div class="id">0</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="1"><s></s><b></b>
<div class="id">1</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="2"><s></s><b></b>
<div class="id">2</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="3"><s></s><b></b>
<div class="id">3</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="4"><s></s><b></b>
<div class="id">4</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="5"><s></s><b></b>
<div class="contentS" style="margin-left:10em;margin-top:0em">
<span class="day" style="width:20em;font-size:15em"></span>
</div></div><p></p>
<div class="nav a0" target="_blank" href="#" id="6"><s></s><b></b>
<div class="id">6</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="7"><s></s><b></b>
<div class="id">7</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="8"><s></s><b></b>
<div class="id">8</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="9"><s></s><b></b>
<div class="content" style="margin-left:10em;margin-top:-5em">
<span class="time" style="font-size:30em;font-family:Futura;font-style:normal"></span>
</div></div><p></p>
<div class="nav a1" target="_blank" href="#" id="CPUCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">CPU</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-70em;font-family:Futura;font-style:normal">
<span class="CPUU" style="font-size:30em;">Fehler</span>
</div></div>
<div class="nav a2" target="_blank" href="#" id="11"><s></s><b></b>
<div class="content" style="margin-left:10em;margin-top:-5em">
<span class="sal"></span>
</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="12"></div>
<div class="nav a0" target="_blank" href="#" id="13"><s></s><b></b>
<div class="id">13</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav battCells" target="_blank" href="#" id="14"><s></s><b1></b1></div>
<div class="nav ai" target="_blank" href="#" id="15"><s></s><b></b>
<div class="contentS" style="margin-left:-25em;margin-top:-4em">
<span style="font-size:15em">verbleibend</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-65em">
<span class="BatRe" style="font-size:30em">Fehler</span>
</div></div><p></p>
<div class="nav a1" target="_blank" href="#" id="MemCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">Speicher</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-55em">
<span class="MEMU" style="font-size:23em">Fehler</span>
</div></div>
<div class="nav battCells" target="_blank" href="#" id="17" style="z-index:9999"><s2></s2><b></b>
<div class="Rotate" style="margin-top:-70em;margin-left:-60em;text-align:left"><span class="Bat"></span></div>
<div class="Rotate" style="margin-top:-65em;margin-left:-35em;text-align:left"><span class="BatStatus"></span></div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="18"></div>
<div class="nav a0" target="_blank" href="#" id="19"><s></s><b></b>
<div class="id">19</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav battCells" target="_blank" href="#" id="BatCell"><s></s><b2></b2>
<div class="Rotate" style="margin-top:-5em;margin-left:-35em;width:200em;text-align:center;font-family:Futura;font-style:normal">
<span class="BatPer" style="font-size:20em">Fehler</span>
</div></div>
<div class="nav a0" target="_blank" href="#" id="21"><s></s><b></b>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="contentS" style="text-decoration:underline overline;font-size:15em"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="22"><s></s><b></b>
<div class="id">22</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="TrashCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em;margin-top:-5em">
<span style="font-size:15em">Papierkorb</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-62em">
<span class="TrashSize" style="font-size:25em">Fehler</span>
</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="24"></div>
<div class="nav a0" target="_blank" href="#" id="25"><s></s><b></b>
<div class="id">25</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="26"><s></s><b></b>
<div class="id">26</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav ai" target="_blank" href="#" id="27" style="background:#{config.colourWarn}">
<s style="border-bottom-color:#{config.colourWarn}"></s>
<b style="border-top-color:#{config.colourWarn}"></b>
<o></o>
<o style="transform:rotate(-60deg)"></o>
<o style="transform:rotate(-120deg)"></o>
<div class="contentS" style="text-align:center;font-size:20em">
Update!
</div>
</div><p></p>
<div class="nav a1" target="_blank" href="#" id="IPCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">PublikIP</span>
</div>
<div class="content" style="margin-left:15em;margin-top:-64em;">
<span class="PubIP" style="font-size:13em;font-family:Futura;font-style:normal">Fehler</span>
</div></div>
<div class="nav a0" target="_blank" href="#" id="29"><s></s><b></b>
<div class="id">29</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="30"></div>
<div class="nav a0" target="_blank" href="#" id="31"><s></s><b></b>
<div class="id">31</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="32"><s></s><div style="font-size:20em">32</div><b></b></div>
<div class="nav ai" target="_blank" href="#" id="33"></div><p></p>
<div class="nav ai" target="_blank" href="#" id="34"></div><p></p>
<div class="nav a4" target="_blank" href="#" id="35" style="margin-right:140em"><s></s><b1></b1></div>
<div class="nav a4" target="_blank" href="#" id="36"><s></s><b1></b1>
<div class='a4x' style="transform:rotate(-90deg);margin-left:-10em;visibility:hidden">
<div style="font-size:20em">OUTPUT</div>
</div>
</div><p></p>
<div class="nav ai" target="_blank" href="#" id="37"></div>
<div class="nav a4" target="_blank" href="#" id="38"><s></s><b3></b3></div>
<div class="nav a4" target="_blank" href="#" id="39"><s2></s2><b3></b3></div>
<div class="nav a4" target="_blank" href="#" id="40" style="z-index:9999"><s2></s2><b></b>
<div class="a4x" style="margin-top:-200em;margin-left:-150em;width:400em;transform:rotate(-90deg);text-align:left;visibility:hidden;line-height:110%">
<span class="OP" style="text-transform:none;font-size:20em;line-height:100%"></span>
</div>
</div>
<p></p>
<div class="nav a4" target="_blank" href="#" id="41" style="margin-right:140em"><s></s><b2></b2></div>
<div class="nav a4" target="_blank" href="#" id="42"><s></s><b2></b2></div><p></p>
<div class="nav ai" target="_blank" href="#" id="43"></div>
</div>
"""
command: ""
afterRender: (domEl) ->
# Define constants
window.segments = ["子時", "丑時", "寅時", "卯時", "辰時", "巳時", "午時", "未時", "申時", "酉時", "戌時", "亥時"]
# I don't know Germany so deleted because I'll reconstruct the code thoroughly
window.voice = "daniel"
window.voiceBatteryLow = "warning, battery level critical"
window.voiceBatteryCharging = "battery charging"
window.voiceCPUzuHohe = "warning, cpu overloaded"
window.voiceMEMzuHohe = "warning, memory pressure too high"
window.voiceNichtStoerenEin = "no disturb mode is on"
window.voiceNichtStoerenAus = "no disturb mode is off"
window.Batterievalues = [
'AC Only'
''
'AC Power'
''
]
window.daylist = [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday'
]
window.TrashEmpty = "Empty"
window.ErrorMessage = "Error"
window.WarningMessage = "WARNING"
window.BatteryStatus = [
'charging'
'charged'
'discharging'
'finishing'
]
window.BatteryType = "internalbattery"
$(domEl).find("#MemCell span").text("Memory")
$(domEl).find("#IPCell span").text("PublicIP")
$(domEl).find("#TrashCell span").text("Trash")
$(domEl).find(".Wcontent ").html("<u></u><d></d>#{window.WarningMessage}")
$(domEl).find("#21 .contentS").html("<u></u><d></d>#{window.WarningMessage}")
# Voice
window.voiceCommand = "say -v " + window.voice + " "
# Initialise warnings
window.Bwarning=0
window.Cwarning=0
window.IPFehler=0
window.Swarning=0
window.Mwarning=0
window.cellColour=-1
window.count = -1
window.BatteryPercentage=""
window.BatteryState=""
window.CPUUsage = ""
window.MemUsage = "1"
window.CPUAmount = ""
window.Disturbvalues = "0"
window.tiktok = -1
$(domEl).on 'click', '.iTunesPre', => @run "osascript -e 'tell application \"iTunes\" to previous track'"
$(domEl).on 'click', '.iTunesNext', => @run "osascript -e 'tell application \"iTunes\" to next track'"
$(domEl).on 'click', '.iTunesPause', => @run "osascript -e 'tell application \"iTunes\" to pause'"
$(domEl).on 'click', '.iTunesPlay', => @run "osascript -e 'tell application \"iTunes\" to play'"
$(domEl).on 'click', '#TrashCell', => @run "osascript -e 'tell application \"Finder\" to empty'"
# Command to open up mounted volumes
$(domEl).on 'click', '#66', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 1 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#69', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 2 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#72', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 3 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#62', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 4 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#65', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 5 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#27', =>
$(domEl).find("#27 .contentS").text("loading")
@run "head -16 Eva.widget/index.coffee > updateConfig.tmp &&
curl -o ../Evangelion_style_dashboard.widget.zip https://raw.githubusercontent.com/jeticg/Evangelion-Uebersicht-Widget/#{config.remoteBranch}/Evangelion_style_dashboard.widget.zip &&
cp -r Eva.widget ../Eva.widget &&
unzip -o ../Evangelion_style_dashboard.widget.zip -d ../ &&
sh ../Eva.widget/updateConfig.sh &&
cp -r ../Eva.widget/* ./Eva.widget/ &&
rm -r ../Evangelion_style_dashboard.widget.zip &&
rm -r ../Eva.widget &&
rm -r ../__MACOSX"
@run "rm Eva.widget/netstat.ipworking", (error, stdout, stderr) ->
@run 'csrutil status', (error, stdout, stderr) ->
if stdout
console.log stdout
if stderr
console.error stderr
update: (output, domEl) ->
# functions
# This is for the warning animations
animation_on = (cell, colour) -> () ->
if colour == 1
$(domEl).find("#{cell}" ).css("animation", "meow 1s linear 0s infinite alternate")
else if colour == 2
$(domEl).find("#{cell}" ).css("animation", "meow 1s linear 0s infinite alternate")
else if colour == 0
animation_off(cell)
animation_off = (cell) ->
$(domEl).find("#{cell} s").css("animation", "")
$(domEl).find("#{cell} b").css("animation", "")
$(domEl).find("#{cell}" ).css("animation", "")
# This function is for changing the colour of cell(s).
colourChange = (cell, colour) ->
if $.type(cell) == "object"
$element = cell
cell = ""
$element.css("background", colour)
else
$element = $(domEl)
$element.find("#{cell}").css("background", colour)
$element.find("#{cell} s").css("border-bottom-color", colour)
$element.find("#{cell} b").css("border-top-color", colour)
$element.find("#{cell} s1").css("border-bottom-color", colour)
$element.find("#{cell} s2").css("border-bottom-color", colour)
$element.find("#{cell} b1").css("border-top-color", colour)
$element.find("#{cell} b2").css("border-top-color", colour)
$element.find("#{cell} b3").css("border-top-color", colour)
# Display disk information
diskDisplay = (cell, tmp) ->
$(domEl).find("#{cell}").css("visibility","visible")
$(domEl).find("#{cell} .DiskN").text("#{tmp[0..(tmp.length-2)]}")
if (tmp.indexOf("@") > -1 )
$(domEl).find("#{cell} .Disk").css("background-color","rgba(128,128,160,1)")
$(domEl).find("#{cell} .Disk").text("Sys。")
else
$(domEl).find("#{cell} .Disk").css("background-color","rgba(226,161,54,1)")
$(domEl).find("#{cell} .Disk").text("Vol。")
# General warning settings. This function is called at the end of each
# widget refreshing.
warning_switch = (red, orange) ->
CorrectColour = 0
if orange > 0
CorrectColour = 2
if red > 0
CorrectColour = 1
if (cellColour != CorrectColour)
cellColour += CorrectColour - cellColour
animation_off(".a0")
for element in $(domEl).find(".a0")
work = (cell) -> () ->
$cell = $(cell)
if cellColour == 1
colourChange($cell, config.colourWarn)
$cell.find(".Wcontent").html("<u></u><d></d>#{WarningMessage}")
$cell.find(".Wcontent").css("visibility","visible")
$cell.find(".id" ).css("display" ,"none" )
else if cellColour == 2
colourChange($cell, config.colourDNDS)
$cell.find(".Wcontent").html("NoDisturb")
$cell.find(".Wcontent").css("visibility","visible")
$cell.find(".id" ).css("display" ,"none" )
else
colourChange($cell, config.colourIdle)
$cell.find(".Wcontent").css("visibility","hidden" )
$cell.find(".id" ).css("display" ,"inline-block")
setTimeout (work(element)), Math.random() * 1000
setTimeout (animation_on(".a0", cellColour)), 1000
convert2B = (input) ->
output = input
if (parseInt(output)>=1024)
output = parseInt(output)/1024
if (parseInt(output)>=1024)
output = parseInt(output)/1024
output = Math.round(output*10)/10 + 'M'
else
output = Math.round(output*10)/10 + 'K'
return output
getTime = () ->
# Processing time
# This is for outputing the time. Nothing really
date = new Date()
hour = date.getHours()
minutes = date.getMinutes()
days = date.getDay()
minutes = "0"+ minutes if minutes < 10
timeSegment = segments[0]
timeSegment = segments[1] if 1 <= hour < 3
timeSegment = segments[2] if 3 <= hour < 5
timeSegment = segments[3] if 5 <= hour < 7
timeSegment = segments[4] if 7 <= hour < 9
timeSegment = segments[5] if 9 <= hour < 11
timeSegment = segments[6] if 11 <= hour < 13
timeSegment = segments[7] if 13 <= hour < 15
timeSegment = segments[8] if 15 <= hour < 17
timeSegment = segments[9] if 17 <= hour < 19
timeSegment = segments[10] if 19 <= hour < 21
timeSegment = segments[11] if 21 <= hour < 23
$(domEl).find('.sal').text("#{timeSegment}")
$(domEl).find('.time').text("#{hour}:#{minutes}")
$(domEl).find('.day').text("#{daylist[days]}")
# Execution
getTime()
window.tiktok += 1
if (window.tiktok == 3)
window.tiktok = 0
# Battery
if (window.tiktok == 0)
@run "sh Eva.widget/battery.sh", (error, stdout, stderr) ->
if (stdout.indexOf("InternalBattery") > -1)
window.Batterievalues = stdout.split(' ')
if (Batterievalues[0].indexOf("InternalBattery") > -1)
$(domEl).find('.Bat').text("#{BatteryType}")
else
$(domEl).find('.Bat').text("#{Batterievalues[0]}")
if (Batterievalues[1].indexOf("id=") > -1)
window.BatteryPercentage=Batterievalues[2]
window.BatteryState=Batterievalues[3]
$(domEl).find('.BatPer').text("#{Batterievalues[2]}")
if (Batterievalues[3].indexOf("discharging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[2]}")
else if (Batterievalues[3].indexOf("charged") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[1]}")
else if (Batterievalues[3].indexOf("charging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[0]}")
else if (Batterievalues[3].indexOf("finishing") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[3]}")
else
$(domEl).find('.BatStatus').text("#{Batterievalues[3]}")
$(domEl).find('.BatRe').text("#{Batterievalues[4]}")
else
window.BatteryPercentage=Batterievalues[1]
window.BatteryState=Batterievalues[2]
$(domEl).find('.BatPer').text("#{Batterievalues[1]}")
if (Batterievalues[2].indexOf("discharging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[2]}")
else if (Batterievalues[2].indexOf("charged") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[1]}")
else if (Batterievalues[2].indexOf("charging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[0]}")
else if (Batterievalues[2].indexOf("finishing") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[3]}")
else
$(domEl).find('.BatStatus').text("#{Batterievalues[2]}")
$(domEl).find('.BatRe').text("#{Batterievalues[3]}")
# CPU and Memory
@run "sh Eva.widget/cpu_mem.sh", (error, stdout, stderr) ->
stdout = stdout.split('\n')
window.CPUUsage = stdout[0].split(' ')
window.MemUsage = stdout[1].split(' ')
window.CPUAmount = stdout[2].split(' ')
$(domEl).find('.CPUU').text("#{Math.floor(CPUUsage/CPUAmount)}%")
if (MemUsage.indexOf("1") > -1)
$(domEl).find('.MEMU').text("NORMAL")
else if (MemUsage.indexOf("2") > -1)
$(domEl).find('.MEMU').text("WARNIN")
else if (MemUsage.indexOf("4") > -1)
$(domEl).find('.MEMU').text("CRITICAL")
# Trash
@run "du -ch ~/.Trash | grep total | cut -c 1-5", (error, stdout, stderr) ->
window.Trashvalues = stdout.split(' ')
window.Trashvalues="#{window.Trashvalues}".replace /,/g, ''
window.Trashvalues="#{window.Trashvalues}".replace /\s+/g, ''
if (Trashvalues.indexOf("0B") > -1)
$(domEl).find('.TrashSize').text("#{TrashEmpty}")
else
$(domEl).find('.TrashSize').text("#{Trashvalues}")
# Network status
@run "sh Eva.widget/netstat.sh", (error, stdout, stderr) ->
stdout = stdout.split('\n')
window.Networkvalues = stdout[0].split(' ')
window.IPaddress = stdout[1]
window.NetworkUp = convert2B(Networkvalues[0])
window.NetworkDl = convert2B(Networkvalues[1])
# The following is for Public IP and it's warning
if (window.IPaddress.indexOf("Fehler") > -1)
window.IPaddress=ErrorMessage
if IPFehler != 1
IPFehler = 1
colourChange("#IPCell", config.colourWarn)
else
if IPFehler != 0
IPFehler = 0
colourChange("#IPCell", config.colourIdle)
$(domEl).find('.PubIP').text("#{window.IPaddress}")
if (NetworkUp?)
$(domEl).find('.NetU').text("#{NetworkUp}")
if (NetworkDl?)
$(domEl).find('.NetD').text("#{NetworkDl}")
# Do Not Disturb
@run "defaults read ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb", (error, stdout, stderr) ->
window.Disturbvalues = stdout[0]
# iTunes
@run "sh Eva.widget/iTunes.sh 2>/dev/null", (error, stdout, stderr) ->
if (stdout.indexOf("osascript: Eva.widget/iTunes.scp:") > -1)
stdout = "¶ ¶ ¶ 0 ¶ 0"
window.iTunesvalues = stdout.split('¶')
if (stdout.indexOf("¶ ¶ ¶ 0 ¶ 0") > -1)
$(domEl).find(".CoverCell").css("visibility","hidden")
$(domEl).find("#44").css("visibility","hidden")
$(domEl).find("#45").css("visibility","hidden")
$(domEl).find("#48").css("visibility","hidden")
else
$(domEl).find(".CoverCell").css("visibility","visible")
$(domEl).find("#44").css("visibility","visible")
$(domEl).find("#45").css("visibility","visible")
$(domEl).find("#48").css("visibility","visible")
window.iTunesvalues[3] = "0" + window.iTunesvalues[3] if window.iTunesvalues[3] < 10
$(domEl).find('#iTunesTrack').text("#{iTunesvalues[3]}")
$(domEl).find('#iTunesArtist').text("#{iTunesvalues[1]}")
$(domEl).find('#iTunesTitle').text("#{iTunesvalues[0]}")
$(domEl).find('#iTunesCoverImg').html("<img style='width:190em;height:190em;margin-left:5em;' src='Eva.widget/album.jpg'>")
if (iTunesvalues[4]>0)
$(domEl).find('#rate1').css("visibility","visible")
else
$(domEl).find('#rate1').css("visibility","hidden")
if (iTunesvalues[4]>20)
$(domEl).find('#rate2').css("visibility","visible")
else
$(domEl).find('#rate2').css("visibility","hidden")
if (iTunesvalues[4]>40)
$(domEl).find('#rate3').css("visibility","visible")
else
$(domEl).find('#rate3').css("visibility","hidden")
if (iTunesvalues[4]>60)
$(domEl).find('#rate4').css("visibility","visible")
else
$(domEl).find('#rate4').css("visibility","hidden")
if (iTunesvalues[4]>80)
$(domEl).find('#rate5').css("visibility","visible")
else
$(domEl).find('#rate5').css("visibility","hidden")
# Disk
if (window.tiktok == 0)
@run "ls -F /Volumes/ | awk -F'\t' '{ print $0}'", (error, stdout, stderr) ->
stdout = stdout.split('\n')
if (stdout.length > 1)
diskDisplay("#66", stdout[0])
else $(domEl).find("#66").css("visibility","hidden")
if (stdout.length > 2)
diskDisplay("#69", stdout[1])
else $(domEl).find("#69").css("visibility","hidden")
if (stdout.length > 3)
diskDisplay("#72", stdout[2])
else $(domEl).find("#72").css("visibility","hidden")
if (stdout.length > 4)
diskDisplay("#62", stdout[3])
else $(domEl).find("#62").css("visibility","hidden")
if (stdout.length > 5)
diskDisplay("#65", stdout[4])
else $(domEl).find("#65").css("visibility","hidden")
# Dealing with warnings
# Bwarning stands for Battery warning, triggers when battery drops below 20% without charging.
if (parseInt(BatteryPercentage) <= config.BatteryAlertLevel & BatteryState.indexOf("discharging") > -1)
if (Bwarning == 0)
if config.Voice
@run voiceCommand + voiceBatteryLow
colourChange(".battCells", config.colourWarn)
colourChange("#15", config.colourWarnHover)
$(domEl).find("#15").css("visibility","visible")
Bwarning += 1
else
if (Bwarning == 1)
if config.Voice
@run voiceCommand + voiceBatteryCharging
colourChange(".battCells", config.colourIdle)
colourChange("#15", "rgba(128,0,0,0)")
$(domEl).find("#15").css("visibility","hidden")
Bwarning -= 1
# Swarning is for Memory usage. Warning is triggered when reaches above
# NORMAL level(1)
if (MemUsage.indexOf("1") <= -1)
if (Swarning == 0)
if config.Voice
@run voiceCommand + voiceMEMzuHohe
colourChange("#MemCell", config.colourWarn)
Swarning += 1
else
if (Swarning == 1)
colourChange("#MemCell", config.colourIdle)
Swarning -= 1
# Cwarning is for CPU usage. Default value is to trigger when CPU usage reaches 90%
if CPUUsage/CPUAmount > config.CPUAlertLevel
if (Cwarning == 0)
if config.Voice
@run voiceCommand + voiceCPUzuHohe
colourChange("#CPUCell", config.colourWarn)
Cwarning += 1
else
if (Cwarning == 1)
colourChange("#CPUCell", config.colourIdle)
Cwarning -= 1
if Disturbvalues == '1'
if (Mwarning == 0)
if config.Voice
@run voiceCommand + voiceNichtStoerenEin
Mwarning += 1
else
if (Mwarning == 1)
if config.Voice
@run voiceCommand + voiceNichtStoerenAus
Mwarning -= 1
warning_switch(Bwarning+Cwarning+Swarning, Mwarning)
# hover effects, dealing with hovering
$('.battCells').hover (->
if Bwarning == 1
colourChange(".battCells", config.colourWarnHover)
else
colourChange(".battCells", config.colourIdleHover)
), (->
if Bwarning == 1
colourChange(".battCells", config.colourWarn)
else
colourChange(".battCells", config.colourIdle)
)
$('#31').hover (
->
$(domEl).find("#31 .id").text("#{Version}")
), (
->
$(domEl).find("#31 .id").text("31")
)
$('#25').hover (
->
$(domEl).find("#25 .id").text("Jetic")
), (
->
$(domEl).find("#25 .id").text("25")
)
#$('#32').hover (
# ->
# colourChange("#32", config.colourIdleHover)
# colourChange(".a4", config.colourIdleHover)
# $(domEl).find(".a4x").css("visibility", "visible")
#), (
# ->
# colourChange("#32", config.colourIdle)
# colourChange(".a4", "rgba(10,10,10,0)")
# $(domEl).find(".a4x").css("visibility", "hidden")
#)
# Outputting all the information for debug
# $(domEl).find('.OP').text("#{output}")
| 68859 | Version = "0.X14.4a"
config = {
Magnification: 1.0
BatteryAlertLevel: 20
CPUAlertLevel: 90
Opacity: 0.5
Voice: false
colourIdle: "rgba(50,50,50,1)" # 10,10,10 black
colourWarn: "rgba(256,0,0,1)"
colourDNDS: "rgba(256,96,0,1)"
colourWhit: "rgba(256,256,256,1)"
colourIdleHover: "rgba(128,128,128,1)"
colourWarnHover: "rgba(128,0,0,1)"
ShowUpdates: true
remoteBranch: "dev"
}
## Any advise or new idea is welcome. Do not hesitate to contact me, my email is: <EMAIL>
# Refreshing Frequency is set to once every 3000ms
refreshFrequency: 30000
# Information on cells Cells consists of three parts. A main body(nav), a top and a bottom(s and b). Cells are rotated 90 degrees to the current position.
# For special cells (Battery cell, iTunes cell), the toppings and bottoms are slightly different, for example s1, s2, b1, b2, these are modified to cover the gaps between the originally seperated cells.
# Almost all the elements in the cells are positioned manually, this is to ensure that the UI looks exactly the same on different environments.
# Übersicht is using the safari engine to render the widgets, therefore the UI under different versions of Safari could be different.
# classes like a0, a1, a2, battCells, a4 act as collective cell controlls allowing me to change the output of all related cells when necessary.
# ai cells are initially hidden;
# a1 and a2 are used to adjust the lines so that the cells won't crash into each other;
# battCells is the battery cell;
# a4 is the console output cell;
# ax hasn't been used.
# Contents in the cells can use the classes content of bigger text or contents for smaller text, although most of the time it might be better to adjust the font-size manually.
# It is obvious that some of the cells are hidden(ai), these can be easily modified to display new contents as you like.
# You can change the size through adjusting the font-size under style. Default is 1px
style: """
font-size: #{config.Magnification}px
top: -25em
font-family: Futura
text-transform: uppercase
position:relative
opacity: #{config.Opacity}
margin:0
text-align:center
text-decoration:none
.left
position: fixed
bottom: -25em
left:-100em
width: 800em
float:left
vertical-align : bottom
.right
float:right
margin-right:-60em
.nav
text-decoration: none
transform:rotate(90deg)
width:100em;height:58em
background:#{config.colourIdle}
display:inline-block
position:relative
line-height:58em
color:#ffffff
float:right
margin-top:-5em
margin-left:45em
margin-right:45em
.nav d
width:0;height:0
display:block
overflow:hidden
position:absolute
border-left:0.4em dotted transparent
border-right:0.4em dotted transparent
border-bottom:0.8em solid #{config.colourWhit}
bottom:3.33333em
right: 2.93333em
.nav u
width:0;height:0
display:block
overflow:hidden
position:absolute
border-left:0.4em dotted transparent
border-right:0.4em dotted transparent
border-top:0.8em solid #{config.colourWhit}
top:3.33333em
right:2.93333em
.nav o
display:block
overflow:hidden
position:absolute
border-right:2em solid #{config.colourWhit}
border-left:2em solid #{config.colourWhit}
padding-right:88em
padding-top:52em
left:4em
top:3em
.nav s
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:50em dotted transparent
border-left:50em dotted transparent
border-bottom:30em solid #{config.colourIdle}
right:0em
top:-30em
.nav b
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:50em dotted transparent
border-left:50em dotted transparent
border-top:30em solid #{config.colourIdle}
bottom:-30em
right:0em
.nav b1
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:0em dotted transparent
border-left:100em dotted transparent
border-top:60em solid #{config.colourIdle}
bottom:-60em
right:0em
.nav b2
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:100em dotted transparent
border-left:0em dotted transparent
border-top:60em solid #{config.colourIdle}
bottom:-60em
right:0em
.nav b3
margin-left:10em
width:100em
height:0
display:block
position:absolute
background-color: #{config.colourIdle}
border-top:95em solid #{config.colourIdle}
right:0em
bottom:-95em
.nav s1
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:0em dotted transparent
border-left:100em dotted transparent
border-bottom:60em solid #{config.colourIdle}
right:0em
top:-60em
.nav s2
margin-left:10em
width:100em
height:0
display:block
position:absolute
background-color: #{config.colourIdle}
border-bottom:95em solid #{config.colourIdle}
right:0em
top:-95em
.a0, .a0 s, .a0 b
@keyframes meow { from { opacity:1; } to { opacity:0.6; } }
.a1
margin-right:140em
.ai
/* visibility: hidden */
.a4
background:rgba(0,0,0,0)
.nav:hover a0 s
border-top-color:#{config.colourIdleHover}
.nav:hover a0 b
border-top-color:#{config.colourIdleHover}
.a4 s, .a4 s2, .a4 b, .a4 b1, .a4 b2, .a4 b3
border-bottom-color:rgba(10,10,10,0)
border-top-color:rgba(10,10,10,0)
border-left-color:rgba(10,10,10,0)
border-right-color:rgba(10,10,10,0)
background-color:rgba(10,10,10,0)
.ax
height:200em
.a1:hover, .a2:hover, .battCells:hover
background-color:#{config.colourIdleHover}
.a1:hover s, .a2:hover s, .battCells:hover s
border-bottom-color:#{config.colourIdleHover}
.a1:hover b, .a2:hover b, .battCells:hover b
border-top-color:#{config.colourIdleHover}
.output
padding: 5em 10em
font-size: 30em
font-weight: 100
text-shadow: 0 0em 5em #000000
background-color: rgba(0,0,0,0.2)
border: 1em solid #fff
.content
transform:rotate(-90deg)
font-style: Black
z-index:99999
.clock
font-size: 30em
.sal
font-family: Songti SC
font-style: Black
font-size:40em
.Wcontent
transform:rotate(-90deg)
font-style: Black
font-size: 15em
z-index:99999
visibility:hidden
.contentS
transform:rotate(-90deg)
font-style: Black
z-index:99999
.Bat
font-weight: bold
font-size: 15em
text-transform: uppercase
.id
font-size:20em
font-family:Futura
font-style:normal
.BatStatus
font-weight: bold
font-size: 20em
text-transform: uppercase
.Rotate
transform:rotate(-90deg)
width:200em
.iTunesPre
width:0;height:0
position:relative
border-right:11em dotted transparent
border-left:11em dotted transparent
border-top:20em solid #{config.colourWhit}
right:-40em
top:-10em
.iTunesNext
width:0;height:0
position:relative
border-right:11em dotted transparent
border-left:11em dotted transparent
border-bottom:20em solid #{config.colourWhit}
right:-40em
top:-260em
.iTunesPause
width:30em;height:8em
position:relative
border-top:8em solid #{config.colourWhit}
border-bottom:8em solid #{config.colourWhit}
right:-37em
top:-100em
.iTunesPlay
width:0;height:0
position:relative
border-right:17em dotted transparent
border-left:17em dotted transparent
border-bottom:30em solid #{config.colourWhit}
right:-35em
top:-170em
.iTunesPlay:active
border-bottom-color: #{config.colourIdleHover}
.iTunesPause:active
border-top-color: #{config.colourIdleHover}
border-bottom-color: #{config.colourIdleHover}
.iTunesNext:active
border-bottom-color: #{config.colourIdleHover}
.iTunesPre:active
border-top-color: #{config.colourIdleHover}
.Disk
background-color: rgba(226,161,54,1)
position: relative
font-size: 10em
left: 1em; top:0.7em
width:5em;height:4em
border:0.2em solid #{config.colourWhit}
border-right: 0.5em solid #{config.colourWhit}
z-index:99999
.DiskN
width: 9em; height:4em
margin-left:2em;
margin-top:-3.5em;
text-overflow:ellipsis;
overflow:hidden;
font-size:10em
transform:rotate(-90deg)
font-style: Black
z-index:99999
.iTunesCover
position: fixed;
left:410em; bottom:500em;
width:200em; height:200em;
background-color: #{config.colourIdle};
z-index:99999
.iTunesCoverMask
color:white
position: fixed;
margin-left:5em; margin-top:5em;
width: 190em; height: 190em;
background-color: rgba(10,10,10,0.75);
.iTunesRatingBlock
width:33em;height:10em;
margin-left:1em;margin-right:1em;
background-color: rgba(256,256,256,0.5);
display:inline-block;
"""
render: -> """
<div class="left" style="float:left">
<div class="iTunesCover CoverCell">
<div class="iTunesCoverMask">
<div style="font-size:30em;font-family:IMPACT">SEELE</div>
<div style="font-size:70em;font-family:IMPACT" id="iTunesTrack">00</div>
<div style="font-size:30em;font-family:IMPACT">SOUND</div>
<div style="font-size:30em;font-family:IMPACT">ONLY</div>
</div>
<div style="width:190em;height:190em;margin-top:5em" id="iTunesCoverImg"></div>
<div class="iTunesRatingBlock" id="rate1"></div>
<div class="iTunesRatingBlock" id="rate2"></div>
<div class="iTunesRatingBlock" id="rate3"></div>
<div class="iTunesRatingBlock" id="rate4"></div>
<div class="iTunesRatingBlock" id="rate5"></div>
</div>
<div class="nav a2 CoverCell" target="_blank" href="#" id="44"><s></s><b1></b1></div>
<div class="nav a2 CoverCell" target="_blank" href="#" id="45"><s1></s1><b></b></div>
<div class="nav a0" target="_blank" href="#" id="46"><s></s><b></b>
<div class="id">46</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="47"><s></s><b></b>
<div class="id">47</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 CoverCell" target="_blank" href="#" id="48"><s></s><b2></b2></div>
<div class="nav a0" target="_blank" href="#" id="49"><s></s><b></b>
<div class="id">49</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="50"><s></s><b></b>
<div class="id">50</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav ai" target="_blank" href="#" id="51"></div>
<div class="nav a2 NetCell" target="_blank" href="#" style="z-index:9999"><s1></s1><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">Ibytes/s</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-70em;font-family:Futura;font-style:normal">
<span class="NetU" style="font-size:25em">Fehler</span>
</div>
<div class="contentS" style="position:absolute;left:55em;top:-95em;">
<span style="font-size:15em">Obytes/s</span>
</div>
</div>
<div class="nav a5" target="_blank" href="#" id="53"><s1></s1><b1></b1></div>
<div class="nav a0" target="_blank" href="#" id="54"><s></s><b></b>
<div class="id">54</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a2 NetCell" target="_blank" href="#"><s></s><b2></b2>
<div class="content" style="margin-left:30em;margin-top:-4em;font-family:Futura;font-style:normal">
<span class="NetD" style="font-size:25em">Fehler</span>
</div></div>
<div class="nav a5" target="_blank" href="#" id="56"><s></s><b3></b3></div>
<div class="nav a5" target="_blank" href="#" id="57" style="z-index:99999"><s2></s2><b></b>
<div class="Rotate" style="text-overflow:ellipsis;
overflow:hidden;
position:absolute;
top:-85em;left:-20em;
text-align:center;height:40em;width:200em">
<span id="iTunesArtist" style="font-size:12em"></span>
</div>
<div class="Rotate" style="text-overflow:ellipsis;
overflow:hidden;
position:absolute;
top:-85em;left:-92em;
text-align:center;height:40em;width:200em">
<span id="iTunesTitle" style="font-size:12em"></span>
</div>
<div class="iTunesPre"></div><div class="iTunesPre"></div>
<div class="iTunesPause"></div><div class="iTunesPlay"></div>
<div class="iTunesNext"></div><div class="iTunesNext"></div></div>
<div class="nav ai" target="_blank" href="#" id="58"><s></s><b></b></div>
<div class="nav a0" target="_blank" href="#" id="59"><s></s><b></b>
<div class="id">59</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a5" target="_blank" href="#" id="60"><s></s><b2></b2></div>
<div class="nav a0" target="_blank" href="#" id="61"><s></s><b></b>
<div class="id">61</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a2" target="_blank" href="#" id="62" style="margin-right:140em"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="62content"></div></div>
<div class="nav a0" target="_blank" href="#" id="63"><s></s><b></b>
<div class="id">63</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="64"><s></s><b></b>
<div class="id">64</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="65"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="65content"></div></div>
<div class="nav a2" target="_blank" href="#" id="66"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="66content"></div></div>
<div class="nav a0" target="_blank" href="#" id="67"><s></s><b></b>
<div class="id">67</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="68"><s></s><b></b>
<div class="id">68</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a2" target="_blank" href="#" id="69" style="margin-right:140em"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="69content"></div></div>
<div class="nav a0" target="_blank" href="#" id="70"><s></s><b></b>
<div class="id">70</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="71"><s></s><b></b>
<div class="id">71</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="72"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="72content"></div></div>
<div class="nav a0" target="_blank" href="#" id="73"><s></s><b></b>
<div class="id">73</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="74"><s></s><b></b>
<div class="id">74</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="75"><s></s><b></b>
<div class="id">75</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="76"><s></s><b></b>
<div class="id">76</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="77"><s></s><b></b>
<div class="id">77</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="78"><s></s><b></b>
<div class="id">78</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="79"><s></s><b></b>
<div class="id">79</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="80"><s></s><b></b>
<div class="id">80</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="81"><s></s><b></b>
<div class="id">81</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="82"><s></s><b></b>
<div class="id">82</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
</div>
<div class="right">
<div class="nav a0" target="_blank" href="#" id="0"><s></s><b></b>
<div class="id">0</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="1"><s></s><b></b>
<div class="id">1</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="2"><s></s><b></b>
<div class="id">2</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="3"><s></s><b></b>
<div class="id">3</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="4"><s></s><b></b>
<div class="id">4</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="5"><s></s><b></b>
<div class="contentS" style="margin-left:10em;margin-top:0em">
<span class="day" style="width:20em;font-size:15em"></span>
</div></div><p></p>
<div class="nav a0" target="_blank" href="#" id="6"><s></s><b></b>
<div class="id">6</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="7"><s></s><b></b>
<div class="id">7</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="8"><s></s><b></b>
<div class="id">8</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="9"><s></s><b></b>
<div class="content" style="margin-left:10em;margin-top:-5em">
<span class="time" style="font-size:30em;font-family:Futura;font-style:normal"></span>
</div></div><p></p>
<div class="nav a1" target="_blank" href="#" id="CPUCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">CPU</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-70em;font-family:Futura;font-style:normal">
<span class="CPUU" style="font-size:30em;">Fehler</span>
</div></div>
<div class="nav a2" target="_blank" href="#" id="11"><s></s><b></b>
<div class="content" style="margin-left:10em;margin-top:-5em">
<span class="sal"></span>
</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="12"></div>
<div class="nav a0" target="_blank" href="#" id="13"><s></s><b></b>
<div class="id">13</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav battCells" target="_blank" href="#" id="14"><s></s><b1></b1></div>
<div class="nav ai" target="_blank" href="#" id="15"><s></s><b></b>
<div class="contentS" style="margin-left:-25em;margin-top:-4em">
<span style="font-size:15em">verbleibend</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-65em">
<span class="BatRe" style="font-size:30em">Fehler</span>
</div></div><p></p>
<div class="nav a1" target="_blank" href="#" id="MemCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">Speicher</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-55em">
<span class="MEMU" style="font-size:23em">Fehler</span>
</div></div>
<div class="nav battCells" target="_blank" href="#" id="17" style="z-index:9999"><s2></s2><b></b>
<div class="Rotate" style="margin-top:-70em;margin-left:-60em;text-align:left"><span class="Bat"></span></div>
<div class="Rotate" style="margin-top:-65em;margin-left:-35em;text-align:left"><span class="BatStatus"></span></div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="18"></div>
<div class="nav a0" target="_blank" href="#" id="19"><s></s><b></b>
<div class="id">19</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav battCells" target="_blank" href="#" id="BatCell"><s></s><b2></b2>
<div class="Rotate" style="margin-top:-5em;margin-left:-35em;width:200em;text-align:center;font-family:Futura;font-style:normal">
<span class="BatPer" style="font-size:20em">Fehler</span>
</div></div>
<div class="nav a0" target="_blank" href="#" id="21"><s></s><b></b>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="contentS" style="text-decoration:underline overline;font-size:15em"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="22"><s></s><b></b>
<div class="id">22</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="TrashCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em;margin-top:-5em">
<span style="font-size:15em">Papierkorb</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-62em">
<span class="TrashSize" style="font-size:25em">Fehler</span>
</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="24"></div>
<div class="nav a0" target="_blank" href="#" id="25"><s></s><b></b>
<div class="id">25</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="26"><s></s><b></b>
<div class="id">26</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav ai" target="_blank" href="#" id="27" style="background:#{config.colourWarn}">
<s style="border-bottom-color:#{config.colourWarn}"></s>
<b style="border-top-color:#{config.colourWarn}"></b>
<o></o>
<o style="transform:rotate(-60deg)"></o>
<o style="transform:rotate(-120deg)"></o>
<div class="contentS" style="text-align:center;font-size:20em">
Update!
</div>
</div><p></p>
<div class="nav a1" target="_blank" href="#" id="IPCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">PublikIP</span>
</div>
<div class="content" style="margin-left:15em;margin-top:-64em;">
<span class="PubIP" style="font-size:13em;font-family:Futura;font-style:normal">Fehler</span>
</div></div>
<div class="nav a0" target="_blank" href="#" id="29"><s></s><b></b>
<div class="id">29</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="30"></div>
<div class="nav a0" target="_blank" href="#" id="31"><s></s><b></b>
<div class="id">31</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="32"><s></s><div style="font-size:20em">32</div><b></b></div>
<div class="nav ai" target="_blank" href="#" id="33"></div><p></p>
<div class="nav ai" target="_blank" href="#" id="34"></div><p></p>
<div class="nav a4" target="_blank" href="#" id="35" style="margin-right:140em"><s></s><b1></b1></div>
<div class="nav a4" target="_blank" href="#" id="36"><s></s><b1></b1>
<div class='a4x' style="transform:rotate(-90deg);margin-left:-10em;visibility:hidden">
<div style="font-size:20em">OUTPUT</div>
</div>
</div><p></p>
<div class="nav ai" target="_blank" href="#" id="37"></div>
<div class="nav a4" target="_blank" href="#" id="38"><s></s><b3></b3></div>
<div class="nav a4" target="_blank" href="#" id="39"><s2></s2><b3></b3></div>
<div class="nav a4" target="_blank" href="#" id="40" style="z-index:9999"><s2></s2><b></b>
<div class="a4x" style="margin-top:-200em;margin-left:-150em;width:400em;transform:rotate(-90deg);text-align:left;visibility:hidden;line-height:110%">
<span class="OP" style="text-transform:none;font-size:20em;line-height:100%"></span>
</div>
</div>
<p></p>
<div class="nav a4" target="_blank" href="#" id="41" style="margin-right:140em"><s></s><b2></b2></div>
<div class="nav a4" target="_blank" href="#" id="42"><s></s><b2></b2></div><p></p>
<div class="nav ai" target="_blank" href="#" id="43"></div>
</div>
"""
command: ""
afterRender: (domEl) ->
# Define constants
window.segments = ["子時", "丑時", "寅時", "卯時", "辰時", "巳時", "午時", "未時", "申時", "酉時", "戌時", "亥時"]
# I don't know Germany so deleted because I'll reconstruct the code thoroughly
window.voice = "daniel"
window.voiceBatteryLow = "warning, battery level critical"
window.voiceBatteryCharging = "battery charging"
window.voiceCPUzuHohe = "warning, cpu overloaded"
window.voiceMEMzuHohe = "warning, memory pressure too high"
window.voiceNichtStoerenEin = "no disturb mode is on"
window.voiceNichtStoerenAus = "no disturb mode is off"
window.Batterievalues = [
'AC Only'
''
'AC Power'
''
]
window.daylist = [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday'
]
window.TrashEmpty = "Empty"
window.ErrorMessage = "Error"
window.WarningMessage = "WARNING"
window.BatteryStatus = [
'charging'
'charged'
'discharging'
'finishing'
]
window.BatteryType = "internalbattery"
$(domEl).find("#MemCell span").text("Memory")
$(domEl).find("#IPCell span").text("PublicIP")
$(domEl).find("#TrashCell span").text("Trash")
$(domEl).find(".Wcontent ").html("<u></u><d></d>#{window.WarningMessage}")
$(domEl).find("#21 .contentS").html("<u></u><d></d>#{window.WarningMessage}")
# Voice
window.voiceCommand = "say -v " + window.voice + " "
# Initialise warnings
window.Bwarning=0
window.Cwarning=0
window.IPFehler=0
window.Swarning=0
window.Mwarning=0
window.cellColour=-1
window.count = -1
window.BatteryPercentage=""
window.BatteryState=""
window.CPUUsage = ""
window.MemUsage = "1"
window.CPUAmount = ""
window.Disturbvalues = "0"
window.tiktok = -1
$(domEl).on 'click', '.iTunesPre', => @run "osascript -e 'tell application \"iTunes\" to previous track'"
$(domEl).on 'click', '.iTunesNext', => @run "osascript -e 'tell application \"iTunes\" to next track'"
$(domEl).on 'click', '.iTunesPause', => @run "osascript -e 'tell application \"iTunes\" to pause'"
$(domEl).on 'click', '.iTunesPlay', => @run "osascript -e 'tell application \"iTunes\" to play'"
$(domEl).on 'click', '#TrashCell', => @run "osascript -e 'tell application \"Finder\" to empty'"
# Command to open up mounted volumes
$(domEl).on 'click', '#66', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 1 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#69', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 2 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#72', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 3 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#62', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 4 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#65', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 5 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#27', =>
$(domEl).find("#27 .contentS").text("loading")
@run "head -16 Eva.widget/index.coffee > updateConfig.tmp &&
curl -o ../Evangelion_style_dashboard.widget.zip https://raw.githubusercontent.com/jeticg/Evangelion-Uebersicht-Widget/#{config.remoteBranch}/Evangelion_style_dashboard.widget.zip &&
cp -r Eva.widget ../Eva.widget &&
unzip -o ../Evangelion_style_dashboard.widget.zip -d ../ &&
sh ../Eva.widget/updateConfig.sh &&
cp -r ../Eva.widget/* ./Eva.widget/ &&
rm -r ../Evangelion_style_dashboard.widget.zip &&
rm -r ../Eva.widget &&
rm -r ../__MACOSX"
@run "rm Eva.widget/netstat.ipworking", (error, stdout, stderr) ->
@run 'csrutil status', (error, stdout, stderr) ->
if stdout
console.log stdout
if stderr
console.error stderr
update: (output, domEl) ->
# functions
# This is for the warning animations
animation_on = (cell, colour) -> () ->
if colour == 1
$(domEl).find("#{cell}" ).css("animation", "meow 1s linear 0s infinite alternate")
else if colour == 2
$(domEl).find("#{cell}" ).css("animation", "meow 1s linear 0s infinite alternate")
else if colour == 0
animation_off(cell)
animation_off = (cell) ->
$(domEl).find("#{cell} s").css("animation", "")
$(domEl).find("#{cell} b").css("animation", "")
$(domEl).find("#{cell}" ).css("animation", "")
# This function is for changing the colour of cell(s).
colourChange = (cell, colour) ->
if $.type(cell) == "object"
$element = cell
cell = ""
$element.css("background", colour)
else
$element = $(domEl)
$element.find("#{cell}").css("background", colour)
$element.find("#{cell} s").css("border-bottom-color", colour)
$element.find("#{cell} b").css("border-top-color", colour)
$element.find("#{cell} s1").css("border-bottom-color", colour)
$element.find("#{cell} s2").css("border-bottom-color", colour)
$element.find("#{cell} b1").css("border-top-color", colour)
$element.find("#{cell} b2").css("border-top-color", colour)
$element.find("#{cell} b3").css("border-top-color", colour)
# Display disk information
diskDisplay = (cell, tmp) ->
$(domEl).find("#{cell}").css("visibility","visible")
$(domEl).find("#{cell} .DiskN").text("#{tmp[0..(tmp.length-2)]}")
if (tmp.indexOf("@") > -1 )
$(domEl).find("#{cell} .Disk").css("background-color","rgba(128,128,160,1)")
$(domEl).find("#{cell} .Disk").text("Sys。")
else
$(domEl).find("#{cell} .Disk").css("background-color","rgba(226,161,54,1)")
$(domEl).find("#{cell} .Disk").text("Vol。")
# General warning settings. This function is called at the end of each
# widget refreshing.
warning_switch = (red, orange) ->
CorrectColour = 0
if orange > 0
CorrectColour = 2
if red > 0
CorrectColour = 1
if (cellColour != CorrectColour)
cellColour += CorrectColour - cellColour
animation_off(".a0")
for element in $(domEl).find(".a0")
work = (cell) -> () ->
$cell = $(cell)
if cellColour == 1
colourChange($cell, config.colourWarn)
$cell.find(".Wcontent").html("<u></u><d></d>#{WarningMessage}")
$cell.find(".Wcontent").css("visibility","visible")
$cell.find(".id" ).css("display" ,"none" )
else if cellColour == 2
colourChange($cell, config.colourDNDS)
$cell.find(".Wcontent").html("NoDisturb")
$cell.find(".Wcontent").css("visibility","visible")
$cell.find(".id" ).css("display" ,"none" )
else
colourChange($cell, config.colourIdle)
$cell.find(".Wcontent").css("visibility","hidden" )
$cell.find(".id" ).css("display" ,"inline-block")
setTimeout (work(element)), Math.random() * 1000
setTimeout (animation_on(".a0", cellColour)), 1000
convert2B = (input) ->
output = input
if (parseInt(output)>=1024)
output = parseInt(output)/1024
if (parseInt(output)>=1024)
output = parseInt(output)/1024
output = Math.round(output*10)/10 + 'M'
else
output = Math.round(output*10)/10 + 'K'
return output
getTime = () ->
# Processing time
# This is for outputing the time. Nothing really
date = new Date()
hour = date.getHours()
minutes = date.getMinutes()
days = date.getDay()
minutes = "0"+ minutes if minutes < 10
timeSegment = segments[0]
timeSegment = segments[1] if 1 <= hour < 3
timeSegment = segments[2] if 3 <= hour < 5
timeSegment = segments[3] if 5 <= hour < 7
timeSegment = segments[4] if 7 <= hour < 9
timeSegment = segments[5] if 9 <= hour < 11
timeSegment = segments[6] if 11 <= hour < 13
timeSegment = segments[7] if 13 <= hour < 15
timeSegment = segments[8] if 15 <= hour < 17
timeSegment = segments[9] if 17 <= hour < 19
timeSegment = segments[10] if 19 <= hour < 21
timeSegment = segments[11] if 21 <= hour < 23
$(domEl).find('.sal').text("#{timeSegment}")
$(domEl).find('.time').text("#{hour}:#{minutes}")
$(domEl).find('.day').text("#{daylist[days]}")
# Execution
getTime()
window.tiktok += 1
if (window.tiktok == 3)
window.tiktok = 0
# Battery
if (window.tiktok == 0)
@run "sh Eva.widget/battery.sh", (error, stdout, stderr) ->
if (stdout.indexOf("InternalBattery") > -1)
window.Batterievalues = stdout.split(' ')
if (Batterievalues[0].indexOf("InternalBattery") > -1)
$(domEl).find('.Bat').text("#{BatteryType}")
else
$(domEl).find('.Bat').text("#{Batterievalues[0]}")
if (Batterievalues[1].indexOf("id=") > -1)
window.BatteryPercentage=Batterievalues[2]
window.BatteryState=Batterievalues[3]
$(domEl).find('.BatPer').text("#{Batterievalues[2]}")
if (Batterievalues[3].indexOf("discharging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[2]}")
else if (Batterievalues[3].indexOf("charged") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[1]}")
else if (Batterievalues[3].indexOf("charging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[0]}")
else if (Batterievalues[3].indexOf("finishing") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[3]}")
else
$(domEl).find('.BatStatus').text("#{Batterievalues[3]}")
$(domEl).find('.BatRe').text("#{Batterievalues[4]}")
else
window.BatteryPercentage=Batterievalues[1]
window.BatteryState=Batterievalues[2]
$(domEl).find('.BatPer').text("#{Batterievalues[1]}")
if (Batterievalues[2].indexOf("discharging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[2]}")
else if (Batterievalues[2].indexOf("charged") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[1]}")
else if (Batterievalues[2].indexOf("charging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[0]}")
else if (Batterievalues[2].indexOf("finishing") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[3]}")
else
$(domEl).find('.BatStatus').text("#{Batterievalues[2]}")
$(domEl).find('.BatRe').text("#{Batterievalues[3]}")
# CPU and Memory
@run "sh Eva.widget/cpu_mem.sh", (error, stdout, stderr) ->
stdout = stdout.split('\n')
window.CPUUsage = stdout[0].split(' ')
window.MemUsage = stdout[1].split(' ')
window.CPUAmount = stdout[2].split(' ')
$(domEl).find('.CPUU').text("#{Math.floor(CPUUsage/CPUAmount)}%")
if (MemUsage.indexOf("1") > -1)
$(domEl).find('.MEMU').text("NORMAL")
else if (MemUsage.indexOf("2") > -1)
$(domEl).find('.MEMU').text("WARNIN")
else if (MemUsage.indexOf("4") > -1)
$(domEl).find('.MEMU').text("CRITICAL")
# Trash
@run "du -ch ~/.Trash | grep total | cut -c 1-5", (error, stdout, stderr) ->
window.Trashvalues = stdout.split(' ')
window.Trashvalues="#{window.Trashvalues}".replace /,/g, ''
window.Trashvalues="#{window.Trashvalues}".replace /\s+/g, ''
if (Trashvalues.indexOf("0B") > -1)
$(domEl).find('.TrashSize').text("#{TrashEmpty}")
else
$(domEl).find('.TrashSize').text("#{Trashvalues}")
# Network status
@run "sh Eva.widget/netstat.sh", (error, stdout, stderr) ->
stdout = stdout.split('\n')
window.Networkvalues = stdout[0].split(' ')
window.IPaddress = stdout[1]
window.NetworkUp = convert2B(Networkvalues[0])
window.NetworkDl = convert2B(Networkvalues[1])
# The following is for Public IP and it's warning
if (window.IPaddress.indexOf("Fehler") > -1)
window.IPaddress=ErrorMessage
if IPFehler != 1
IPFehler = 1
colourChange("#IPCell", config.colourWarn)
else
if IPFehler != 0
IPFehler = 0
colourChange("#IPCell", config.colourIdle)
$(domEl).find('.PubIP').text("#{window.IPaddress}")
if (NetworkUp?)
$(domEl).find('.NetU').text("#{NetworkUp}")
if (NetworkDl?)
$(domEl).find('.NetD').text("#{NetworkDl}")
# Do Not Disturb
@run "defaults read ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb", (error, stdout, stderr) ->
window.Disturbvalues = stdout[0]
# iTunes
@run "sh Eva.widget/iTunes.sh 2>/dev/null", (error, stdout, stderr) ->
if (stdout.indexOf("osascript: Eva.widget/iTunes.scp:") > -1)
stdout = "¶ ¶ ¶ 0 ¶ 0"
window.iTunesvalues = stdout.split('¶')
if (stdout.indexOf("¶ ¶ ¶ 0 ¶ 0") > -1)
$(domEl).find(".CoverCell").css("visibility","hidden")
$(domEl).find("#44").css("visibility","hidden")
$(domEl).find("#45").css("visibility","hidden")
$(domEl).find("#48").css("visibility","hidden")
else
$(domEl).find(".CoverCell").css("visibility","visible")
$(domEl).find("#44").css("visibility","visible")
$(domEl).find("#45").css("visibility","visible")
$(domEl).find("#48").css("visibility","visible")
window.iTunesvalues[3] = "0" + window.iTunesvalues[3] if window.iTunesvalues[3] < 10
$(domEl).find('#iTunesTrack').text("#{iTunesvalues[3]}")
$(domEl).find('#iTunesArtist').text("#{iTunesvalues[1]}")
$(domEl).find('#iTunesTitle').text("#{iTunesvalues[0]}")
$(domEl).find('#iTunesCoverImg').html("<img style='width:190em;height:190em;margin-left:5em;' src='Eva.widget/album.jpg'>")
if (iTunesvalues[4]>0)
$(domEl).find('#rate1').css("visibility","visible")
else
$(domEl).find('#rate1').css("visibility","hidden")
if (iTunesvalues[4]>20)
$(domEl).find('#rate2').css("visibility","visible")
else
$(domEl).find('#rate2').css("visibility","hidden")
if (iTunesvalues[4]>40)
$(domEl).find('#rate3').css("visibility","visible")
else
$(domEl).find('#rate3').css("visibility","hidden")
if (iTunesvalues[4]>60)
$(domEl).find('#rate4').css("visibility","visible")
else
$(domEl).find('#rate4').css("visibility","hidden")
if (iTunesvalues[4]>80)
$(domEl).find('#rate5').css("visibility","visible")
else
$(domEl).find('#rate5').css("visibility","hidden")
# Disk
if (window.tiktok == 0)
@run "ls -F /Volumes/ | awk -F'\t' '{ print $0}'", (error, stdout, stderr) ->
stdout = stdout.split('\n')
if (stdout.length > 1)
diskDisplay("#66", stdout[0])
else $(domEl).find("#66").css("visibility","hidden")
if (stdout.length > 2)
diskDisplay("#69", stdout[1])
else $(domEl).find("#69").css("visibility","hidden")
if (stdout.length > 3)
diskDisplay("#72", stdout[2])
else $(domEl).find("#72").css("visibility","hidden")
if (stdout.length > 4)
diskDisplay("#62", stdout[3])
else $(domEl).find("#62").css("visibility","hidden")
if (stdout.length > 5)
diskDisplay("#65", stdout[4])
else $(domEl).find("#65").css("visibility","hidden")
# Dealing with warnings
# Bwarning stands for Battery warning, triggers when battery drops below 20% without charging.
if (parseInt(BatteryPercentage) <= config.BatteryAlertLevel & BatteryState.indexOf("discharging") > -1)
if (Bwarning == 0)
if config.Voice
@run voiceCommand + voiceBatteryLow
colourChange(".battCells", config.colourWarn)
colourChange("#15", config.colourWarnHover)
$(domEl).find("#15").css("visibility","visible")
Bwarning += 1
else
if (Bwarning == 1)
if config.Voice
@run voiceCommand + voiceBatteryCharging
colourChange(".battCells", config.colourIdle)
colourChange("#15", "rgba(128,0,0,0)")
$(domEl).find("#15").css("visibility","hidden")
Bwarning -= 1
# Swarning is for Memory usage. Warning is triggered when reaches above
# NORMAL level(1)
if (MemUsage.indexOf("1") <= -1)
if (Swarning == 0)
if config.Voice
@run voiceCommand + voiceMEMzuHohe
colourChange("#MemCell", config.colourWarn)
Swarning += 1
else
if (Swarning == 1)
colourChange("#MemCell", config.colourIdle)
Swarning -= 1
# Cwarning is for CPU usage. Default value is to trigger when CPU usage reaches 90%
if CPUUsage/CPUAmount > config.CPUAlertLevel
if (Cwarning == 0)
if config.Voice
@run voiceCommand + voiceCPUzuHohe
colourChange("#CPUCell", config.colourWarn)
Cwarning += 1
else
if (Cwarning == 1)
colourChange("#CPUCell", config.colourIdle)
Cwarning -= 1
if Disturbvalues == '1'
if (Mwarning == 0)
if config.Voice
@run voiceCommand + voiceNichtStoerenEin
Mwarning += 1
else
if (Mwarning == 1)
if config.Voice
@run voiceCommand + voiceNichtStoerenAus
Mwarning -= 1
warning_switch(Bwarning+Cwarning+Swarning, Mwarning)
# hover effects, dealing with hovering
$('.battCells').hover (->
if Bwarning == 1
colourChange(".battCells", config.colourWarnHover)
else
colourChange(".battCells", config.colourIdleHover)
), (->
if Bwarning == 1
colourChange(".battCells", config.colourWarn)
else
colourChange(".battCells", config.colourIdle)
)
$('#31').hover (
->
$(domEl).find("#31 .id").text("#{Version}")
), (
->
$(domEl).find("#31 .id").text("31")
)
$('#25').hover (
->
$(domEl).find("#25 .id").text("Jetic")
), (
->
$(domEl).find("#25 .id").text("25")
)
#$('#32').hover (
# ->
# colourChange("#32", config.colourIdleHover)
# colourChange(".a4", config.colourIdleHover)
# $(domEl).find(".a4x").css("visibility", "visible")
#), (
# ->
# colourChange("#32", config.colourIdle)
# colourChange(".a4", "rgba(10,10,10,0)")
# $(domEl).find(".a4x").css("visibility", "hidden")
#)
# Outputting all the information for debug
# $(domEl).find('.OP').text("#{output}")
| true | Version = "0.X14.4a"
config = {
Magnification: 1.0
BatteryAlertLevel: 20
CPUAlertLevel: 90
Opacity: 0.5
Voice: false
colourIdle: "rgba(50,50,50,1)" # 10,10,10 black
colourWarn: "rgba(256,0,0,1)"
colourDNDS: "rgba(256,96,0,1)"
colourWhit: "rgba(256,256,256,1)"
colourIdleHover: "rgba(128,128,128,1)"
colourWarnHover: "rgba(128,0,0,1)"
ShowUpdates: true
remoteBranch: "dev"
}
## Any advise or new idea is welcome. Do not hesitate to contact me, my email is: PI:EMAIL:<EMAIL>END_PI
# Refreshing Frequency is set to once every 3000ms
refreshFrequency: 30000
# Information on cells Cells consists of three parts. A main body(nav), a top and a bottom(s and b). Cells are rotated 90 degrees to the current position.
# For special cells (Battery cell, iTunes cell), the toppings and bottoms are slightly different, for example s1, s2, b1, b2, these are modified to cover the gaps between the originally seperated cells.
# Almost all the elements in the cells are positioned manually, this is to ensure that the UI looks exactly the same on different environments.
# Übersicht is using the safari engine to render the widgets, therefore the UI under different versions of Safari could be different.
# classes like a0, a1, a2, battCells, a4 act as collective cell controlls allowing me to change the output of all related cells when necessary.
# ai cells are initially hidden;
# a1 and a2 are used to adjust the lines so that the cells won't crash into each other;
# battCells is the battery cell;
# a4 is the console output cell;
# ax hasn't been used.
# Contents in the cells can use the classes content of bigger text or contents for smaller text, although most of the time it might be better to adjust the font-size manually.
# It is obvious that some of the cells are hidden(ai), these can be easily modified to display new contents as you like.
# You can change the size through adjusting the font-size under style. Default is 1px
style: """
font-size: #{config.Magnification}px
top: -25em
font-family: Futura
text-transform: uppercase
position:relative
opacity: #{config.Opacity}
margin:0
text-align:center
text-decoration:none
.left
position: fixed
bottom: -25em
left:-100em
width: 800em
float:left
vertical-align : bottom
.right
float:right
margin-right:-60em
.nav
text-decoration: none
transform:rotate(90deg)
width:100em;height:58em
background:#{config.colourIdle}
display:inline-block
position:relative
line-height:58em
color:#ffffff
float:right
margin-top:-5em
margin-left:45em
margin-right:45em
.nav d
width:0;height:0
display:block
overflow:hidden
position:absolute
border-left:0.4em dotted transparent
border-right:0.4em dotted transparent
border-bottom:0.8em solid #{config.colourWhit}
bottom:3.33333em
right: 2.93333em
.nav u
width:0;height:0
display:block
overflow:hidden
position:absolute
border-left:0.4em dotted transparent
border-right:0.4em dotted transparent
border-top:0.8em solid #{config.colourWhit}
top:3.33333em
right:2.93333em
.nav o
display:block
overflow:hidden
position:absolute
border-right:2em solid #{config.colourWhit}
border-left:2em solid #{config.colourWhit}
padding-right:88em
padding-top:52em
left:4em
top:3em
.nav s
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:50em dotted transparent
border-left:50em dotted transparent
border-bottom:30em solid #{config.colourIdle}
right:0em
top:-30em
.nav b
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:50em dotted transparent
border-left:50em dotted transparent
border-top:30em solid #{config.colourIdle}
bottom:-30em
right:0em
.nav b1
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:0em dotted transparent
border-left:100em dotted transparent
border-top:60em solid #{config.colourIdle}
bottom:-60em
right:0em
.nav b2
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:100em dotted transparent
border-left:0em dotted transparent
border-top:60em solid #{config.colourIdle}
bottom:-60em
right:0em
.nav b3
margin-left:10em
width:100em
height:0
display:block
position:absolute
background-color: #{config.colourIdle}
border-top:95em solid #{config.colourIdle}
right:0em
bottom:-95em
.nav s1
margin-left:10em
width:0;height:0
display:block
overflow:hidden
position:absolute
border-right:0em dotted transparent
border-left:100em dotted transparent
border-bottom:60em solid #{config.colourIdle}
right:0em
top:-60em
.nav s2
margin-left:10em
width:100em
height:0
display:block
position:absolute
background-color: #{config.colourIdle}
border-bottom:95em solid #{config.colourIdle}
right:0em
top:-95em
.a0, .a0 s, .a0 b
@keyframes meow { from { opacity:1; } to { opacity:0.6; } }
.a1
margin-right:140em
.ai
/* visibility: hidden */
.a4
background:rgba(0,0,0,0)
.nav:hover a0 s
border-top-color:#{config.colourIdleHover}
.nav:hover a0 b
border-top-color:#{config.colourIdleHover}
.a4 s, .a4 s2, .a4 b, .a4 b1, .a4 b2, .a4 b3
border-bottom-color:rgba(10,10,10,0)
border-top-color:rgba(10,10,10,0)
border-left-color:rgba(10,10,10,0)
border-right-color:rgba(10,10,10,0)
background-color:rgba(10,10,10,0)
.ax
height:200em
.a1:hover, .a2:hover, .battCells:hover
background-color:#{config.colourIdleHover}
.a1:hover s, .a2:hover s, .battCells:hover s
border-bottom-color:#{config.colourIdleHover}
.a1:hover b, .a2:hover b, .battCells:hover b
border-top-color:#{config.colourIdleHover}
.output
padding: 5em 10em
font-size: 30em
font-weight: 100
text-shadow: 0 0em 5em #000000
background-color: rgba(0,0,0,0.2)
border: 1em solid #fff
.content
transform:rotate(-90deg)
font-style: Black
z-index:99999
.clock
font-size: 30em
.sal
font-family: Songti SC
font-style: Black
font-size:40em
.Wcontent
transform:rotate(-90deg)
font-style: Black
font-size: 15em
z-index:99999
visibility:hidden
.contentS
transform:rotate(-90deg)
font-style: Black
z-index:99999
.Bat
font-weight: bold
font-size: 15em
text-transform: uppercase
.id
font-size:20em
font-family:Futura
font-style:normal
.BatStatus
font-weight: bold
font-size: 20em
text-transform: uppercase
.Rotate
transform:rotate(-90deg)
width:200em
.iTunesPre
width:0;height:0
position:relative
border-right:11em dotted transparent
border-left:11em dotted transparent
border-top:20em solid #{config.colourWhit}
right:-40em
top:-10em
.iTunesNext
width:0;height:0
position:relative
border-right:11em dotted transparent
border-left:11em dotted transparent
border-bottom:20em solid #{config.colourWhit}
right:-40em
top:-260em
.iTunesPause
width:30em;height:8em
position:relative
border-top:8em solid #{config.colourWhit}
border-bottom:8em solid #{config.colourWhit}
right:-37em
top:-100em
.iTunesPlay
width:0;height:0
position:relative
border-right:17em dotted transparent
border-left:17em dotted transparent
border-bottom:30em solid #{config.colourWhit}
right:-35em
top:-170em
.iTunesPlay:active
border-bottom-color: #{config.colourIdleHover}
.iTunesPause:active
border-top-color: #{config.colourIdleHover}
border-bottom-color: #{config.colourIdleHover}
.iTunesNext:active
border-bottom-color: #{config.colourIdleHover}
.iTunesPre:active
border-top-color: #{config.colourIdleHover}
.Disk
background-color: rgba(226,161,54,1)
position: relative
font-size: 10em
left: 1em; top:0.7em
width:5em;height:4em
border:0.2em solid #{config.colourWhit}
border-right: 0.5em solid #{config.colourWhit}
z-index:99999
.DiskN
width: 9em; height:4em
margin-left:2em;
margin-top:-3.5em;
text-overflow:ellipsis;
overflow:hidden;
font-size:10em
transform:rotate(-90deg)
font-style: Black
z-index:99999
.iTunesCover
position: fixed;
left:410em; bottom:500em;
width:200em; height:200em;
background-color: #{config.colourIdle};
z-index:99999
.iTunesCoverMask
color:white
position: fixed;
margin-left:5em; margin-top:5em;
width: 190em; height: 190em;
background-color: rgba(10,10,10,0.75);
.iTunesRatingBlock
width:33em;height:10em;
margin-left:1em;margin-right:1em;
background-color: rgba(256,256,256,0.5);
display:inline-block;
"""
render: -> """
<div class="left" style="float:left">
<div class="iTunesCover CoverCell">
<div class="iTunesCoverMask">
<div style="font-size:30em;font-family:IMPACT">SEELE</div>
<div style="font-size:70em;font-family:IMPACT" id="iTunesTrack">00</div>
<div style="font-size:30em;font-family:IMPACT">SOUND</div>
<div style="font-size:30em;font-family:IMPACT">ONLY</div>
</div>
<div style="width:190em;height:190em;margin-top:5em" id="iTunesCoverImg"></div>
<div class="iTunesRatingBlock" id="rate1"></div>
<div class="iTunesRatingBlock" id="rate2"></div>
<div class="iTunesRatingBlock" id="rate3"></div>
<div class="iTunesRatingBlock" id="rate4"></div>
<div class="iTunesRatingBlock" id="rate5"></div>
</div>
<div class="nav a2 CoverCell" target="_blank" href="#" id="44"><s></s><b1></b1></div>
<div class="nav a2 CoverCell" target="_blank" href="#" id="45"><s1></s1><b></b></div>
<div class="nav a0" target="_blank" href="#" id="46"><s></s><b></b>
<div class="id">46</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="47"><s></s><b></b>
<div class="id">47</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 CoverCell" target="_blank" href="#" id="48"><s></s><b2></b2></div>
<div class="nav a0" target="_blank" href="#" id="49"><s></s><b></b>
<div class="id">49</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="50"><s></s><b></b>
<div class="id">50</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav ai" target="_blank" href="#" id="51"></div>
<div class="nav a2 NetCell" target="_blank" href="#" style="z-index:9999"><s1></s1><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">Ibytes/s</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-70em;font-family:Futura;font-style:normal">
<span class="NetU" style="font-size:25em">Fehler</span>
</div>
<div class="contentS" style="position:absolute;left:55em;top:-95em;">
<span style="font-size:15em">Obytes/s</span>
</div>
</div>
<div class="nav a5" target="_blank" href="#" id="53"><s1></s1><b1></b1></div>
<div class="nav a0" target="_blank" href="#" id="54"><s></s><b></b>
<div class="id">54</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a2 NetCell" target="_blank" href="#"><s></s><b2></b2>
<div class="content" style="margin-left:30em;margin-top:-4em;font-family:Futura;font-style:normal">
<span class="NetD" style="font-size:25em">Fehler</span>
</div></div>
<div class="nav a5" target="_blank" href="#" id="56"><s></s><b3></b3></div>
<div class="nav a5" target="_blank" href="#" id="57" style="z-index:99999"><s2></s2><b></b>
<div class="Rotate" style="text-overflow:ellipsis;
overflow:hidden;
position:absolute;
top:-85em;left:-20em;
text-align:center;height:40em;width:200em">
<span id="iTunesArtist" style="font-size:12em"></span>
</div>
<div class="Rotate" style="text-overflow:ellipsis;
overflow:hidden;
position:absolute;
top:-85em;left:-92em;
text-align:center;height:40em;width:200em">
<span id="iTunesTitle" style="font-size:12em"></span>
</div>
<div class="iTunesPre"></div><div class="iTunesPre"></div>
<div class="iTunesPause"></div><div class="iTunesPlay"></div>
<div class="iTunesNext"></div><div class="iTunesNext"></div></div>
<div class="nav ai" target="_blank" href="#" id="58"><s></s><b></b></div>
<div class="nav a0" target="_blank" href="#" id="59"><s></s><b></b>
<div class="id">59</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a5" target="_blank" href="#" id="60"><s></s><b2></b2></div>
<div class="nav a0" target="_blank" href="#" id="61"><s></s><b></b>
<div class="id">61</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a2" target="_blank" href="#" id="62" style="margin-right:140em"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="62content"></div></div>
<div class="nav a0" target="_blank" href="#" id="63"><s></s><b></b>
<div class="id">63</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="64"><s></s><b></b>
<div class="id">64</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="65"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="65content"></div></div>
<div class="nav a2" target="_blank" href="#" id="66"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="66content"></div></div>
<div class="nav a0" target="_blank" href="#" id="67"><s></s><b></b>
<div class="id">67</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="68"><s></s><b></b>
<div class="id">68</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a2" target="_blank" href="#" id="69" style="margin-right:140em"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="69content"></div></div>
<div class="nav a0" target="_blank" href="#" id="70"><s></s><b></b>
<div class="id">70</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="71"><s></s><b></b>
<div class="id">71</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="72"><s></s><b></b>
<div class="Disk">Vol。</div>
<div class="DiskN" id="72content"></div></div>
<div class="nav a0" target="_blank" href="#" id="73"><s></s><b></b>
<div class="id">73</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="74"><s></s><b></b>
<div class="id">74</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="75"><s></s><b></b>
<div class="id">75</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="76"><s></s><b></b>
<div class="id">76</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="77"><s></s><b></b>
<div class="id">77</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="78"><s></s><b></b>
<div class="id">78</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="79"><s></s><b></b>
<div class="id">79</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="80"><s></s><b></b>
<div class="id">80</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="81"><s></s><b></b>
<div class="id">81</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="82"><s></s><b></b>
<div class="id">82</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
</div>
<div class="right">
<div class="nav a0" target="_blank" href="#" id="0"><s></s><b></b>
<div class="id">0</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="1"><s></s><b></b>
<div class="id">1</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="2"><s></s><b></b>
<div class="id">2</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="3"><s></s><b></b>
<div class="id">3</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="4"><s></s><b></b>
<div class="id">4</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="5"><s></s><b></b>
<div class="contentS" style="margin-left:10em;margin-top:0em">
<span class="day" style="width:20em;font-size:15em"></span>
</div></div><p></p>
<div class="nav a0" target="_blank" href="#" id="6"><s></s><b></b>
<div class="id">6</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="7"><s></s><b></b>
<div class="id">7</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="8"><s></s><b></b>
<div class="id">8</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="9"><s></s><b></b>
<div class="content" style="margin-left:10em;margin-top:-5em">
<span class="time" style="font-size:30em;font-family:Futura;font-style:normal"></span>
</div></div><p></p>
<div class="nav a1" target="_blank" href="#" id="CPUCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">CPU</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-70em;font-family:Futura;font-style:normal">
<span class="CPUU" style="font-size:30em;">Fehler</span>
</div></div>
<div class="nav a2" target="_blank" href="#" id="11"><s></s><b></b>
<div class="content" style="margin-left:10em;margin-top:-5em">
<span class="sal"></span>
</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="12"></div>
<div class="nav a0" target="_blank" href="#" id="13"><s></s><b></b>
<div class="id">13</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav battCells" target="_blank" href="#" id="14"><s></s><b1></b1></div>
<div class="nav ai" target="_blank" href="#" id="15"><s></s><b></b>
<div class="contentS" style="margin-left:-25em;margin-top:-4em">
<span style="font-size:15em">verbleibend</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-65em">
<span class="BatRe" style="font-size:30em">Fehler</span>
</div></div><p></p>
<div class="nav a1" target="_blank" href="#" id="MemCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">Speicher</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-55em">
<span class="MEMU" style="font-size:23em">Fehler</span>
</div></div>
<div class="nav battCells" target="_blank" href="#" id="17" style="z-index:9999"><s2></s2><b></b>
<div class="Rotate" style="margin-top:-70em;margin-left:-60em;text-align:left"><span class="Bat"></span></div>
<div class="Rotate" style="margin-top:-65em;margin-left:-35em;text-align:left"><span class="BatStatus"></span></div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="18"></div>
<div class="nav a0" target="_blank" href="#" id="19"><s></s><b></b>
<div class="id">19</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav battCells" target="_blank" href="#" id="BatCell"><s></s><b2></b2>
<div class="Rotate" style="margin-top:-5em;margin-left:-35em;width:200em;text-align:center;font-family:Futura;font-style:normal">
<span class="BatPer" style="font-size:20em">Fehler</span>
</div></div>
<div class="nav a0" target="_blank" href="#" id="21"><s></s><b></b>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="contentS" style="text-decoration:underline overline;font-size:15em"><u></u><d></d>WARNUNG</div></div>
<p></p>
<div class="nav a1 a0" target="_blank" href="#" id="22"><s></s><b></b>
<div class="id">22</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="TrashCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em;margin-top:-5em">
<span style="font-size:15em">Papierkorb</span>
</div>
<div class="content" style="margin-left:30em;margin-top:-62em">
<span class="TrashSize" style="font-size:25em">Fehler</span>
</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="24"></div>
<div class="nav a0" target="_blank" href="#" id="25"><s></s><b></b>
<div class="id">25</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a0" target="_blank" href="#" id="26"><s></s><b></b>
<div class="id">26</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav ai" target="_blank" href="#" id="27" style="background:#{config.colourWarn}">
<s style="border-bottom-color:#{config.colourWarn}"></s>
<b style="border-top-color:#{config.colourWarn}"></b>
<o></o>
<o style="transform:rotate(-60deg)"></o>
<o style="transform:rotate(-120deg)"></o>
<div class="contentS" style="text-align:center;font-size:20em">
Update!
</div>
</div><p></p>
<div class="nav a1" target="_blank" href="#" id="IPCell"><s></s><b></b>
<div class="contentS" style="margin-left:-25em">
<span style="font-size:15em">PublikIP</span>
</div>
<div class="content" style="margin-left:15em;margin-top:-64em;">
<span class="PubIP" style="font-size:13em;font-family:Futura;font-style:normal">Fehler</span>
</div></div>
<div class="nav a0" target="_blank" href="#" id="29"><s></s><b></b>
<div class="id">29</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div><p></p>
<div class="nav ai" target="_blank" href="#" id="30"></div>
<div class="nav a0" target="_blank" href="#" id="31"><s></s><b></b>
<div class="id">31</div>
<o></o><o style="transform:rotate(-60deg)"></o><o style="transform:rotate(-120deg)"></o>
<div class="Wcontent" style="text-decoration:underline overline"><u></u><d></d>WARNUNG</div></div>
<div class="nav a2" target="_blank" href="#" id="32"><s></s><div style="font-size:20em">32</div><b></b></div>
<div class="nav ai" target="_blank" href="#" id="33"></div><p></p>
<div class="nav ai" target="_blank" href="#" id="34"></div><p></p>
<div class="nav a4" target="_blank" href="#" id="35" style="margin-right:140em"><s></s><b1></b1></div>
<div class="nav a4" target="_blank" href="#" id="36"><s></s><b1></b1>
<div class='a4x' style="transform:rotate(-90deg);margin-left:-10em;visibility:hidden">
<div style="font-size:20em">OUTPUT</div>
</div>
</div><p></p>
<div class="nav ai" target="_blank" href="#" id="37"></div>
<div class="nav a4" target="_blank" href="#" id="38"><s></s><b3></b3></div>
<div class="nav a4" target="_blank" href="#" id="39"><s2></s2><b3></b3></div>
<div class="nav a4" target="_blank" href="#" id="40" style="z-index:9999"><s2></s2><b></b>
<div class="a4x" style="margin-top:-200em;margin-left:-150em;width:400em;transform:rotate(-90deg);text-align:left;visibility:hidden;line-height:110%">
<span class="OP" style="text-transform:none;font-size:20em;line-height:100%"></span>
</div>
</div>
<p></p>
<div class="nav a4" target="_blank" href="#" id="41" style="margin-right:140em"><s></s><b2></b2></div>
<div class="nav a4" target="_blank" href="#" id="42"><s></s><b2></b2></div><p></p>
<div class="nav ai" target="_blank" href="#" id="43"></div>
</div>
"""
command: ""
afterRender: (domEl) ->
# Define constants
window.segments = ["子時", "丑時", "寅時", "卯時", "辰時", "巳時", "午時", "未時", "申時", "酉時", "戌時", "亥時"]
# I don't know Germany so deleted because I'll reconstruct the code thoroughly
window.voice = "daniel"
window.voiceBatteryLow = "warning, battery level critical"
window.voiceBatteryCharging = "battery charging"
window.voiceCPUzuHohe = "warning, cpu overloaded"
window.voiceMEMzuHohe = "warning, memory pressure too high"
window.voiceNichtStoerenEin = "no disturb mode is on"
window.voiceNichtStoerenAus = "no disturb mode is off"
window.Batterievalues = [
'AC Only'
''
'AC Power'
''
]
window.daylist = [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday'
]
window.TrashEmpty = "Empty"
window.ErrorMessage = "Error"
window.WarningMessage = "WARNING"
window.BatteryStatus = [
'charging'
'charged'
'discharging'
'finishing'
]
window.BatteryType = "internalbattery"
$(domEl).find("#MemCell span").text("Memory")
$(domEl).find("#IPCell span").text("PublicIP")
$(domEl).find("#TrashCell span").text("Trash")
$(domEl).find(".Wcontent ").html("<u></u><d></d>#{window.WarningMessage}")
$(domEl).find("#21 .contentS").html("<u></u><d></d>#{window.WarningMessage}")
# Voice
window.voiceCommand = "say -v " + window.voice + " "
# Initialise warnings
window.Bwarning=0
window.Cwarning=0
window.IPFehler=0
window.Swarning=0
window.Mwarning=0
window.cellColour=-1
window.count = -1
window.BatteryPercentage=""
window.BatteryState=""
window.CPUUsage = ""
window.MemUsage = "1"
window.CPUAmount = ""
window.Disturbvalues = "0"
window.tiktok = -1
$(domEl).on 'click', '.iTunesPre', => @run "osascript -e 'tell application \"iTunes\" to previous track'"
$(domEl).on 'click', '.iTunesNext', => @run "osascript -e 'tell application \"iTunes\" to next track'"
$(domEl).on 'click', '.iTunesPause', => @run "osascript -e 'tell application \"iTunes\" to pause'"
$(domEl).on 'click', '.iTunesPlay', => @run "osascript -e 'tell application \"iTunes\" to play'"
$(domEl).on 'click', '#TrashCell', => @run "osascript -e 'tell application \"Finder\" to empty'"
# Command to open up mounted volumes
$(domEl).on 'click', '#66', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 1 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#69', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 2 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#72', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 3 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#62', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 4 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#65', => @run "ls /Volumes/ | awk -F'\t' '{ print $0}' > tmp.txt;i=1; cat tmp.txt | sed -e 's/[ ]/\\ /g ' | while read line; do if [ \"$i\" -eq 5 ]; then open /Volumes/\"${line}\"; fi; let i=i+1; done; rm tmp.txt
"
$(domEl).on 'click', '#27', =>
$(domEl).find("#27 .contentS").text("loading")
@run "head -16 Eva.widget/index.coffee > updateConfig.tmp &&
curl -o ../Evangelion_style_dashboard.widget.zip https://raw.githubusercontent.com/jeticg/Evangelion-Uebersicht-Widget/#{config.remoteBranch}/Evangelion_style_dashboard.widget.zip &&
cp -r Eva.widget ../Eva.widget &&
unzip -o ../Evangelion_style_dashboard.widget.zip -d ../ &&
sh ../Eva.widget/updateConfig.sh &&
cp -r ../Eva.widget/* ./Eva.widget/ &&
rm -r ../Evangelion_style_dashboard.widget.zip &&
rm -r ../Eva.widget &&
rm -r ../__MACOSX"
@run "rm Eva.widget/netstat.ipworking", (error, stdout, stderr) ->
@run 'csrutil status', (error, stdout, stderr) ->
if stdout
console.log stdout
if stderr
console.error stderr
update: (output, domEl) ->
# functions
# This is for the warning animations
animation_on = (cell, colour) -> () ->
if colour == 1
$(domEl).find("#{cell}" ).css("animation", "meow 1s linear 0s infinite alternate")
else if colour == 2
$(domEl).find("#{cell}" ).css("animation", "meow 1s linear 0s infinite alternate")
else if colour == 0
animation_off(cell)
animation_off = (cell) ->
$(domEl).find("#{cell} s").css("animation", "")
$(domEl).find("#{cell} b").css("animation", "")
$(domEl).find("#{cell}" ).css("animation", "")
# This function is for changing the colour of cell(s).
colourChange = (cell, colour) ->
if $.type(cell) == "object"
$element = cell
cell = ""
$element.css("background", colour)
else
$element = $(domEl)
$element.find("#{cell}").css("background", colour)
$element.find("#{cell} s").css("border-bottom-color", colour)
$element.find("#{cell} b").css("border-top-color", colour)
$element.find("#{cell} s1").css("border-bottom-color", colour)
$element.find("#{cell} s2").css("border-bottom-color", colour)
$element.find("#{cell} b1").css("border-top-color", colour)
$element.find("#{cell} b2").css("border-top-color", colour)
$element.find("#{cell} b3").css("border-top-color", colour)
# Display disk information
diskDisplay = (cell, tmp) ->
$(domEl).find("#{cell}").css("visibility","visible")
$(domEl).find("#{cell} .DiskN").text("#{tmp[0..(tmp.length-2)]}")
if (tmp.indexOf("@") > -1 )
$(domEl).find("#{cell} .Disk").css("background-color","rgba(128,128,160,1)")
$(domEl).find("#{cell} .Disk").text("Sys。")
else
$(domEl).find("#{cell} .Disk").css("background-color","rgba(226,161,54,1)")
$(domEl).find("#{cell} .Disk").text("Vol。")
# General warning settings. This function is called at the end of each
# widget refreshing.
warning_switch = (red, orange) ->
CorrectColour = 0
if orange > 0
CorrectColour = 2
if red > 0
CorrectColour = 1
if (cellColour != CorrectColour)
cellColour += CorrectColour - cellColour
animation_off(".a0")
for element in $(domEl).find(".a0")
work = (cell) -> () ->
$cell = $(cell)
if cellColour == 1
colourChange($cell, config.colourWarn)
$cell.find(".Wcontent").html("<u></u><d></d>#{WarningMessage}")
$cell.find(".Wcontent").css("visibility","visible")
$cell.find(".id" ).css("display" ,"none" )
else if cellColour == 2
colourChange($cell, config.colourDNDS)
$cell.find(".Wcontent").html("NoDisturb")
$cell.find(".Wcontent").css("visibility","visible")
$cell.find(".id" ).css("display" ,"none" )
else
colourChange($cell, config.colourIdle)
$cell.find(".Wcontent").css("visibility","hidden" )
$cell.find(".id" ).css("display" ,"inline-block")
setTimeout (work(element)), Math.random() * 1000
setTimeout (animation_on(".a0", cellColour)), 1000
convert2B = (input) ->
output = input
if (parseInt(output)>=1024)
output = parseInt(output)/1024
if (parseInt(output)>=1024)
output = parseInt(output)/1024
output = Math.round(output*10)/10 + 'M'
else
output = Math.round(output*10)/10 + 'K'
return output
getTime = () ->
# Processing time
# This is for outputing the time. Nothing really
date = new Date()
hour = date.getHours()
minutes = date.getMinutes()
days = date.getDay()
minutes = "0"+ minutes if minutes < 10
timeSegment = segments[0]
timeSegment = segments[1] if 1 <= hour < 3
timeSegment = segments[2] if 3 <= hour < 5
timeSegment = segments[3] if 5 <= hour < 7
timeSegment = segments[4] if 7 <= hour < 9
timeSegment = segments[5] if 9 <= hour < 11
timeSegment = segments[6] if 11 <= hour < 13
timeSegment = segments[7] if 13 <= hour < 15
timeSegment = segments[8] if 15 <= hour < 17
timeSegment = segments[9] if 17 <= hour < 19
timeSegment = segments[10] if 19 <= hour < 21
timeSegment = segments[11] if 21 <= hour < 23
$(domEl).find('.sal').text("#{timeSegment}")
$(domEl).find('.time').text("#{hour}:#{minutes}")
$(domEl).find('.day').text("#{daylist[days]}")
# Execution
getTime()
window.tiktok += 1
if (window.tiktok == 3)
window.tiktok = 0
# Battery
if (window.tiktok == 0)
@run "sh Eva.widget/battery.sh", (error, stdout, stderr) ->
if (stdout.indexOf("InternalBattery") > -1)
window.Batterievalues = stdout.split(' ')
if (Batterievalues[0].indexOf("InternalBattery") > -1)
$(domEl).find('.Bat').text("#{BatteryType}")
else
$(domEl).find('.Bat').text("#{Batterievalues[0]}")
if (Batterievalues[1].indexOf("id=") > -1)
window.BatteryPercentage=Batterievalues[2]
window.BatteryState=Batterievalues[3]
$(domEl).find('.BatPer').text("#{Batterievalues[2]}")
if (Batterievalues[3].indexOf("discharging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[2]}")
else if (Batterievalues[3].indexOf("charged") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[1]}")
else if (Batterievalues[3].indexOf("charging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[0]}")
else if (Batterievalues[3].indexOf("finishing") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[3]}")
else
$(domEl).find('.BatStatus').text("#{Batterievalues[3]}")
$(domEl).find('.BatRe').text("#{Batterievalues[4]}")
else
window.BatteryPercentage=Batterievalues[1]
window.BatteryState=Batterievalues[2]
$(domEl).find('.BatPer').text("#{Batterievalues[1]}")
if (Batterievalues[2].indexOf("discharging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[2]}")
else if (Batterievalues[2].indexOf("charged") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[1]}")
else if (Batterievalues[2].indexOf("charging") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[0]}")
else if (Batterievalues[2].indexOf("finishing") > -1)
$(domEl).find('.BatStatus').text("#{BatteryStatus[3]}")
else
$(domEl).find('.BatStatus').text("#{Batterievalues[2]}")
$(domEl).find('.BatRe').text("#{Batterievalues[3]}")
# CPU and Memory
@run "sh Eva.widget/cpu_mem.sh", (error, stdout, stderr) ->
stdout = stdout.split('\n')
window.CPUUsage = stdout[0].split(' ')
window.MemUsage = stdout[1].split(' ')
window.CPUAmount = stdout[2].split(' ')
$(domEl).find('.CPUU').text("#{Math.floor(CPUUsage/CPUAmount)}%")
if (MemUsage.indexOf("1") > -1)
$(domEl).find('.MEMU').text("NORMAL")
else if (MemUsage.indexOf("2") > -1)
$(domEl).find('.MEMU').text("WARNIN")
else if (MemUsage.indexOf("4") > -1)
$(domEl).find('.MEMU').text("CRITICAL")
# Trash
@run "du -ch ~/.Trash | grep total | cut -c 1-5", (error, stdout, stderr) ->
window.Trashvalues = stdout.split(' ')
window.Trashvalues="#{window.Trashvalues}".replace /,/g, ''
window.Trashvalues="#{window.Trashvalues}".replace /\s+/g, ''
if (Trashvalues.indexOf("0B") > -1)
$(domEl).find('.TrashSize').text("#{TrashEmpty}")
else
$(domEl).find('.TrashSize').text("#{Trashvalues}")
# Network status
@run "sh Eva.widget/netstat.sh", (error, stdout, stderr) ->
stdout = stdout.split('\n')
window.Networkvalues = stdout[0].split(' ')
window.IPaddress = stdout[1]
window.NetworkUp = convert2B(Networkvalues[0])
window.NetworkDl = convert2B(Networkvalues[1])
# The following is for Public IP and it's warning
if (window.IPaddress.indexOf("Fehler") > -1)
window.IPaddress=ErrorMessage
if IPFehler != 1
IPFehler = 1
colourChange("#IPCell", config.colourWarn)
else
if IPFehler != 0
IPFehler = 0
colourChange("#IPCell", config.colourIdle)
$(domEl).find('.PubIP').text("#{window.IPaddress}")
if (NetworkUp?)
$(domEl).find('.NetU').text("#{NetworkUp}")
if (NetworkDl?)
$(domEl).find('.NetD').text("#{NetworkDl}")
# Do Not Disturb
@run "defaults read ~/Library/Preferences/ByHost/com.apple.notificationcenterui doNotDisturb", (error, stdout, stderr) ->
window.Disturbvalues = stdout[0]
# iTunes
@run "sh Eva.widget/iTunes.sh 2>/dev/null", (error, stdout, stderr) ->
if (stdout.indexOf("osascript: Eva.widget/iTunes.scp:") > -1)
stdout = "¶ ¶ ¶ 0 ¶ 0"
window.iTunesvalues = stdout.split('¶')
if (stdout.indexOf("¶ ¶ ¶ 0 ¶ 0") > -1)
$(domEl).find(".CoverCell").css("visibility","hidden")
$(domEl).find("#44").css("visibility","hidden")
$(domEl).find("#45").css("visibility","hidden")
$(domEl).find("#48").css("visibility","hidden")
else
$(domEl).find(".CoverCell").css("visibility","visible")
$(domEl).find("#44").css("visibility","visible")
$(domEl).find("#45").css("visibility","visible")
$(domEl).find("#48").css("visibility","visible")
window.iTunesvalues[3] = "0" + window.iTunesvalues[3] if window.iTunesvalues[3] < 10
$(domEl).find('#iTunesTrack').text("#{iTunesvalues[3]}")
$(domEl).find('#iTunesArtist').text("#{iTunesvalues[1]}")
$(domEl).find('#iTunesTitle').text("#{iTunesvalues[0]}")
$(domEl).find('#iTunesCoverImg').html("<img style='width:190em;height:190em;margin-left:5em;' src='Eva.widget/album.jpg'>")
if (iTunesvalues[4]>0)
$(domEl).find('#rate1').css("visibility","visible")
else
$(domEl).find('#rate1').css("visibility","hidden")
if (iTunesvalues[4]>20)
$(domEl).find('#rate2').css("visibility","visible")
else
$(domEl).find('#rate2').css("visibility","hidden")
if (iTunesvalues[4]>40)
$(domEl).find('#rate3').css("visibility","visible")
else
$(domEl).find('#rate3').css("visibility","hidden")
if (iTunesvalues[4]>60)
$(domEl).find('#rate4').css("visibility","visible")
else
$(domEl).find('#rate4').css("visibility","hidden")
if (iTunesvalues[4]>80)
$(domEl).find('#rate5').css("visibility","visible")
else
$(domEl).find('#rate5').css("visibility","hidden")
# Disk
if (window.tiktok == 0)
@run "ls -F /Volumes/ | awk -F'\t' '{ print $0}'", (error, stdout, stderr) ->
stdout = stdout.split('\n')
if (stdout.length > 1)
diskDisplay("#66", stdout[0])
else $(domEl).find("#66").css("visibility","hidden")
if (stdout.length > 2)
diskDisplay("#69", stdout[1])
else $(domEl).find("#69").css("visibility","hidden")
if (stdout.length > 3)
diskDisplay("#72", stdout[2])
else $(domEl).find("#72").css("visibility","hidden")
if (stdout.length > 4)
diskDisplay("#62", stdout[3])
else $(domEl).find("#62").css("visibility","hidden")
if (stdout.length > 5)
diskDisplay("#65", stdout[4])
else $(domEl).find("#65").css("visibility","hidden")
# Dealing with warnings
# Bwarning stands for Battery warning, triggers when battery drops below 20% without charging.
if (parseInt(BatteryPercentage) <= config.BatteryAlertLevel & BatteryState.indexOf("discharging") > -1)
if (Bwarning == 0)
if config.Voice
@run voiceCommand + voiceBatteryLow
colourChange(".battCells", config.colourWarn)
colourChange("#15", config.colourWarnHover)
$(domEl).find("#15").css("visibility","visible")
Bwarning += 1
else
if (Bwarning == 1)
if config.Voice
@run voiceCommand + voiceBatteryCharging
colourChange(".battCells", config.colourIdle)
colourChange("#15", "rgba(128,0,0,0)")
$(domEl).find("#15").css("visibility","hidden")
Bwarning -= 1
# Swarning is for Memory usage. Warning is triggered when reaches above
# NORMAL level(1)
if (MemUsage.indexOf("1") <= -1)
if (Swarning == 0)
if config.Voice
@run voiceCommand + voiceMEMzuHohe
colourChange("#MemCell", config.colourWarn)
Swarning += 1
else
if (Swarning == 1)
colourChange("#MemCell", config.colourIdle)
Swarning -= 1
# Cwarning is for CPU usage. Default value is to trigger when CPU usage reaches 90%
if CPUUsage/CPUAmount > config.CPUAlertLevel
if (Cwarning == 0)
if config.Voice
@run voiceCommand + voiceCPUzuHohe
colourChange("#CPUCell", config.colourWarn)
Cwarning += 1
else
if (Cwarning == 1)
colourChange("#CPUCell", config.colourIdle)
Cwarning -= 1
if Disturbvalues == '1'
if (Mwarning == 0)
if config.Voice
@run voiceCommand + voiceNichtStoerenEin
Mwarning += 1
else
if (Mwarning == 1)
if config.Voice
@run voiceCommand + voiceNichtStoerenAus
Mwarning -= 1
warning_switch(Bwarning+Cwarning+Swarning, Mwarning)
# hover effects, dealing with hovering
$('.battCells').hover (->
if Bwarning == 1
colourChange(".battCells", config.colourWarnHover)
else
colourChange(".battCells", config.colourIdleHover)
), (->
if Bwarning == 1
colourChange(".battCells", config.colourWarn)
else
colourChange(".battCells", config.colourIdle)
)
$('#31').hover (
->
$(domEl).find("#31 .id").text("#{Version}")
), (
->
$(domEl).find("#31 .id").text("31")
)
$('#25').hover (
->
$(domEl).find("#25 .id").text("Jetic")
), (
->
$(domEl).find("#25 .id").text("25")
)
#$('#32').hover (
# ->
# colourChange("#32", config.colourIdleHover)
# colourChange(".a4", config.colourIdleHover)
# $(domEl).find(".a4x").css("visibility", "visible")
#), (
# ->
# colourChange("#32", config.colourIdle)
# colourChange(".a4", "rgba(10,10,10,0)")
# $(domEl).find(".a4x").css("visibility", "hidden")
#)
# Outputting all the information for debug
# $(domEl).find('.OP').text("#{output}")
|
[
{
"context": "\"\n\tparent: Drawer\n\t\nTitle = new TextLayer\n\ttext: \"John Locke\"\n\tfontFamily: \"Roboto\"\n\tfontWeight: 700\n\tfontSize",
"end": 2030,
"score": 0.9998742938041687,
"start": 2020,
"tag": "NAME",
"value": "John Locke"
},
{
"context": "rent: TopPortion\n\nSubtext ... | Android-Components/Nav Drawer/Drawer.coffee | iamkeeler/UXTOOLTIME-Framer | 4 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Drawer- hidden until hotspot is tapped
#Change Color Here
primarycolor = "#007cb0"
#Dark transparent screen bg
scrimbg = new Layer
backgroundColor: "rgba(50,50,50,0.50)"
width: Screen.width
height: Screen.height-48
y: Align.top
opacity: 0.0
#scrimbg states/animation
scrimbg.states.show=
opacity: 1.0
scrimbg.states.hide=
opacity: 0.0
options:
time: 0.5
#Main Container
Drawer = new Layer
width: 304
height: Screen.height-48
y: Align.top
x: Align.left -Screen.width-57
backgroundColor: "#fff"
shadowBlur: 16
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.24)"
shadowY: 0
shadowBlur: 16
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.18)"
shadowY: 0
#Drawer Icon Array
DrawerIcon = []
#Drawer Menu Option Titles - Set options here
MenuOptionText = ["Inbox","Outbox", "Trash", "Spam", "Forums", "Updates", "Promos", "Purchases"]
selecteditem = []
#set number of options here. Change number in []
for i in [0..7]
MenuLineItem = new Layer
height: 48
width: Drawer.width
backgroundColor: ""
y: i*48 + 184
name: [i]
parent: Drawer
Selected = new Layer
height: 40
width: Drawer.width-16
y: Align.center
x: 8
borderRadius: 4
backgroundColor: primarycolor
opacity: 0.0
name: "Selected" + [i]
parent: MenuLineItem
Icon = new Layer
size: 24
backgroundColor: "rgba(0,0,0,0.54)"
x: Align.left 16
y: Align.center
parent: MenuLineItem
MenuOption = new TextLayer
text: MenuOptionText[i]
fontFamily: "Roboto"
fontWeight: 500
color: "#000"
opacity: 0.87
fontSize: 14
x: Align.left 72
y: Align.center
parent: MenuLineItem
selecteditem.push(Selected)
#SelectedHighlight
Selected.onTap ->
for Selected in selecteditem
Selected.backgroundColor=""
this.backgroundColor=primarycolor
this.opacity= 0.2
#Top Color
TopPortion = new Layer
width: Drawer.width
height: 167
y: Align.top
backgroundColor: "primarycolor"
parent: Drawer
Title = new TextLayer
text: "John Locke"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 20
color: "rgba(0,0,0,0.87)"
y: Align.top 109
x: Align.left 16
parent: TopPortion
Subtext = new TextLayer
text: "heyfromjohn@gmail.com"
fontFamily: "Roboto"
fontWeight: 400
fontSize: 14
color: "rgba(0,0,0,0.87)"
y: Align.top 135
x: Align.left 16
parent: TopPortion
DrawerAvatar = new Layer
width: 48
height: 48
x: Align.left 16
y: Align.top 40
borderRadius: 100
backgroundColor: "#E0E0E0"
parent: TopPortion
DrawerDivider = new Layer
width: Drawer.width
height: 1
y: Align.bottom
backgroundColor: "#000"
opacity: 0.12
parent: TopPortion
# Hotspot layer - - set opacity to 0.0 to hide
DrawerHotSpot = new Layer
x: Align.left 5
y: Align.top 28
opacity: 0.3
width: 48
height: 48
# Show on hotspot click
DrawerHotSpot.onClick ->
Drawer.animate
x: Align.left
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("show")
#Hide on scrimbg click
scrimbg.onClick ->
Drawer.animate
x: Align.left -Screen.width-57
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("hide")
# Hide on bottomsheet swipe left
Drawer.onSwipeLeft ->
Drawer.animate
x: Align.left -Screen.width-57
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("hide")
# </fold>
"""
| 80493 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Drawer- hidden until hotspot is tapped
#Change Color Here
primarycolor = "#007cb0"
#Dark transparent screen bg
scrimbg = new Layer
backgroundColor: "rgba(50,50,50,0.50)"
width: Screen.width
height: Screen.height-48
y: Align.top
opacity: 0.0
#scrimbg states/animation
scrimbg.states.show=
opacity: 1.0
scrimbg.states.hide=
opacity: 0.0
options:
time: 0.5
#Main Container
Drawer = new Layer
width: 304
height: Screen.height-48
y: Align.top
x: Align.left -Screen.width-57
backgroundColor: "#fff"
shadowBlur: 16
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.24)"
shadowY: 0
shadowBlur: 16
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.18)"
shadowY: 0
#Drawer Icon Array
DrawerIcon = []
#Drawer Menu Option Titles - Set options here
MenuOptionText = ["Inbox","Outbox", "Trash", "Spam", "Forums", "Updates", "Promos", "Purchases"]
selecteditem = []
#set number of options here. Change number in []
for i in [0..7]
MenuLineItem = new Layer
height: 48
width: Drawer.width
backgroundColor: ""
y: i*48 + 184
name: [i]
parent: Drawer
Selected = new Layer
height: 40
width: Drawer.width-16
y: Align.center
x: 8
borderRadius: 4
backgroundColor: primarycolor
opacity: 0.0
name: "Selected" + [i]
parent: MenuLineItem
Icon = new Layer
size: 24
backgroundColor: "rgba(0,0,0,0.54)"
x: Align.left 16
y: Align.center
parent: MenuLineItem
MenuOption = new TextLayer
text: MenuOptionText[i]
fontFamily: "Roboto"
fontWeight: 500
color: "#000"
opacity: 0.87
fontSize: 14
x: Align.left 72
y: Align.center
parent: MenuLineItem
selecteditem.push(Selected)
#SelectedHighlight
Selected.onTap ->
for Selected in selecteditem
Selected.backgroundColor=""
this.backgroundColor=primarycolor
this.opacity= 0.2
#Top Color
TopPortion = new Layer
width: Drawer.width
height: 167
y: Align.top
backgroundColor: "primarycolor"
parent: Drawer
Title = new TextLayer
text: "<NAME>"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 20
color: "rgba(0,0,0,0.87)"
y: Align.top 109
x: Align.left 16
parent: TopPortion
Subtext = new TextLayer
text: "<EMAIL>"
fontFamily: "Roboto"
fontWeight: 400
fontSize: 14
color: "rgba(0,0,0,0.87)"
y: Align.top 135
x: Align.left 16
parent: TopPortion
DrawerAvatar = new Layer
width: 48
height: 48
x: Align.left 16
y: Align.top 40
borderRadius: 100
backgroundColor: "#E0E0E0"
parent: TopPortion
DrawerDivider = new Layer
width: Drawer.width
height: 1
y: Align.bottom
backgroundColor: "#000"
opacity: 0.12
parent: TopPortion
# Hotspot layer - - set opacity to 0.0 to hide
DrawerHotSpot = new Layer
x: Align.left 5
y: Align.top 28
opacity: 0.3
width: 48
height: 48
# Show on hotspot click
DrawerHotSpot.onClick ->
Drawer.animate
x: Align.left
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("show")
#Hide on scrimbg click
scrimbg.onClick ->
Drawer.animate
x: Align.left -Screen.width-57
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("hide")
# Hide on bottomsheet swipe left
Drawer.onSwipeLeft ->
Drawer.animate
x: Align.left -Screen.width-57
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("hide")
# </fold>
"""
| true | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Drawer- hidden until hotspot is tapped
#Change Color Here
primarycolor = "#007cb0"
#Dark transparent screen bg
scrimbg = new Layer
backgroundColor: "rgba(50,50,50,0.50)"
width: Screen.width
height: Screen.height-48
y: Align.top
opacity: 0.0
#scrimbg states/animation
scrimbg.states.show=
opacity: 1.0
scrimbg.states.hide=
opacity: 0.0
options:
time: 0.5
#Main Container
Drawer = new Layer
width: 304
height: Screen.height-48
y: Align.top
x: Align.left -Screen.width-57
backgroundColor: "#fff"
shadowBlur: 16
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.24)"
shadowY: 0
shadowBlur: 16
shadowSpread: 0
shadowColor: "rgba(0,0,0,0.18)"
shadowY: 0
#Drawer Icon Array
DrawerIcon = []
#Drawer Menu Option Titles - Set options here
MenuOptionText = ["Inbox","Outbox", "Trash", "Spam", "Forums", "Updates", "Promos", "Purchases"]
selecteditem = []
#set number of options here. Change number in []
for i in [0..7]
MenuLineItem = new Layer
height: 48
width: Drawer.width
backgroundColor: ""
y: i*48 + 184
name: [i]
parent: Drawer
Selected = new Layer
height: 40
width: Drawer.width-16
y: Align.center
x: 8
borderRadius: 4
backgroundColor: primarycolor
opacity: 0.0
name: "Selected" + [i]
parent: MenuLineItem
Icon = new Layer
size: 24
backgroundColor: "rgba(0,0,0,0.54)"
x: Align.left 16
y: Align.center
parent: MenuLineItem
MenuOption = new TextLayer
text: MenuOptionText[i]
fontFamily: "Roboto"
fontWeight: 500
color: "#000"
opacity: 0.87
fontSize: 14
x: Align.left 72
y: Align.center
parent: MenuLineItem
selecteditem.push(Selected)
#SelectedHighlight
Selected.onTap ->
for Selected in selecteditem
Selected.backgroundColor=""
this.backgroundColor=primarycolor
this.opacity= 0.2
#Top Color
TopPortion = new Layer
width: Drawer.width
height: 167
y: Align.top
backgroundColor: "primarycolor"
parent: Drawer
Title = new TextLayer
text: "PI:NAME:<NAME>END_PI"
fontFamily: "Roboto"
fontWeight: 700
fontSize: 20
color: "rgba(0,0,0,0.87)"
y: Align.top 109
x: Align.left 16
parent: TopPortion
Subtext = new TextLayer
text: "PI:EMAIL:<EMAIL>END_PI"
fontFamily: "Roboto"
fontWeight: 400
fontSize: 14
color: "rgba(0,0,0,0.87)"
y: Align.top 135
x: Align.left 16
parent: TopPortion
DrawerAvatar = new Layer
width: 48
height: 48
x: Align.left 16
y: Align.top 40
borderRadius: 100
backgroundColor: "#E0E0E0"
parent: TopPortion
DrawerDivider = new Layer
width: Drawer.width
height: 1
y: Align.bottom
backgroundColor: "#000"
opacity: 0.12
parent: TopPortion
# Hotspot layer - - set opacity to 0.0 to hide
DrawerHotSpot = new Layer
x: Align.left 5
y: Align.top 28
opacity: 0.3
width: 48
height: 48
# Show on hotspot click
DrawerHotSpot.onClick ->
Drawer.animate
x: Align.left
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("show")
#Hide on scrimbg click
scrimbg.onClick ->
Drawer.animate
x: Align.left -Screen.width-57
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("hide")
# Hide on bottomsheet swipe left
Drawer.onSwipeLeft ->
Drawer.animate
x: Align.left -Screen.width-57
options:
curve: "spring(250,37,20)"
scrimbg.stateSwitch("hide")
# </fold>
"""
|
[
{
"context": "book, you can stop this in your settings page.\", \"Cheers feen\"\n\n generateEmbedCode: (model) ->\n conso",
"end": 293,
"score": 0.9567973613739014,
"start": 282,
"tag": "NAME",
"value": "Cheers feen"
}
] | static/js/dss/lib/social.coffee | fergalmoran/dss | 0 | @social = do ->
postFacebookLike: (mixId) ->
#first off, find if the current user has allowed facebook likes
$.getJSON "social/like/" + mixId + "/", (data) ->
utils.showAlert "Posted your like to facebook, you can stop this in your settings page.", "Cheers feen"
generateEmbedCode: (model) ->
console.log("Generating embed code");
utils.modal "/dlg/embed/" + model.get('slug')
sharePageToTwitter: (model) ->
title = $(this).attr("title")
url = "http://" + window.location.host + model.get("item_url")
text = model.get("title")
window.open "http://twitter.com/share?url=#{url}&text={#text}", "twitterwindow", "height=450, width=550, top=" + ($(window).height() / 2 - 225) + ", left=" + $(window).width() / 2 + ", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"
sharePlaylistToTwitter: (model) ->
url = "http://" + window.location.host + model.get("item_url")
text = model.get("name")
window.open "http://twitter.com/share?url=#{url}&text={#text}", "twitterwindow", "height=450, width=550, top=" + ($(window).height() / 2 - 225) + ", left=" + $(window).width() / 2 + ", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"
_initFacebook: ->
FB.init({
appId : '154504534677009',
xfbml : true
});
sharePageToFacebook: (model) ->
@_initFacebook()
FB.getLoginStatus (oResponse) ->
if oResponse.status is "connected"
FB.ui
method: "feed"
name: "Check out this mix on Deep South Sounds"
display: "iframe"
link: "http://" + window.location.host + "/" + model.get("item_url")
picture: model.get("mix_image")
caption: model.get("title")
description: model.get("description")
, (response) ->
if response and response.post_id
utils.showAlert "Success", "Post shared to facebook"
else
utils.showError "Error", "Failure sharing post"
sharePlaylistToFacebook: (model) ->
@_initFacebook()
FB.getLoginStatus (oResponse) ->
if oResponse.status is "connected"
FB.ui
method: "feed"
name: "Check out this playlist on Deep South Sounds"
display: "iframe"
link: "http://" + window.location.host + "/" + model.get("item_url")
picture: model.get("playlist_image")
caption: model.get("name")
description: model.get("name")
, (response) ->
if response and response.post_id
utils.showAlert "Success", "Post shared to facebook"
else
utils.showError "Error", "Failure sharing post"
| 193803 | @social = do ->
postFacebookLike: (mixId) ->
#first off, find if the current user has allowed facebook likes
$.getJSON "social/like/" + mixId + "/", (data) ->
utils.showAlert "Posted your like to facebook, you can stop this in your settings page.", "<NAME>"
generateEmbedCode: (model) ->
console.log("Generating embed code");
utils.modal "/dlg/embed/" + model.get('slug')
sharePageToTwitter: (model) ->
title = $(this).attr("title")
url = "http://" + window.location.host + model.get("item_url")
text = model.get("title")
window.open "http://twitter.com/share?url=#{url}&text={#text}", "twitterwindow", "height=450, width=550, top=" + ($(window).height() / 2 - 225) + ", left=" + $(window).width() / 2 + ", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"
sharePlaylistToTwitter: (model) ->
url = "http://" + window.location.host + model.get("item_url")
text = model.get("name")
window.open "http://twitter.com/share?url=#{url}&text={#text}", "twitterwindow", "height=450, width=550, top=" + ($(window).height() / 2 - 225) + ", left=" + $(window).width() / 2 + ", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"
_initFacebook: ->
FB.init({
appId : '154504534677009',
xfbml : true
});
sharePageToFacebook: (model) ->
@_initFacebook()
FB.getLoginStatus (oResponse) ->
if oResponse.status is "connected"
FB.ui
method: "feed"
name: "Check out this mix on Deep South Sounds"
display: "iframe"
link: "http://" + window.location.host + "/" + model.get("item_url")
picture: model.get("mix_image")
caption: model.get("title")
description: model.get("description")
, (response) ->
if response and response.post_id
utils.showAlert "Success", "Post shared to facebook"
else
utils.showError "Error", "Failure sharing post"
sharePlaylistToFacebook: (model) ->
@_initFacebook()
FB.getLoginStatus (oResponse) ->
if oResponse.status is "connected"
FB.ui
method: "feed"
name: "Check out this playlist on Deep South Sounds"
display: "iframe"
link: "http://" + window.location.host + "/" + model.get("item_url")
picture: model.get("playlist_image")
caption: model.get("name")
description: model.get("name")
, (response) ->
if response and response.post_id
utils.showAlert "Success", "Post shared to facebook"
else
utils.showError "Error", "Failure sharing post"
| true | @social = do ->
postFacebookLike: (mixId) ->
#first off, find if the current user has allowed facebook likes
$.getJSON "social/like/" + mixId + "/", (data) ->
utils.showAlert "Posted your like to facebook, you can stop this in your settings page.", "PI:NAME:<NAME>END_PI"
generateEmbedCode: (model) ->
console.log("Generating embed code");
utils.modal "/dlg/embed/" + model.get('slug')
sharePageToTwitter: (model) ->
title = $(this).attr("title")
url = "http://" + window.location.host + model.get("item_url")
text = model.get("title")
window.open "http://twitter.com/share?url=#{url}&text={#text}", "twitterwindow", "height=450, width=550, top=" + ($(window).height() / 2 - 225) + ", left=" + $(window).width() / 2 + ", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"
sharePlaylistToTwitter: (model) ->
url = "http://" + window.location.host + model.get("item_url")
text = model.get("name")
window.open "http://twitter.com/share?url=#{url}&text={#text}", "twitterwindow", "height=450, width=550, top=" + ($(window).height() / 2 - 225) + ", left=" + $(window).width() / 2 + ", toolbar=0, location=0, menubar=0, directories=0, scrollbars=0"
_initFacebook: ->
FB.init({
appId : '154504534677009',
xfbml : true
});
sharePageToFacebook: (model) ->
@_initFacebook()
FB.getLoginStatus (oResponse) ->
if oResponse.status is "connected"
FB.ui
method: "feed"
name: "Check out this mix on Deep South Sounds"
display: "iframe"
link: "http://" + window.location.host + "/" + model.get("item_url")
picture: model.get("mix_image")
caption: model.get("title")
description: model.get("description")
, (response) ->
if response and response.post_id
utils.showAlert "Success", "Post shared to facebook"
else
utils.showError "Error", "Failure sharing post"
sharePlaylistToFacebook: (model) ->
@_initFacebook()
FB.getLoginStatus (oResponse) ->
if oResponse.status is "connected"
FB.ui
method: "feed"
name: "Check out this playlist on Deep South Sounds"
display: "iframe"
link: "http://" + window.location.host + "/" + model.get("item_url")
picture: model.get("playlist_image")
caption: model.get("name")
description: model.get("name")
, (response) ->
if response and response.post_id
utils.showAlert "Success", "Post shared to facebook"
else
utils.showError "Error", "Failure sharing post"
|
[
{
"context": " not have an unsupported ARIA attribute.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------",
"end": 135,
"score": 0.9998686909675598,
"start": 124,
"tag": "NAME",
"value": "Ethan Cohen"
}
] | src/tests/rules/role-supports-aria-props.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce that an element does not have an unsupported ARIA attribute.
# @author Ethan Cohen
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{aria, roles} = require 'aria-query'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/role-supports-aria-props'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
generateErrorMessage = (attr, role, tag, isImplicit) ->
return """
The attribute #{attr} is not supported by the role #{role}. \
This role is implicit on the element #{tag}.
""" if isImplicit
"The attribute #{attr} is not supported by the role #{role}."
errorMessage = (attr, role, tag, isImplicit) ->
message: generateErrorMessage attr, role, tag, isImplicit
type: 'JSXOpeningElement'
nonAbstractRoles = [...roles.keys()].filter (role) ->
roles.get(role).abstract is no
createTests = (rolesNames) ->
rolesNames.reduce(
(tests, role) ->
{props: propKeyValues} = roles.get role
validPropsForRole = Object.keys propKeyValues
invalidPropsForRole =
[...aria.keys()]
.map (attribute) -> attribute.toLowerCase()
.filter (attribute) -> validPropsForRole.indexOf(attribute) is -1
normalRole = role.toLowerCase()
allTests = []
allTests[0] = tests[0].concat(
validPropsForRole.map (prop) ->
code: "<div role=\"#{normalRole}\" #{prop.toLowerCase()} />"
)
allTests[1] = tests[1].concat(
invalidPropsForRole.map (prop) ->
code: "<div role=\"#{normalRole}\" #{prop.toLowerCase()} />"
errors: [errorMessage prop.toLowerCase(), normalRole, 'div', no]
)
allTests
,
[[], []]
)
[validTests, invalidTests] = createTests nonAbstractRoles
ruleTester.run 'role-supports-aria-props', rule,
valid:
[
code: '<Foo bar />'
,
code: '<div />'
,
code: '<div id="main" />'
,
code: '<div role />'
,
code: '<div role="presentation" {...props} />'
,
code: '<Foo.Bar baz={true} />'
,
# IMPLICIT ROLE TESTS
# A TESTS - implicit role is `link`
code: '<a href="#" aria-expanded />'
,
code: '<a href="#" aria-atomic />'
,
code: '<a href="#" aria-busy />'
,
code: '<a href="#" aria-controls />'
,
code: '<a href="#" aria-current />'
,
code: '<a href="#" aria-describedby />'
,
code: '<a href="#" aria-disabled />'
,
code: '<a href="#" aria-dropeffect />'
,
code: '<a href="#" aria-flowto />'
,
code: '<a href="#" aria-grabbed />'
,
code: '<a href="#" aria-haspopup />'
,
code: '<a href="#" aria-hidden />'
,
code: '<a href="#" aria-invalid />'
,
code: '<a href="#" aria-label />'
,
code: '<a href="#" aria-labelledby />'
,
code: '<a href="#" aria-live />'
,
code: '<a href="#" aria-owns />'
,
code: '<a href="#" aria-relevant />'
,
# this will have global
code: '<a aria-checked />'
,
# AREA TESTS - implicit role is `link`
code: '<area href="#" aria-expanded />'
,
code: '<area href="#" aria-atomic />'
,
code: '<area href="#" aria-busy />'
,
code: '<area href="#" aria-controls />'
,
code: '<area href="#" aria-describedby />'
,
code: '<area href="#" aria-disabled />'
,
code: '<area href="#" aria-dropeffect />'
,
code: '<area href="#" aria-flowto />'
,
code: '<area href="#" aria-grabbed />'
,
code: '<area href="#" aria-haspopup />'
,
code: '<area href="#" aria-hidden />'
,
code: '<area href="#" aria-invalid />'
,
code: '<area href="#" aria-label />'
,
code: '<area href="#" aria-labelledby />'
,
code: '<area href="#" aria-live />'
,
code: '<area href="#" aria-owns />'
,
code: '<area href="#" aria-relevant />'
,
# this will have global
code: '<area aria-checked />'
,
# LINK TESTS - implicit role is `link`
code: '<link href="#" aria-expanded />'
,
code: '<link href="#" aria-atomic />'
,
code: '<link href="#" aria-busy />'
,
code: '<link href="#" aria-controls />'
,
code: '<link href="#" aria-describedby />'
,
code: '<link href="#" aria-disabled />'
,
code: '<link href="#" aria-dropeffect />'
,
code: '<link href="#" aria-flowto />'
,
code: '<link href="#" aria-grabbed />'
,
code: '<link href="#" aria-haspopup />'
,
code: '<link href="#" aria-hidden />'
,
code: '<link href="#" aria-invalid />'
,
code: '<link href="#" aria-label />'
,
code: '<link href="#" aria-labelledby />'
,
code: '<link href="#" aria-live />'
,
code: '<link href="#" aria-owns />'
,
code: '<link href="#" aria-relevant />'
,
# this will have global
code: '<link aria-checked />'
,
# IMG TESTS - no implicit role
code: '<img alt="" aria-checked />'
,
# this will have role of `img`
code: '<img alt="foobar" aria-busy />'
,
# MENU TESTS - implicit role is `toolbar` when `type="toolbar"`
code: '<menu type="toolbar" aria-activedescendant />'
,
code: '<menu type="toolbar" aria-expanded />'
,
code: '<menu type="toolbar" aria-atomic />'
,
code: '<menu type="toolbar" aria-busy />'
,
code: '<menu type="toolbar" aria-controls />'
,
code: '<menu type="toolbar" aria-describedby />'
,
code: '<menu type="toolbar" aria-disabled />'
,
code: '<menu type="toolbar" aria-dropeffect />'
,
code: '<menu type="toolbar" aria-flowto />'
,
code: '<menu type="toolbar" aria-grabbed />'
,
code: '<menu type="toolbar" aria-haspopup />'
,
code: '<menu type="toolbar" aria-hidden />'
,
code: '<menu type="toolbar" aria-invalid />'
,
code: '<menu type="toolbar" aria-label />'
,
code: '<menu type="toolbar" aria-labelledby />'
,
code: '<menu type="toolbar" aria-live />'
,
code: '<menu type="toolbar" aria-owns />'
,
code: '<menu type="toolbar" aria-relevant />'
,
# this will have global
code: '<menu aria-checked />'
,
# MENUITEM TESTS
# when `type="command`, the implicit role is `menuitem`
code: '<menuitem type="command" aria-atomic />'
,
code: '<menuitem type="command" aria-busy />'
,
code: '<menuitem type="command" aria-controls />'
,
code: '<menuitem type="command" aria-describedby />'
,
code: '<menuitem type="command" aria-disabled />'
,
code: '<menuitem type="command" aria-dropeffect />'
,
code: '<menuitem type="command" aria-flowto />'
,
code: '<menuitem type="command" aria-grabbed />'
,
code: '<menuitem type="command" aria-haspopup />'
,
code: '<menuitem type="command" aria-hidden />'
,
code: '<menuitem type="command" aria-invalid />'
,
code: '<menuitem type="command" aria-label />'
,
code: '<menuitem type="command" aria-labelledby />'
,
code: '<menuitem type="command" aria-live />'
,
code: '<menuitem type="command" aria-owns />'
,
code: '<menuitem type="command" aria-relevant />'
,
# when `type="checkbox`, the implicit role is `menuitemcheckbox`
code: '<menuitem type="checkbox" aria-checked />'
,
code: '<menuitem type="checkbox" aria-atomic />'
,
code: '<menuitem type="checkbox" aria-busy />'
,
code: '<menuitem type="checkbox" aria-controls />'
,
code: '<menuitem type="checkbox" aria-describedby />'
,
code: '<menuitem type="checkbox" aria-disabled />'
,
code: '<menuitem type="checkbox" aria-dropeffect />'
,
code: '<menuitem type="checkbox" aria-flowto />'
,
code: '<menuitem type="checkbox" aria-grabbed />'
,
code: '<menuitem type="checkbox" aria-haspopup />'
,
code: '<menuitem type="checkbox" aria-hidden />'
,
code: '<menuitem type="checkbox" aria-invalid />'
,
code: '<menuitem type="checkbox" aria-label />'
,
code: '<menuitem type="checkbox" aria-labelledby />'
,
code: '<menuitem type="checkbox" aria-live />'
,
code: '<menuitem type="checkbox" aria-owns />'
,
code: '<menuitem type="checkbox" aria-relevant />'
,
# when `type="radio`, the implicit role is `menuitemradio`
code: '<menuitem type="radio" aria-checked />'
,
code: '<menuitem type="radio" aria-atomic />'
,
code: '<menuitem type="radio" aria-busy />'
,
code: '<menuitem type="radio" aria-controls />'
,
code: '<menuitem type="radio" aria-describedby />'
,
code: '<menuitem type="radio" aria-disabled />'
,
code: '<menuitem type="radio" aria-dropeffect />'
,
code: '<menuitem type="radio" aria-flowto />'
,
code: '<menuitem type="radio" aria-grabbed />'
,
code: '<menuitem type="radio" aria-haspopup />'
,
code: '<menuitem type="radio" aria-hidden />'
,
code: '<menuitem type="radio" aria-invalid />'
,
code: '<menuitem type="radio" aria-label />'
,
code: '<menuitem type="radio" aria-labelledby />'
,
code: '<menuitem type="radio" aria-live />'
,
code: '<menuitem type="radio" aria-owns />'
,
code: '<menuitem type="radio" aria-relevant />'
,
code: '<menuitem type="radio" aria-posinset />'
,
code: '<menuitem type="radio" aria-selected />'
,
code: '<menuitem type="radio" aria-setsize />'
,
# these will have global
code: '<menuitem aria-checked />'
,
code: '<menuitem type="foo" aria-checked />'
,
# INPUT TESTS
# when `type="button"`, the implicit role is `button`
code: '<input type="button" aria-expanded />'
,
code: '<input type="button" aria-pressed />'
,
code: '<input type="button" aria-atomic />'
,
code: '<input type="button" aria-busy />'
,
code: '<input type="button" aria-controls />'
,
code: '<input type="button" aria-describedby />'
,
code: '<input type="button" aria-disabled />'
,
code: '<input type="button" aria-dropeffect />'
,
code: '<input type="button" aria-flowto />'
,
code: '<input type="button" aria-grabbed />'
,
code: '<input type="button" aria-haspopup />'
,
code: '<input type="button" aria-hidden />'
,
code: '<input type="button" aria-invalid />'
,
code: '<input type="button" aria-label />'
,
code: '<input type="button" aria-labelledby />'
,
code: '<input type="button" aria-live />'
,
code: '<input type="button" aria-owns />'
,
code: '<input type="button" aria-relevant />'
,
# when `type="image"`, the implicit role is `button`
code: '<input type="image" aria-expanded />'
,
code: '<input type="image" aria-pressed />'
,
code: '<input type="image" aria-atomic />'
,
code: '<input type="image" aria-busy />'
,
code: '<input type="image" aria-controls />'
,
code: '<input type="image" aria-describedby />'
,
code: '<input type="image" aria-disabled />'
,
code: '<input type="image" aria-dropeffect />'
,
code: '<input type="image" aria-flowto />'
,
code: '<input type="image" aria-grabbed />'
,
code: '<input type="image" aria-haspopup />'
,
code: '<input type="image" aria-hidden />'
,
code: '<input type="image" aria-invalid />'
,
code: '<input type="image" aria-label />'
,
code: '<input type="image" aria-labelledby />'
,
code: '<input type="image" aria-live />'
,
code: '<input type="image" aria-owns />'
,
code: '<input type="image" aria-relevant />'
,
# when `type="reset"`, the implicit role is `button`
code: '<input type="reset" aria-expanded />'
,
code: '<input type="reset" aria-pressed />'
,
code: '<input type="reset" aria-atomic />'
,
code: '<input type="reset" aria-busy />'
,
code: '<input type="reset" aria-controls />'
,
code: '<input type="reset" aria-describedby />'
,
code: '<input type="reset" aria-disabled />'
,
code: '<input type="reset" aria-dropeffect />'
,
code: '<input type="reset" aria-flowto />'
,
code: '<input type="reset" aria-grabbed />'
,
code: '<input type="reset" aria-haspopup />'
,
code: '<input type="reset" aria-hidden />'
,
code: '<input type="reset" aria-invalid />'
,
code: '<input type="reset" aria-label />'
,
code: '<input type="reset" aria-labelledby />'
,
code: '<input type="reset" aria-live />'
,
code: '<input type="reset" aria-owns />'
,
code: '<input type="reset" aria-relevant />'
,
# when `type="submit"`, the implicit role is `button`
code: '<input type="submit" aria-expanded />'
,
code: '<input type="submit" aria-pressed />'
,
code: '<input type="submit" aria-atomic />'
,
code: '<input type="submit" aria-busy />'
,
code: '<input type="submit" aria-controls />'
,
code: '<input type="submit" aria-describedby />'
,
code: '<input type="submit" aria-disabled />'
,
code: '<input type="submit" aria-dropeffect />'
,
code: '<input type="submit" aria-flowto />'
,
code: '<input type="submit" aria-grabbed />'
,
code: '<input type="submit" aria-haspopup />'
,
code: '<input type="submit" aria-hidden />'
,
code: '<input type="submit" aria-invalid />'
,
code: '<input type="submit" aria-label />'
,
code: '<input type="submit" aria-labelledby />'
,
code: '<input type="submit" aria-live />'
,
code: '<input type="submit" aria-owns />'
,
code: '<input type="submit" aria-relevant />'
,
# when `type="checkbox"`, the implicit role is `checkbox`
code: '<input type="checkbox" aria-checked />'
,
code: '<input type="checkbox" aria-atomic />'
,
code: '<input type="checkbox" aria-busy />'
,
code: '<input type="checkbox" aria-controls />'
,
code: '<input type="checkbox" aria-describedby />'
,
code: '<input type="checkbox" aria-disabled />'
,
code: '<input type="checkbox" aria-dropeffect />'
,
code: '<input type="checkbox" aria-flowto />'
,
code: '<input type="checkbox" aria-grabbed />'
,
code: '<input type="checkbox" aria-haspopup />'
,
code: '<input type="checkbox" aria-hidden />'
,
code: '<input type="checkbox" aria-invalid />'
,
code: '<input type="checkbox" aria-label />'
,
code: '<input type="checkbox" aria-labelledby />'
,
code: '<input type="checkbox" aria-live />'
,
code: '<input type="checkbox" aria-owns />'
,
code: '<input type="checkbox" aria-relevant />'
,
# when `type="radio"`, the implicit role is `radio`
code: '<input type="radio" aria-checked />'
,
code: '<input type="radio" aria-atomic />'
,
code: '<input type="radio" aria-busy />'
,
code: '<input type="radio" aria-controls />'
,
code: '<input type="radio" aria-describedby />'
,
code: '<input type="radio" aria-disabled />'
,
code: '<input type="radio" aria-dropeffect />'
,
code: '<input type="radio" aria-flowto />'
,
code: '<input type="radio" aria-grabbed />'
,
code: '<input type="radio" aria-haspopup />'
,
code: '<input type="radio" aria-hidden />'
,
code: '<input type="radio" aria-invalid />'
,
code: '<input type="radio" aria-label />'
,
code: '<input type="radio" aria-labelledby />'
,
code: '<input type="radio" aria-live />'
,
code: '<input type="radio" aria-owns />'
,
code: '<input type="radio" aria-relevant />'
,
code: '<input type="radio" aria-posinset />'
,
code: '<input type="radio" aria-selected />'
,
code: '<input type="radio" aria-setsize />'
,
# when `type="range"`, the implicit role is `slider`
code: '<input type="range" aria-valuemax />'
,
code: '<input type="range" aria-valuemin />'
,
code: '<input type="range" aria-valuenow />'
,
code: '<input type="range" aria-orientation />'
,
code: '<input type="range" aria-atomic />'
,
code: '<input type="range" aria-busy />'
,
code: '<input type="range" aria-controls />'
,
code: '<input type="range" aria-describedby />'
,
code: '<input type="range" aria-disabled />'
,
code: '<input type="range" aria-dropeffect />'
,
code: '<input type="range" aria-flowto />'
,
code: '<input type="range" aria-grabbed />'
,
code: '<input type="range" aria-haspopup />'
,
code: '<input type="range" aria-hidden />'
,
code: '<input type="range" aria-invalid />'
,
code: '<input type="range" aria-label />'
,
code: '<input type="range" aria-labelledby />'
,
code: '<input type="range" aria-live />'
,
code: '<input type="range" aria-owns />'
,
code: '<input type="range" aria-relevant />'
,
code: '<input type="range" aria-valuetext />'
,
# these will have role of `textbox`,
code: '<input type="email" aria-disabled />'
,
code: '<input type="password" aria-disabled />'
,
code: '<input type="search" aria-disabled />'
,
code: '<input type="tel" aria-disabled />'
,
code: '<input type="url" aria-disabled />'
,
code: '<input aria-disabled />'
,
# Allow null/undefined values regardless of role
code: '<h2 role="presentation" aria-level={null} />'
,
code: '<h2 role="presentation" aria-level={undefined} />'
,
# OTHER TESTS
code: '<aside aria-expanded />'
,
code: '<article aria-expanded />'
,
code: '<body aria-expanded />'
,
code: '<button aria-pressed />'
,
code: '<datalist aria-expanded />'
,
code: '<details aria-expanded />'
,
code: '<dialog aria-expanded />'
,
code: '<dl aria-expanded />'
,
code: '<form aria-hidden />'
,
code: '<h1 aria-hidden />'
,
code: '<h2 aria-hidden />'
,
code: '<h3 aria-hidden />'
,
code: '<h4 aria-hidden />'
,
code: '<h5 aria-hidden />'
,
code: '<h6 aria-hidden />'
,
code: '<hr aria-hidden />'
,
code: '<li aria-current />'
,
code: '<li aria-expanded />'
,
code: '<meter aria-atomic />'
,
code: '<nav aria-expanded />'
,
code: '<ol aria-expanded />'
,
code: '<option aria-atomic />'
,
code: '<output aria-expanded />'
,
code: '<progress aria-atomic />'
,
code: '<section aria-expanded />'
,
code: '<select aria-expanded />'
,
code: '<tbody aria-expanded />'
,
code: '<textarea aria-hidden />'
,
code: '<tfoot aria-expanded />'
,
code: '<thead aria-expanded />'
,
code: '<ul aria-expanded />'
]
.concat validTests
.map parserOptionsMapper
invalid:
[
# implicit basic checks
code: '<a href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'a', yes]
,
code: '<area href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'area', yes]
,
code: '<link href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'link', yes]
,
code: '<img alt="foobar" aria-checked />'
errors: [errorMessage 'aria-checked', 'img', 'img', yes]
,
code: '<menu type="toolbar" aria-checked />'
errors: [errorMessage 'aria-checked', 'toolbar', 'menu', yes]
,
code: '<aside aria-checked />'
errors: [errorMessage 'aria-checked', 'complementary', 'aside', yes]
]
.concat invalidTests
.map parserOptionsMapper
| 33021 | ### eslint-env jest ###
###*
# @fileoverview Enforce that an element does not have an unsupported ARIA attribute.
# @author <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{aria, roles} = require 'aria-query'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/role-supports-aria-props'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
generateErrorMessage = (attr, role, tag, isImplicit) ->
return """
The attribute #{attr} is not supported by the role #{role}. \
This role is implicit on the element #{tag}.
""" if isImplicit
"The attribute #{attr} is not supported by the role #{role}."
errorMessage = (attr, role, tag, isImplicit) ->
message: generateErrorMessage attr, role, tag, isImplicit
type: 'JSXOpeningElement'
nonAbstractRoles = [...roles.keys()].filter (role) ->
roles.get(role).abstract is no
createTests = (rolesNames) ->
rolesNames.reduce(
(tests, role) ->
{props: propKeyValues} = roles.get role
validPropsForRole = Object.keys propKeyValues
invalidPropsForRole =
[...aria.keys()]
.map (attribute) -> attribute.toLowerCase()
.filter (attribute) -> validPropsForRole.indexOf(attribute) is -1
normalRole = role.toLowerCase()
allTests = []
allTests[0] = tests[0].concat(
validPropsForRole.map (prop) ->
code: "<div role=\"#{normalRole}\" #{prop.toLowerCase()} />"
)
allTests[1] = tests[1].concat(
invalidPropsForRole.map (prop) ->
code: "<div role=\"#{normalRole}\" #{prop.toLowerCase()} />"
errors: [errorMessage prop.toLowerCase(), normalRole, 'div', no]
)
allTests
,
[[], []]
)
[validTests, invalidTests] = createTests nonAbstractRoles
ruleTester.run 'role-supports-aria-props', rule,
valid:
[
code: '<Foo bar />'
,
code: '<div />'
,
code: '<div id="main" />'
,
code: '<div role />'
,
code: '<div role="presentation" {...props} />'
,
code: '<Foo.Bar baz={true} />'
,
# IMPLICIT ROLE TESTS
# A TESTS - implicit role is `link`
code: '<a href="#" aria-expanded />'
,
code: '<a href="#" aria-atomic />'
,
code: '<a href="#" aria-busy />'
,
code: '<a href="#" aria-controls />'
,
code: '<a href="#" aria-current />'
,
code: '<a href="#" aria-describedby />'
,
code: '<a href="#" aria-disabled />'
,
code: '<a href="#" aria-dropeffect />'
,
code: '<a href="#" aria-flowto />'
,
code: '<a href="#" aria-grabbed />'
,
code: '<a href="#" aria-haspopup />'
,
code: '<a href="#" aria-hidden />'
,
code: '<a href="#" aria-invalid />'
,
code: '<a href="#" aria-label />'
,
code: '<a href="#" aria-labelledby />'
,
code: '<a href="#" aria-live />'
,
code: '<a href="#" aria-owns />'
,
code: '<a href="#" aria-relevant />'
,
# this will have global
code: '<a aria-checked />'
,
# AREA TESTS - implicit role is `link`
code: '<area href="#" aria-expanded />'
,
code: '<area href="#" aria-atomic />'
,
code: '<area href="#" aria-busy />'
,
code: '<area href="#" aria-controls />'
,
code: '<area href="#" aria-describedby />'
,
code: '<area href="#" aria-disabled />'
,
code: '<area href="#" aria-dropeffect />'
,
code: '<area href="#" aria-flowto />'
,
code: '<area href="#" aria-grabbed />'
,
code: '<area href="#" aria-haspopup />'
,
code: '<area href="#" aria-hidden />'
,
code: '<area href="#" aria-invalid />'
,
code: '<area href="#" aria-label />'
,
code: '<area href="#" aria-labelledby />'
,
code: '<area href="#" aria-live />'
,
code: '<area href="#" aria-owns />'
,
code: '<area href="#" aria-relevant />'
,
# this will have global
code: '<area aria-checked />'
,
# LINK TESTS - implicit role is `link`
code: '<link href="#" aria-expanded />'
,
code: '<link href="#" aria-atomic />'
,
code: '<link href="#" aria-busy />'
,
code: '<link href="#" aria-controls />'
,
code: '<link href="#" aria-describedby />'
,
code: '<link href="#" aria-disabled />'
,
code: '<link href="#" aria-dropeffect />'
,
code: '<link href="#" aria-flowto />'
,
code: '<link href="#" aria-grabbed />'
,
code: '<link href="#" aria-haspopup />'
,
code: '<link href="#" aria-hidden />'
,
code: '<link href="#" aria-invalid />'
,
code: '<link href="#" aria-label />'
,
code: '<link href="#" aria-labelledby />'
,
code: '<link href="#" aria-live />'
,
code: '<link href="#" aria-owns />'
,
code: '<link href="#" aria-relevant />'
,
# this will have global
code: '<link aria-checked />'
,
# IMG TESTS - no implicit role
code: '<img alt="" aria-checked />'
,
# this will have role of `img`
code: '<img alt="foobar" aria-busy />'
,
# MENU TESTS - implicit role is `toolbar` when `type="toolbar"`
code: '<menu type="toolbar" aria-activedescendant />'
,
code: '<menu type="toolbar" aria-expanded />'
,
code: '<menu type="toolbar" aria-atomic />'
,
code: '<menu type="toolbar" aria-busy />'
,
code: '<menu type="toolbar" aria-controls />'
,
code: '<menu type="toolbar" aria-describedby />'
,
code: '<menu type="toolbar" aria-disabled />'
,
code: '<menu type="toolbar" aria-dropeffect />'
,
code: '<menu type="toolbar" aria-flowto />'
,
code: '<menu type="toolbar" aria-grabbed />'
,
code: '<menu type="toolbar" aria-haspopup />'
,
code: '<menu type="toolbar" aria-hidden />'
,
code: '<menu type="toolbar" aria-invalid />'
,
code: '<menu type="toolbar" aria-label />'
,
code: '<menu type="toolbar" aria-labelledby />'
,
code: '<menu type="toolbar" aria-live />'
,
code: '<menu type="toolbar" aria-owns />'
,
code: '<menu type="toolbar" aria-relevant />'
,
# this will have global
code: '<menu aria-checked />'
,
# MENUITEM TESTS
# when `type="command`, the implicit role is `menuitem`
code: '<menuitem type="command" aria-atomic />'
,
code: '<menuitem type="command" aria-busy />'
,
code: '<menuitem type="command" aria-controls />'
,
code: '<menuitem type="command" aria-describedby />'
,
code: '<menuitem type="command" aria-disabled />'
,
code: '<menuitem type="command" aria-dropeffect />'
,
code: '<menuitem type="command" aria-flowto />'
,
code: '<menuitem type="command" aria-grabbed />'
,
code: '<menuitem type="command" aria-haspopup />'
,
code: '<menuitem type="command" aria-hidden />'
,
code: '<menuitem type="command" aria-invalid />'
,
code: '<menuitem type="command" aria-label />'
,
code: '<menuitem type="command" aria-labelledby />'
,
code: '<menuitem type="command" aria-live />'
,
code: '<menuitem type="command" aria-owns />'
,
code: '<menuitem type="command" aria-relevant />'
,
# when `type="checkbox`, the implicit role is `menuitemcheckbox`
code: '<menuitem type="checkbox" aria-checked />'
,
code: '<menuitem type="checkbox" aria-atomic />'
,
code: '<menuitem type="checkbox" aria-busy />'
,
code: '<menuitem type="checkbox" aria-controls />'
,
code: '<menuitem type="checkbox" aria-describedby />'
,
code: '<menuitem type="checkbox" aria-disabled />'
,
code: '<menuitem type="checkbox" aria-dropeffect />'
,
code: '<menuitem type="checkbox" aria-flowto />'
,
code: '<menuitem type="checkbox" aria-grabbed />'
,
code: '<menuitem type="checkbox" aria-haspopup />'
,
code: '<menuitem type="checkbox" aria-hidden />'
,
code: '<menuitem type="checkbox" aria-invalid />'
,
code: '<menuitem type="checkbox" aria-label />'
,
code: '<menuitem type="checkbox" aria-labelledby />'
,
code: '<menuitem type="checkbox" aria-live />'
,
code: '<menuitem type="checkbox" aria-owns />'
,
code: '<menuitem type="checkbox" aria-relevant />'
,
# when `type="radio`, the implicit role is `menuitemradio`
code: '<menuitem type="radio" aria-checked />'
,
code: '<menuitem type="radio" aria-atomic />'
,
code: '<menuitem type="radio" aria-busy />'
,
code: '<menuitem type="radio" aria-controls />'
,
code: '<menuitem type="radio" aria-describedby />'
,
code: '<menuitem type="radio" aria-disabled />'
,
code: '<menuitem type="radio" aria-dropeffect />'
,
code: '<menuitem type="radio" aria-flowto />'
,
code: '<menuitem type="radio" aria-grabbed />'
,
code: '<menuitem type="radio" aria-haspopup />'
,
code: '<menuitem type="radio" aria-hidden />'
,
code: '<menuitem type="radio" aria-invalid />'
,
code: '<menuitem type="radio" aria-label />'
,
code: '<menuitem type="radio" aria-labelledby />'
,
code: '<menuitem type="radio" aria-live />'
,
code: '<menuitem type="radio" aria-owns />'
,
code: '<menuitem type="radio" aria-relevant />'
,
code: '<menuitem type="radio" aria-posinset />'
,
code: '<menuitem type="radio" aria-selected />'
,
code: '<menuitem type="radio" aria-setsize />'
,
# these will have global
code: '<menuitem aria-checked />'
,
code: '<menuitem type="foo" aria-checked />'
,
# INPUT TESTS
# when `type="button"`, the implicit role is `button`
code: '<input type="button" aria-expanded />'
,
code: '<input type="button" aria-pressed />'
,
code: '<input type="button" aria-atomic />'
,
code: '<input type="button" aria-busy />'
,
code: '<input type="button" aria-controls />'
,
code: '<input type="button" aria-describedby />'
,
code: '<input type="button" aria-disabled />'
,
code: '<input type="button" aria-dropeffect />'
,
code: '<input type="button" aria-flowto />'
,
code: '<input type="button" aria-grabbed />'
,
code: '<input type="button" aria-haspopup />'
,
code: '<input type="button" aria-hidden />'
,
code: '<input type="button" aria-invalid />'
,
code: '<input type="button" aria-label />'
,
code: '<input type="button" aria-labelledby />'
,
code: '<input type="button" aria-live />'
,
code: '<input type="button" aria-owns />'
,
code: '<input type="button" aria-relevant />'
,
# when `type="image"`, the implicit role is `button`
code: '<input type="image" aria-expanded />'
,
code: '<input type="image" aria-pressed />'
,
code: '<input type="image" aria-atomic />'
,
code: '<input type="image" aria-busy />'
,
code: '<input type="image" aria-controls />'
,
code: '<input type="image" aria-describedby />'
,
code: '<input type="image" aria-disabled />'
,
code: '<input type="image" aria-dropeffect />'
,
code: '<input type="image" aria-flowto />'
,
code: '<input type="image" aria-grabbed />'
,
code: '<input type="image" aria-haspopup />'
,
code: '<input type="image" aria-hidden />'
,
code: '<input type="image" aria-invalid />'
,
code: '<input type="image" aria-label />'
,
code: '<input type="image" aria-labelledby />'
,
code: '<input type="image" aria-live />'
,
code: '<input type="image" aria-owns />'
,
code: '<input type="image" aria-relevant />'
,
# when `type="reset"`, the implicit role is `button`
code: '<input type="reset" aria-expanded />'
,
code: '<input type="reset" aria-pressed />'
,
code: '<input type="reset" aria-atomic />'
,
code: '<input type="reset" aria-busy />'
,
code: '<input type="reset" aria-controls />'
,
code: '<input type="reset" aria-describedby />'
,
code: '<input type="reset" aria-disabled />'
,
code: '<input type="reset" aria-dropeffect />'
,
code: '<input type="reset" aria-flowto />'
,
code: '<input type="reset" aria-grabbed />'
,
code: '<input type="reset" aria-haspopup />'
,
code: '<input type="reset" aria-hidden />'
,
code: '<input type="reset" aria-invalid />'
,
code: '<input type="reset" aria-label />'
,
code: '<input type="reset" aria-labelledby />'
,
code: '<input type="reset" aria-live />'
,
code: '<input type="reset" aria-owns />'
,
code: '<input type="reset" aria-relevant />'
,
# when `type="submit"`, the implicit role is `button`
code: '<input type="submit" aria-expanded />'
,
code: '<input type="submit" aria-pressed />'
,
code: '<input type="submit" aria-atomic />'
,
code: '<input type="submit" aria-busy />'
,
code: '<input type="submit" aria-controls />'
,
code: '<input type="submit" aria-describedby />'
,
code: '<input type="submit" aria-disabled />'
,
code: '<input type="submit" aria-dropeffect />'
,
code: '<input type="submit" aria-flowto />'
,
code: '<input type="submit" aria-grabbed />'
,
code: '<input type="submit" aria-haspopup />'
,
code: '<input type="submit" aria-hidden />'
,
code: '<input type="submit" aria-invalid />'
,
code: '<input type="submit" aria-label />'
,
code: '<input type="submit" aria-labelledby />'
,
code: '<input type="submit" aria-live />'
,
code: '<input type="submit" aria-owns />'
,
code: '<input type="submit" aria-relevant />'
,
# when `type="checkbox"`, the implicit role is `checkbox`
code: '<input type="checkbox" aria-checked />'
,
code: '<input type="checkbox" aria-atomic />'
,
code: '<input type="checkbox" aria-busy />'
,
code: '<input type="checkbox" aria-controls />'
,
code: '<input type="checkbox" aria-describedby />'
,
code: '<input type="checkbox" aria-disabled />'
,
code: '<input type="checkbox" aria-dropeffect />'
,
code: '<input type="checkbox" aria-flowto />'
,
code: '<input type="checkbox" aria-grabbed />'
,
code: '<input type="checkbox" aria-haspopup />'
,
code: '<input type="checkbox" aria-hidden />'
,
code: '<input type="checkbox" aria-invalid />'
,
code: '<input type="checkbox" aria-label />'
,
code: '<input type="checkbox" aria-labelledby />'
,
code: '<input type="checkbox" aria-live />'
,
code: '<input type="checkbox" aria-owns />'
,
code: '<input type="checkbox" aria-relevant />'
,
# when `type="radio"`, the implicit role is `radio`
code: '<input type="radio" aria-checked />'
,
code: '<input type="radio" aria-atomic />'
,
code: '<input type="radio" aria-busy />'
,
code: '<input type="radio" aria-controls />'
,
code: '<input type="radio" aria-describedby />'
,
code: '<input type="radio" aria-disabled />'
,
code: '<input type="radio" aria-dropeffect />'
,
code: '<input type="radio" aria-flowto />'
,
code: '<input type="radio" aria-grabbed />'
,
code: '<input type="radio" aria-haspopup />'
,
code: '<input type="radio" aria-hidden />'
,
code: '<input type="radio" aria-invalid />'
,
code: '<input type="radio" aria-label />'
,
code: '<input type="radio" aria-labelledby />'
,
code: '<input type="radio" aria-live />'
,
code: '<input type="radio" aria-owns />'
,
code: '<input type="radio" aria-relevant />'
,
code: '<input type="radio" aria-posinset />'
,
code: '<input type="radio" aria-selected />'
,
code: '<input type="radio" aria-setsize />'
,
# when `type="range"`, the implicit role is `slider`
code: '<input type="range" aria-valuemax />'
,
code: '<input type="range" aria-valuemin />'
,
code: '<input type="range" aria-valuenow />'
,
code: '<input type="range" aria-orientation />'
,
code: '<input type="range" aria-atomic />'
,
code: '<input type="range" aria-busy />'
,
code: '<input type="range" aria-controls />'
,
code: '<input type="range" aria-describedby />'
,
code: '<input type="range" aria-disabled />'
,
code: '<input type="range" aria-dropeffect />'
,
code: '<input type="range" aria-flowto />'
,
code: '<input type="range" aria-grabbed />'
,
code: '<input type="range" aria-haspopup />'
,
code: '<input type="range" aria-hidden />'
,
code: '<input type="range" aria-invalid />'
,
code: '<input type="range" aria-label />'
,
code: '<input type="range" aria-labelledby />'
,
code: '<input type="range" aria-live />'
,
code: '<input type="range" aria-owns />'
,
code: '<input type="range" aria-relevant />'
,
code: '<input type="range" aria-valuetext />'
,
# these will have role of `textbox`,
code: '<input type="email" aria-disabled />'
,
code: '<input type="password" aria-disabled />'
,
code: '<input type="search" aria-disabled />'
,
code: '<input type="tel" aria-disabled />'
,
code: '<input type="url" aria-disabled />'
,
code: '<input aria-disabled />'
,
# Allow null/undefined values regardless of role
code: '<h2 role="presentation" aria-level={null} />'
,
code: '<h2 role="presentation" aria-level={undefined} />'
,
# OTHER TESTS
code: '<aside aria-expanded />'
,
code: '<article aria-expanded />'
,
code: '<body aria-expanded />'
,
code: '<button aria-pressed />'
,
code: '<datalist aria-expanded />'
,
code: '<details aria-expanded />'
,
code: '<dialog aria-expanded />'
,
code: '<dl aria-expanded />'
,
code: '<form aria-hidden />'
,
code: '<h1 aria-hidden />'
,
code: '<h2 aria-hidden />'
,
code: '<h3 aria-hidden />'
,
code: '<h4 aria-hidden />'
,
code: '<h5 aria-hidden />'
,
code: '<h6 aria-hidden />'
,
code: '<hr aria-hidden />'
,
code: '<li aria-current />'
,
code: '<li aria-expanded />'
,
code: '<meter aria-atomic />'
,
code: '<nav aria-expanded />'
,
code: '<ol aria-expanded />'
,
code: '<option aria-atomic />'
,
code: '<output aria-expanded />'
,
code: '<progress aria-atomic />'
,
code: '<section aria-expanded />'
,
code: '<select aria-expanded />'
,
code: '<tbody aria-expanded />'
,
code: '<textarea aria-hidden />'
,
code: '<tfoot aria-expanded />'
,
code: '<thead aria-expanded />'
,
code: '<ul aria-expanded />'
]
.concat validTests
.map parserOptionsMapper
invalid:
[
# implicit basic checks
code: '<a href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'a', yes]
,
code: '<area href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'area', yes]
,
code: '<link href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'link', yes]
,
code: '<img alt="foobar" aria-checked />'
errors: [errorMessage 'aria-checked', 'img', 'img', yes]
,
code: '<menu type="toolbar" aria-checked />'
errors: [errorMessage 'aria-checked', 'toolbar', 'menu', yes]
,
code: '<aside aria-checked />'
errors: [errorMessage 'aria-checked', 'complementary', 'aside', yes]
]
.concat invalidTests
.map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce that an element does not have an unsupported ARIA attribute.
# @author PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{aria, roles} = require 'aria-query'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/role-supports-aria-props'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
generateErrorMessage = (attr, role, tag, isImplicit) ->
return """
The attribute #{attr} is not supported by the role #{role}. \
This role is implicit on the element #{tag}.
""" if isImplicit
"The attribute #{attr} is not supported by the role #{role}."
errorMessage = (attr, role, tag, isImplicit) ->
message: generateErrorMessage attr, role, tag, isImplicit
type: 'JSXOpeningElement'
nonAbstractRoles = [...roles.keys()].filter (role) ->
roles.get(role).abstract is no
createTests = (rolesNames) ->
rolesNames.reduce(
(tests, role) ->
{props: propKeyValues} = roles.get role
validPropsForRole = Object.keys propKeyValues
invalidPropsForRole =
[...aria.keys()]
.map (attribute) -> attribute.toLowerCase()
.filter (attribute) -> validPropsForRole.indexOf(attribute) is -1
normalRole = role.toLowerCase()
allTests = []
allTests[0] = tests[0].concat(
validPropsForRole.map (prop) ->
code: "<div role=\"#{normalRole}\" #{prop.toLowerCase()} />"
)
allTests[1] = tests[1].concat(
invalidPropsForRole.map (prop) ->
code: "<div role=\"#{normalRole}\" #{prop.toLowerCase()} />"
errors: [errorMessage prop.toLowerCase(), normalRole, 'div', no]
)
allTests
,
[[], []]
)
[validTests, invalidTests] = createTests nonAbstractRoles
ruleTester.run 'role-supports-aria-props', rule,
valid:
[
code: '<Foo bar />'
,
code: '<div />'
,
code: '<div id="main" />'
,
code: '<div role />'
,
code: '<div role="presentation" {...props} />'
,
code: '<Foo.Bar baz={true} />'
,
# IMPLICIT ROLE TESTS
# A TESTS - implicit role is `link`
code: '<a href="#" aria-expanded />'
,
code: '<a href="#" aria-atomic />'
,
code: '<a href="#" aria-busy />'
,
code: '<a href="#" aria-controls />'
,
code: '<a href="#" aria-current />'
,
code: '<a href="#" aria-describedby />'
,
code: '<a href="#" aria-disabled />'
,
code: '<a href="#" aria-dropeffect />'
,
code: '<a href="#" aria-flowto />'
,
code: '<a href="#" aria-grabbed />'
,
code: '<a href="#" aria-haspopup />'
,
code: '<a href="#" aria-hidden />'
,
code: '<a href="#" aria-invalid />'
,
code: '<a href="#" aria-label />'
,
code: '<a href="#" aria-labelledby />'
,
code: '<a href="#" aria-live />'
,
code: '<a href="#" aria-owns />'
,
code: '<a href="#" aria-relevant />'
,
# this will have global
code: '<a aria-checked />'
,
# AREA TESTS - implicit role is `link`
code: '<area href="#" aria-expanded />'
,
code: '<area href="#" aria-atomic />'
,
code: '<area href="#" aria-busy />'
,
code: '<area href="#" aria-controls />'
,
code: '<area href="#" aria-describedby />'
,
code: '<area href="#" aria-disabled />'
,
code: '<area href="#" aria-dropeffect />'
,
code: '<area href="#" aria-flowto />'
,
code: '<area href="#" aria-grabbed />'
,
code: '<area href="#" aria-haspopup />'
,
code: '<area href="#" aria-hidden />'
,
code: '<area href="#" aria-invalid />'
,
code: '<area href="#" aria-label />'
,
code: '<area href="#" aria-labelledby />'
,
code: '<area href="#" aria-live />'
,
code: '<area href="#" aria-owns />'
,
code: '<area href="#" aria-relevant />'
,
# this will have global
code: '<area aria-checked />'
,
# LINK TESTS - implicit role is `link`
code: '<link href="#" aria-expanded />'
,
code: '<link href="#" aria-atomic />'
,
code: '<link href="#" aria-busy />'
,
code: '<link href="#" aria-controls />'
,
code: '<link href="#" aria-describedby />'
,
code: '<link href="#" aria-disabled />'
,
code: '<link href="#" aria-dropeffect />'
,
code: '<link href="#" aria-flowto />'
,
code: '<link href="#" aria-grabbed />'
,
code: '<link href="#" aria-haspopup />'
,
code: '<link href="#" aria-hidden />'
,
code: '<link href="#" aria-invalid />'
,
code: '<link href="#" aria-label />'
,
code: '<link href="#" aria-labelledby />'
,
code: '<link href="#" aria-live />'
,
code: '<link href="#" aria-owns />'
,
code: '<link href="#" aria-relevant />'
,
# this will have global
code: '<link aria-checked />'
,
# IMG TESTS - no implicit role
code: '<img alt="" aria-checked />'
,
# this will have role of `img`
code: '<img alt="foobar" aria-busy />'
,
# MENU TESTS - implicit role is `toolbar` when `type="toolbar"`
code: '<menu type="toolbar" aria-activedescendant />'
,
code: '<menu type="toolbar" aria-expanded />'
,
code: '<menu type="toolbar" aria-atomic />'
,
code: '<menu type="toolbar" aria-busy />'
,
code: '<menu type="toolbar" aria-controls />'
,
code: '<menu type="toolbar" aria-describedby />'
,
code: '<menu type="toolbar" aria-disabled />'
,
code: '<menu type="toolbar" aria-dropeffect />'
,
code: '<menu type="toolbar" aria-flowto />'
,
code: '<menu type="toolbar" aria-grabbed />'
,
code: '<menu type="toolbar" aria-haspopup />'
,
code: '<menu type="toolbar" aria-hidden />'
,
code: '<menu type="toolbar" aria-invalid />'
,
code: '<menu type="toolbar" aria-label />'
,
code: '<menu type="toolbar" aria-labelledby />'
,
code: '<menu type="toolbar" aria-live />'
,
code: '<menu type="toolbar" aria-owns />'
,
code: '<menu type="toolbar" aria-relevant />'
,
# this will have global
code: '<menu aria-checked />'
,
# MENUITEM TESTS
# when `type="command`, the implicit role is `menuitem`
code: '<menuitem type="command" aria-atomic />'
,
code: '<menuitem type="command" aria-busy />'
,
code: '<menuitem type="command" aria-controls />'
,
code: '<menuitem type="command" aria-describedby />'
,
code: '<menuitem type="command" aria-disabled />'
,
code: '<menuitem type="command" aria-dropeffect />'
,
code: '<menuitem type="command" aria-flowto />'
,
code: '<menuitem type="command" aria-grabbed />'
,
code: '<menuitem type="command" aria-haspopup />'
,
code: '<menuitem type="command" aria-hidden />'
,
code: '<menuitem type="command" aria-invalid />'
,
code: '<menuitem type="command" aria-label />'
,
code: '<menuitem type="command" aria-labelledby />'
,
code: '<menuitem type="command" aria-live />'
,
code: '<menuitem type="command" aria-owns />'
,
code: '<menuitem type="command" aria-relevant />'
,
# when `type="checkbox`, the implicit role is `menuitemcheckbox`
code: '<menuitem type="checkbox" aria-checked />'
,
code: '<menuitem type="checkbox" aria-atomic />'
,
code: '<menuitem type="checkbox" aria-busy />'
,
code: '<menuitem type="checkbox" aria-controls />'
,
code: '<menuitem type="checkbox" aria-describedby />'
,
code: '<menuitem type="checkbox" aria-disabled />'
,
code: '<menuitem type="checkbox" aria-dropeffect />'
,
code: '<menuitem type="checkbox" aria-flowto />'
,
code: '<menuitem type="checkbox" aria-grabbed />'
,
code: '<menuitem type="checkbox" aria-haspopup />'
,
code: '<menuitem type="checkbox" aria-hidden />'
,
code: '<menuitem type="checkbox" aria-invalid />'
,
code: '<menuitem type="checkbox" aria-label />'
,
code: '<menuitem type="checkbox" aria-labelledby />'
,
code: '<menuitem type="checkbox" aria-live />'
,
code: '<menuitem type="checkbox" aria-owns />'
,
code: '<menuitem type="checkbox" aria-relevant />'
,
# when `type="radio`, the implicit role is `menuitemradio`
code: '<menuitem type="radio" aria-checked />'
,
code: '<menuitem type="radio" aria-atomic />'
,
code: '<menuitem type="radio" aria-busy />'
,
code: '<menuitem type="radio" aria-controls />'
,
code: '<menuitem type="radio" aria-describedby />'
,
code: '<menuitem type="radio" aria-disabled />'
,
code: '<menuitem type="radio" aria-dropeffect />'
,
code: '<menuitem type="radio" aria-flowto />'
,
code: '<menuitem type="radio" aria-grabbed />'
,
code: '<menuitem type="radio" aria-haspopup />'
,
code: '<menuitem type="radio" aria-hidden />'
,
code: '<menuitem type="radio" aria-invalid />'
,
code: '<menuitem type="radio" aria-label />'
,
code: '<menuitem type="radio" aria-labelledby />'
,
code: '<menuitem type="radio" aria-live />'
,
code: '<menuitem type="radio" aria-owns />'
,
code: '<menuitem type="radio" aria-relevant />'
,
code: '<menuitem type="radio" aria-posinset />'
,
code: '<menuitem type="radio" aria-selected />'
,
code: '<menuitem type="radio" aria-setsize />'
,
# these will have global
code: '<menuitem aria-checked />'
,
code: '<menuitem type="foo" aria-checked />'
,
# INPUT TESTS
# when `type="button"`, the implicit role is `button`
code: '<input type="button" aria-expanded />'
,
code: '<input type="button" aria-pressed />'
,
code: '<input type="button" aria-atomic />'
,
code: '<input type="button" aria-busy />'
,
code: '<input type="button" aria-controls />'
,
code: '<input type="button" aria-describedby />'
,
code: '<input type="button" aria-disabled />'
,
code: '<input type="button" aria-dropeffect />'
,
code: '<input type="button" aria-flowto />'
,
code: '<input type="button" aria-grabbed />'
,
code: '<input type="button" aria-haspopup />'
,
code: '<input type="button" aria-hidden />'
,
code: '<input type="button" aria-invalid />'
,
code: '<input type="button" aria-label />'
,
code: '<input type="button" aria-labelledby />'
,
code: '<input type="button" aria-live />'
,
code: '<input type="button" aria-owns />'
,
code: '<input type="button" aria-relevant />'
,
# when `type="image"`, the implicit role is `button`
code: '<input type="image" aria-expanded />'
,
code: '<input type="image" aria-pressed />'
,
code: '<input type="image" aria-atomic />'
,
code: '<input type="image" aria-busy />'
,
code: '<input type="image" aria-controls />'
,
code: '<input type="image" aria-describedby />'
,
code: '<input type="image" aria-disabled />'
,
code: '<input type="image" aria-dropeffect />'
,
code: '<input type="image" aria-flowto />'
,
code: '<input type="image" aria-grabbed />'
,
code: '<input type="image" aria-haspopup />'
,
code: '<input type="image" aria-hidden />'
,
code: '<input type="image" aria-invalid />'
,
code: '<input type="image" aria-label />'
,
code: '<input type="image" aria-labelledby />'
,
code: '<input type="image" aria-live />'
,
code: '<input type="image" aria-owns />'
,
code: '<input type="image" aria-relevant />'
,
# when `type="reset"`, the implicit role is `button`
code: '<input type="reset" aria-expanded />'
,
code: '<input type="reset" aria-pressed />'
,
code: '<input type="reset" aria-atomic />'
,
code: '<input type="reset" aria-busy />'
,
code: '<input type="reset" aria-controls />'
,
code: '<input type="reset" aria-describedby />'
,
code: '<input type="reset" aria-disabled />'
,
code: '<input type="reset" aria-dropeffect />'
,
code: '<input type="reset" aria-flowto />'
,
code: '<input type="reset" aria-grabbed />'
,
code: '<input type="reset" aria-haspopup />'
,
code: '<input type="reset" aria-hidden />'
,
code: '<input type="reset" aria-invalid />'
,
code: '<input type="reset" aria-label />'
,
code: '<input type="reset" aria-labelledby />'
,
code: '<input type="reset" aria-live />'
,
code: '<input type="reset" aria-owns />'
,
code: '<input type="reset" aria-relevant />'
,
# when `type="submit"`, the implicit role is `button`
code: '<input type="submit" aria-expanded />'
,
code: '<input type="submit" aria-pressed />'
,
code: '<input type="submit" aria-atomic />'
,
code: '<input type="submit" aria-busy />'
,
code: '<input type="submit" aria-controls />'
,
code: '<input type="submit" aria-describedby />'
,
code: '<input type="submit" aria-disabled />'
,
code: '<input type="submit" aria-dropeffect />'
,
code: '<input type="submit" aria-flowto />'
,
code: '<input type="submit" aria-grabbed />'
,
code: '<input type="submit" aria-haspopup />'
,
code: '<input type="submit" aria-hidden />'
,
code: '<input type="submit" aria-invalid />'
,
code: '<input type="submit" aria-label />'
,
code: '<input type="submit" aria-labelledby />'
,
code: '<input type="submit" aria-live />'
,
code: '<input type="submit" aria-owns />'
,
code: '<input type="submit" aria-relevant />'
,
# when `type="checkbox"`, the implicit role is `checkbox`
code: '<input type="checkbox" aria-checked />'
,
code: '<input type="checkbox" aria-atomic />'
,
code: '<input type="checkbox" aria-busy />'
,
code: '<input type="checkbox" aria-controls />'
,
code: '<input type="checkbox" aria-describedby />'
,
code: '<input type="checkbox" aria-disabled />'
,
code: '<input type="checkbox" aria-dropeffect />'
,
code: '<input type="checkbox" aria-flowto />'
,
code: '<input type="checkbox" aria-grabbed />'
,
code: '<input type="checkbox" aria-haspopup />'
,
code: '<input type="checkbox" aria-hidden />'
,
code: '<input type="checkbox" aria-invalid />'
,
code: '<input type="checkbox" aria-label />'
,
code: '<input type="checkbox" aria-labelledby />'
,
code: '<input type="checkbox" aria-live />'
,
code: '<input type="checkbox" aria-owns />'
,
code: '<input type="checkbox" aria-relevant />'
,
# when `type="radio"`, the implicit role is `radio`
code: '<input type="radio" aria-checked />'
,
code: '<input type="radio" aria-atomic />'
,
code: '<input type="radio" aria-busy />'
,
code: '<input type="radio" aria-controls />'
,
code: '<input type="radio" aria-describedby />'
,
code: '<input type="radio" aria-disabled />'
,
code: '<input type="radio" aria-dropeffect />'
,
code: '<input type="radio" aria-flowto />'
,
code: '<input type="radio" aria-grabbed />'
,
code: '<input type="radio" aria-haspopup />'
,
code: '<input type="radio" aria-hidden />'
,
code: '<input type="radio" aria-invalid />'
,
code: '<input type="radio" aria-label />'
,
code: '<input type="radio" aria-labelledby />'
,
code: '<input type="radio" aria-live />'
,
code: '<input type="radio" aria-owns />'
,
code: '<input type="radio" aria-relevant />'
,
code: '<input type="radio" aria-posinset />'
,
code: '<input type="radio" aria-selected />'
,
code: '<input type="radio" aria-setsize />'
,
# when `type="range"`, the implicit role is `slider`
code: '<input type="range" aria-valuemax />'
,
code: '<input type="range" aria-valuemin />'
,
code: '<input type="range" aria-valuenow />'
,
code: '<input type="range" aria-orientation />'
,
code: '<input type="range" aria-atomic />'
,
code: '<input type="range" aria-busy />'
,
code: '<input type="range" aria-controls />'
,
code: '<input type="range" aria-describedby />'
,
code: '<input type="range" aria-disabled />'
,
code: '<input type="range" aria-dropeffect />'
,
code: '<input type="range" aria-flowto />'
,
code: '<input type="range" aria-grabbed />'
,
code: '<input type="range" aria-haspopup />'
,
code: '<input type="range" aria-hidden />'
,
code: '<input type="range" aria-invalid />'
,
code: '<input type="range" aria-label />'
,
code: '<input type="range" aria-labelledby />'
,
code: '<input type="range" aria-live />'
,
code: '<input type="range" aria-owns />'
,
code: '<input type="range" aria-relevant />'
,
code: '<input type="range" aria-valuetext />'
,
# these will have role of `textbox`,
code: '<input type="email" aria-disabled />'
,
code: '<input type="password" aria-disabled />'
,
code: '<input type="search" aria-disabled />'
,
code: '<input type="tel" aria-disabled />'
,
code: '<input type="url" aria-disabled />'
,
code: '<input aria-disabled />'
,
# Allow null/undefined values regardless of role
code: '<h2 role="presentation" aria-level={null} />'
,
code: '<h2 role="presentation" aria-level={undefined} />'
,
# OTHER TESTS
code: '<aside aria-expanded />'
,
code: '<article aria-expanded />'
,
code: '<body aria-expanded />'
,
code: '<button aria-pressed />'
,
code: '<datalist aria-expanded />'
,
code: '<details aria-expanded />'
,
code: '<dialog aria-expanded />'
,
code: '<dl aria-expanded />'
,
code: '<form aria-hidden />'
,
code: '<h1 aria-hidden />'
,
code: '<h2 aria-hidden />'
,
code: '<h3 aria-hidden />'
,
code: '<h4 aria-hidden />'
,
code: '<h5 aria-hidden />'
,
code: '<h6 aria-hidden />'
,
code: '<hr aria-hidden />'
,
code: '<li aria-current />'
,
code: '<li aria-expanded />'
,
code: '<meter aria-atomic />'
,
code: '<nav aria-expanded />'
,
code: '<ol aria-expanded />'
,
code: '<option aria-atomic />'
,
code: '<output aria-expanded />'
,
code: '<progress aria-atomic />'
,
code: '<section aria-expanded />'
,
code: '<select aria-expanded />'
,
code: '<tbody aria-expanded />'
,
code: '<textarea aria-hidden />'
,
code: '<tfoot aria-expanded />'
,
code: '<thead aria-expanded />'
,
code: '<ul aria-expanded />'
]
.concat validTests
.map parserOptionsMapper
invalid:
[
# implicit basic checks
code: '<a href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'a', yes]
,
code: '<area href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'area', yes]
,
code: '<link href="#" aria-checked />'
errors: [errorMessage 'aria-checked', 'link', 'link', yes]
,
code: '<img alt="foobar" aria-checked />'
errors: [errorMessage 'aria-checked', 'img', 'img', yes]
,
code: '<menu type="toolbar" aria-checked />'
errors: [errorMessage 'aria-checked', 'toolbar', 'menu', yes]
,
code: '<aside aria-checked />'
errors: [errorMessage 'aria-checked', 'complementary', 'aside', yes]
]
.concat invalidTests
.map parserOptionsMapper
|
[
{
"context": "###\n * cena_auth\n * https://github.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan Gaus\n * Li",
"end": 46,
"score": 0.9972999691963196,
"start": 39,
"tag": "USERNAME",
"value": "1egoman"
},
{
"context": "thub.com/1egoman/cena_app\n *\n * Copyright (c) 2015 Ryan ... | src/auth_setup.coffee | 1egoman/cena_app | 0 | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 Ryan Gaus
* Licensed under the MIT license.
###
'use strict';
passport = require "passport"
User = require "./models/user"
module.exports = (app) ->
# add passport middleware
app.use passport.initialize()
app.use passport.session()
# some middleware:
# test if a user has authenticated themselves
app.protected = (user) ->
(req, res, next) ->
if req.user and ((user and req.user.username is user) or not user)
next()
else
next
status: 403
error: "User has not been authenticated."
# set up local auth strategy
LocalStrategy = require('passport-local').Strategy
passport.use new LocalStrategy((username, password, done) ->
User.findOne username: username, (err, user) ->
if err
done err
# check for valid username
else if not user
done null, false, message: 'Incorrect username.'
else
user.validPassword username, password, (valid) ->
if err
done err
# check for valid password
else if not valid
done null, false, message: 'Incorrect password.'
# otherwise, success!
else
done null, user
)
# user serialization and deserialization
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
User.findById id, (err, user) ->
done err, user
# settings
app.get "/settings", (req, res) ->
if req.user
User.findOne username: req.user.username, (err, user) ->
res.render "settings", user: user
else
# not authorized
res.redirect "/#"
| 109195 | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
###
'use strict';
passport = require "passport"
User = require "./models/user"
module.exports = (app) ->
# add passport middleware
app.use passport.initialize()
app.use passport.session()
# some middleware:
# test if a user has authenticated themselves
app.protected = (user) ->
(req, res, next) ->
if req.user and ((user and req.user.username is user) or not user)
next()
else
next
status: 403
error: "User has not been authenticated."
# set up local auth strategy
LocalStrategy = require('passport-local').Strategy
passport.use new LocalStrategy((username, password, done) ->
User.findOne username: username, (err, user) ->
if err
done err
# check for valid username
else if not user
done null, false, message: 'Incorrect username.'
else
user.validPassword username, password, (valid) ->
if err
done err
# check for valid password
else if not valid
done null, false, message: 'Incorrect password.'
# otherwise, success!
else
done null, user
)
# user serialization and deserialization
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
User.findById id, (err, user) ->
done err, user
# settings
app.get "/settings", (req, res) ->
if req.user
User.findOne username: req.user.username, (err, user) ->
res.render "settings", user: user
else
# not authorized
res.redirect "/#"
| true | ###
* cena_auth
* https://github.com/1egoman/cena_app
*
* Copyright (c) 2015 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
'use strict';
passport = require "passport"
User = require "./models/user"
module.exports = (app) ->
# add passport middleware
app.use passport.initialize()
app.use passport.session()
# some middleware:
# test if a user has authenticated themselves
app.protected = (user) ->
(req, res, next) ->
if req.user and ((user and req.user.username is user) or not user)
next()
else
next
status: 403
error: "User has not been authenticated."
# set up local auth strategy
LocalStrategy = require('passport-local').Strategy
passport.use new LocalStrategy((username, password, done) ->
User.findOne username: username, (err, user) ->
if err
done err
# check for valid username
else if not user
done null, false, message: 'Incorrect username.'
else
user.validPassword username, password, (valid) ->
if err
done err
# check for valid password
else if not valid
done null, false, message: 'Incorrect password.'
# otherwise, success!
else
done null, user
)
# user serialization and deserialization
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
User.findById id, (err, user) ->
done err, user
# settings
app.get "/settings", (req, res) ->
if req.user
User.findOne username: req.user.username, (err, user) ->
res.render "settings", user: user
else
# not authorized
res.redirect "/#"
|
[
{
"context": "rce.indexOf(orig_body)\nnew_body_patch = \"{return 'Capybara';\" + \" ",
"end": 2913,
"score": 0.9894013404846191,
"start": 2905,
"tag": "NAME",
"value": "Capybara"
},
{
"context": "oOp\nCallM NoOp\nres = CallM(Changer)\nassertE... | deps/v8/test/mjsunit/debug-liveedit-patch-positions-replace.coffee | lxe/io.coffee | 0 | # Copyright 2010 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER 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.
# Flags: --expose-debug-as debug
# Get the Debug object exposed from the debug context global object.
# Scenario: a function is being changed, which causes enclosing function to
# have its positions patched; position changing requires new instance of Code
# object to be introduced; the function happens to be on stack at this moment;
# later it will resume over new instance of Code.
# Before the change 2 rinfo are 22 characters away from each other. After the
# change they are 114 characters away from each other. New instance of Code is
# required when those numbers cross the border value of 64 (in any direction).
# Line long enough to change rinfo encoding.
Changer = ->
Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_body.length, new_body_patch, change_log
print "Change log: " + JSON.stringify(change_log) + "\n"
return
NoOp = ->
CallM = (changer) ->
# We expect call IC here after several function runs.
BeingReplaced changer
Debug = debug.Debug
eval "function BeingReplaced(changer, opt_x, opt_y) {\n" + " changer();\n" + " var res = new Object();\n" + " if (opt_x) { res.y = opt_y; }\n" + " res.a = (function() {})();\n" + " return res.a;\n" + "}"
script = Debug.findScript(BeingReplaced)
orig_body = "{}"
patch_pos = script.source.indexOf(orig_body)
new_body_patch = "{return 'Capybara';" + " " + "}"
change_log = new Array()
# This several iterations should cause call IC for BeingReplaced call. This IC
# will keep reference to code object of BeingRepalced function. This reference
# should also be patched. Unfortunately, this is a manually checked fact (from
# debugger or debug print) and doesn't work as an automatic test.
CallM NoOp
CallM NoOp
CallM NoOp
res = CallM(Changer)
assertEquals "Capybara", res
| 102844 | # Copyright 2010 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER 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.
# Flags: --expose-debug-as debug
# Get the Debug object exposed from the debug context global object.
# Scenario: a function is being changed, which causes enclosing function to
# have its positions patched; position changing requires new instance of Code
# object to be introduced; the function happens to be on stack at this moment;
# later it will resume over new instance of Code.
# Before the change 2 rinfo are 22 characters away from each other. After the
# change they are 114 characters away from each other. New instance of Code is
# required when those numbers cross the border value of 64 (in any direction).
# Line long enough to change rinfo encoding.
Changer = ->
Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_body.length, new_body_patch, change_log
print "Change log: " + JSON.stringify(change_log) + "\n"
return
NoOp = ->
CallM = (changer) ->
# We expect call IC here after several function runs.
BeingReplaced changer
Debug = debug.Debug
eval "function BeingReplaced(changer, opt_x, opt_y) {\n" + " changer();\n" + " var res = new Object();\n" + " if (opt_x) { res.y = opt_y; }\n" + " res.a = (function() {})();\n" + " return res.a;\n" + "}"
script = Debug.findScript(BeingReplaced)
orig_body = "{}"
patch_pos = script.source.indexOf(orig_body)
new_body_patch = "{return '<NAME>';" + " " + "}"
change_log = new Array()
# This several iterations should cause call IC for BeingReplaced call. This IC
# will keep reference to code object of BeingRepalced function. This reference
# should also be patched. Unfortunately, this is a manually checked fact (from
# debugger or debug print) and doesn't work as an automatic test.
CallM NoOp
CallM NoOp
CallM NoOp
res = CallM(Changer)
assertEquals "<NAME>", res
| true | # Copyright 2010 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER 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.
# Flags: --expose-debug-as debug
# Get the Debug object exposed from the debug context global object.
# Scenario: a function is being changed, which causes enclosing function to
# have its positions patched; position changing requires new instance of Code
# object to be introduced; the function happens to be on stack at this moment;
# later it will resume over new instance of Code.
# Before the change 2 rinfo are 22 characters away from each other. After the
# change they are 114 characters away from each other. New instance of Code is
# required when those numbers cross the border value of 64 (in any direction).
# Line long enough to change rinfo encoding.
Changer = ->
Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_body.length, new_body_patch, change_log
print "Change log: " + JSON.stringify(change_log) + "\n"
return
NoOp = ->
CallM = (changer) ->
# We expect call IC here after several function runs.
BeingReplaced changer
Debug = debug.Debug
eval "function BeingReplaced(changer, opt_x, opt_y) {\n" + " changer();\n" + " var res = new Object();\n" + " if (opt_x) { res.y = opt_y; }\n" + " res.a = (function() {})();\n" + " return res.a;\n" + "}"
script = Debug.findScript(BeingReplaced)
orig_body = "{}"
patch_pos = script.source.indexOf(orig_body)
new_body_patch = "{return 'PI:NAME:<NAME>END_PI';" + " " + "}"
change_log = new Array()
# This several iterations should cause call IC for BeingReplaced call. This IC
# will keep reference to code object of BeingRepalced function. This reference
# should also be patched. Unfortunately, this is a manually checked fact (from
# debugger or debug print) and doesn't work as an automatic test.
CallM NoOp
CallM NoOp
CallM NoOp
res = CallM(Changer)
assertEquals "PI:NAME:<NAME>END_PI", res
|
[
{
"context": "t.email' : 'email'\n 'keyup input.password': 'password'\n render: ->\n App.router.clearActive($('heade",
"end": 232,
"score": 0.9993804693222046,
"start": 224,
"tag": "PASSWORD",
"value": "password"
}
] | app/views/register-page.coffee | RelistenNet/relisten.net-original | 2 | { validateEmail } = App.utils.validate
class App.Views.RegisterPage extends App.Views.View
className: 'register-page'
template: JST['register']
events:
'keyup input.email' : 'email'
'keyup input.password': 'password'
render: ->
App.router.clearActive($('header .register'))
if window.location.search
params = App.utils.getURLParameters(window.location.search)
switch params.err
when 'emailexists' then App.notify.send('Error', "This email is already in use. But you knew that already, didn't you?")
when 'pleaseregister' then App.notify.send('Please Register', "Or don't. I don't care.")
@$el.html @template
csrf: App.csrf
@$email = @$el.find('.email')
@$password = @$el.find('.password')
@submitButton = @$el.find('form input[type="submit"]')
email: (e) ->
unless validateEmail @$email.val()
@button true
return @$email.siblings('.invalid').show()
@button()
@$email.siblings('.invalid').hide()
password: (e) ->
if @$password.val().length < 6
@button true
return @$password.siblings('.invalid').show()
@button()
@$password.siblings('.invalid').hide()
button: (hide) ->
disabled = 'disabled'
unless hide
disabled = false
@submitButton.attr 'disabled', disabled
| 35847 | { validateEmail } = App.utils.validate
class App.Views.RegisterPage extends App.Views.View
className: 'register-page'
template: JST['register']
events:
'keyup input.email' : 'email'
'keyup input.password': '<PASSWORD>'
render: ->
App.router.clearActive($('header .register'))
if window.location.search
params = App.utils.getURLParameters(window.location.search)
switch params.err
when 'emailexists' then App.notify.send('Error', "This email is already in use. But you knew that already, didn't you?")
when 'pleaseregister' then App.notify.send('Please Register', "Or don't. I don't care.")
@$el.html @template
csrf: App.csrf
@$email = @$el.find('.email')
@$password = @$el.find('.password')
@submitButton = @$el.find('form input[type="submit"]')
email: (e) ->
unless validateEmail @$email.val()
@button true
return @$email.siblings('.invalid').show()
@button()
@$email.siblings('.invalid').hide()
password: (e) ->
if @$password.val().length < 6
@button true
return @$password.siblings('.invalid').show()
@button()
@$password.siblings('.invalid').hide()
button: (hide) ->
disabled = 'disabled'
unless hide
disabled = false
@submitButton.attr 'disabled', disabled
| true | { validateEmail } = App.utils.validate
class App.Views.RegisterPage extends App.Views.View
className: 'register-page'
template: JST['register']
events:
'keyup input.email' : 'email'
'keyup input.password': 'PI:PASSWORD:<PASSWORD>END_PI'
render: ->
App.router.clearActive($('header .register'))
if window.location.search
params = App.utils.getURLParameters(window.location.search)
switch params.err
when 'emailexists' then App.notify.send('Error', "This email is already in use. But you knew that already, didn't you?")
when 'pleaseregister' then App.notify.send('Please Register', "Or don't. I don't care.")
@$el.html @template
csrf: App.csrf
@$email = @$el.find('.email')
@$password = @$el.find('.password')
@submitButton = @$el.find('form input[type="submit"]')
email: (e) ->
unless validateEmail @$email.val()
@button true
return @$email.siblings('.invalid').show()
@button()
@$email.siblings('.invalid').hide()
password: (e) ->
if @$password.val().length < 6
@button true
return @$password.siblings('.invalid').show()
@button()
@$password.siblings('.invalid').hide()
button: (hide) ->
disabled = 'disabled'
unless hide
disabled = false
@submitButton.attr 'disabled', disabled
|
[
{
"context": " user: ftpdetails.username\n pass: ftpdetails.password\n port: ftpdetails.port\n ",
"end": 4688,
"score": 0.9989939332008362,
"start": 4669,
"tag": "PASSWORD",
"value": "ftpdetails.password"
}
] | lib/ftpclass.coffee | theproducer/ftp | 0 | File = require("pathwatcher").File
Directory = require("pathwatcher").Directory
Chokidar = require 'chokidar'
fs = require 'fs'
jsftp = require 'jsftp'
{Subscriber} = require 'emissary'
FtpSettingsView = require "./ftp-settings-view"
FtpStatusView = require "./ftp-status-view"
module.exports =
class Ftp
Subscriber.includeInto(this)
watcher = null
constructor: ->
@subscribe atom.workspace.eachEditor (editor) =>
@handleEvents(editor)
@subscribe atom.workspaceView.command 'ftp:settings', =>
@settings()
@subscribe atom.workspaceView.command 'ftp:uploadfile', =>
@contextMenuUploadFile()
@subscribe atom.workspaceView.command 'ftp:uploaddirectory', =>
@contextMenuUploadDirectory()
@subscribe atom.workspaceView.command 'ftp:watchfile', =>
@markfileaswatched()
@initdirectorywatching()
destroy: ->
@unsubscribe()
watcher.close()
watcher = null
settings: ->
settingsView = new FtpSettingsView();
initdirectorywatching: ->
if watcher
watcher.close()
watcher = null
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles.length > 0
watcher = Chokidar.watch ftpdetails.watchedfiles[0], {ignored: /[\/\\]\./, persistent: true}
i = 1
while i < ftpdetails.watchedfiles.length
watcher.add ftpdetails.watchedfiles[i]
i++
watcher.on 'change', (path) =>
console.log "something has been changed!" + path
@uploadFileOnChange(path)
markfileaswatched: ->
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
fileobj = new File(filepath)
currentProject = atom.project
CSON = require 'season'
statusView = new FtpStatusView()
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles is null
ftpdetails.watchedfiles = []
if ftpdetails.watchedfiles.indexOf(filepath) is -1
ftpdetails.watchedfiles.push filepath
statusView.addToStatusBar("Watching file: " + fileobj.getBaseName())
statusView.removeFromMessageBar()
else
ftpdetails.watchedfiles.splice ftpdetails.watchedfiles.indexOf(filepath), 1
statusView.addToStatusBar("Unwatching file: " + fileobj.getBaseName())
statusView.removeFromMessageBar()
settingsFile.write JSON.stringify(ftpdetails);
@initdirectorywatching()
contextMenuUploadFile: ->
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
console.log filepath
@uploadFile(filepath)
contextMenuUploadDirectory: ->
directorypath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
console.log directorypath
selectedDirectory = new Directory(directorypath)
selectedDirectory.getEntries (err, files) =>
i = 0
while i < files.length
console.log files[i].getPath()
@uploadFile(files[i].getPath())
i++
uploadFileOnChange: (filepath) ->
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.uploadonchange
@uploadFile(filepath)
uploadFile: (filepath) ->
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
statusView = new FtpStatusView()
statusView.addToStatusBar("Uploading file...")
client = new jsftp(
host: ftpdetails.server
user: ftpdetails.username
pass: ftpdetails.password
port: ftpdetails.port
)
filetoupload = new File(filepath)
patharray = atom.project.relativize filetoupload.getParent().path
patharray = patharray.split "/"
console.log filetoupload.getParent().path
console.log filetoupload.getBaseName()
console.log patharray
streamData = fs.createReadStream(filepath)
console.log streamData
streamData.pause();
client.auth ftpdetails.username, ftpdetails.password, (err, res) ->
if err
console.error err
else
console.log "authentication successful"
i = 0;
pathArrayString = ftpdetails.remotepath
while i < patharray.length
pathArrayString = pathArrayString + "/" + patharray[i]
console.log "creating directory: " + pathArrayString
client.raw.mkd pathArrayString, (err, data) ->
client.raw.cwd pathArrayString, (err, data) ->
return
return
i++
client.put filepath, pathArrayString + "/" + filetoupload.getBaseName(), (hadError) ->
if hadError
console.error err
statusView.addToStatusBar("Upload Error")
statusView.removeFromMessageBar()
client.raw.quit()
else
client.raw.quit();
statusView.addToStatusBar("Upload Successful")
console.log "upload sucessful"
statusView.removeFromMessageBar()
handleEvents: (editor) ->
buffer = editor.getBuffer()
@subscribe buffer, 'saved', =>
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles.length > 0
if ftpdetails.uploadonsave and ftpdetails.watchedfiles.indexOf(buffer.getPath()) is -1
console.log "file saved! Upload..."
@uploadFile(buffer.getPath())
else
if ftpdetails.uploadonsave
console.log "file saved! Upload..."
@uploadFile(buffer.getPath())
@subscribe buffer, 'destroyed', =>
@unsubscribe(buffer)
| 113595 | File = require("pathwatcher").File
Directory = require("pathwatcher").Directory
Chokidar = require 'chokidar'
fs = require 'fs'
jsftp = require 'jsftp'
{Subscriber} = require 'emissary'
FtpSettingsView = require "./ftp-settings-view"
FtpStatusView = require "./ftp-status-view"
module.exports =
class Ftp
Subscriber.includeInto(this)
watcher = null
constructor: ->
@subscribe atom.workspace.eachEditor (editor) =>
@handleEvents(editor)
@subscribe atom.workspaceView.command 'ftp:settings', =>
@settings()
@subscribe atom.workspaceView.command 'ftp:uploadfile', =>
@contextMenuUploadFile()
@subscribe atom.workspaceView.command 'ftp:uploaddirectory', =>
@contextMenuUploadDirectory()
@subscribe atom.workspaceView.command 'ftp:watchfile', =>
@markfileaswatched()
@initdirectorywatching()
destroy: ->
@unsubscribe()
watcher.close()
watcher = null
settings: ->
settingsView = new FtpSettingsView();
initdirectorywatching: ->
if watcher
watcher.close()
watcher = null
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles.length > 0
watcher = Chokidar.watch ftpdetails.watchedfiles[0], {ignored: /[\/\\]\./, persistent: true}
i = 1
while i < ftpdetails.watchedfiles.length
watcher.add ftpdetails.watchedfiles[i]
i++
watcher.on 'change', (path) =>
console.log "something has been changed!" + path
@uploadFileOnChange(path)
markfileaswatched: ->
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
fileobj = new File(filepath)
currentProject = atom.project
CSON = require 'season'
statusView = new FtpStatusView()
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles is null
ftpdetails.watchedfiles = []
if ftpdetails.watchedfiles.indexOf(filepath) is -1
ftpdetails.watchedfiles.push filepath
statusView.addToStatusBar("Watching file: " + fileobj.getBaseName())
statusView.removeFromMessageBar()
else
ftpdetails.watchedfiles.splice ftpdetails.watchedfiles.indexOf(filepath), 1
statusView.addToStatusBar("Unwatching file: " + fileobj.getBaseName())
statusView.removeFromMessageBar()
settingsFile.write JSON.stringify(ftpdetails);
@initdirectorywatching()
contextMenuUploadFile: ->
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
console.log filepath
@uploadFile(filepath)
contextMenuUploadDirectory: ->
directorypath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
console.log directorypath
selectedDirectory = new Directory(directorypath)
selectedDirectory.getEntries (err, files) =>
i = 0
while i < files.length
console.log files[i].getPath()
@uploadFile(files[i].getPath())
i++
uploadFileOnChange: (filepath) ->
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.uploadonchange
@uploadFile(filepath)
uploadFile: (filepath) ->
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
statusView = new FtpStatusView()
statusView.addToStatusBar("Uploading file...")
client = new jsftp(
host: ftpdetails.server
user: ftpdetails.username
pass: <PASSWORD>
port: ftpdetails.port
)
filetoupload = new File(filepath)
patharray = atom.project.relativize filetoupload.getParent().path
patharray = patharray.split "/"
console.log filetoupload.getParent().path
console.log filetoupload.getBaseName()
console.log patharray
streamData = fs.createReadStream(filepath)
console.log streamData
streamData.pause();
client.auth ftpdetails.username, ftpdetails.password, (err, res) ->
if err
console.error err
else
console.log "authentication successful"
i = 0;
pathArrayString = ftpdetails.remotepath
while i < patharray.length
pathArrayString = pathArrayString + "/" + patharray[i]
console.log "creating directory: " + pathArrayString
client.raw.mkd pathArrayString, (err, data) ->
client.raw.cwd pathArrayString, (err, data) ->
return
return
i++
client.put filepath, pathArrayString + "/" + filetoupload.getBaseName(), (hadError) ->
if hadError
console.error err
statusView.addToStatusBar("Upload Error")
statusView.removeFromMessageBar()
client.raw.quit()
else
client.raw.quit();
statusView.addToStatusBar("Upload Successful")
console.log "upload sucessful"
statusView.removeFromMessageBar()
handleEvents: (editor) ->
buffer = editor.getBuffer()
@subscribe buffer, 'saved', =>
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles.length > 0
if ftpdetails.uploadonsave and ftpdetails.watchedfiles.indexOf(buffer.getPath()) is -1
console.log "file saved! Upload..."
@uploadFile(buffer.getPath())
else
if ftpdetails.uploadonsave
console.log "file saved! Upload..."
@uploadFile(buffer.getPath())
@subscribe buffer, 'destroyed', =>
@unsubscribe(buffer)
| true | File = require("pathwatcher").File
Directory = require("pathwatcher").Directory
Chokidar = require 'chokidar'
fs = require 'fs'
jsftp = require 'jsftp'
{Subscriber} = require 'emissary'
FtpSettingsView = require "./ftp-settings-view"
FtpStatusView = require "./ftp-status-view"
module.exports =
class Ftp
Subscriber.includeInto(this)
watcher = null
constructor: ->
@subscribe atom.workspace.eachEditor (editor) =>
@handleEvents(editor)
@subscribe atom.workspaceView.command 'ftp:settings', =>
@settings()
@subscribe atom.workspaceView.command 'ftp:uploadfile', =>
@contextMenuUploadFile()
@subscribe atom.workspaceView.command 'ftp:uploaddirectory', =>
@contextMenuUploadDirectory()
@subscribe atom.workspaceView.command 'ftp:watchfile', =>
@markfileaswatched()
@initdirectorywatching()
destroy: ->
@unsubscribe()
watcher.close()
watcher = null
settings: ->
settingsView = new FtpSettingsView();
initdirectorywatching: ->
if watcher
watcher.close()
watcher = null
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles.length > 0
watcher = Chokidar.watch ftpdetails.watchedfiles[0], {ignored: /[\/\\]\./, persistent: true}
i = 1
while i < ftpdetails.watchedfiles.length
watcher.add ftpdetails.watchedfiles[i]
i++
watcher.on 'change', (path) =>
console.log "something has been changed!" + path
@uploadFileOnChange(path)
markfileaswatched: ->
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
fileobj = new File(filepath)
currentProject = atom.project
CSON = require 'season'
statusView = new FtpStatusView()
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles is null
ftpdetails.watchedfiles = []
if ftpdetails.watchedfiles.indexOf(filepath) is -1
ftpdetails.watchedfiles.push filepath
statusView.addToStatusBar("Watching file: " + fileobj.getBaseName())
statusView.removeFromMessageBar()
else
ftpdetails.watchedfiles.splice ftpdetails.watchedfiles.indexOf(filepath), 1
statusView.addToStatusBar("Unwatching file: " + fileobj.getBaseName())
statusView.removeFromMessageBar()
settingsFile.write JSON.stringify(ftpdetails);
@initdirectorywatching()
contextMenuUploadFile: ->
filepath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
console.log filepath
@uploadFile(filepath)
contextMenuUploadDirectory: ->
directorypath = atom.workspaceView.find('.tree-view .selected')?.view()?.getPath?()
console.log directorypath
selectedDirectory = new Directory(directorypath)
selectedDirectory.getEntries (err, files) =>
i = 0
while i < files.length
console.log files[i].getPath()
@uploadFile(files[i].getPath())
i++
uploadFileOnChange: (filepath) ->
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.uploadonchange
@uploadFile(filepath)
uploadFile: (filepath) ->
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
statusView = new FtpStatusView()
statusView.addToStatusBar("Uploading file...")
client = new jsftp(
host: ftpdetails.server
user: ftpdetails.username
pass: PI:PASSWORD:<PASSWORD>END_PI
port: ftpdetails.port
)
filetoupload = new File(filepath)
patharray = atom.project.relativize filetoupload.getParent().path
patharray = patharray.split "/"
console.log filetoupload.getParent().path
console.log filetoupload.getBaseName()
console.log patharray
streamData = fs.createReadStream(filepath)
console.log streamData
streamData.pause();
client.auth ftpdetails.username, ftpdetails.password, (err, res) ->
if err
console.error err
else
console.log "authentication successful"
i = 0;
pathArrayString = ftpdetails.remotepath
while i < patharray.length
pathArrayString = pathArrayString + "/" + patharray[i]
console.log "creating directory: " + pathArrayString
client.raw.mkd pathArrayString, (err, data) ->
client.raw.cwd pathArrayString, (err, data) ->
return
return
i++
client.put filepath, pathArrayString + "/" + filetoupload.getBaseName(), (hadError) ->
if hadError
console.error err
statusView.addToStatusBar("Upload Error")
statusView.removeFromMessageBar()
client.raw.quit()
else
client.raw.quit();
statusView.addToStatusBar("Upload Successful")
console.log "upload sucessful"
statusView.removeFromMessageBar()
handleEvents: (editor) ->
buffer = editor.getBuffer()
@subscribe buffer, 'saved', =>
currentProject = atom.project
CSON = require 'season'
settingsFile = new File(currentProject.getPath() + "/ftp.json")
if settingsFile.exists()
ftpdetails = CSON.readFileSync currentProject.getPath() + "/ftp.json"
if ftpdetails.watchedfiles.length > 0
if ftpdetails.uploadonsave and ftpdetails.watchedfiles.indexOf(buffer.getPath()) is -1
console.log "file saved! Upload..."
@uploadFile(buffer.getPath())
else
if ftpdetails.uploadonsave
console.log "file saved! Upload..."
@uploadFile(buffer.getPath())
@subscribe buffer, 'destroyed', =>
@unsubscribe(buffer)
|
[
{
"context": "[\n {\n name : \"Lorem Ispum\",\n text : \"Lorem ipsum dolor sit amet, consect",
"end": 29,
"score": 0.999890148639679,
"start": 18,
"tag": "NAME",
"value": "Lorem Ispum"
},
{
"context": "tpat. Maecenas feugiat, mi.\"\n },\n {\n name : \"Samuel L. Ipsum\",\n... | data/data.cson | Nonameghost/atom-placeholder-text | 2 | [
{
name : "Lorem Ispum",
text : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ut ligula dui. Maecenas in sapien cursus, condimentum nulla vitae, pellentesque metus. Sed accumsan tellus et molestie volutpat. Maecenas feugiat, mi."
},
{
name : "Samuel L. Ipsum",
text : "The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee."
},
{
name : "Pirate",
text : "Bounty tack Gold Road cutlass topsail parley parrel hardtack flogging topmast. Wench gally haul wind main sheet barkadeer lateen sail brigantine killick league lass. Aft Nelsons folly to go on account belaying pin brigantine topsail hands lad marooned doubloon. "
},
{
name : "This is the Body text",
text : "This is the main body text. Here is where we write the major content of the page. Try to keep it concise and relevant. This is what the user will most likely read directly after looking at the title, so it should immediately hook their interest and keep them involved until the end. This is crappy filler text but serves mostly as an example of what you could do with stored bits of filler text. No more having to copy paste from a text file or generator. Immediately have what you need, a mere hotkey away!"
},
{
name : "Insert Text Here",
text : "Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here."
},
{
name : "Now is the time",
text : "Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country."
}
]
| 213699 | [
{
name : "<NAME>",
text : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ut ligula dui. Maecenas in sapien cursus, condimentum nulla vitae, pellentesque metus. Sed accumsan tellus et molestie volutpat. Maecenas feugiat, mi."
},
{
name : "<NAME>",
text : "The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee."
},
{
name : "<NAME>",
text : "Bounty tack Gold Road cutlass topsail parley parrel hardtack flogging topmast. Wench gally haul wind main sheet barkadeer lateen sail brigantine killick league lass. Aft <NAME>elsons folly to go on account belaying pin brigantine topsail hands lad marooned doubloon. "
},
{
name : "This is the Body text",
text : "This is the main body text. Here is where we write the major content of the page. Try to keep it concise and relevant. This is what the user will most likely read directly after looking at the title, so it should immediately hook their interest and keep them involved until the end. This is crappy filler text but serves mostly as an example of what you could do with stored bits of filler text. No more having to copy paste from a text file or generator. Immediately have what you need, a mere hotkey away!"
},
{
name : "Insert Text Here",
text : "Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here."
},
{
name : "<NAME>",
text : "Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country."
}
]
| true | [
{
name : "PI:NAME:<NAME>END_PI",
text : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ut ligula dui. Maecenas in sapien cursus, condimentum nulla vitae, pellentesque metus. Sed accumsan tellus et molestie volutpat. Maecenas feugiat, mi."
},
{
name : "PI:NAME:<NAME>END_PI",
text : "The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee."
},
{
name : "PI:NAME:<NAME>END_PI",
text : "Bounty tack Gold Road cutlass topsail parley parrel hardtack flogging topmast. Wench gally haul wind main sheet barkadeer lateen sail brigantine killick league lass. Aft PI:NAME:<NAME>END_PIelsons folly to go on account belaying pin brigantine topsail hands lad marooned doubloon. "
},
{
name : "This is the Body text",
text : "This is the main body text. Here is where we write the major content of the page. Try to keep it concise and relevant. This is what the user will most likely read directly after looking at the title, so it should immediately hook their interest and keep them involved until the end. This is crappy filler text but serves mostly as an example of what you could do with stored bits of filler text. No more having to copy paste from a text file or generator. Immediately have what you need, a mere hotkey away!"
},
{
name : "Insert Text Here",
text : "Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here. Insert Text Here."
},
{
name : "PI:NAME:<NAME>END_PI",
text : "Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country. Now is the time for all good men to come to the aid of the party. Now is the time for all good men to come to the aid of their country."
}
]
|
[
{
"context": " * <tbody>\n * <tr>\n * <td>John</td>\n * <td>Male</td>\n * </tr>\n",
"end": 9996,
"score": 0.9995545744895935,
"start": 9992,
"tag": "NAME",
"value": "John"
},
{
"context": " <tr>\n * <th>Name</th>\n * <td>J... | src/testing/findable.coffee | ohsu-qin/qiprofile | 0 | _ = require 'lodash'
webdriver = require 'selenium-webdriver'
expect = require('./expect')()
require './object'
###*
* The WebElement extension for finding subelements.
*
* @module testing
* @class Findable
###
class Findable
###*
* Finds the element with the given search selection chain.
* Each selector is either a Protractor By object or a search
* condition string. The search condition string can be CSS,
* an id or an xpath, determined as follows:
*
* * If the string contains a '/' or equals '..', then the
* string is assumed to be an xpath.
*
* * Otherwise, if the string starts with '#', then the search
* is on the id following the hash.
*
* * Otherwise, if the search argument starts with '.', then
* the search is by CSS.
*
* * Otherwise, the search is by tag name.
*
* For example,
*
* page.find('h6.qi-title', 'h3', '..')
*
* returns the parent of the h3 elt within the h6.qi-title
* elt on the page.
*
* The ElementFinder result is extended with a find function
* for chaining, so the above example is equivalent to:
*
* page.element(By.css('h6.qi-title'))
* .then (bb) ->
* bb.element(By.tagName('h3'))
* .then (h3) ->
* h3.element(By.xpath('..'))
*
* @method find
* @param selectors the search conditions
* @return a promise which resolves to the target
* Findable, or null if no such WebElement exists
###
find: (selectors...) ->
@_find(selectors...).then (elt) ->
if elt? then addFindableMixin(elt) else elt
###*
* @method _find
* @private
* @param selectors the search conditions
* @return a promise which resolves to the target
* ElementFinder, or null if no such elt exists
###
_find: (selectors...) ->
###*
* @method next
* @param current the Findable to search from, or this
* Page to search from the document root
* @param locator the protractor By object
* @return the result of calling *elt* on the current
* object with the given locator
###
next = (current, locator) ->
current.element(locator)
# Convert the selectors to locators.
locators = (@_locatorFor(selector) for selector in selectors)
# Chain the selects and return a promise which adds the
# Findable methods to the result, if it exists.
target = locators.reduce(next, this)
target.isPresent().then (exists) ->
if exists then target else null
###*
* Finds the elements with the given search selection.
* The selectors are described in the find function.
* Unlike the find function, findAll only accepts one
* selector argument.
*
* Each Findable in the array result is extended
* with a find function for chaining.
*
* @method findAll
* @param selectors the search condition
* @return a promise which resolves to the target
* Findable array
###
findAll: (selectors...) ->
# Work around the following bug:
# * Protractor 3.x `all(...).map(...)` hangs after the first
# element is mapped. E.g. the following hangs:
# @_findAll(selectors...).map(addFindableMixin)
# The work-around is to start with `all(...).count()` and
# then get each element by index.
#
# TODO - revisit this in 2017.
elements = @_findAll(selectors...)
elements.count().then (n) ->
(addFindableMixin(elements.get(i)) for i in _.range(n))
###*
* @method _findAll
* @private
* @param selectors the search condition
* @return a promise which resolves to the target
* WebElement array
###
_findAll: (selectors...) ->
###*
* @method next
* @param parent the Findable to search from, or
* this Page to search from the document root
* @param locator the protractor By object
* @return the search result WebElement array
###
next = (current, locator) ->
current.all(locator)
# Convert the selectors to locators.
locators = (@_locatorFor(selector) for selector in selectors)
# Chain the search.
locators.reduce(next, this)
###*
* @method text
* @param selectors the search condition
* @return a promise which resolves to this WebElement's visible
* text, or null if either:
* * the search result does not exist
* * the element is not displayed
* * the text content is empty
###
text: (selectors...) ->
@find(selectors...)
.then (target) ->
if target?
target.isDisplayed().then (shown) ->
if shown then target else null
else
null
.then (target) ->
if target? then target.getText() else null
.then (text) ->
if text? and text.length then text else null
###*
* Clicks on this element, captures the visited URL,
* and returns.
*
* @method visit
* @return the visited URL
###
visit: ->
###*
* Navigates to the previous page, if necessary.
*
* @method restore
* @param prev_url the previous location
* @return the URL of the page navigated from
###
restore = (prev_url) ->
# The current URL.
browser.getCurrentUrl().then (curr_url) ->
# If the location changed, then navigate back to
# the previous page.
if curr_url == prev_url
curr_url
else
browser.navigate().back().then ->
# Resolve to the page navigated from.
curr_url
# Capture the current location.
browser.getCurrentUrl().then (url) =>
url
# Click the button and resolve to the home page.
@click().then -> restore(url)
###*
* Finds a nested hyperlink. The hyperlink is the href
* attribute of an anchor element (<a href=...></a>) contained
* within this Findable's HTML.
*
* @method hyperlink
* @param selectors the search condition
* @return a promise which resolves to the hyperlink URL
###
hyperlink: (selectors...) ->
selectors.push('a')
@_find(selectors...).then (anchor) ->
if anchor then anchor.getAttribute('href') else null
###*
* Finds all nested hyperlinks.
* See the hyperlink method.
*
* @method hyperlinks
* @param selectors the search condition
* @return a promise which resolves to the hyperlink URLs
###
hyperlinks: (selectors...) ->
selectors.push('a')
@_findAll(selectors...).then (anchors) ->
anchors.map (anchor) ->
anchor.getAttribute('href')
###*
* Finds the table WebElement for the given find() selector.
* The return value is a promisr resolving to a Table object.
* Each table promise resolves to an object {header, body},
* where:
* * header is a promise which resolves to an array of table
* heading text value promises
* * body is a promise which resolves to an array of row promises
*
* Each row promise resolves to an array of column text promises.
*
* If the function argument is provided, then it is applied to
* each table cell text value promise.
*
* @method findTable
* @param bindings the table {field: ng-bind expression}
* bindings
* @param selectors the table elt find selectors
* @return a promise resolving to the table WebElement
* with the field properties, or null if the table
* does not exist
###
findTable: (selectors...) ->
finder = @_find(selectors...).then (table) ->
# Add the Table methods to the elt.
if table? then addTableMixin(table) else table
###*
* Finds the table WebElements for the given Page.findAll()
* selector. The return value is an array of table promises.
* Each table promise resolves to an object {header, body},
* where:
* * header is a promise which resolves to an array of table
* heading text value promises
* * body is a promise which resolves to an array of row promises
*
* Each row promise resolves to an array of column text promises.
*
* If the function argument is provided, then it is applied to
* each table cell text value promise.
*
* @method findTables
* @param selector the Protractor CSS locator argument
* @return a promise resolving to the Table array
###
findTables: (selectors...) ->
@_findAll(selectors...).then (tables) ->
# Add the Table prototype to each WebElement in the result.
tables.map(addTableMixin)
###*
* @method _locatorFor
* @private
* @param selector the search condition
* @return the By locator object
###
_locatorFor: (selector) ->
# If the selector is a string, then make a By locator.
# Otherwise, the selector is assumed to already be a
# By locator.
if _.isString(selector)
# An xpath selector string has a slash or equals.
# An id selector starts with # and doesn't have a space.
# Anything else is assumed to be CSS.
if selector == '..' or '/' in selector
By.xpath(selector)
else if selector[0] == '#' and not ' ' in selector
By.id(selector[1..-1])
else if selector.match('in ')
By.repeater(selector)
else if selector.match(/^\w[\w-]*$/)
By.tagName(selector)
else
By.css(selector)
else if selector?
# Pass through a non-string selector.
selector
else
throw new Error("The selector is not defined")
###*
* The Table class represents a table WebElement with the
* following properties:
*
* * header - a promise resolving to the array of `<th/>`
* WebElement text values
*
* * rows - a promise resolving to the two-dimensional
* `<tr/> x <td/>` cell value array
*
* The header values can be either in a separate `thead`
* row or as the leading `th` element in each `tbody` row,
* e.g.:
*
* <table id="t01">
* <thead>
* <tr>
* <th>Name</th>
* <th>Gender</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>John</td>
* <td>Male</td>
* </tr>
* </tbody>
* </table>
*
* or:
*
* <table id="t02">
* <tbody>
* <tr>
* <th>Name</th>
* <td>John</td>
* </tr>
* <tr>
* <th>Gender</th>
* <td>Male</td>
* </tr>
* </tbody>
* </table>
*
* In the both cases, the Table *heading* resolves to
* ['Name', 'Gender']. In the first case, the Table
* *rows* resolves to [['John', 'Male]]. In the second
* case, the Table *rows* resolves to [['John'], ['Male]].
*
* If this table contains a `<tbody/>` subelement, then this
* property includes the rows in the first such body
* subelement. Otherwise, this methods returns all `<tr/>`
* rows contained in the table.
*
* Note - If there are multiple `<tbody/>` elements in the
* table, only the rows of the first `<tbody>` are returned.
*
* Note - The rows of nested `<table/>` elements are returned
* along with the parent rows.
*
* TODO - address the above two notes by adding a Table
* subTables property for subtables and include only the
* direct rows in a parent Table.
*
* Note - The Table class is not defined in it's own file
* because there is a cyclical Findable dependency.
*
* @module testing
* @class Table
* @extends Findable
###
class Table extends Findable
###*
* Adds *field* properties to this table which resolve to the
* the value given by the corresponding AngularJS binding
* expression.
*
* @method addBindings
* @param bindings {Object} the {field: binding} object, where
* *binding* is the AngularJS expression to which the field
* element is bound
* @return this table WebElement
###
addBindings: (bindings) ->
for field, binding of bindings
locator = By.binding(binding)
this[field] = @find(locator).then (elt) ->
if elt? then elt.text() else elt
this
# @return a promise which resolves to the [[cell, ...], ...]
# row x column Finder array
@property rows: ->
# Chain the finder to preferably look for rows in a tbody tag,
# otherwise look in the table itself.
@find(By.tagName('tbody'))
.then (body) ->
# The parent element is the table child tbody, if it exists,
# otherwise the table itself.
if body? then body else this
.then (parent) ->
# Find the rows...
parent.findAll(By.tagName('tr'))
.then (rows) ->
rows.map (row) ->
# ...then find the cells...
row.findAll(By.tagName('td'))
.then (rows) ->
webdriver.promise.all(rows)
# @return a promise which resolves to a header text array
@property header: ->
@findAll(By.tagName('th'))
.then (headings) ->
headings.map (heading) ->
heading.text()
.then (headings) ->
webdriver.promise.all(headings)
#
# Findable utility functions.
#
# The following mix-ins return a new mix-in instance which
# delegates to the mixin argument, e.g.:
# extended = addFindableMixin(result)
# expect(extended).to.be.an.instanceOf(Findable)
# expect(_.functionsIn(extended).to.include.members(_.functionsIn(result))
#
# @method addMixin
# @param mixin the mix-in class
# @param obj the source object
# @return an empty new mixin object which delegates to
# the given object
#
addMixin = (mixin, obj) ->
extended = _.extend(new mixin, obj)
# Work around the following bug:
# * lodash only copies the functions defined in the superclass
# WebdriverWebElement of an ElementFinder. The functions defined
# in the ElementFinder class itself are ignored.
# This is a bizarre behavior that only occurs in this case and
# is inexplicable from inspected the lodash source code.
# TODO - file and track a lodash bug.
for key of obj
if _.isUndefined(extended[key])
extended[key] = obj[key]
extended
# Adds Findable methods to the given WebElement.
addFindableMixin = _.partial(addMixin, Findable)
# Adds Table methods to the given WebElement.
addTableMixin = _.partial(addMixin, Table)
module.exports = Findable
| 31100 | _ = require 'lodash'
webdriver = require 'selenium-webdriver'
expect = require('./expect')()
require './object'
###*
* The WebElement extension for finding subelements.
*
* @module testing
* @class Findable
###
class Findable
###*
* Finds the element with the given search selection chain.
* Each selector is either a Protractor By object or a search
* condition string. The search condition string can be CSS,
* an id or an xpath, determined as follows:
*
* * If the string contains a '/' or equals '..', then the
* string is assumed to be an xpath.
*
* * Otherwise, if the string starts with '#', then the search
* is on the id following the hash.
*
* * Otherwise, if the search argument starts with '.', then
* the search is by CSS.
*
* * Otherwise, the search is by tag name.
*
* For example,
*
* page.find('h6.qi-title', 'h3', '..')
*
* returns the parent of the h3 elt within the h6.qi-title
* elt on the page.
*
* The ElementFinder result is extended with a find function
* for chaining, so the above example is equivalent to:
*
* page.element(By.css('h6.qi-title'))
* .then (bb) ->
* bb.element(By.tagName('h3'))
* .then (h3) ->
* h3.element(By.xpath('..'))
*
* @method find
* @param selectors the search conditions
* @return a promise which resolves to the target
* Findable, or null if no such WebElement exists
###
find: (selectors...) ->
@_find(selectors...).then (elt) ->
if elt? then addFindableMixin(elt) else elt
###*
* @method _find
* @private
* @param selectors the search conditions
* @return a promise which resolves to the target
* ElementFinder, or null if no such elt exists
###
_find: (selectors...) ->
###*
* @method next
* @param current the Findable to search from, or this
* Page to search from the document root
* @param locator the protractor By object
* @return the result of calling *elt* on the current
* object with the given locator
###
next = (current, locator) ->
current.element(locator)
# Convert the selectors to locators.
locators = (@_locatorFor(selector) for selector in selectors)
# Chain the selects and return a promise which adds the
# Findable methods to the result, if it exists.
target = locators.reduce(next, this)
target.isPresent().then (exists) ->
if exists then target else null
###*
* Finds the elements with the given search selection.
* The selectors are described in the find function.
* Unlike the find function, findAll only accepts one
* selector argument.
*
* Each Findable in the array result is extended
* with a find function for chaining.
*
* @method findAll
* @param selectors the search condition
* @return a promise which resolves to the target
* Findable array
###
findAll: (selectors...) ->
# Work around the following bug:
# * Protractor 3.x `all(...).map(...)` hangs after the first
# element is mapped. E.g. the following hangs:
# @_findAll(selectors...).map(addFindableMixin)
# The work-around is to start with `all(...).count()` and
# then get each element by index.
#
# TODO - revisit this in 2017.
elements = @_findAll(selectors...)
elements.count().then (n) ->
(addFindableMixin(elements.get(i)) for i in _.range(n))
###*
* @method _findAll
* @private
* @param selectors the search condition
* @return a promise which resolves to the target
* WebElement array
###
_findAll: (selectors...) ->
###*
* @method next
* @param parent the Findable to search from, or
* this Page to search from the document root
* @param locator the protractor By object
* @return the search result WebElement array
###
next = (current, locator) ->
current.all(locator)
# Convert the selectors to locators.
locators = (@_locatorFor(selector) for selector in selectors)
# Chain the search.
locators.reduce(next, this)
###*
* @method text
* @param selectors the search condition
* @return a promise which resolves to this WebElement's visible
* text, or null if either:
* * the search result does not exist
* * the element is not displayed
* * the text content is empty
###
text: (selectors...) ->
@find(selectors...)
.then (target) ->
if target?
target.isDisplayed().then (shown) ->
if shown then target else null
else
null
.then (target) ->
if target? then target.getText() else null
.then (text) ->
if text? and text.length then text else null
###*
* Clicks on this element, captures the visited URL,
* and returns.
*
* @method visit
* @return the visited URL
###
visit: ->
###*
* Navigates to the previous page, if necessary.
*
* @method restore
* @param prev_url the previous location
* @return the URL of the page navigated from
###
restore = (prev_url) ->
# The current URL.
browser.getCurrentUrl().then (curr_url) ->
# If the location changed, then navigate back to
# the previous page.
if curr_url == prev_url
curr_url
else
browser.navigate().back().then ->
# Resolve to the page navigated from.
curr_url
# Capture the current location.
browser.getCurrentUrl().then (url) =>
url
# Click the button and resolve to the home page.
@click().then -> restore(url)
###*
* Finds a nested hyperlink. The hyperlink is the href
* attribute of an anchor element (<a href=...></a>) contained
* within this Findable's HTML.
*
* @method hyperlink
* @param selectors the search condition
* @return a promise which resolves to the hyperlink URL
###
hyperlink: (selectors...) ->
selectors.push('a')
@_find(selectors...).then (anchor) ->
if anchor then anchor.getAttribute('href') else null
###*
* Finds all nested hyperlinks.
* See the hyperlink method.
*
* @method hyperlinks
* @param selectors the search condition
* @return a promise which resolves to the hyperlink URLs
###
hyperlinks: (selectors...) ->
selectors.push('a')
@_findAll(selectors...).then (anchors) ->
anchors.map (anchor) ->
anchor.getAttribute('href')
###*
* Finds the table WebElement for the given find() selector.
* The return value is a promisr resolving to a Table object.
* Each table promise resolves to an object {header, body},
* where:
* * header is a promise which resolves to an array of table
* heading text value promises
* * body is a promise which resolves to an array of row promises
*
* Each row promise resolves to an array of column text promises.
*
* If the function argument is provided, then it is applied to
* each table cell text value promise.
*
* @method findTable
* @param bindings the table {field: ng-bind expression}
* bindings
* @param selectors the table elt find selectors
* @return a promise resolving to the table WebElement
* with the field properties, or null if the table
* does not exist
###
findTable: (selectors...) ->
finder = @_find(selectors...).then (table) ->
# Add the Table methods to the elt.
if table? then addTableMixin(table) else table
###*
* Finds the table WebElements for the given Page.findAll()
* selector. The return value is an array of table promises.
* Each table promise resolves to an object {header, body},
* where:
* * header is a promise which resolves to an array of table
* heading text value promises
* * body is a promise which resolves to an array of row promises
*
* Each row promise resolves to an array of column text promises.
*
* If the function argument is provided, then it is applied to
* each table cell text value promise.
*
* @method findTables
* @param selector the Protractor CSS locator argument
* @return a promise resolving to the Table array
###
findTables: (selectors...) ->
@_findAll(selectors...).then (tables) ->
# Add the Table prototype to each WebElement in the result.
tables.map(addTableMixin)
###*
* @method _locatorFor
* @private
* @param selector the search condition
* @return the By locator object
###
_locatorFor: (selector) ->
# If the selector is a string, then make a By locator.
# Otherwise, the selector is assumed to already be a
# By locator.
if _.isString(selector)
# An xpath selector string has a slash or equals.
# An id selector starts with # and doesn't have a space.
# Anything else is assumed to be CSS.
if selector == '..' or '/' in selector
By.xpath(selector)
else if selector[0] == '#' and not ' ' in selector
By.id(selector[1..-1])
else if selector.match('in ')
By.repeater(selector)
else if selector.match(/^\w[\w-]*$/)
By.tagName(selector)
else
By.css(selector)
else if selector?
# Pass through a non-string selector.
selector
else
throw new Error("The selector is not defined")
###*
* The Table class represents a table WebElement with the
* following properties:
*
* * header - a promise resolving to the array of `<th/>`
* WebElement text values
*
* * rows - a promise resolving to the two-dimensional
* `<tr/> x <td/>` cell value array
*
* The header values can be either in a separate `thead`
* row or as the leading `th` element in each `tbody` row,
* e.g.:
*
* <table id="t01">
* <thead>
* <tr>
* <th>Name</th>
* <th>Gender</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td><NAME></td>
* <td>Male</td>
* </tr>
* </tbody>
* </table>
*
* or:
*
* <table id="t02">
* <tbody>
* <tr>
* <th>Name</th>
* <td><NAME></td>
* </tr>
* <tr>
* <th>Gender</th>
* <td>Male</td>
* </tr>
* </tbody>
* </table>
*
* In the both cases, the Table *heading* resolves to
* ['Name', 'Gender']. In the first case, the Table
* *rows* resolves to [['<NAME>', 'Male]]. In the second
* case, the Table *rows* resolves to [['<NAME>'], ['Male]].
*
* If this table contains a `<tbody/>` subelement, then this
* property includes the rows in the first such body
* subelement. Otherwise, this methods returns all `<tr/>`
* rows contained in the table.
*
* Note - If there are multiple `<tbody/>` elements in the
* table, only the rows of the first `<tbody>` are returned.
*
* Note - The rows of nested `<table/>` elements are returned
* along with the parent rows.
*
* TODO - address the above two notes by adding a Table
* subTables property for subtables and include only the
* direct rows in a parent Table.
*
* Note - The Table class is not defined in it's own file
* because there is a cyclical Findable dependency.
*
* @module testing
* @class Table
* @extends Findable
###
class Table extends Findable
###*
* Adds *field* properties to this table which resolve to the
* the value given by the corresponding AngularJS binding
* expression.
*
* @method addBindings
* @param bindings {Object} the {field: binding} object, where
* *binding* is the AngularJS expression to which the field
* element is bound
* @return this table WebElement
###
addBindings: (bindings) ->
for field, binding of bindings
locator = By.binding(binding)
this[field] = @find(locator).then (elt) ->
if elt? then elt.text() else elt
this
# @return a promise which resolves to the [[cell, ...], ...]
# row x column Finder array
@property rows: ->
# Chain the finder to preferably look for rows in a tbody tag,
# otherwise look in the table itself.
@find(By.tagName('tbody'))
.then (body) ->
# The parent element is the table child tbody, if it exists,
# otherwise the table itself.
if body? then body else this
.then (parent) ->
# Find the rows...
parent.findAll(By.tagName('tr'))
.then (rows) ->
rows.map (row) ->
# ...then find the cells...
row.findAll(By.tagName('td'))
.then (rows) ->
webdriver.promise.all(rows)
# @return a promise which resolves to a header text array
@property header: ->
@findAll(By.tagName('th'))
.then (headings) ->
headings.map (heading) ->
heading.text()
.then (headings) ->
webdriver.promise.all(headings)
#
# Findable utility functions.
#
# The following mix-ins return a new mix-in instance which
# delegates to the mixin argument, e.g.:
# extended = addFindableMixin(result)
# expect(extended).to.be.an.instanceOf(Findable)
# expect(_.functionsIn(extended).to.include.members(_.functionsIn(result))
#
# @method addMixin
# @param mixin the mix-in class
# @param obj the source object
# @return an empty new mixin object which delegates to
# the given object
#
addMixin = (mixin, obj) ->
extended = _.extend(new mixin, obj)
# Work around the following bug:
# * lodash only copies the functions defined in the superclass
# WebdriverWebElement of an ElementFinder. The functions defined
# in the ElementFinder class itself are ignored.
# This is a bizarre behavior that only occurs in this case and
# is inexplicable from inspected the lodash source code.
# TODO - file and track a lodash bug.
for key of obj
if _.isUndefined(extended[key])
extended[key] = obj[key]
extended
# Adds Findable methods to the given WebElement.
addFindableMixin = _.partial(addMixin, Findable)
# Adds Table methods to the given WebElement.
addTableMixin = _.partial(addMixin, Table)
module.exports = Findable
| true | _ = require 'lodash'
webdriver = require 'selenium-webdriver'
expect = require('./expect')()
require './object'
###*
* The WebElement extension for finding subelements.
*
* @module testing
* @class Findable
###
class Findable
###*
* Finds the element with the given search selection chain.
* Each selector is either a Protractor By object or a search
* condition string. The search condition string can be CSS,
* an id or an xpath, determined as follows:
*
* * If the string contains a '/' or equals '..', then the
* string is assumed to be an xpath.
*
* * Otherwise, if the string starts with '#', then the search
* is on the id following the hash.
*
* * Otherwise, if the search argument starts with '.', then
* the search is by CSS.
*
* * Otherwise, the search is by tag name.
*
* For example,
*
* page.find('h6.qi-title', 'h3', '..')
*
* returns the parent of the h3 elt within the h6.qi-title
* elt on the page.
*
* The ElementFinder result is extended with a find function
* for chaining, so the above example is equivalent to:
*
* page.element(By.css('h6.qi-title'))
* .then (bb) ->
* bb.element(By.tagName('h3'))
* .then (h3) ->
* h3.element(By.xpath('..'))
*
* @method find
* @param selectors the search conditions
* @return a promise which resolves to the target
* Findable, or null if no such WebElement exists
###
find: (selectors...) ->
@_find(selectors...).then (elt) ->
if elt? then addFindableMixin(elt) else elt
###*
* @method _find
* @private
* @param selectors the search conditions
* @return a promise which resolves to the target
* ElementFinder, or null if no such elt exists
###
_find: (selectors...) ->
###*
* @method next
* @param current the Findable to search from, or this
* Page to search from the document root
* @param locator the protractor By object
* @return the result of calling *elt* on the current
* object with the given locator
###
next = (current, locator) ->
current.element(locator)
# Convert the selectors to locators.
locators = (@_locatorFor(selector) for selector in selectors)
# Chain the selects and return a promise which adds the
# Findable methods to the result, if it exists.
target = locators.reduce(next, this)
target.isPresent().then (exists) ->
if exists then target else null
###*
* Finds the elements with the given search selection.
* The selectors are described in the find function.
* Unlike the find function, findAll only accepts one
* selector argument.
*
* Each Findable in the array result is extended
* with a find function for chaining.
*
* @method findAll
* @param selectors the search condition
* @return a promise which resolves to the target
* Findable array
###
findAll: (selectors...) ->
# Work around the following bug:
# * Protractor 3.x `all(...).map(...)` hangs after the first
# element is mapped. E.g. the following hangs:
# @_findAll(selectors...).map(addFindableMixin)
# The work-around is to start with `all(...).count()` and
# then get each element by index.
#
# TODO - revisit this in 2017.
elements = @_findAll(selectors...)
elements.count().then (n) ->
(addFindableMixin(elements.get(i)) for i in _.range(n))
###*
* @method _findAll
* @private
* @param selectors the search condition
* @return a promise which resolves to the target
* WebElement array
###
_findAll: (selectors...) ->
###*
* @method next
* @param parent the Findable to search from, or
* this Page to search from the document root
* @param locator the protractor By object
* @return the search result WebElement array
###
next = (current, locator) ->
current.all(locator)
# Convert the selectors to locators.
locators = (@_locatorFor(selector) for selector in selectors)
# Chain the search.
locators.reduce(next, this)
###*
* @method text
* @param selectors the search condition
* @return a promise which resolves to this WebElement's visible
* text, or null if either:
* * the search result does not exist
* * the element is not displayed
* * the text content is empty
###
text: (selectors...) ->
@find(selectors...)
.then (target) ->
if target?
target.isDisplayed().then (shown) ->
if shown then target else null
else
null
.then (target) ->
if target? then target.getText() else null
.then (text) ->
if text? and text.length then text else null
###*
* Clicks on this element, captures the visited URL,
* and returns.
*
* @method visit
* @return the visited URL
###
visit: ->
###*
* Navigates to the previous page, if necessary.
*
* @method restore
* @param prev_url the previous location
* @return the URL of the page navigated from
###
restore = (prev_url) ->
# The current URL.
browser.getCurrentUrl().then (curr_url) ->
# If the location changed, then navigate back to
# the previous page.
if curr_url == prev_url
curr_url
else
browser.navigate().back().then ->
# Resolve to the page navigated from.
curr_url
# Capture the current location.
browser.getCurrentUrl().then (url) =>
url
# Click the button and resolve to the home page.
@click().then -> restore(url)
###*
* Finds a nested hyperlink. The hyperlink is the href
* attribute of an anchor element (<a href=...></a>) contained
* within this Findable's HTML.
*
* @method hyperlink
* @param selectors the search condition
* @return a promise which resolves to the hyperlink URL
###
hyperlink: (selectors...) ->
selectors.push('a')
@_find(selectors...).then (anchor) ->
if anchor then anchor.getAttribute('href') else null
###*
* Finds all nested hyperlinks.
* See the hyperlink method.
*
* @method hyperlinks
* @param selectors the search condition
* @return a promise which resolves to the hyperlink URLs
###
hyperlinks: (selectors...) ->
selectors.push('a')
@_findAll(selectors...).then (anchors) ->
anchors.map (anchor) ->
anchor.getAttribute('href')
###*
* Finds the table WebElement for the given find() selector.
* The return value is a promisr resolving to a Table object.
* Each table promise resolves to an object {header, body},
* where:
* * header is a promise which resolves to an array of table
* heading text value promises
* * body is a promise which resolves to an array of row promises
*
* Each row promise resolves to an array of column text promises.
*
* If the function argument is provided, then it is applied to
* each table cell text value promise.
*
* @method findTable
* @param bindings the table {field: ng-bind expression}
* bindings
* @param selectors the table elt find selectors
* @return a promise resolving to the table WebElement
* with the field properties, or null if the table
* does not exist
###
findTable: (selectors...) ->
finder = @_find(selectors...).then (table) ->
# Add the Table methods to the elt.
if table? then addTableMixin(table) else table
###*
* Finds the table WebElements for the given Page.findAll()
* selector. The return value is an array of table promises.
* Each table promise resolves to an object {header, body},
* where:
* * header is a promise which resolves to an array of table
* heading text value promises
* * body is a promise which resolves to an array of row promises
*
* Each row promise resolves to an array of column text promises.
*
* If the function argument is provided, then it is applied to
* each table cell text value promise.
*
* @method findTables
* @param selector the Protractor CSS locator argument
* @return a promise resolving to the Table array
###
findTables: (selectors...) ->
@_findAll(selectors...).then (tables) ->
# Add the Table prototype to each WebElement in the result.
tables.map(addTableMixin)
###*
* @method _locatorFor
* @private
* @param selector the search condition
* @return the By locator object
###
_locatorFor: (selector) ->
# If the selector is a string, then make a By locator.
# Otherwise, the selector is assumed to already be a
# By locator.
if _.isString(selector)
# An xpath selector string has a slash or equals.
# An id selector starts with # and doesn't have a space.
# Anything else is assumed to be CSS.
if selector == '..' or '/' in selector
By.xpath(selector)
else if selector[0] == '#' and not ' ' in selector
By.id(selector[1..-1])
else if selector.match('in ')
By.repeater(selector)
else if selector.match(/^\w[\w-]*$/)
By.tagName(selector)
else
By.css(selector)
else if selector?
# Pass through a non-string selector.
selector
else
throw new Error("The selector is not defined")
###*
* The Table class represents a table WebElement with the
* following properties:
*
* * header - a promise resolving to the array of `<th/>`
* WebElement text values
*
* * rows - a promise resolving to the two-dimensional
* `<tr/> x <td/>` cell value array
*
* The header values can be either in a separate `thead`
* row or as the leading `th` element in each `tbody` row,
* e.g.:
*
* <table id="t01">
* <thead>
* <tr>
* <th>Name</th>
* <th>Gender</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>PI:NAME:<NAME>END_PI</td>
* <td>Male</td>
* </tr>
* </tbody>
* </table>
*
* or:
*
* <table id="t02">
* <tbody>
* <tr>
* <th>Name</th>
* <td>PI:NAME:<NAME>END_PI</td>
* </tr>
* <tr>
* <th>Gender</th>
* <td>Male</td>
* </tr>
* </tbody>
* </table>
*
* In the both cases, the Table *heading* resolves to
* ['Name', 'Gender']. In the first case, the Table
* *rows* resolves to [['PI:NAME:<NAME>END_PI', 'Male]]. In the second
* case, the Table *rows* resolves to [['PI:NAME:<NAME>END_PI'], ['Male]].
*
* If this table contains a `<tbody/>` subelement, then this
* property includes the rows in the first such body
* subelement. Otherwise, this methods returns all `<tr/>`
* rows contained in the table.
*
* Note - If there are multiple `<tbody/>` elements in the
* table, only the rows of the first `<tbody>` are returned.
*
* Note - The rows of nested `<table/>` elements are returned
* along with the parent rows.
*
* TODO - address the above two notes by adding a Table
* subTables property for subtables and include only the
* direct rows in a parent Table.
*
* Note - The Table class is not defined in it's own file
* because there is a cyclical Findable dependency.
*
* @module testing
* @class Table
* @extends Findable
###
class Table extends Findable
###*
* Adds *field* properties to this table which resolve to the
* the value given by the corresponding AngularJS binding
* expression.
*
* @method addBindings
* @param bindings {Object} the {field: binding} object, where
* *binding* is the AngularJS expression to which the field
* element is bound
* @return this table WebElement
###
addBindings: (bindings) ->
for field, binding of bindings
locator = By.binding(binding)
this[field] = @find(locator).then (elt) ->
if elt? then elt.text() else elt
this
# @return a promise which resolves to the [[cell, ...], ...]
# row x column Finder array
@property rows: ->
# Chain the finder to preferably look for rows in a tbody tag,
# otherwise look in the table itself.
@find(By.tagName('tbody'))
.then (body) ->
# The parent element is the table child tbody, if it exists,
# otherwise the table itself.
if body? then body else this
.then (parent) ->
# Find the rows...
parent.findAll(By.tagName('tr'))
.then (rows) ->
rows.map (row) ->
# ...then find the cells...
row.findAll(By.tagName('td'))
.then (rows) ->
webdriver.promise.all(rows)
# @return a promise which resolves to a header text array
@property header: ->
@findAll(By.tagName('th'))
.then (headings) ->
headings.map (heading) ->
heading.text()
.then (headings) ->
webdriver.promise.all(headings)
#
# Findable utility functions.
#
# The following mix-ins return a new mix-in instance which
# delegates to the mixin argument, e.g.:
# extended = addFindableMixin(result)
# expect(extended).to.be.an.instanceOf(Findable)
# expect(_.functionsIn(extended).to.include.members(_.functionsIn(result))
#
# @method addMixin
# @param mixin the mix-in class
# @param obj the source object
# @return an empty new mixin object which delegates to
# the given object
#
addMixin = (mixin, obj) ->
extended = _.extend(new mixin, obj)
# Work around the following bug:
# * lodash only copies the functions defined in the superclass
# WebdriverWebElement of an ElementFinder. The functions defined
# in the ElementFinder class itself are ignored.
# This is a bizarre behavior that only occurs in this case and
# is inexplicable from inspected the lodash source code.
# TODO - file and track a lodash bug.
for key of obj
if _.isUndefined(extended[key])
extended[key] = obj[key]
extended
# Adds Findable methods to the given WebElement.
addFindableMixin = _.partial(addMixin, Findable)
# Adds Table methods to the given WebElement.
addTableMixin = _.partial(addMixin, Table)
module.exports = Findable
|
[
{
"context": " = new Sections [\n {\n body: \"<p>==Alice== was ==brave==</p>\"\n type: \"text\"\n ",
"end": 2520,
"score": 0.9992608428001404,
"start": 2515,
"tag": "NAME",
"value": "Alice"
},
{
"context": "\"text\"\n },\n {\n body:... | src/client/apps/edit/components/layout/test/index.coffee | craigspaeth/positron | 76 | _ = require 'underscore'
benv = require 'benv'
sinon = require 'sinon'
Article = require '../../../../../models/article.coffee'
Channel = require '../../../../../models/channel'
Sections = require '../../../../../collections/sections'
Backbone = require 'backbone'
fixtures = require '../../../../../../test/helpers/fixtures'
rewire = require 'rewire'
{ resolve } = require 'path'
describe 'EditLayout', ->
beforeEach (done) ->
benv.setup =>
tmpl = resolve __dirname, '../index.jade'
sd = _.extend fixtures().locals.sd,
CURRENT_CHANNEL: fixtures().channels
USER: accessToken: 'foo'
FORCE_URL: 'https://artsy.net'
locals = _.extend fixtures().locals,
article: @article = new Article fixtures().articles
sd: sd
channel: new Channel
benv.render tmpl, locals, =>
benv.expose $: benv.require('jquery')
Backbone.$ = $
sinon.stub Backbone, 'sync'
@EditLayout = rewire '../index.coffee'
@EditLayout.__set__ 'YoastView', @YoastView = sinon.stub().returns onKeyup: @yoastKeyup = sinon.stub()
@EditLayout.__set__ 'sd', sd
sinon.stub _, 'debounce'
$.fn.autosize = sinon.stub()
_.debounce.callsArg 0
@view = new @EditLayout
el: $('#layout-content')
article: @article
@view.article.sync = sinon.stub()
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
_.debounce.restore()
describe '#getBodyText', ->
it 'parses the article and pulls out an html string of its text', ->
text = @view.getBodyText()
text.should.containEql '<p>Just before the lines'
text.should.containEql 'Check out this video art:</p>'
describe '#onYoastKeyup', ->
it 'returns if its not an artsy internal channel', ->
@view.channel.set 'type', 'partner'
@view.onYoastKeyup()
@yoastKeyup.callCount.should.equal 0
it 'calls onKeyup on the yoast view', ->
@view.channel.set 'type', 'team'
@view.onYoastKeyup()
@yoastKeyup.callCount.should.equal 1
describe '#setupYoast', ->
it 'initializes YoastView with args', ->
@YoastView.args[0][0].contentField.should.containEql 'Just before the lines start forming...'
@YoastView.args[0][0].contentField.should.containEql 'Check out this video art'
describe '#getLinkableText', ->
it 'returns an array of linkable text', ->
@view.article.sections = new Sections [
{
body: "<p>==Alice== was ==brave==</p>"
type: "text"
},
{
body: "<p>==Andy== was a ==pop== artist</p>"
type: "text"
}
]
linkableText = @view.getLinkableText()
linkableText.length.should.equal 4
describe '#autolinkText', ->
it 'creates links from search', ->
request =
get: sinon.stub().returns
set: sinon.stub().returns
end: @requestEnd = sinon.stub().yields(null, {
body:
total: 1
hits: [
{
_type: 'artist'
_score: 9,
_source:
visible_to_public: true
name: 'Cat'
slug: 'cat'
},
]
})
@EditLayout.__set__ 'request', request
view = new @EditLayout
el: $('#layout-content')
article: @article
channel: new Channel
view.article.sections = new Sections [
{
body: "<p>==Alice== was ==brave==</p>"
type: "text"
}
]
view.autolinkText()
view.article.sections.first().get('body').should.equal "<p><a href='https://artsy.net/artist/cat'>Cat</a> was <a href='https://artsy.net/artist/cat'>Cat</a></p>"
it 'removes delims if no good result is found', ->
request =
get: sinon.stub().returns
set: sinon.stub().returns
end: @requestEnd = sinon.stub().yields(null, {
body:
total: 0
})
@EditLayout.__set__ 'request', request
view = new @EditLayout
el: $('#layout-content')
article: @article
channel: new Channel
view.article.sections = new Sections [
{
body: "<p>==Alice== was ==brave==</p>"
type: "text"
}
]
view.autolinkText()
view.article.sections.first().get('body').should.equal "<p>Alice was brave</p>"
describe '#findValidResults', ->
it 'rejects scores less than 6.5', ->
hits = [
{_score: 1, _source: visible_to_public: true},
{_score: 2, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: true}
]
@view.findValidResults(hits).length.should.equal 1
it 'rejects hits that are not visible to the public', ->
hits = [
{_score: 9, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: false}
]
@view.findValidResults(hits).length.should.equal 2
describe '#getNewLinkFromHits', ->
it 'returns a new link for artist type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'artist'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/artist/cat'>Cat</a>"
it 'returns a new link for partner type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'partner'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/cat'>Cat</a>"
it 'returns a new link for city type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'city'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/shows/cat'>Cat</a>"
| 185445 | _ = require 'underscore'
benv = require 'benv'
sinon = require 'sinon'
Article = require '../../../../../models/article.coffee'
Channel = require '../../../../../models/channel'
Sections = require '../../../../../collections/sections'
Backbone = require 'backbone'
fixtures = require '../../../../../../test/helpers/fixtures'
rewire = require 'rewire'
{ resolve } = require 'path'
describe 'EditLayout', ->
beforeEach (done) ->
benv.setup =>
tmpl = resolve __dirname, '../index.jade'
sd = _.extend fixtures().locals.sd,
CURRENT_CHANNEL: fixtures().channels
USER: accessToken: 'foo'
FORCE_URL: 'https://artsy.net'
locals = _.extend fixtures().locals,
article: @article = new Article fixtures().articles
sd: sd
channel: new Channel
benv.render tmpl, locals, =>
benv.expose $: benv.require('jquery')
Backbone.$ = $
sinon.stub Backbone, 'sync'
@EditLayout = rewire '../index.coffee'
@EditLayout.__set__ 'YoastView', @YoastView = sinon.stub().returns onKeyup: @yoastKeyup = sinon.stub()
@EditLayout.__set__ 'sd', sd
sinon.stub _, 'debounce'
$.fn.autosize = sinon.stub()
_.debounce.callsArg 0
@view = new @EditLayout
el: $('#layout-content')
article: @article
@view.article.sync = sinon.stub()
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
_.debounce.restore()
describe '#getBodyText', ->
it 'parses the article and pulls out an html string of its text', ->
text = @view.getBodyText()
text.should.containEql '<p>Just before the lines'
text.should.containEql 'Check out this video art:</p>'
describe '#onYoastKeyup', ->
it 'returns if its not an artsy internal channel', ->
@view.channel.set 'type', 'partner'
@view.onYoastKeyup()
@yoastKeyup.callCount.should.equal 0
it 'calls onKeyup on the yoast view', ->
@view.channel.set 'type', 'team'
@view.onYoastKeyup()
@yoastKeyup.callCount.should.equal 1
describe '#setupYoast', ->
it 'initializes YoastView with args', ->
@YoastView.args[0][0].contentField.should.containEql 'Just before the lines start forming...'
@YoastView.args[0][0].contentField.should.containEql 'Check out this video art'
describe '#getLinkableText', ->
it 'returns an array of linkable text', ->
@view.article.sections = new Sections [
{
body: "<p>==<NAME>== was ==brave==</p>"
type: "text"
},
{
body: "<p>==<NAME>== was a ==pop== artist</p>"
type: "text"
}
]
linkableText = @view.getLinkableText()
linkableText.length.should.equal 4
describe '#autolinkText', ->
it 'creates links from search', ->
request =
get: sinon.stub().returns
set: sinon.stub().returns
end: @requestEnd = sinon.stub().yields(null, {
body:
total: 1
hits: [
{
_type: 'artist'
_score: 9,
_source:
visible_to_public: true
name: '<NAME>'
slug: 'cat'
},
]
})
@EditLayout.__set__ 'request', request
view = new @EditLayout
el: $('#layout-content')
article: @article
channel: new Channel
view.article.sections = new Sections [
{
body: "<p>==<NAME>== was ==brave==</p>"
type: "text"
}
]
view.autolinkText()
view.article.sections.first().get('body').should.equal "<p><a href='https://artsy.net/artist/cat'>Cat</a> was <a href='https://artsy.net/artist/cat'>Cat</a></p>"
it 'removes delims if no good result is found', ->
request =
get: sinon.stub().returns
set: sinon.stub().returns
end: @requestEnd = sinon.stub().yields(null, {
body:
total: 0
})
@EditLayout.__set__ 'request', request
view = new @EditLayout
el: $('#layout-content')
article: @article
channel: new Channel
view.article.sections = new Sections [
{
body: "<p>==<NAME>== was ==brave==</p>"
type: "text"
}
]
view.autolinkText()
view.article.sections.first().get('body').should.equal "<p><NAME> was brave</p>"
describe '#findValidResults', ->
it 'rejects scores less than 6.5', ->
hits = [
{_score: 1, _source: visible_to_public: true},
{_score: 2, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: true}
]
@view.findValidResults(hits).length.should.equal 1
it 'rejects hits that are not visible to the public', ->
hits = [
{_score: 9, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: false}
]
@view.findValidResults(hits).length.should.equal 2
describe '#getNewLinkFromHits', ->
it 'returns a new link for artist type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'artist'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/artist/cat'>Cat</a>"
it 'returns a new link for partner type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'partner'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/cat'>Cat</a>"
it 'returns a new link for city type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'city'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/shows/cat'>Cat</a>"
| true | _ = require 'underscore'
benv = require 'benv'
sinon = require 'sinon'
Article = require '../../../../../models/article.coffee'
Channel = require '../../../../../models/channel'
Sections = require '../../../../../collections/sections'
Backbone = require 'backbone'
fixtures = require '../../../../../../test/helpers/fixtures'
rewire = require 'rewire'
{ resolve } = require 'path'
describe 'EditLayout', ->
beforeEach (done) ->
benv.setup =>
tmpl = resolve __dirname, '../index.jade'
sd = _.extend fixtures().locals.sd,
CURRENT_CHANNEL: fixtures().channels
USER: accessToken: 'foo'
FORCE_URL: 'https://artsy.net'
locals = _.extend fixtures().locals,
article: @article = new Article fixtures().articles
sd: sd
channel: new Channel
benv.render tmpl, locals, =>
benv.expose $: benv.require('jquery')
Backbone.$ = $
sinon.stub Backbone, 'sync'
@EditLayout = rewire '../index.coffee'
@EditLayout.__set__ 'YoastView', @YoastView = sinon.stub().returns onKeyup: @yoastKeyup = sinon.stub()
@EditLayout.__set__ 'sd', sd
sinon.stub _, 'debounce'
$.fn.autosize = sinon.stub()
_.debounce.callsArg 0
@view = new @EditLayout
el: $('#layout-content')
article: @article
@view.article.sync = sinon.stub()
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
_.debounce.restore()
describe '#getBodyText', ->
it 'parses the article and pulls out an html string of its text', ->
text = @view.getBodyText()
text.should.containEql '<p>Just before the lines'
text.should.containEql 'Check out this video art:</p>'
describe '#onYoastKeyup', ->
it 'returns if its not an artsy internal channel', ->
@view.channel.set 'type', 'partner'
@view.onYoastKeyup()
@yoastKeyup.callCount.should.equal 0
it 'calls onKeyup on the yoast view', ->
@view.channel.set 'type', 'team'
@view.onYoastKeyup()
@yoastKeyup.callCount.should.equal 1
describe '#setupYoast', ->
it 'initializes YoastView with args', ->
@YoastView.args[0][0].contentField.should.containEql 'Just before the lines start forming...'
@YoastView.args[0][0].contentField.should.containEql 'Check out this video art'
describe '#getLinkableText', ->
it 'returns an array of linkable text', ->
@view.article.sections = new Sections [
{
body: "<p>==PI:NAME:<NAME>END_PI== was ==brave==</p>"
type: "text"
},
{
body: "<p>==PI:NAME:<NAME>END_PI== was a ==pop== artist</p>"
type: "text"
}
]
linkableText = @view.getLinkableText()
linkableText.length.should.equal 4
describe '#autolinkText', ->
it 'creates links from search', ->
request =
get: sinon.stub().returns
set: sinon.stub().returns
end: @requestEnd = sinon.stub().yields(null, {
body:
total: 1
hits: [
{
_type: 'artist'
_score: 9,
_source:
visible_to_public: true
name: 'PI:NAME:<NAME>END_PI'
slug: 'cat'
},
]
})
@EditLayout.__set__ 'request', request
view = new @EditLayout
el: $('#layout-content')
article: @article
channel: new Channel
view.article.sections = new Sections [
{
body: "<p>==PI:NAME:<NAME>END_PI== was ==brave==</p>"
type: "text"
}
]
view.autolinkText()
view.article.sections.first().get('body').should.equal "<p><a href='https://artsy.net/artist/cat'>Cat</a> was <a href='https://artsy.net/artist/cat'>Cat</a></p>"
it 'removes delims if no good result is found', ->
request =
get: sinon.stub().returns
set: sinon.stub().returns
end: @requestEnd = sinon.stub().yields(null, {
body:
total: 0
})
@EditLayout.__set__ 'request', request
view = new @EditLayout
el: $('#layout-content')
article: @article
channel: new Channel
view.article.sections = new Sections [
{
body: "<p>==PI:NAME:<NAME>END_PI== was ==brave==</p>"
type: "text"
}
]
view.autolinkText()
view.article.sections.first().get('body').should.equal "<p>PI:NAME:<NAME>END_PI was brave</p>"
describe '#findValidResults', ->
it 'rejects scores less than 6.5', ->
hits = [
{_score: 1, _source: visible_to_public: true},
{_score: 2, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: true}
]
@view.findValidResults(hits).length.should.equal 1
it 'rejects hits that are not visible to the public', ->
hits = [
{_score: 9, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: true},
{_score: 9, _source: visible_to_public: false}
]
@view.findValidResults(hits).length.should.equal 2
describe '#getNewLinkFromHits', ->
it 'returns a new link for artist type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'artist'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/artist/cat'>Cat</a>"
it 'returns a new link for partner type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'partner'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/cat'>Cat</a>"
it 'returns a new link for city type', ->
results = [
_source:
name: 'Cat'
slug: 'cat'
_type: 'city'
]
@view.getNewLinkFromHits(results).should.equal "<a href='https://artsy.net/shows/cat'>Cat</a>"
|
[
{
"context": "ges': (test) ->\n message = \"<message from='thing@clayster.com/imc'\n to='discovery.clayster.com'\n ",
"end": 1308,
"score": 0.9973559975624084,
"start": 1290,
"tag": "EMAIL",
"value": "thing@clayster.com"
},
{
"context": " message = \"<iq type='... | test/processor.test.coffee | TNO-IoT/ekster | 3 | # Tests if the server component complies to
# https://xmpp.org/extensions/xep-0347.html
#
# Some test cases refer to paragraphs and / or examples from the spec.
{EventEmitter} = require 'events'
Processor = require '../src/processor.coffee'
Backend = require '../src/backend.coffee'
Thing = require '../src/thing.coffee'
Property = require '../src/property.coffee'
Q = require 'q'
_ = require 'lodash'
ltx = require('node-xmpp-core').ltx
class Connection extends EventEmitter
constructor: () ->
class TestBackend extends Backend
constructor: (@callback) ->
super 'test'
register: (thing) ->
return @callback('register', thing)
claim: (thing) ->
return @callback('claim', thing)
remove: (thing) ->
return @callback('remove', thing)
update: (thing) ->
return @callback('update', thing)
search: (properties, offset, maxCount) ->
return @callback('search', properties, offset, maxCount)
unregister: (thing) ->
return @callback('unregister', thing)
disown: (thing) ->
return @callback('disown', thing)
get: (thing) ->
return @callback('get', thing)
exports.ProcessorTest =
'test do not response to non-iq type messages': (test) ->
message = "<message from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
backend = new TestBackend
processor = new Processor connection, 'discovery.clayster.com', backend
connection.send = (stanza) ->
test.ok false, 'do not call this'
connection.emit 'stanza', ltx.parse(message)
test.done()
'test do not respond to result type messages': (test) ->
message = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='5'/>"
connection = new Connection
backend = new TestBackend
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
test.done()
'test respond with error when the message has no child elements': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with error when the iq message is not of type
get or set': (test) ->
message = "<iq type='blaat'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with error when the iq message has to many
children': (test) ->
message = "<iq type='get'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'>
<register/>
<register/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with service-unavailable when the iq message has an unknown
child': (test) ->
test.expect 12
message = "<iq type='get'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'><unknown fruit='banana'><bla/></unknown></iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 2
for child in stanza.children
if child.name is 'unknown'
test.equal child.children.length, 1
test.equal child.attrs.fruit, 'banana'
if child.name is 'error'
test.equal child.attrs.type, 'cancel'
test.equal child.children.length, 1
test.equal child.children[0].name, 'service-unavailable'
test.equal child.children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond to ping': (test) ->
test.expect 6
message = "<iq type='get'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'><ping xmlns='urn:xmpp:ping'/></iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 register a thing': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.properties.length, 5
for property in thing.properties
switch property.name
when 'SN'
test.equal property.type, 'string'
test.equal property.value, '394872348732948723'
when 'V'
test.equal property.type, 'number'
test.equal property.value, 1.2
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 register a self owned thing': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery' selfOwned='true'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.properties.length, 5
test.equal thing.owner, 'thing@clayster.com'
for property in thing.properties
switch property.name
when 'SN'
test.equal property.type, 'string'
test.equal property.value, '394872348732948723'
when 'V'
test.equal property.type, 'number'
test.equal property.value, 1.2
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
throw new Error('fails in this test case')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of illegal value': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<num name='V' value='banaan'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of unknown
property type': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<banana name='V' value='monkey'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of illegal namespace': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:bananas'>
<num name='V' value='1'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering thing that already has been claimed': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'owner@clayster.com'
test.expect 10
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
error = new Error('claimed')
error.owner = 'owner@clayster.com'
throw error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.8 register thing behind concentrator': (test) ->
message = "<iq type='set'
from='rack@clayster.com/plcs'
to='discovery.clayster.com'
id='3'>
<register xmlns='urn:xmpp:iot:discovery'
nodeId='imc1'
sourceId='MeteringTopology'
cacheType='test'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'rack@clayster.com/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '3'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'rack@clayster.com'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, 'test'
test.equal thing.properties.length, 5
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.8 register thing behind concentrator without cacheType': (test) ->
message = "<iq type='set'
from='rack@clayster.com/plcs'
to='discovery.clayster.com'
id='3'>
<register xmlns='urn:xmpp:iot:discovery'
nodeId='imc1'
sourceId='MeteringTopology'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'rack@clayster.com/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '3'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'rack@clayster.com'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, undefined
test.equal thing.properties.length, 5
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 15 and 20 - claim ownership of public thing': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'thing@clayster.com'
else
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'owner@clayster.com'
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='thing@clayster.com/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.needsNotification, true
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
return thing
else if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.expect 26
test.done()
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 16 and 20 - claim ownership of a private thing': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery' public='false'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'thing@clayster.com'
else
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'owner@clayster.com'
test.equal stanza.children[0].attrs.public, 'false'
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='thing@clayster.com/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.public, false
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
return thing
else if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
thing.public = false
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.equal thing.public, false
test.expect 28
test.done()
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 16 and 20 - claim ownership of a public thing (attrib)': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery' public='true'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'thing@clayster.com'
else
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'owner@clayster.com'
test.equal stanza.children[0].attrs.public, undefined
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='thing@clayster.com/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.public, true
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
return thing
else if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
thing.public = true
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.equal thing.public, true
test.expect 28
test.done()
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 18 and 22 - claim ownership of public thing behind
a concentrator': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid,
'thing@clayster.com'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal _.has(stanza.children[0].attrs, 'cacheType'), false
else
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'owner@clayster.com'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal _.has(stanza.children[0].attrs, 'cacheType'), false
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='thing@clayster.com/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return thing
else if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.owner = 'owner@clayster.com'
thing.needsNotification = true
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.expect 29
test.done()
return Q.fcall ->
thing.jid = 'thing@clayster.com'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because thing was already
claimed': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'claimed'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because thing was
not found': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'not-found'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because of
other reason': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='4857402340298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'banana'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 24 - removing a thing from the registry': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
else
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'removed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
getCalled = 0
backend = new TestBackend (method, thing) ->
if method is 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.owner, 'owner@clayster.com'
test.equal thing.removed, true
test.equal thing.needsNotification, true
return Q.fcall ->
return thing
else if method is 'get'
getCalled++
test.equal thing.jid, 'thing@clayster.com'
if getCalled is 2
test.expect 25
test.done()
return Q.fcall ->
thing.removed = true
thing.owner = 'owner@clayster.com'
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'remove'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.owner, 'owner@clayster.com'
test.equal thing.nodeId, undefined
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 25 - removing a thing behind a concentrator
from the registry': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery'
jid='rack@clayster.com'
nodeId='imc1'
sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
else
test.equal stanza.attrs.to, 'rack@clayster.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'removed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId,
'MeteringTopology'
test.equal _.has(stanza.children[0].attrs.cacheType), false
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'rack@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='rack@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
getCalled = 0
backend = new TestBackend (method, thing) ->
if method is 'update'
test.equal thing.jid, 'rack@clayster.com'
test.equal thing.owner, 'owner@clayster.com'
test.equal thing.removed, true
test.equal thing.needsNotification, true
return Q.fcall ->
return thing
else if method is 'get'
getCalled++
test.equal thing.jid, 'rack@clayster.com'
if getCalled is 2
test.expect 30
test.done()
return Q.fcall ->
thing.removed = true
thing.owner = 'owner@clayster.com'
thing.needsNotification = true
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return [ thing ]
else
test.equal method, 'remove'
test.equal thing.jid, 'rack@clayster.com'
test.equal thing.owner, 'owner@clayster.com'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, undefined
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 27 - removing a thing from the registry
fails': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
throw new Error 'not-found'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 27 - removing a thing from the registry
fails with general error': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
throw new Error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 33 - update meta data request': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.properties.length, 4
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 32 and 33 - update meta data request
behind a concentrator': (test) ->
message = "<iq type='set'
from='rack@clayster.com/plcs'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery' nodeId='imc1'
sourceId='MeteringTopology'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'rack@clayster.com/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 15
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'rack@clayster.com'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal _.has('cacheType'), false
test.equal thing.properties.length, 4
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 - update meta data request fails': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 34 - update meta data request fails': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 14
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error('not-found')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 35 - update meta data request fails
because of disowned Thing': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error('disowned')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 36 and 38 - update meta data request by the owner': (test) ->
message = "<iq type='set'
from='owner@clayster.com/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.properties.length, 4
test.equal thing.owner, 'owner@clayster.com'
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 36 - searching for Things [strEq & numEq]': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<strEq name='MAN' value='www.ktc.se'/>
<strEq name='MODEL' value='IMC'/>
<numEq name='V' value='1'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, false
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, 'owner@clayster.com'
test.equal thing.attrs.jid, 'thing@clayster.com'
test.equal thing.children.length, 3 # should not contain KEY
test.equal thing.attrs.nodeId, undefined
test.equal thing.attrs.sourceId, undefined
test.equal thing.attrs.cacheType, undefined
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 24
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 3
test.equal offset, 0
test.equal maxCount, 20
properties = []
properties.push new Property('string', 'KEY', 'doesnottellthis')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing 'thing@clayster.com', properties
found.owner = 'owner@clayster.com'
result = {
things: [ found ]
more: false
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 42 - searching for Things [strEq & numEq]': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='1' maxCount='10'>
<strEq name='MAN' value='www.ktc.se'/>
<strEq name='MODEL' value='IMC'/>
<numEq name='V' value='1'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, true
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, 'owner@clayster.com'
test.equal thing.attrs.jid, 'thing@clayster.com'
test.equal thing.attrs.nodeId, 'imc1'
test.equal thing.attrs.sourceId, 'MeteringTopology'
test.equal thing.attrs.cacheType, 'typedCache'
test.equal thing.children.length, 3 # should not contain KEY
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 24
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 3
test.equal offset, 1
test.equal maxCount, 10
properties = []
properties.push new Property('string', 'KEY', 'doesnottellthis')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing 'thing@clayster.com', properties
found.owner = 'owner@clayster.com'
found.nodeId = 'imc1'
found.sourceId = 'MeteringTopology'
found.cacheType = 'typedCache'
result = {
things: [ found ]
more: true
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 42 - searching for Things [strRange & strNRange & strMask
& numRange & numNRange]': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='1' maxCount='10'>
<strRange name='MAN' minIncluded='false' maxIncluded='false' min='A' max='B'/>
<strNRange name='MAN' min='A' max='B'/>
<strMask name='MAN' value='bla*' wildcard='*'/>
<numRange name='V' min='1' max='2'/>
<numNRange name='V' min='1' max='2'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, true
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, 'owner@clayster.com'
test.equal thing.attrs.jid, 'thing@clayster.com'
test.equal thing.attrs.nodeId, 'imc1'
test.equal thing.attrs.sourceId, 'MeteringTopology'
test.equal thing.attrs.cacheType, 'typedCache'
test.equal thing.children.length, 3 # should not contain KEY
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 44
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 5
test.equal offset, 1
test.equal maxCount, 10
for filter in filters
if filter.type is 'strRange'
test.equal filter.name, 'MAN'
test.equal filter.min, 'A'
test.equal filter.max, 'B'
test.equal filter.minIncluded, false
test.equal filter.maxIncluded, false
test.equal filter.value, undefined
if filter.type is 'strNRange'
test.equal filter.name, 'MAN'
test.equal filter.min, 'A'
test.equal filter.max, 'B'
test.equal filter.minIncluded, true
test.equal filter.maxIncluded, true
if filter.type is 'strMask'
test.equal filter.name, 'MAN'
test.equal filter.value, 'bla*'
test.equal filter.wildcard, '*'
if filter.type is 'numRange'
test.equal filter.name, 'V'
test.equal filter.min, '1'
test.equal filter.max, '2'
if filter.type is 'numNRange'
test.equal filter.name, 'V'
test.equal filter.min, '1'
test.equal filter.max, '2'
properties = []
properties.push new Property('string', 'KEY', 'doesnottellthis')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing 'thing@clayster.com', properties
found.owner = 'owner@clayster.com'
found.nodeId = 'imc1'
found.sourceId = 'MeteringTopology'
found.cacheType = 'typedCache'
result = {
things: [ found ]
more: true
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search for KEY': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<strEq name='KEY' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].children.length, 0
test.expect 9
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search with illegal offset': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='aap' maxCount='20'>
<strEq name='KEY' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search without offset': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' maxCount='20'>
<strEq name='KEY' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search without maxCount': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0'>
<strEq name='KEY' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search with illegal maxCount': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='aap'>
<strEq name='KEY' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search for unsupported filter type': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<notAFilter name='MAN' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name,
'feature-not-implemented'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 14
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 1
test.equal filters[0].type, 'notAFilter'
return Q.fcall ->
throw new Error 'feature-not-implemented'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 4 - example 60 - determine support': (test) ->
message = "<iq type='get'
from='device@clayster.com/device'
to='discovery.clayster.com'
id='16'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'device@clayster.com/device'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '16'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'query'
test.equal stanza.children[0].attrs.xmlns, 'http://jabber.org/protocol/disco#info'
test.equal stanza.children[0].children.length, 1
features = stanza.children[0].children
test.equal features[0].name, 'feature'
test.equal features[0].attrs.var, 'urn:xmpp:iot:discovery'
test.expect 10
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 43 - unregister thing': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 43 - unregister thing fails': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
return new Error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 44 - unregister thing behind a concentrator': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery' nodeId='imc1' sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 10
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 48 - disowning thing fails: item not found': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 1
error = stanza.children[0]
test.equal error.name, 'error'
test.equal error.attrs.type, 'cancel'
test.equal error.children.length, 1
test.equal error.children[0].name, 'item-not-found'
test.equal error.children[0].attrs.xmlns, 'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, 'thing@clayster.com'
return Q.fcall ->
return [ ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 48 - disowning thing fails: not the owner': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
# as the backend should not return items not owned
# by the owner this test case validates what happens
# if the backend is not implemented correctly and
# accidently returns an item that is not owned by
# the caller
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 0
test.expect 7
test.done()
else
test.equal true, false, 'should not call this'
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, 'thing@clayster.com'
result = new Thing thing.jid
result.owner = 'not the owner'
return Q.fcall ->
return [ result ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 49 - disowning thing fails: offline': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 1
error = stanza.children[0]
test.equal error.name, 'error'
test.equal error.attrs.type, 'cancel'
test.equal error.children.length, 1
test.equal error.children[0].name, 'not-allowed'
test.equal error.children[0].attrs.xmlns, 'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 17
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='123'
type='unavailable'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.owner, 'owner@clayster.com'
return Q.fcall ->
return [ thing ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing successful': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'result'
test.expect 26
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
properties = []
properties.push new Property('string', 'KEY', 'mysecret')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('number', 'V', 1)
thing.properties = properties
thing.owner = 'owner@clayster.com'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.owner, undefined
test.equal thing.properties.length, 4
for property in thing.properties
if property.name is 'KEY'
test.notEqual property.value, 'mysecret'
else
test.equal property.type, 'string', 'changed in string
so it can be removed from the registry'
test.equal property.value, ''
return Q.fcall ->
return [ thing ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing successfully
behind a concentrator': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery'
jid='thing@clayster.com'
nodeId='imcl'
sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.nodeId, 'imcl'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'result'
test.expect 21
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
properties = []
properties.push new Property('string', 'KEY', 'mysecret')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
thing.properties = properties
thing.owner = 'owner@clayster.com'
thing.nodeId = 'imcl'
thing.sourceId = 'MeteringTopology'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
test.equal thing.jid, 'thing@clayster.com'
test.equal thing.owner, undefined
test.equal thing.properties.length, 4
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing fails, unexpected response': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='error'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.expect 15
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
properties = []
properties.push new Property('string', 'KEY', 'mysecret')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
thing.properties = properties
thing.owner = 'owner@clayster.com'
return Q.fcall ->
return [ thing ]
else
test.equal true, false, 'should not update'
test.done()
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing fails because of backend': (test) ->
message = "<iq type='set'
from='owner@clayster.com/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='thing@clayster.com'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'owner@clayster.com/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.expect 16
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'thing@clayster.com'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'thing@clayster.com'
properties = []
properties.push new Property('string', 'KEY', 'mysecret')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('number', 'V', 1)
thing.properties = properties
thing.owner = 'owner@clayster.com'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
return Q.fcall ->
throw new Error()
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
# more test cases:
# - test offset and maxcount
# - test logging for unknown property type
| 197849 | # Tests if the server component complies to
# https://xmpp.org/extensions/xep-0347.html
#
# Some test cases refer to paragraphs and / or examples from the spec.
{EventEmitter} = require 'events'
Processor = require '../src/processor.coffee'
Backend = require '../src/backend.coffee'
Thing = require '../src/thing.coffee'
Property = require '../src/property.coffee'
Q = require 'q'
_ = require 'lodash'
ltx = require('node-xmpp-core').ltx
class Connection extends EventEmitter
constructor: () ->
class TestBackend extends Backend
constructor: (@callback) ->
super 'test'
register: (thing) ->
return @callback('register', thing)
claim: (thing) ->
return @callback('claim', thing)
remove: (thing) ->
return @callback('remove', thing)
update: (thing) ->
return @callback('update', thing)
search: (properties, offset, maxCount) ->
return @callback('search', properties, offset, maxCount)
unregister: (thing) ->
return @callback('unregister', thing)
disown: (thing) ->
return @callback('disown', thing)
get: (thing) ->
return @callback('get', thing)
exports.ProcessorTest =
'test do not response to non-iq type messages': (test) ->
message = "<message from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
backend = new TestBackend
processor = new Processor connection, 'discovery.clayster.com', backend
connection.send = (stanza) ->
test.ok false, 'do not call this'
connection.emit 'stanza', ltx.parse(message)
test.done()
'test do not respond to result type messages': (test) ->
message = "<iq type='result'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='5'/>"
connection = new Connection
backend = new TestBackend
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
test.done()
'test respond with error when the message has no child elements': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with error when the iq message is not of type
get or set': (test) ->
message = "<iq type='blaat'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with error when the iq message has to many
children': (test) ->
message = "<iq type='get'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'>
<register/>
<register/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with service-unavailable when the iq message has an unknown
child': (test) ->
test.expect 12
message = "<iq type='get'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'><unknown fruit='banana'><bla/></unknown></iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 2
for child in stanza.children
if child.name is 'unknown'
test.equal child.children.length, 1
test.equal child.attrs.fruit, 'banana'
if child.name is 'error'
test.equal child.attrs.type, 'cancel'
test.equal child.children.length, 1
test.equal child.children[0].name, 'service-unavailable'
test.equal child.children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond to ping': (test) ->
test.expect 6
message = "<iq type='get'
from='<EMAIL>/imc'
to='discovery.clay<EMAIL>'
id='1'><ping xmlns='urn:xmpp:ping'/></iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 register a thing': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, '<EMAIL>'
test.equal thing.properties.length, 5
for property in thing.properties
switch property.name
when 'SN'
test.equal property.type, 'string'
test.equal property.value, '394872348732948723'
when 'V'
test.equal property.type, 'number'
test.equal property.value, 1.2
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 register a self owned thing': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery' selfOwned='true'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, '<EMAIL>'
test.equal thing.properties.length, 5
test.equal thing.owner, '<EMAIL>'
for property in thing.properties
switch property.name
when 'SN'
test.equal property.type, 'string'
test.equal property.value, '394872348732948723'
when 'V'
test.equal property.type, 'number'
test.equal property.value, 1.2
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
throw new Error('fails in this test case')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of illegal value': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<num name='V' value='banaan'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of unknown
property type': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<banana name='V' value='monkey'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of illegal namespace': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:bananas'>
<num name='V' value='1'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering thing that already has been claimed': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
test.expect 10
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
error = new Error('claimed')
error.owner = '<EMAIL>'
throw error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.8 register thing behind concentrator': (test) ->
message = "<iq type='set'
from='<EMAIL>/plcs'
to='discovery.clayster.com'
id='3'>
<register xmlns='urn:xmpp:iot:discovery'
nodeId='imc1'
sourceId='MeteringTopology'
cacheType='test'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '3'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, '<EMAIL>'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, 'test'
test.equal thing.properties.length, 5
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.8 register thing behind concentrator without cacheType': (test) ->
message = "<iq type='set'
from='<EMAIL>/plcs'
to='discovery.clayster.com'
id='3'>
<register xmlns='urn:xmpp:iot:discovery'
nodeId='imc1'
sourceId='MeteringTopology'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '3'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, '<EMAIL>'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, undefined
test.equal thing.properties.length, 5
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 15 and 20 - claim ownership of public thing': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
else
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
response = "<iq type='result'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='<EMAIL>/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.needsNotification, true
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
return thing
else if method is 'get'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.expect 26
test.done()
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 16 and 20 - claim ownership of a private thing': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery' public='false'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>40298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
else
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
test.equal stanza.children[0].attrs.public, 'false'
response = "<iq type='result'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='<EMAIL>.com/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.public, false
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
return thing
else if method is 'get'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
thing.public = false
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.equal thing.public, false
test.expect 28
test.done()
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 16 and 20 - claim ownership of a public thing (attrib)': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery' public='true'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
else
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
test.equal stanza.children[0].attrs.public, undefined
response = "<iq type='result'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='<EMAIL>/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.public, true
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
return thing
else if method is 'get'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
thing.public = true
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.equal thing.public, true
test.expect 28
test.done()
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 18 and 22 - claim ownership of public thing behind
a concentrator': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid,
'<EMAIL>'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal _.has(stanza.children[0].attrs, 'cacheType'), false
else
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, '<EMAIL>'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal _.has(stanza.children[0].attrs, 'cacheType'), false
response = "<iq type='result'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='<EMAIL>/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return thing
else if method is 'get'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.owner = '<EMAIL>'
thing.needsNotification = true
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.expect 29
test.done()
return Q.fcall ->
thing.jid = '<EMAIL>'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because thing was already
claimed': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'claimed'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because thing was
not found': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'not-found'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because of
other reason': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='<KEY>'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'banana'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 24 - removing a thing from the registry': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
else
test.equal stanza.attrs.to, '<EMAIL>ster<EMAIL>.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'removed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
getCalled = 0
backend = new TestBackend (method, thing) ->
if method is 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.owner, '<EMAIL>'
test.equal thing.removed, true
test.equal thing.needsNotification, true
return Q.fcall ->
return thing
else if method is 'get'
getCalled++
test.equal thing.jid, '<EMAIL>'
if getCalled is 2
test.expect 25
test.done()
return Q.fcall ->
thing.removed = true
thing.owner = '<EMAIL>'
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'remove'
test.equal thing.jid, '<EMAIL>'
test.equal thing.owner, '<EMAIL>'
test.equal thing.nodeId, undefined
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 25 - removing a thing behind a concentrator
from the registry': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery'
jid='<EMAIL>'
nodeId='imc1'
sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
else
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'removed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId,
'MeteringTopology'
test.equal _.has(stanza.children[0].attrs.cacheType), false
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
getCalled = 0
backend = new TestBackend (method, thing) ->
if method is 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.owner, '<EMAIL>'
test.equal thing.removed, true
test.equal thing.needsNotification, true
return Q.fcall ->
return thing
else if method is 'get'
getCalled++
test.equal thing.jid, '<EMAIL>'
if getCalled is 2
test.expect 30
test.done()
return Q.fcall ->
thing.removed = true
thing.owner = '<EMAIL>'
thing.needsNotification = true
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return [ thing ]
else
test.equal method, 'remove'
test.equal thing.jid, '<EMAIL>'
test.equal thing.owner, '<EMAIL>'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, undefined
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 27 - removing a thing from the registry
fails': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
throw new Error 'not-found'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 27 - removing a thing from the registry
fails with general error': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
throw new Error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 33 - update meta data request': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.properties.length, 4
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 32 and 33 - update meta data request
behind a concentrator': (test) ->
message = "<iq type='set'
from='<EMAIL>/plcs'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery' nodeId='imc1'
sourceId='MeteringTopology'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 15
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal _.has('cacheType'), false
test.equal thing.properties.length, 4
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 - update meta data request fails': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 34 - update meta data request fails': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 14
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error('not-found')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 35 - update meta data request fails
because of disowned Thing': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error('disowned')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 36 and 38 - update meta data request by the owner': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.properties.length, 4
test.equal thing.owner, '<EMAIL>'
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 36 - searching for Things [strEq & numEq]': (test) ->
message = "<iq type='get'
from='<EMAIL>/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<strEq name='MAN' value='www.ktc.se'/>
<strEq name='MODEL' value='IMC'/>
<numEq name='V' value='1'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, false
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, '<EMAIL>'
test.equal thing.attrs.jid, '<EMAIL>'
test.equal thing.children.length, 3 # should not contain KEY
test.equal thing.attrs.nodeId, undefined
test.equal thing.attrs.sourceId, undefined
test.equal thing.attrs.cacheType, undefined
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 24
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 3
test.equal offset, 0
test.equal maxCount, 20
properties = []
properties.push new Property('string', 'KEY', '<KEY>')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing '<EMAIL>', properties
found.owner = '<EMAIL>'
result = {
things: [ found ]
more: false
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 42 - searching for Things [strEq & numEq]': (test) ->
message = "<iq type='get'
from='<EMAIL>/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='1' maxCount='10'>
<strEq name='MAN' value='www.ktc.se'/>
<strEq name='MODEL' value='IMC'/>
<numEq name='V' value='1'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, true
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, '<EMAIL>'
test.equal thing.attrs.jid, '<EMAIL>'
test.equal thing.attrs.nodeId, 'imc1'
test.equal thing.attrs.sourceId, 'MeteringTopology'
test.equal thing.attrs.cacheType, 'typedCache'
test.equal thing.children.length, 3 # should not contain KEY
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 24
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 3
test.equal offset, 1
test.equal maxCount, 10
properties = []
properties.push new Property('string', 'KEY', '<KEY>')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing '<EMAIL>', properties
found.owner = '<EMAIL>'
found.nodeId = 'imc1'
found.sourceId = 'MeteringTopology'
found.cacheType = 'typedCache'
result = {
things: [ found ]
more: true
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 42 - searching for Things [strRange & strNRange & strMask
& numRange & numNRange]': (test) ->
message = "<iq type='get'
from='<EMAIL>.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='1' maxCount='10'>
<strRange name='MAN' minIncluded='false' maxIncluded='false' min='A' max='B'/>
<strNRange name='MAN' min='A' max='B'/>
<strMask name='MAN' value='bla*' wildcard='*'/>
<numRange name='V' min='1' max='2'/>
<numNRange name='V' min='1' max='2'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>ay<EMAIL>.com/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, true
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, '<EMAIL>'
test.equal thing.attrs.jid, '<EMAIL>'
test.equal thing.attrs.nodeId, 'imc1'
test.equal thing.attrs.sourceId, 'MeteringTopology'
test.equal thing.attrs.cacheType, 'typedCache'
test.equal thing.children.length, 3 # should not contain KEY
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 44
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 5
test.equal offset, 1
test.equal maxCount, 10
for filter in filters
if filter.type is 'strRange'
test.equal filter.name, 'MAN'
test.equal filter.min, 'A'
test.equal filter.max, 'B'
test.equal filter.minIncluded, false
test.equal filter.maxIncluded, false
test.equal filter.value, undefined
if filter.type is 'strNRange'
test.equal filter.name, 'MAN'
test.equal filter.min, 'A'
test.equal filter.max, 'B'
test.equal filter.minIncluded, true
test.equal filter.maxIncluded, true
if filter.type is 'strMask'
test.equal filter.name, 'MAN'
test.equal filter.value, 'bla*'
test.equal filter.wildcard, '*'
if filter.type is 'numRange'
test.equal filter.name, 'V'
test.equal filter.min, '1'
test.equal filter.max, '2'
if filter.type is 'numNRange'
test.equal filter.name, 'V'
test.equal filter.min, '1'
test.equal filter.max, '2'
properties = []
properties.push new Property('string', 'KEY', 'doesnottellthis')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing '<EMAIL>', properties
found.owner = '<EMAIL>'
found.nodeId = 'imc1'
found.sourceId = 'MeteringTopology'
found.cacheType = 'typedCache'
result = {
things: [ found ]
more: true
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search for KEY': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<strEq name='KEY' value='<KEY>34'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].children.length, 0
test.expect 9
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search with illegal offset': (test) ->
message = "<iq type='get'
from='<EMAIL>/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='aap' maxCount='20'>
<strEq name='KEY' value='<KEY>'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search without offset': (test) ->
message = "<iq type='get'
from='<EMAIL>/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' maxCount='20'>
<strEq name='KEY' value='<KEY>'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search without maxCount': (test) ->
message = "<iq type='get'
from='<EMAIL>/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0'>
<strEq name='KEY' value='<KEY>'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search with illegal maxCount': (test) ->
message = "<iq type='get'
from='<EMAIL>.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='aap'>
<strEq name='KEY' value='<KEY>'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search for unsupported filter type': (test) ->
message = "<iq type='get'
from='<EMAIL>/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<notAFilter name='MAN' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious<EMAIL>@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name,
'feature-not-implemented'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 14
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 1
test.equal filters[0].type, 'notAFilter'
return Q.fcall ->
throw new Error 'feature-not-implemented'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 4 - example 60 - determine support': (test) ->
message = "<iq type='get'
from='device@clayster.com/device'
to='discovery.clayster.com'
id='16'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'device@clayster.com/device'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '16'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'query'
test.equal stanza.children[0].attrs.xmlns, 'http://jabber.org/protocol/disco#info'
test.equal stanza.children[0].children.length, 1
features = stanza.children[0].children
test.equal features[0].name, 'feature'
test.equal features[0].attrs.var, 'urn:xmpp:iot:discovery'
test.expect 10
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 43 - unregister thing': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 43 - unregister thing fails': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
return new Error
processor = new Processor connection, 'discovery.clayster.<EMAIL>', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 44 - unregister thing behind a concentrator': (test) ->
message = "<iq type='set'
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery' nodeId='imc1' sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, '<EMAIL>/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 10
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, '<EMAIL>'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 48 - disowning thing fails: item not found': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.from, 'discovery.clayster.<EMAIL>'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 1
error = stanza.children[0]
test.equal error.name, 'error'
test.equal error.attrs.type, 'cancel'
test.equal error.children.length, 1
test.equal error.children[0].name, 'item-not-found'
test.equal error.children[0].attrs.xmlns, 'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, '<EMAIL>'
return Q.fcall ->
return [ ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 48 - disowning thing fails: not the owner': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
# as the backend should not return items not owned
# by the owner this test case validates what happens
# if the backend is not implemented correctly and
# accidently returns an item that is not owned by
# the caller
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 0
test.expect 7
test.done()
else
test.equal true, false, 'should not call this'
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, '<EMAIL>'
result = new Thing thing.jid
result.owner = 'not the owner'
return Q.fcall ->
return [ result ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 49 - disowning thing fails: offline': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 1
error = stanza.children[0]
test.equal error.name, 'error'
test.equal error.attrs.type, 'cancel'
test.equal error.children.length, 1
test.equal error.children[0].name, 'not-allowed'
test.equal error.children[0].attrs.xmlns, 'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 17
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='123'
type='unavailable'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, '<EMAIL>'
test.equal thing.owner, '<EMAIL>'
return Q.fcall ->
return [ thing ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing successful': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'result'
test.expect 26
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, '<EMAIL>'
properties = []
properties.push new Property('string', 'KEY', '<KEY>')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('number', 'V', 1)
thing.properties = properties
thing.owner = '<EMAIL>'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.owner, undefined
test.equal thing.properties.length, 4
for property in thing.properties
if property.name is 'KEY'
test.notEqual property.value, 'mysecret'
else
test.equal property.type, 'string', 'changed in string
so it can be removed from the registry'
test.equal property.value, ''
return Q.fcall ->
return [ thing ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing successfully
behind a concentrator': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery'
jid='<EMAIL>'
nodeId='imcl'
sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is '<EMAIL>/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.nodeId, 'imcl'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'result'
test.expect 21
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, '<EMAIL>'
properties = []
properties.push new Property('string', 'KEY', '<KEY>')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
thing.properties = properties
thing.owner = '<EMAIL>'
thing.nodeId = 'imcl'
thing.sourceId = 'MeteringTopology'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
test.equal thing.jid, '<EMAIL>'
test.equal thing.owner, undefined
test.equal thing.properties.length, 4
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing fails, unexpected response': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is '<EMAIL>/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='error'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.expect 15
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, '<EMAIL>'
properties = []
properties.push new Property('string', 'KEY', '<KEY>')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
thing.properties = properties
thing.owner = '<EMAIL>'
return Q.fcall ->
return [ thing ]
else
test.equal true, false, 'should not update'
test.done()
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing fails because of backend': (test) ->
message = "<iq type='set'
from='<EMAIL>/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='<EMAIL>'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is '<EMAIL>/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, '<EMAIL>/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.expect 16
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, '<EMAIL>'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='<EMAIL>/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, '<EMAIL>'
properties = []
properties.push new Property('string', 'KEY', '<KEY>')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('number', 'V', 1)
thing.properties = properties
thing.owner = '<EMAIL>'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
return Q.fcall ->
throw new Error()
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
# more test cases:
# - test offset and maxcount
# - test logging for unknown property type
| true | # Tests if the server component complies to
# https://xmpp.org/extensions/xep-0347.html
#
# Some test cases refer to paragraphs and / or examples from the spec.
{EventEmitter} = require 'events'
Processor = require '../src/processor.coffee'
Backend = require '../src/backend.coffee'
Thing = require '../src/thing.coffee'
Property = require '../src/property.coffee'
Q = require 'q'
_ = require 'lodash'
ltx = require('node-xmpp-core').ltx
class Connection extends EventEmitter
constructor: () ->
class TestBackend extends Backend
constructor: (@callback) ->
super 'test'
register: (thing) ->
return @callback('register', thing)
claim: (thing) ->
return @callback('claim', thing)
remove: (thing) ->
return @callback('remove', thing)
update: (thing) ->
return @callback('update', thing)
search: (properties, offset, maxCount) ->
return @callback('search', properties, offset, maxCount)
unregister: (thing) ->
return @callback('unregister', thing)
disown: (thing) ->
return @callback('disown', thing)
get: (thing) ->
return @callback('get', thing)
exports.ProcessorTest =
'test do not response to non-iq type messages': (test) ->
message = "<message from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
backend = new TestBackend
processor = new Processor connection, 'discovery.clayster.com', backend
connection.send = (stanza) ->
test.ok false, 'do not call this'
connection.emit 'stanza', ltx.parse(message)
test.done()
'test do not respond to result type messages': (test) ->
message = "<iq type='result'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='5'/>"
connection = new Connection
backend = new TestBackend
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
test.done()
'test respond with error when the message has no child elements': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with error when the iq message is not of type
get or set': (test) ->
message = "<iq type='blaat'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'/>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with error when the iq message has to many
children': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'>
<register/>
<register/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond with service-unavailable when the iq message has an unknown
child': (test) ->
test.expect 12
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'><unknown fruit='banana'><bla/></unknown></iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 2
for child in stanza.children
if child.name is 'unknown'
test.equal child.children.length, 1
test.equal child.attrs.fruit, 'banana'
if child.name is 'error'
test.equal child.attrs.type, 'cancel'
test.equal child.children.length, 1
test.equal child.children[0].name, 'service-unavailable'
test.equal child.children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test respond to ping': (test) ->
test.expect 6
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayPI:EMAIL:<EMAIL>END_PI'
id='1'><ping xmlns='urn:xmpp:ping'/></iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 register a thing': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.properties.length, 5
for property in thing.properties
switch property.name
when 'SN'
test.equal property.type, 'string'
test.equal property.value, '394872348732948723'
when 'V'
test.equal property.type, 'number'
test.equal property.value, 1.2
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 register a self owned thing': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery' selfOwned='true'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.properties.length, 5
test.equal thing.owner, 'PI:EMAIL:<EMAIL>END_PI'
for property in thing.properties
switch property.name
when 'SN'
test.equal property.type, 'string'
test.equal property.value, '394872348732948723'
when 'V'
test.equal property.type, 'number'
test.equal property.value, 1.2
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
throw new Error('fails in this test case')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of illegal value': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<num name='V' value='banaan'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of unknown
property type': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:discovery'>
<banana name='V' value='monkey'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering a thing fails because of illegal namespace': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='2'>
<register xmlns='urn:xmpp:iot:bananas'>
<num name='V' value='1'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '2'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 5
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.6 registering thing that already has been claimed': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='1'>
<register xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '1'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.expect 10
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
error = new Error('claimed')
error.owner = 'PI:EMAIL:<EMAIL>END_PI'
throw error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.8 register thing behind concentrator': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/plcs'
to='discovery.clayster.com'
id='3'>
<register xmlns='urn:xmpp:iot:discovery'
nodeId='imc1'
sourceId='MeteringTopology'
cacheType='test'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '3'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, 'test'
test.equal thing.properties.length, 5
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.8 register thing behind concentrator without cacheType': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/plcs'
to='discovery.clayster.com'
id='3'>
<register xmlns='urn:xmpp:iot:discovery'
nodeId='imc1'
sourceId='MeteringTopology'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</register>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '3'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'register'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, undefined
test.equal thing.properties.length, 5
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 15 and 20 - claim ownership of public thing': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
response = "<iq type='result'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.needsNotification, true
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
return thing
else if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.expect 26
test.done()
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 16 and 20 - claim ownership of a private thing': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery' public='false'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI40298342'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.children[0].attrs.public, 'false'
response = "<iq type='result'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='PI:EMAIL:<EMAIL>END_PI.com/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.public, false
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
return thing
else if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.public = false
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.equal thing.public, false
test.expect 28
test.done()
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 16 and 20 - claim ownership of a public thing (attrib)': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery' public='true'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.name, 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.children[0].attrs.public, undefined
response = "<iq type='result'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
test.equal thing.public, true
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
return thing
else if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.public = true
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.equal thing.public, true
test.expect 28
test.done()
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - example 18 and 22 - claim ownership of public thing behind
a concentrator': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid,
'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal _.has(stanza.children[0].attrs, 'cacheType'), false
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'claimed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal _.has(stanza.children[0].attrs, 'cacheType'), false
response = "<iq type='result'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'probe'
presence = "<presence from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
type='available'/>"
connection.emit 'stanza', ltx.parse(presence)
backend = new TestBackend (method, thing) ->
if method is 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return thing
else if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = true
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return [ thing ]
else
test.equal method, 'update'
test.equal thing.needsNotification, false
test.expect 29
test.done()
return Q.fcall ->
thing.jid = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = undefined
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because thing was already
claimed': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'claimed'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because thing was
not found': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'not-found'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.9 - claim ownership of thing fails because of
other reason': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='4'>
<mine xmlns='urn:xmpp:iot:discovery'>
<str name='SN' value='394872348732948723'/>
<str name='MAN' value='www.ktc.se'/>
<str name='MODEL' value='IMC'/>
<num name='V' value='1.2'/>
<str name='KEY' value='PI:KEY:<KEY>END_PI'/>
</mine>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '4'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'claim'
test.equal thing.properties.length, 5
return Q.fcall ->
throw new Error 'banana'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 24 - removing a thing from the registry': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PIsterPI:EMAIL:<EMAIL>END_PI.com/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'removed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
getCalled = 0
backend = new TestBackend (method, thing) ->
if method is 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.owner, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.removed, true
test.equal thing.needsNotification, true
return Q.fcall ->
return thing
else if method is 'get'
getCalled++
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
if getCalled is 2
test.expect 25
test.done()
return Q.fcall ->
thing.removed = true
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = true
return [ thing ]
else
test.equal method, 'remove'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.owner, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.nodeId, undefined
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 25 - removing a thing behind a concentrator
from the registry': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery'
jid='PI:EMAIL:<EMAIL>END_PI'
nodeId='imc1'
sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.type is 'result'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'set'
test.equal _.has(stanza.attrs, 'id'), true
test.equal _.isString(stanza.attrs.id), true
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'removed'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.nodeId, 'imc1'
test.equal stanza.children[0].attrs.sourceId,
'MeteringTopology'
test.equal _.has(stanza.children[0].attrs.cacheType), false
response = "<iq type='result'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
getCalled = 0
backend = new TestBackend (method, thing) ->
if method is 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.owner, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.removed, true
test.equal thing.needsNotification, true
return Q.fcall ->
return thing
else if method is 'get'
getCalled++
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
if getCalled is 2
test.expect 30
test.done()
return Q.fcall ->
thing.removed = true
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.needsNotification = true
thing.nodeId = 'imc1'
thing.sourceId = 'MeteringTopology'
return [ thing ]
else
test.equal method, 'remove'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.owner, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal thing.cacheType, undefined
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 27 - removing a thing from the registry
fails': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
throw new Error 'not-found'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.10 - example 27 - removing a thing from the registry
fails with general error': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='6'>
<remove xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '6'
test.expect 7
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
throw new Error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 33 - update meta data request': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.properties.length, 4
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 32 and 33 - update meta data request
behind a concentrator': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/plcs'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery' nodeId='imc1'
sourceId='MeteringTopology'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/plcs'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 15
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
test.equal _.has('cacheType'), false
test.equal thing.properties.length, 4
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 - update meta data request fails': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI@clayster.com/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 34 - update meta data request fails': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name, 'item-not-found'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 14
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error('not-found')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 31 and 35 - update meta data request fails
because of disowned Thing': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns,
'urn:xmpp:iot:discovery'
test.expect 11
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.properties.length, 4
return Q.fcall ->
throw new Error('disowned')
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.13 - example 36 and 38 - update meta data request by the owner': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='8'>
<update xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'>
<str name='KEY' value=''/>
<str name='CLASS' value='PLC'/>
<num name='LON' value='-71.519722'/>
<num name='LAT' value='-33.008055'/>
</update>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '8'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.expect 13
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.properties.length, 4
test.equal thing.owner, 'PI:EMAIL:<EMAIL>END_PI'
for property in thing.properties
switch property.name
when 'KEY'
test.equal property.type, 'string'
test.equal property.value, ''
when 'LAT'
test.equal property.type, 'number'
test.equal property.value, -33.008055
return Q.fcall ->
return
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 36 - searching for Things [strEq & numEq]': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<strEq name='MAN' value='www.ktc.se'/>
<strEq name='MODEL' value='IMC'/>
<numEq name='V' value='1'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, false
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.children.length, 3 # should not contain KEY
test.equal thing.attrs.nodeId, undefined
test.equal thing.attrs.sourceId, undefined
test.equal thing.attrs.cacheType, undefined
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 24
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 3
test.equal offset, 0
test.equal maxCount, 20
properties = []
properties.push new Property('string', 'KEY', 'PI:KEY:<KEY>END_PI')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing 'PI:EMAIL:<EMAIL>END_PI', properties
found.owner = 'PI:EMAIL:<EMAIL>END_PI'
result = {
things: [ found ]
more: false
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 42 - searching for Things [strEq & numEq]': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='1' maxCount='10'>
<strEq name='MAN' value='www.ktc.se'/>
<strEq name='MODEL' value='IMC'/>
<numEq name='V' value='1'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, true
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.attrs.nodeId, 'imc1'
test.equal thing.attrs.sourceId, 'MeteringTopology'
test.equal thing.attrs.cacheType, 'typedCache'
test.equal thing.children.length, 3 # should not contain KEY
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 24
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 3
test.equal offset, 1
test.equal maxCount, 10
properties = []
properties.push new Property('string', 'KEY', 'PI:PASSWORD:<KEY>END_PI')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing 'PI:EMAIL:<EMAIL>END_PI', properties
found.owner = 'PI:EMAIL:<EMAIL>END_PI'
found.nodeId = 'imc1'
found.sourceId = 'MeteringTopology'
found.cacheType = 'typedCache'
result = {
things: [ found ]
more: true
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - example 42 - searching for Things [strRange & strNRange & strMask
& numRange & numNRange]': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='1' maxCount='10'>
<strRange name='MAN' minIncluded='false' maxIncluded='false' min='A' max='B'/>
<strNRange name='MAN' min='A' max='B'/>
<strMask name='MAN' value='bla*' wildcard='*'/>
<numRange name='V' min='1' max='2'/>
<numNRange name='V' min='1' max='2'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PIayPI:EMAIL:<EMAIL>END_PI.com/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].attrs.more, true
test.equal stanza.children[0].children.length, 1
thing = stanza.children[0].children[0]
test.equal thing.name, 'thing'
test.equal thing.attrs.owner, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.attrs.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.attrs.nodeId, 'imc1'
test.equal thing.attrs.sourceId, 'MeteringTopology'
test.equal thing.attrs.cacheType, 'typedCache'
test.equal thing.children.length, 3 # should not contain KEY
for child in thing.children
test.equal child.attrs.name is 'KEY', false
test.expect 44
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 5
test.equal offset, 1
test.equal maxCount, 10
for filter in filters
if filter.type is 'strRange'
test.equal filter.name, 'MAN'
test.equal filter.min, 'A'
test.equal filter.max, 'B'
test.equal filter.minIncluded, false
test.equal filter.maxIncluded, false
test.equal filter.value, undefined
if filter.type is 'strNRange'
test.equal filter.name, 'MAN'
test.equal filter.min, 'A'
test.equal filter.max, 'B'
test.equal filter.minIncluded, true
test.equal filter.maxIncluded, true
if filter.type is 'strMask'
test.equal filter.name, 'MAN'
test.equal filter.value, 'bla*'
test.equal filter.wildcard, '*'
if filter.type is 'numRange'
test.equal filter.name, 'V'
test.equal filter.min, '1'
test.equal filter.max, '2'
if filter.type is 'numNRange'
test.equal filter.name, 'V'
test.equal filter.min, '1'
test.equal filter.max, '2'
properties = []
properties.push new Property('string', 'KEY', 'doesnottellthis')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
found = new Thing 'PI:EMAIL:<EMAIL>END_PI', properties
found.owner = 'PI:EMAIL:<EMAIL>END_PI'
found.nodeId = 'imc1'
found.sourceId = 'MeteringTopology'
found.cacheType = 'typedCache'
result = {
things: [ found ]
more: true
}
return Q.fcall ->
return result
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search for KEY': (test) ->
message = "<iq type='get'
from='curious@clayster.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<strEq name='KEY' value='PI:KEY:<KEY>END_PI34'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/client'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'found'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
test.equal stanza.children[0].children.length, 0
test.expect 9
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search with illegal offset': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='aap' maxCount='20'>
<strEq name='KEY' value='PI:KEY:<KEY>END_PI'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search without offset': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' maxCount='20'>
<strEq name='KEY' value='PI:KEY:<KEY>END_PI'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search without maxCount': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0'>
<strEq name='KEY' value='PI:KEY:<KEY>END_PI'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curious@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search with illegal maxCount': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI.com/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='aap'>
<strEq name='KEY' value='PI:KEY:<KEY>END_PI'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 0
test.expect 6
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.14 - cannot search for unsupported filter type': (test) ->
message = "<iq type='get'
from='PI:EMAIL:<EMAIL>END_PI/client'
to='discovery.clayster.com'
id='9'>
<search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'>
<notAFilter name='MAN' value='1234'/>
</search>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'curiousPI:EMAIL:<EMAIL>END_PI@clayster.com/client'
test.equal stanza.attrs.type, 'error'
test.equal stanza.attrs.id, '9'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'error'
test.equal stanza.children[0].attrs.type, 'cancel'
test.equal stanza.children[0].children.length, 1
test.equal stanza.children[0].children[0].name,
'feature-not-implemented'
test.equal stanza.children[0].children[0].attrs.xmlns,
'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 14
test.done()
backend = new TestBackend (method, filters, offset, maxCount) ->
test.equal method, 'search'
test.equal filters.length, 1
test.equal filters[0].type, 'notAFilter'
return Q.fcall ->
throw new Error 'feature-not-implemented'
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 4 - example 60 - determine support': (test) ->
message = "<iq type='get'
from='device@clayster.com/device'
to='discovery.clayster.com'
id='16'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'device@clayster.com/device'
test.equal stanza.attrs.type, 'result'
test.equal stanza.attrs.id, '16'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'query'
test.equal stanza.children[0].attrs.xmlns, 'http://jabber.org/protocol/disco#info'
test.equal stanza.children[0].children.length, 1
features = stanza.children[0].children
test.equal features[0].name, 'feature'
test.equal features[0].attrs.var, 'urn:xmpp:iot:discovery'
test.expect 10
test.done()
processor = new Processor connection, 'discovery.clayster.com'
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 43 - unregister thing': (test) ->
message = "<iq type='set'
from='thing@clayster.com/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 43 - unregister thing fails': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 8
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
return new Error
processor = new Processor connection, 'discovery.clayster.PI:EMAIL:<EMAIL>END_PI', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.16 - example 44 - unregister thing behind a concentrator': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='10'>
<unregister xmlns='urn:xmpp:iot:discovery' nodeId='imc1' sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
test.equal stanza.name, 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '10'
test.equal stanza.attrs.type, 'result'
test.equal stanza.children.length, 0
test.expect 10
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'unregister'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.nodeId, 'imc1'
test.equal thing.sourceId, 'MeteringTopology'
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 48 - disowning thing fails: item not found': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.from, 'discovery.clayster.PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 1
error = stanza.children[0]
test.equal error.name, 'error'
test.equal error.attrs.type, 'cancel'
test.equal error.children.length, 1
test.equal error.children[0].name, 'item-not-found'
test.equal error.children[0].attrs.xmlns, 'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 12
test.done()
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
return [ ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 48 - disowning thing fails: not the owner': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
# as the backend should not return items not owned
# by the owner this test case validates what happens
# if the backend is not implemented correctly and
# accidently returns an item that is not owned by
# the caller
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 0
test.expect 7
test.done()
else
test.equal true, false, 'should not call this'
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
result = new Thing thing.jid
result.owner = 'not the owner'
return Q.fcall ->
return [ result ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 49 - disowning thing fails: offline': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.equal stanza.children.length, 1
error = stanza.children[0]
test.equal error.name, 'error'
test.equal error.attrs.type, 'cancel'
test.equal error.children.length, 1
test.equal error.children[0].name, 'not-allowed'
test.equal error.children[0].attrs.xmlns, 'urn:ietf:params:xml:ns:xmpp-stanzas'
test.expect 17
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='123'
type='unavailable'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
test.equal method, 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.owner, 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
return [ thing ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing successful': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'thing@clayster.com/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'result'
test.expect 26
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
properties = []
properties.push new Property('string', 'KEY', 'PI:KEY:<KEY>END_PI')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('number', 'V', 1)
thing.properties = properties
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.owner, undefined
test.equal thing.properties.length, 4
for property in thing.properties
if property.name is 'KEY'
test.notEqual property.value, 'mysecret'
else
test.equal property.type, 'string', 'changed in string
so it can be removed from the registry'
test.equal property.value, ''
return Q.fcall ->
return [ thing ]
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing successfully
behind a concentrator': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery'
jid='PI:EMAIL:<EMAIL>END_PI'
nodeId='imcl'
sourceId='MeteringTopology'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.nodeId, 'imcl'
test.equal stanza.children[0].attrs.sourceId, 'MeteringTopology'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'result'
test.expect 21
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
properties = []
properties.push new Property('string', 'KEY', 'PI:KEY:<KEY>END_PI')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
thing.properties = properties
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
thing.nodeId = 'imcl'
thing.sourceId = 'MeteringTopology'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
test.equal thing.owner, undefined
test.equal thing.properties.length, 4
return Q.fcall ->
return thing
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing fails, unexpected response': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='error'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.expect 15
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
properties = []
properties.push new Property('string', 'KEY', 'PI:KEY:<KEY>END_PI')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('string', 'V', 1)
thing.properties = properties
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
return [ thing ]
else
test.equal true, false, 'should not update'
test.done()
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
'test 3.17 - example 46 / 50 / 52 / 53 - disowning thing fails because of backend': (test) ->
message = "<iq type='set'
from='PI:EMAIL:<EMAIL>END_PI/phone'
to='discovery.clayster.com'
id='11'>
<disown xmlns='urn:xmpp:iot:discovery' jid='PI:EMAIL:<EMAIL>END_PI'/>
</iq>"
connection = new Connection
connection.send = (stanza) ->
if stanza.name is 'iq'
if stanza.attrs.to is 'PI:EMAIL:<EMAIL>END_PI/imc'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.type, 'set'
test.equal stanza.children.length, 1
test.equal stanza.children[0].name, 'disowned'
test.equal stanza.children[0].attrs.xmlns, 'urn:xmpp:iot:discovery'
response = "<iq type='result'
from='discovery.clayster.com',
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'/>"
connection.emit 'stanza', ltx.parse(response)
else
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI/phone'
test.equal stanza.attrs.from, 'discovery.clayster.com'
test.equal stanza.attrs.id, '11'
test.equal stanza.attrs.type, 'error'
test.expect 16
test.done()
else
test.equal stanza.name, 'presence'
test.equal stanza.attrs.type, 'probe'
test.equal stanza.attrs.to, 'PI:EMAIL:<EMAIL>END_PI'
test.equal stanza.attrs.from, 'discovery.clayster.com'
response = "<presence
from='PI:EMAIL:<EMAIL>END_PI/imc'
to='discovery.clayster.com'
id='#{ stanza.attrs.id }'
type='available'/>"
connection.emit 'stanza', ltx.parse(response)
backend = new TestBackend (method, thing) ->
if method is 'get'
test.equal thing.jid, 'PI:EMAIL:<EMAIL>END_PI'
properties = []
properties.push new Property('string', 'KEY', 'PI:KEY:<KEY>END_PI')
properties.push new Property('string', 'MAN', 'www.ktc.se')
properties.push new Property('string', 'MODEL', 'IMC')
properties.push new Property('number', 'V', 1)
thing.properties = properties
thing.owner = 'PI:EMAIL:<EMAIL>END_PI'
return Q.fcall ->
return [ thing ]
else
test.equal method, 'update'
return Q.fcall ->
throw new Error()
processor = new Processor connection, 'discovery.clayster.com', backend
connection.emit 'stanza', ltx.parse(message)
# more test cases:
# - test offset and maxcount
# - test logging for unknown property type
|
[
{
"context": "rm'\nFIELD_MAIL = 'mail'\nFIELD_PASS = 'pass[pass1]'\nFIELD_PASS_2 = 'pass[pass2]'\nFIELD_FIRST_NAME",
"end": 221,
"score": 0.8907308578491211,
"start": 211,
"tag": "PASSWORD",
"value": "pass[pass1"
},
{
"context": "LD_PASS = 'pass[pass1]'\nFIELD_P... | tests/integration/uk/sso.coffee | jonuy/dosomething | 1 | # SSO
# Sometimes SSO server response takes long.
casper.options.waitTimeout = 10000
# Constants.
AGE_TOO_OLD = 25
# Form selectors.
FORM = '#user-register-form'
FIELD_MAIL = 'mail'
FIELD_PASS = 'pass[pass1]'
FIELD_PASS_2 = 'pass[pass2]'
FIELD_FIRST_NAME = 'field_first_name[und][0][value]'
FIELD_LAST_NAME = 'field_last_name[und][0][value]'
FIELD_BIRTHDATE = 'field_birthdate[und][0][value][date]'
FIELD_POSTCODE = 'field_address[und][0][postal_code]'
FIELD_PHONE = 'field_mobile[und][0][value]'
USER_COUNTRY = 'GB'
# Generate user.
user = casper.getRandomUser()
uid = false
# ------------------------------------------------------------------------
# Test registration form
casper.test.begin "Test the registration form", 3, (test) ->
# Launch browser on registration page.
casper.start "#{url}/user/register"
# Wait for user to be loaded.
casper.waitFor userIsLoaded = -> !!user.username
# Ensure registration form.
casper.then -> test.assertExists FORM, 'Registration form found.'
# Check remote validation by providing user with date out of range.
casper.then -> growOld user; fillSignupForm user
casper.thenClick '#edit-submit'
# Ensure error message is generated.
casper.waitForSelector '.error', ->
test.assertSelectorHasText '.error',
"You're too old for us now",
'SSO validates data remotely, user can see validation error messages.'
return
# Submit valid registration form.
casper.then -> rejuvenate user; fillSignupForm user
casper.thenClick '#edit-submit'
# Check whether the registration is successful.
assert_message = 'User is registered can see own profile.'
casper.waitForUrl /\/user\/[0-9]+\/edit$/,
-> test.assertExists '.status', assert_message # Success
-> # Fail
@echo 'Registration form errors:', 'ERROR'
@echo @fetchText('.error').trim(), 'WARNING'
test.assert false, assert_message
# Run tests.
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test the user created
casper.test.begin "Test the registered user", 7, (test) ->
casper.start url
login test
user_profile test
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test user created from new login
casper.test.begin "Test the user created from new login", 7, (test) ->
# Test the nid is present so we can remove it.
test.assertTruthy uid, "User id from the signup test found."
casper.start url
casper.then ->
# Delete user account.
@logAction "Remove the user to test login using remote account only:"
@deleteUser uid
# Reset phone number since API doesn't expose it.
delete user.phone
# Check user profile.
login test
user_profile test
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test login form
casper.test.begin "Test that the user created can login again", 1, (test) ->
casper.start url
login test
casper.then -> @logAction "Cleanup:"; @deleteUser uid
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Utilities
fillSignupForm = (user) ->
# Override generated postcode with British.
user.postcode = "CF10 5AN"
# Hardcode vInspired contact phone number for testing purposes.
user.phone = "02079 607 000"
# Prepare user data.
data = {}
data[FIELD_MAIL] = user.email
data[FIELD_PASS] = user.password
data[FIELD_PASS_2] = user.password
data[FIELD_FIRST_NAME] = user.first_name
data[FIELD_LAST_NAME] = user.last_name
data[FIELD_BIRTHDATE] = user.dob.format "DD/MM/YYYY"
data[FIELD_POSTCODE] = user.postcode
data[FIELD_PHONE] = user.phone
# Fill in the registration form.
casper.fill FORM, data
return
# Sets user's birthrate within validation range.
rejuvenate = (user) ->
user.dob.year moment().subtract(AGE_TOO_OLD - 5, 'years').year()
# Sets user birthrate greater than SSO accepts.
growOld = (user) ->
user.dob.year moment().subtract(AGE_TOO_OLD + 10, 'years').year()
# Finds user uid on the profile edit page ans saves it to global variable.
saveUserUid = ->
uid = casper.getCurrentUrl().match(/\/user\/([0-9]+)\/edit$/)[1]
# Fills and submits the login form.
login = (test) ->
# Login user.
casper.then -> @login user.email, user.password
# Ensure user has landed on its profile page.
casper.then ->
test.assertSelectorHasText "h1.__title", "Hey, #{user.first_name}",
"Test if user is logged in."
return
return
# Performs 5 or 6 (depends on the phone number) tests to check user's profile.
user_profile = (test) ->
# Test user's profile.
# Go to the edit profile page.
# We don't know new uid yet, but user/register will redirect to the page.
casper.thenOpen "#{url}/user/register"
# Ensure user data is consistent with the original one.
casper.then ->
test.assertField FIELD_FIRST_NAME, user.first_name,
"Test if user has correct first name."
test.assertField FIELD_LAST_NAME, user.last_name,
"Test if user has correct last name."
test.assertField FIELD_BIRTHDATE, user.dob.format("DD/MM/YYYY"),
"Test if user has correct birthdate."
test.assertField FIELD_POSTCODE, user.postcode,
"Test if user has correct postcode."
if user.phone?
test.assertField FIELD_PHONE, user.phone,
"Test if user has correct phone number."
test.assertExists "div.addressfield-container-inline.country-#{USER_COUNTRY}",
"Test if user has correct country."
saveUserUid()
return
return
# ------------------------------------------------------------------------
| 50512 | # SSO
# Sometimes SSO server response takes long.
casper.options.waitTimeout = 10000
# Constants.
AGE_TOO_OLD = 25
# Form selectors.
FORM = '#user-register-form'
FIELD_MAIL = 'mail'
FIELD_PASS = '<PASSWORD>]'
FIELD_PASS_2 = '<PASSWORD>[<PASSWORD>]'
FIELD_FIRST_NAME = 'field_first_name[und][0][value]'
FIELD_LAST_NAME = 'field_last_name[und][0][value]'
FIELD_BIRTHDATE = 'field_birthdate[und][0][value][date]'
FIELD_POSTCODE = 'field_address[und][0][postal_code]'
FIELD_PHONE = 'field_mobile[und][0][value]'
USER_COUNTRY = 'GB'
# Generate user.
user = casper.getRandomUser()
uid = false
# ------------------------------------------------------------------------
# Test registration form
casper.test.begin "Test the registration form", 3, (test) ->
# Launch browser on registration page.
casper.start "#{url}/user/register"
# Wait for user to be loaded.
casper.waitFor userIsLoaded = -> !!user.username
# Ensure registration form.
casper.then -> test.assertExists FORM, 'Registration form found.'
# Check remote validation by providing user with date out of range.
casper.then -> growOld user; fillSignupForm user
casper.thenClick '#edit-submit'
# Ensure error message is generated.
casper.waitForSelector '.error', ->
test.assertSelectorHasText '.error',
"You're too old for us now",
'SSO validates data remotely, user can see validation error messages.'
return
# Submit valid registration form.
casper.then -> rejuvenate user; fillSignupForm user
casper.thenClick '#edit-submit'
# Check whether the registration is successful.
assert_message = 'User is registered can see own profile.'
casper.waitForUrl /\/user\/[0-9]+\/edit$/,
-> test.assertExists '.status', assert_message # Success
-> # Fail
@echo 'Registration form errors:', 'ERROR'
@echo @fetchText('.error').trim(), 'WARNING'
test.assert false, assert_message
# Run tests.
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test the user created
casper.test.begin "Test the registered user", 7, (test) ->
casper.start url
login test
user_profile test
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test user created from new login
casper.test.begin "Test the user created from new login", 7, (test) ->
# Test the nid is present so we can remove it.
test.assertTruthy uid, "User id from the signup test found."
casper.start url
casper.then ->
# Delete user account.
@logAction "Remove the user to test login using remote account only:"
@deleteUser uid
# Reset phone number since API doesn't expose it.
delete user.phone
# Check user profile.
login test
user_profile test
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test login form
casper.test.begin "Test that the user created can login again", 1, (test) ->
casper.start url
login test
casper.then -> @logAction "Cleanup:"; @deleteUser uid
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Utilities
fillSignupForm = (user) ->
# Override generated postcode with British.
user.postcode = "CF10 5AN"
# Hardcode vInspired contact phone number for testing purposes.
user.phone = "02079 607 000"
# Prepare user data.
data = {}
data[FIELD_MAIL] = user.email
data[FIELD_PASS] = user.password
data[FIELD_PASS_2] = user.password
data[FIELD_FIRST_NAME] = user.first_name
data[FIELD_LAST_NAME] = user.last_name
data[FIELD_BIRTHDATE] = user.dob.format "DD/MM/YYYY"
data[FIELD_POSTCODE] = user.postcode
data[FIELD_PHONE] = user.phone
# Fill in the registration form.
casper.fill FORM, data
return
# Sets user's birthrate within validation range.
rejuvenate = (user) ->
user.dob.year moment().subtract(AGE_TOO_OLD - 5, 'years').year()
# Sets user birthrate greater than SSO accepts.
growOld = (user) ->
user.dob.year moment().subtract(AGE_TOO_OLD + 10, 'years').year()
# Finds user uid on the profile edit page ans saves it to global variable.
saveUserUid = ->
uid = casper.getCurrentUrl().match(/\/user\/([0-9]+)\/edit$/)[1]
# Fills and submits the login form.
login = (test) ->
# Login user.
casper.then -> @login user.email, user.password
# Ensure user has landed on its profile page.
casper.then ->
test.assertSelectorHasText "h1.__title", "Hey, #{user.first_name}",
"Test if user is logged in."
return
return
# Performs 5 or 6 (depends on the phone number) tests to check user's profile.
user_profile = (test) ->
# Test user's profile.
# Go to the edit profile page.
# We don't know new uid yet, but user/register will redirect to the page.
casper.thenOpen "#{url}/user/register"
# Ensure user data is consistent with the original one.
casper.then ->
test.assertField FIELD_FIRST_NAME, user.first_name,
"Test if user has correct first name."
test.assertField FIELD_LAST_NAME, user.last_name,
"Test if user has correct last name."
test.assertField FIELD_BIRTHDATE, user.dob.format("DD/MM/YYYY"),
"Test if user has correct birthdate."
test.assertField FIELD_POSTCODE, user.postcode,
"Test if user has correct postcode."
if user.phone?
test.assertField FIELD_PHONE, user.phone,
"Test if user has correct phone number."
test.assertExists "div.addressfield-container-inline.country-#{USER_COUNTRY}",
"Test if user has correct country."
saveUserUid()
return
return
# ------------------------------------------------------------------------
| true | # SSO
# Sometimes SSO server response takes long.
casper.options.waitTimeout = 10000
# Constants.
AGE_TOO_OLD = 25
# Form selectors.
FORM = '#user-register-form'
FIELD_MAIL = 'mail'
FIELD_PASS = 'PI:PASSWORD:<PASSWORD>END_PI]'
FIELD_PASS_2 = 'PI:PASSWORD:<PASSWORD>END_PI[PI:PASSWORD:<PASSWORD>END_PI]'
FIELD_FIRST_NAME = 'field_first_name[und][0][value]'
FIELD_LAST_NAME = 'field_last_name[und][0][value]'
FIELD_BIRTHDATE = 'field_birthdate[und][0][value][date]'
FIELD_POSTCODE = 'field_address[und][0][postal_code]'
FIELD_PHONE = 'field_mobile[und][0][value]'
USER_COUNTRY = 'GB'
# Generate user.
user = casper.getRandomUser()
uid = false
# ------------------------------------------------------------------------
# Test registration form
casper.test.begin "Test the registration form", 3, (test) ->
# Launch browser on registration page.
casper.start "#{url}/user/register"
# Wait for user to be loaded.
casper.waitFor userIsLoaded = -> !!user.username
# Ensure registration form.
casper.then -> test.assertExists FORM, 'Registration form found.'
# Check remote validation by providing user with date out of range.
casper.then -> growOld user; fillSignupForm user
casper.thenClick '#edit-submit'
# Ensure error message is generated.
casper.waitForSelector '.error', ->
test.assertSelectorHasText '.error',
"You're too old for us now",
'SSO validates data remotely, user can see validation error messages.'
return
# Submit valid registration form.
casper.then -> rejuvenate user; fillSignupForm user
casper.thenClick '#edit-submit'
# Check whether the registration is successful.
assert_message = 'User is registered can see own profile.'
casper.waitForUrl /\/user\/[0-9]+\/edit$/,
-> test.assertExists '.status', assert_message # Success
-> # Fail
@echo 'Registration form errors:', 'ERROR'
@echo @fetchText('.error').trim(), 'WARNING'
test.assert false, assert_message
# Run tests.
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test the user created
casper.test.begin "Test the registered user", 7, (test) ->
casper.start url
login test
user_profile test
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test user created from new login
casper.test.begin "Test the user created from new login", 7, (test) ->
# Test the nid is present so we can remove it.
test.assertTruthy uid, "User id from the signup test found."
casper.start url
casper.then ->
# Delete user account.
@logAction "Remove the user to test login using remote account only:"
@deleteUser uid
# Reset phone number since API doesn't expose it.
delete user.phone
# Check user profile.
login test
user_profile test
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Test login form
casper.test.begin "Test that the user created can login again", 1, (test) ->
casper.start url
login test
casper.then -> @logAction "Cleanup:"; @deleteUser uid
casper.run -> @test.done()
return
# ------------------------------------------------------------------------
# Utilities
fillSignupForm = (user) ->
# Override generated postcode with British.
user.postcode = "CF10 5AN"
# Hardcode vInspired contact phone number for testing purposes.
user.phone = "02079 607 000"
# Prepare user data.
data = {}
data[FIELD_MAIL] = user.email
data[FIELD_PASS] = user.password
data[FIELD_PASS_2] = user.password
data[FIELD_FIRST_NAME] = user.first_name
data[FIELD_LAST_NAME] = user.last_name
data[FIELD_BIRTHDATE] = user.dob.format "DD/MM/YYYY"
data[FIELD_POSTCODE] = user.postcode
data[FIELD_PHONE] = user.phone
# Fill in the registration form.
casper.fill FORM, data
return
# Sets user's birthrate within validation range.
rejuvenate = (user) ->
user.dob.year moment().subtract(AGE_TOO_OLD - 5, 'years').year()
# Sets user birthrate greater than SSO accepts.
growOld = (user) ->
user.dob.year moment().subtract(AGE_TOO_OLD + 10, 'years').year()
# Finds user uid on the profile edit page ans saves it to global variable.
saveUserUid = ->
uid = casper.getCurrentUrl().match(/\/user\/([0-9]+)\/edit$/)[1]
# Fills and submits the login form.
login = (test) ->
# Login user.
casper.then -> @login user.email, user.password
# Ensure user has landed on its profile page.
casper.then ->
test.assertSelectorHasText "h1.__title", "Hey, #{user.first_name}",
"Test if user is logged in."
return
return
# Performs 5 or 6 (depends on the phone number) tests to check user's profile.
user_profile = (test) ->
# Test user's profile.
# Go to the edit profile page.
# We don't know new uid yet, but user/register will redirect to the page.
casper.thenOpen "#{url}/user/register"
# Ensure user data is consistent with the original one.
casper.then ->
test.assertField FIELD_FIRST_NAME, user.first_name,
"Test if user has correct first name."
test.assertField FIELD_LAST_NAME, user.last_name,
"Test if user has correct last name."
test.assertField FIELD_BIRTHDATE, user.dob.format("DD/MM/YYYY"),
"Test if user has correct birthdate."
test.assertField FIELD_POSTCODE, user.postcode,
"Test if user has correct postcode."
if user.phone?
test.assertField FIELD_PHONE, user.phone,
"Test if user has correct phone number."
test.assertExists "div.addressfield-container-inline.country-#{USER_COUNTRY}",
"Test if user has correct country."
saveUserUid()
return
return
# ------------------------------------------------------------------------
|
[
{
"context": "nt = 0\n\nmakeSelection = ->\n\n Account.one email: 'user123@koding.me', (err, account)->\n throw err if err\n \n ",
"end": 227,
"score": 0.9999151229858398,
"start": 210,
"tag": "EMAIL",
"value": "user123@koding.me"
},
{
"context": "Account\n nickname: \... | node_modules_koding/jraphical/examples/graphlet/index.coffee | ezgikaysi/koding | 1 | bongo = require 'bongo'
{Graphlet,Relationship} = require '../../lib'
{Account,Message,Reply} = require './models'
bongo.setClient 'localhost:27017/test'
count = 0
makeSelection = ->
Account.one email: 'user123@koding.me', (err, account)->
throw err if err
account?.beginGraphlet()
.edges
query :
targetName : 'Message'
.nodes()
.edges
query :
targetName : 'Reply'
.nodes
limit : 5
sort :
'meta.votes' : -1
.endGraphlet()
.then (err, pipeline)->
throw err if err
{graphlet} = pipeline.last()
console.log graphlet[0] is account
console.log account.messages[0].replies[0]
initializeExample = do (makeSelection)->
targetTypes = ['Message','Reply','Wallet','DatabaseMySql','DatabaseCouch','DatabaseMongo']
len = targetTypes.length
id = new bongo.ObjectId
bongo.sequence (err, docs, i, next)->
throw err if err
[next, docs] = [docs, next] unless next
account = new Account
nickname: "user #{i}"
email: "user#{i}@koding.me"
account.save (err,docs)->
throw err if err
message = new Message
title : "Message #{i}"
body : 'lorum ipsum text'
message.save (err, docs)->
account.addMessage message, (err)->
reply = new Reply
title : "Reply 0 of #{i}"
body : "Lorum ipsum text..."
reply.save (err)->
message.addReply reply, next
, makeSelection
Relationship.count (err, count)->
if count is 0
# add 1000 semi-random relationships
initializeExample null, undefined, i for i in [0...1000]
else
makeSelection()
| 14551 | bongo = require 'bongo'
{Graphlet,Relationship} = require '../../lib'
{Account,Message,Reply} = require './models'
bongo.setClient 'localhost:27017/test'
count = 0
makeSelection = ->
Account.one email: '<EMAIL>', (err, account)->
throw err if err
account?.beginGraphlet()
.edges
query :
targetName : 'Message'
.nodes()
.edges
query :
targetName : 'Reply'
.nodes
limit : 5
sort :
'meta.votes' : -1
.endGraphlet()
.then (err, pipeline)->
throw err if err
{graphlet} = pipeline.last()
console.log graphlet[0] is account
console.log account.messages[0].replies[0]
initializeExample = do (makeSelection)->
targetTypes = ['Message','Reply','Wallet','DatabaseMySql','DatabaseCouch','DatabaseMongo']
len = targetTypes.length
id = new bongo.ObjectId
bongo.sequence (err, docs, i, next)->
throw err if err
[next, docs] = [docs, next] unless next
account = new Account
nickname: "user #{i}"
email: "<EMAIL>"
account.save (err,docs)->
throw err if err
message = new Message
title : "Message #{i}"
body : 'lorum ipsum text'
message.save (err, docs)->
account.addMessage message, (err)->
reply = new Reply
title : "Reply 0 of #{i}"
body : "Lorum ipsum text..."
reply.save (err)->
message.addReply reply, next
, makeSelection
Relationship.count (err, count)->
if count is 0
# add 1000 semi-random relationships
initializeExample null, undefined, i for i in [0...1000]
else
makeSelection()
| true | bongo = require 'bongo'
{Graphlet,Relationship} = require '../../lib'
{Account,Message,Reply} = require './models'
bongo.setClient 'localhost:27017/test'
count = 0
makeSelection = ->
Account.one email: 'PI:EMAIL:<EMAIL>END_PI', (err, account)->
throw err if err
account?.beginGraphlet()
.edges
query :
targetName : 'Message'
.nodes()
.edges
query :
targetName : 'Reply'
.nodes
limit : 5
sort :
'meta.votes' : -1
.endGraphlet()
.then (err, pipeline)->
throw err if err
{graphlet} = pipeline.last()
console.log graphlet[0] is account
console.log account.messages[0].replies[0]
initializeExample = do (makeSelection)->
targetTypes = ['Message','Reply','Wallet','DatabaseMySql','DatabaseCouch','DatabaseMongo']
len = targetTypes.length
id = new bongo.ObjectId
bongo.sequence (err, docs, i, next)->
throw err if err
[next, docs] = [docs, next] unless next
account = new Account
nickname: "user #{i}"
email: "PI:EMAIL:<EMAIL>END_PI"
account.save (err,docs)->
throw err if err
message = new Message
title : "Message #{i}"
body : 'lorum ipsum text'
message.save (err, docs)->
account.addMessage message, (err)->
reply = new Reply
title : "Reply 0 of #{i}"
body : "Lorum ipsum text..."
reply.save (err)->
message.addReply reply, next
, makeSelection
Relationship.count (err, count)->
if count is 0
# add 1000 semi-random relationships
initializeExample null, undefined, i for i in [0...1000]
else
makeSelection()
|
[
{
"context": "###\nlogin.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 44,
"score": 0.9994895458221436,
"start": 36,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "###\nlogin.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.co... | src/web/loginCtrl.coffee | xuender/mindfulness | 0 | ###
login.coffee
Copyright (C) 2014 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
LoginCtrl = ($scope, $http, $log, $modalInstance, m, cid)->
### 登录控制 ###
$scope.old = false
$scope.user =
phone: ''
password: ''
m: m
CaptchaId: cid
Solution: ''
$scope.img = "/captcha/img/#{ cid }"
count = 0
$scope.reload = ->
count++
$scope.img = "/captcha/reload/#{ cid }?#{ count }"
$scope.ok= (valid)->
# 登录
$scope.old = true
if valid
if $scope.user.m == 'l'
url = '/login'
else
url = '/register'
$http.post(url, $scope.user).success($scope.return)
$scope.return = (data)->
$scope.user.CaptchaId = data.cid
$scope.img = "/captcha/img/#{ data.cid }"
if data.ok
data.data.cid = data.cid
$modalInstance.close(data.data)
else
alert(data.err)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
LoginCtrl.$inject = ['$scope', '$http', '$log', '$modalInstance', 'm', 'cid']
| 163641 | ###
login.coffee
Copyright (C) 2014 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
LoginCtrl = ($scope, $http, $log, $modalInstance, m, cid)->
### 登录控制 ###
$scope.old = false
$scope.user =
phone: ''
password: ''
m: m
CaptchaId: cid
Solution: ''
$scope.img = "/captcha/img/#{ cid }"
count = 0
$scope.reload = ->
count++
$scope.img = "/captcha/reload/#{ cid }?#{ count }"
$scope.ok= (valid)->
# 登录
$scope.old = true
if valid
if $scope.user.m == 'l'
url = '/login'
else
url = '/register'
$http.post(url, $scope.user).success($scope.return)
$scope.return = (data)->
$scope.user.CaptchaId = data.cid
$scope.img = "/captcha/img/#{ data.cid }"
if data.ok
data.data.cid = data.cid
$modalInstance.close(data.data)
else
alert(data.err)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
LoginCtrl.$inject = ['$scope', '$http', '$log', '$modalInstance', 'm', 'cid']
| true | ###
login.coffee
Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
LoginCtrl = ($scope, $http, $log, $modalInstance, m, cid)->
### 登录控制 ###
$scope.old = false
$scope.user =
phone: ''
password: ''
m: m
CaptchaId: cid
Solution: ''
$scope.img = "/captcha/img/#{ cid }"
count = 0
$scope.reload = ->
count++
$scope.img = "/captcha/reload/#{ cid }?#{ count }"
$scope.ok= (valid)->
# 登录
$scope.old = true
if valid
if $scope.user.m == 'l'
url = '/login'
else
url = '/register'
$http.post(url, $scope.user).success($scope.return)
$scope.return = (data)->
$scope.user.CaptchaId = data.cid
$scope.img = "/captcha/img/#{ data.cid }"
if data.ok
data.data.cid = data.cid
$modalInstance.close(data.data)
else
alert(data.err)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
LoginCtrl.$inject = ['$scope', '$http', '$log', '$modalInstance', 'm', 'cid']
|
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998908638954163,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/database/seeders/demo-data.coffee | AbdelhakimRafik/Project | 1 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date June 2021
###
userManufacture = require './manufactures/users'
articleManufacure = require './manufactures/articles'
tagsManufature = require './manufactures/tags'
articleTagsManufature = require './manufactures/article-tags'
commentManufacture = require './manufactures/comments'
###
Create articles demo data
###
module.exports =
up: (queryInterface, Sequelize) ->
# generate users data
users = userManufacture 20
# insert users data
userStartId = await queryInterface.bulkInsert 'Users', users
# generate articles data
articles = articleManufacure users, parseInt userStartId
# inset articles data
articleStartId = await queryInterface.bulkInsert 'Articles', articles
# generate tags
tags = tagsManufature 10
# insert tags
tagStartId = await queryInterface.bulkInsert 'Tags', tags
# generate article-tags
articleTags = articleTagsManufature articles, articleStartId, tags, tagStartId, 2, 6
# insert article tags
await queryInterface.bulkInsert 'Article-tags', articleTags
# generate articles comments
comments = commentManufacture users, userStartId, articles, articleStartId, 0, 10
# insert comments
await queryInterface.bulkInsert 'Comments', comments
return
down: (queryInterface, Sequelize) ->
queryInterface.bulkDelete 'Articles'
return | 153529 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date June 2021
###
userManufacture = require './manufactures/users'
articleManufacure = require './manufactures/articles'
tagsManufature = require './manufactures/tags'
articleTagsManufature = require './manufactures/article-tags'
commentManufacture = require './manufactures/comments'
###
Create articles demo data
###
module.exports =
up: (queryInterface, Sequelize) ->
# generate users data
users = userManufacture 20
# insert users data
userStartId = await queryInterface.bulkInsert 'Users', users
# generate articles data
articles = articleManufacure users, parseInt userStartId
# inset articles data
articleStartId = await queryInterface.bulkInsert 'Articles', articles
# generate tags
tags = tagsManufature 10
# insert tags
tagStartId = await queryInterface.bulkInsert 'Tags', tags
# generate article-tags
articleTags = articleTagsManufature articles, articleStartId, tags, tagStartId, 2, 6
# insert article tags
await queryInterface.bulkInsert 'Article-tags', articleTags
# generate articles comments
comments = commentManufacture users, userStartId, articles, articleStartId, 0, 10
# insert comments
await queryInterface.bulkInsert 'Comments', comments
return
down: (queryInterface, Sequelize) ->
queryInterface.bulkDelete 'Articles'
return | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date June 2021
###
userManufacture = require './manufactures/users'
articleManufacure = require './manufactures/articles'
tagsManufature = require './manufactures/tags'
articleTagsManufature = require './manufactures/article-tags'
commentManufacture = require './manufactures/comments'
###
Create articles demo data
###
module.exports =
up: (queryInterface, Sequelize) ->
# generate users data
users = userManufacture 20
# insert users data
userStartId = await queryInterface.bulkInsert 'Users', users
# generate articles data
articles = articleManufacure users, parseInt userStartId
# inset articles data
articleStartId = await queryInterface.bulkInsert 'Articles', articles
# generate tags
tags = tagsManufature 10
# insert tags
tagStartId = await queryInterface.bulkInsert 'Tags', tags
# generate article-tags
articleTags = articleTagsManufature articles, articleStartId, tags, tagStartId, 2, 6
# insert article tags
await queryInterface.bulkInsert 'Article-tags', articleTags
# generate articles comments
comments = commentManufacture users, userStartId, articles, articleStartId, 0, 10
# insert comments
await queryInterface.bulkInsert 'Comments', comments
return
down: (queryInterface, Sequelize) ->
queryInterface.bulkDelete 'Articles'
return |
[
{
"context": "470, 15, align: 'right', width: 75\n @doc.text 'support@toggl.com', 470, 25, align: 'right', width: 75\n @doc.rec",
"end": 1240,
"score": 0.9999224543571472,
"start": 1223,
"tag": "EMAIL",
"value": "support@toggl.com"
}
] | app/invoice.coffee | meeDamian/toggl-pdf | 1 | PDFDocument = require 'pdfkit'
moment = require 'moment'
util = require 'util'
class Invoice
@PAGE_WIDTH = 595
constructor: (@data) ->
@doc = new PDFDocument size: 'A4'
@initFonts()
@LEFT = 35
initFonts: ->
@doc.registerFont('FontRegular', __dirname + '/fonts/NotoSans-Regular.ttf', 'Noto Sans')
@doc.registerFont('FontBold', __dirname + '/fonts/NotoSans-Bold.ttf', 'Noto Sans Bold')
@doc.font('FontRegular').fontSize(7)
output: (stream) ->
@doc.pipe stream
@finalize()
@doc.end()
fileName: ->
'toggl-invoice'
finalize: ->
@doc.translate 0, 35
@drawHeader()
@doc.translate 0, 55
@invoiceNumber()
@doc.translate 0, 30
@userDetails()
@doc.translate 0, 50
@tableHeader()
@doc.translate 0, 30
@tableContent()
@doc.translate 0, 175
@tableFooter()
@doc.translate 0, 60
@pageFooter()
drawHeader: ->
@doc.image __dirname + '/images/toggl.png', 35, 5, fit: [98, 40]
@doc.text 'Invoice from Toggl LLC', 135, 10
@doc.text 'Ravala 8 10143 Tallinn, Estonia', 135, 20
@doc.text 'VAT: EE101124102', 135, 30
@doc.text 'www.toggl.com', 470, 15, align: 'right', width: 75
@doc.text 'support@toggl.com', 470, 25, align: 'right', width: 75
@doc.rect(@LEFT, 1, 595-70, 45).lineWidth(0.5).dash(2, space: 2).stroke()
invoiceNumber: ->
headerWidth = 200
@doc.font('FontBold').fontSize 20
@doc.text "Invoice #N#{@data.id}", 595/2 - headerWidth/2, 10, align: 'center', width: headerWidth
userDetails: ->
createdAt = moment @data.created_at
@doc.font('FontBold').fontSize 10
@doc.text @data.company_name, @LEFT, 5
@doc.font('FontRegular').fontSize 7
@doc.text "#{@data.company_address} #{(if @data.country? then @data.country else '')}", @LEFT, 18
@doc.text @data.contact_person, @LEFT, 28
@doc.text @data.vat_number, @LEFT, 38
@doc.font('FontRegular').fontSize 7
@doc.text createdAt.format('MMMM D, YYYY'), 458, 20, align: 'right', width: 100
@doc.text @status(), 458, 30, align: 'right', width: 100
tableHeader: ->
@doc.rect(@LEFT, 1, 595-70, 250).lineWidth(0.5).dash(2, space: 2).stroke()
@doc.rect(@LEFT + 1, 2, 595-70-2, 20).fill('#eaebea')
@doc.font('FontBold').fill('#000').fontSize 8
@doc.text 'Description', 40, 5
@doc.text 'Users', 300, 5
@doc.text 'From', 375, 5
@doc.text 'To', 440, 5
@doc.text 'Amount', 505, 5, width: 0
tableContent: ->
subStart = new Date(@data.subscription_from)
subUntil = new Date(@data.subscription_to)
@doc.text 'Toggl subscription', 40, 1
@doc.font('FontRegular').fontSize 8
@doc.text @data.users_in_workspace, 300, 1
@doc.text subStart.toISOString().substr(0,10), 375, 1
@doc.text subUntil.toISOString().substr(0,10), 440, 1
@doc.text " #{@data.amount_in_usd} USD", 503, 1, width: 0
if @data.discount_percentage > 0
if @data.discount_percentage < 100
@doc.text "Discount #{@data.discount_percentage}%", 40, 15
else
@doc.text 'Free 1 month trial period', 40, 15
@doc.text "-#{@data.amount_in_usd * @data.discount_percentage / 100.0} USD", 503, 15
tableFooter: ->
alignOpts = align: 'right', width: 60
@doc.text 'Amount', 440, 1
@doc.text "#{@price().toFixed(2)} USD", 490, 1, alignOpts
@doc.text "VAT #{@data.vat_percentage}%", 440, 15
@doc.text "#{@vatAmount().toFixed(2)} USD", 490, 15, alignOpts
@doc.font('FontBold').text "Total paid", 440, 30
@doc.text "#{@totalPrice().toFixed(2)} USD", 490, 30, alignOpts
pageFooter: ->
@doc.font('FontRegular')
@doc.text 'Thank you!', 510, 1, width: 0
# Helpers
status: ->
if @data.cancelled_at?
cancelledAt = moment @data.cancelled_at
"Cancelled at: #{cancelledAt.format('MMMM D, YYYY')}"
else if @data.paid_at?
paidAt = moment @data.paid_at
"Paid at: #{paidAt.format('MMMM D, YYYY')}"
else
"Not paid"
price: ->
amount = @data.amount_in_usd
if @data.discount_percentage > 0
amount - (amount * @data.discount_percentage / 100.0)
else
@data.amount_in_usd
vatAmount: ->
@price() * @data.vat_percentage / 100.0
totalPrice: ->
if @data.vat_percentage > 0
@price() + @price() * @data.vat_percentage / 100.0
else
@price()
module.exports = Invoice
| 21073 | PDFDocument = require 'pdfkit'
moment = require 'moment'
util = require 'util'
class Invoice
@PAGE_WIDTH = 595
constructor: (@data) ->
@doc = new PDFDocument size: 'A4'
@initFonts()
@LEFT = 35
initFonts: ->
@doc.registerFont('FontRegular', __dirname + '/fonts/NotoSans-Regular.ttf', 'Noto Sans')
@doc.registerFont('FontBold', __dirname + '/fonts/NotoSans-Bold.ttf', 'Noto Sans Bold')
@doc.font('FontRegular').fontSize(7)
output: (stream) ->
@doc.pipe stream
@finalize()
@doc.end()
fileName: ->
'toggl-invoice'
finalize: ->
@doc.translate 0, 35
@drawHeader()
@doc.translate 0, 55
@invoiceNumber()
@doc.translate 0, 30
@userDetails()
@doc.translate 0, 50
@tableHeader()
@doc.translate 0, 30
@tableContent()
@doc.translate 0, 175
@tableFooter()
@doc.translate 0, 60
@pageFooter()
drawHeader: ->
@doc.image __dirname + '/images/toggl.png', 35, 5, fit: [98, 40]
@doc.text 'Invoice from Toggl LLC', 135, 10
@doc.text 'Ravala 8 10143 Tallinn, Estonia', 135, 20
@doc.text 'VAT: EE101124102', 135, 30
@doc.text 'www.toggl.com', 470, 15, align: 'right', width: 75
@doc.text '<EMAIL>', 470, 25, align: 'right', width: 75
@doc.rect(@LEFT, 1, 595-70, 45).lineWidth(0.5).dash(2, space: 2).stroke()
invoiceNumber: ->
headerWidth = 200
@doc.font('FontBold').fontSize 20
@doc.text "Invoice #N#{@data.id}", 595/2 - headerWidth/2, 10, align: 'center', width: headerWidth
userDetails: ->
createdAt = moment @data.created_at
@doc.font('FontBold').fontSize 10
@doc.text @data.company_name, @LEFT, 5
@doc.font('FontRegular').fontSize 7
@doc.text "#{@data.company_address} #{(if @data.country? then @data.country else '')}", @LEFT, 18
@doc.text @data.contact_person, @LEFT, 28
@doc.text @data.vat_number, @LEFT, 38
@doc.font('FontRegular').fontSize 7
@doc.text createdAt.format('MMMM D, YYYY'), 458, 20, align: 'right', width: 100
@doc.text @status(), 458, 30, align: 'right', width: 100
tableHeader: ->
@doc.rect(@LEFT, 1, 595-70, 250).lineWidth(0.5).dash(2, space: 2).stroke()
@doc.rect(@LEFT + 1, 2, 595-70-2, 20).fill('#eaebea')
@doc.font('FontBold').fill('#000').fontSize 8
@doc.text 'Description', 40, 5
@doc.text 'Users', 300, 5
@doc.text 'From', 375, 5
@doc.text 'To', 440, 5
@doc.text 'Amount', 505, 5, width: 0
tableContent: ->
subStart = new Date(@data.subscription_from)
subUntil = new Date(@data.subscription_to)
@doc.text 'Toggl subscription', 40, 1
@doc.font('FontRegular').fontSize 8
@doc.text @data.users_in_workspace, 300, 1
@doc.text subStart.toISOString().substr(0,10), 375, 1
@doc.text subUntil.toISOString().substr(0,10), 440, 1
@doc.text " #{@data.amount_in_usd} USD", 503, 1, width: 0
if @data.discount_percentage > 0
if @data.discount_percentage < 100
@doc.text "Discount #{@data.discount_percentage}%", 40, 15
else
@doc.text 'Free 1 month trial period', 40, 15
@doc.text "-#{@data.amount_in_usd * @data.discount_percentage / 100.0} USD", 503, 15
tableFooter: ->
alignOpts = align: 'right', width: 60
@doc.text 'Amount', 440, 1
@doc.text "#{@price().toFixed(2)} USD", 490, 1, alignOpts
@doc.text "VAT #{@data.vat_percentage}%", 440, 15
@doc.text "#{@vatAmount().toFixed(2)} USD", 490, 15, alignOpts
@doc.font('FontBold').text "Total paid", 440, 30
@doc.text "#{@totalPrice().toFixed(2)} USD", 490, 30, alignOpts
pageFooter: ->
@doc.font('FontRegular')
@doc.text 'Thank you!', 510, 1, width: 0
# Helpers
status: ->
if @data.cancelled_at?
cancelledAt = moment @data.cancelled_at
"Cancelled at: #{cancelledAt.format('MMMM D, YYYY')}"
else if @data.paid_at?
paidAt = moment @data.paid_at
"Paid at: #{paidAt.format('MMMM D, YYYY')}"
else
"Not paid"
price: ->
amount = @data.amount_in_usd
if @data.discount_percentage > 0
amount - (amount * @data.discount_percentage / 100.0)
else
@data.amount_in_usd
vatAmount: ->
@price() * @data.vat_percentage / 100.0
totalPrice: ->
if @data.vat_percentage > 0
@price() + @price() * @data.vat_percentage / 100.0
else
@price()
module.exports = Invoice
| true | PDFDocument = require 'pdfkit'
moment = require 'moment'
util = require 'util'
class Invoice
@PAGE_WIDTH = 595
constructor: (@data) ->
@doc = new PDFDocument size: 'A4'
@initFonts()
@LEFT = 35
initFonts: ->
@doc.registerFont('FontRegular', __dirname + '/fonts/NotoSans-Regular.ttf', 'Noto Sans')
@doc.registerFont('FontBold', __dirname + '/fonts/NotoSans-Bold.ttf', 'Noto Sans Bold')
@doc.font('FontRegular').fontSize(7)
output: (stream) ->
@doc.pipe stream
@finalize()
@doc.end()
fileName: ->
'toggl-invoice'
finalize: ->
@doc.translate 0, 35
@drawHeader()
@doc.translate 0, 55
@invoiceNumber()
@doc.translate 0, 30
@userDetails()
@doc.translate 0, 50
@tableHeader()
@doc.translate 0, 30
@tableContent()
@doc.translate 0, 175
@tableFooter()
@doc.translate 0, 60
@pageFooter()
drawHeader: ->
@doc.image __dirname + '/images/toggl.png', 35, 5, fit: [98, 40]
@doc.text 'Invoice from Toggl LLC', 135, 10
@doc.text 'Ravala 8 10143 Tallinn, Estonia', 135, 20
@doc.text 'VAT: EE101124102', 135, 30
@doc.text 'www.toggl.com', 470, 15, align: 'right', width: 75
@doc.text 'PI:EMAIL:<EMAIL>END_PI', 470, 25, align: 'right', width: 75
@doc.rect(@LEFT, 1, 595-70, 45).lineWidth(0.5).dash(2, space: 2).stroke()
invoiceNumber: ->
headerWidth = 200
@doc.font('FontBold').fontSize 20
@doc.text "Invoice #N#{@data.id}", 595/2 - headerWidth/2, 10, align: 'center', width: headerWidth
userDetails: ->
createdAt = moment @data.created_at
@doc.font('FontBold').fontSize 10
@doc.text @data.company_name, @LEFT, 5
@doc.font('FontRegular').fontSize 7
@doc.text "#{@data.company_address} #{(if @data.country? then @data.country else '')}", @LEFT, 18
@doc.text @data.contact_person, @LEFT, 28
@doc.text @data.vat_number, @LEFT, 38
@doc.font('FontRegular').fontSize 7
@doc.text createdAt.format('MMMM D, YYYY'), 458, 20, align: 'right', width: 100
@doc.text @status(), 458, 30, align: 'right', width: 100
tableHeader: ->
@doc.rect(@LEFT, 1, 595-70, 250).lineWidth(0.5).dash(2, space: 2).stroke()
@doc.rect(@LEFT + 1, 2, 595-70-2, 20).fill('#eaebea')
@doc.font('FontBold').fill('#000').fontSize 8
@doc.text 'Description', 40, 5
@doc.text 'Users', 300, 5
@doc.text 'From', 375, 5
@doc.text 'To', 440, 5
@doc.text 'Amount', 505, 5, width: 0
tableContent: ->
subStart = new Date(@data.subscription_from)
subUntil = new Date(@data.subscription_to)
@doc.text 'Toggl subscription', 40, 1
@doc.font('FontRegular').fontSize 8
@doc.text @data.users_in_workspace, 300, 1
@doc.text subStart.toISOString().substr(0,10), 375, 1
@doc.text subUntil.toISOString().substr(0,10), 440, 1
@doc.text " #{@data.amount_in_usd} USD", 503, 1, width: 0
if @data.discount_percentage > 0
if @data.discount_percentage < 100
@doc.text "Discount #{@data.discount_percentage}%", 40, 15
else
@doc.text 'Free 1 month trial period', 40, 15
@doc.text "-#{@data.amount_in_usd * @data.discount_percentage / 100.0} USD", 503, 15
tableFooter: ->
alignOpts = align: 'right', width: 60
@doc.text 'Amount', 440, 1
@doc.text "#{@price().toFixed(2)} USD", 490, 1, alignOpts
@doc.text "VAT #{@data.vat_percentage}%", 440, 15
@doc.text "#{@vatAmount().toFixed(2)} USD", 490, 15, alignOpts
@doc.font('FontBold').text "Total paid", 440, 30
@doc.text "#{@totalPrice().toFixed(2)} USD", 490, 30, alignOpts
pageFooter: ->
@doc.font('FontRegular')
@doc.text 'Thank you!', 510, 1, width: 0
# Helpers
status: ->
if @data.cancelled_at?
cancelledAt = moment @data.cancelled_at
"Cancelled at: #{cancelledAt.format('MMMM D, YYYY')}"
else if @data.paid_at?
paidAt = moment @data.paid_at
"Paid at: #{paidAt.format('MMMM D, YYYY')}"
else
"Not paid"
price: ->
amount = @data.amount_in_usd
if @data.discount_percentage > 0
amount - (amount * @data.discount_percentage / 100.0)
else
@data.amount_in_usd
vatAmount: ->
@price() * @data.vat_percentage / 100.0
totalPrice: ->
if @data.vat_percentage > 0
@price() + @price() * @data.vat_percentage / 100.0
else
@price()
module.exports = Invoice
|
[
{
"context": " username: process.env.DB_DEV_USER\n password: process.env.DB_DEV_PASSWORD\n database: process.env.DB_DEV_DATABASE\n ",
"end": 561,
"score": 0.9942550659179688,
"start": 534,
"tag": "PASSWORD",
"value": "process.env.DB_DEV_PASSWORD"
},
{
"context": "userna... | lib/config.coffee | rayshan/bower-server-etl | 1 | url = require 'url'
# ==========
# ask repo owner for GA Service Account key.pem & foreman .env file; place into project root
config =
development:
port: 3000
apiBaseUri: '/api/1'
ga:
clientEmail: process.env.APP_GA_CLIENT_EMAIL
privateKeyPath: "../gaServiceAcctKeyDev.pem"
profile: '75972512'
scopeUri: 'https://www.googleapis.com/auth/analytics.readonly'
db:
host: process.env.DB_DEV_HOST
port: process.env.DB_DEV_PORT
username: process.env.DB_DEV_USER
password: process.env.DB_DEV_PASSWORD
database: process.env.DB_DEV_DATABASE
dialect: process.env.DB_DEV_DIALECT
cache: '/tmp/redis-stats.bower.io.sock'
production:
port: 3000
apiBaseUri: '/api/1'
ga:
clientEmail: process.env.APP_GA_CLIENT_EMAIL
privateKeyContent: process.env.APP_GA_KEY_CONTENT
profile: '75972512'
scopeUri: 'https://www.googleapis.com/auth/analytics.readonly'
db:
host: process.env.DB_PROD_HOST
port: process.env.DB_PROD_PORT
username: process.env.DB_PROD_USER
password: process.env.DB_PROD_PASSWORD
database: process.env.DB_PROD_DATABASE
dialect: process.env.DB_PROD_DIALECT
cache: url.parse process.env.REDISCLOUD_URL
module.exports = config
| 174810 | url = require 'url'
# ==========
# ask repo owner for GA Service Account key.pem & foreman .env file; place into project root
config =
development:
port: 3000
apiBaseUri: '/api/1'
ga:
clientEmail: process.env.APP_GA_CLIENT_EMAIL
privateKeyPath: "../gaServiceAcctKeyDev.pem"
profile: '75972512'
scopeUri: 'https://www.googleapis.com/auth/analytics.readonly'
db:
host: process.env.DB_DEV_HOST
port: process.env.DB_DEV_PORT
username: process.env.DB_DEV_USER
password: <PASSWORD>
database: process.env.DB_DEV_DATABASE
dialect: process.env.DB_DEV_DIALECT
cache: '/tmp/redis-stats.bower.io.sock'
production:
port: 3000
apiBaseUri: '/api/1'
ga:
clientEmail: process.env.APP_GA_CLIENT_EMAIL
privateKeyContent: process.env.APP_GA_KEY_CONTENT
profile: '75972512'
scopeUri: 'https://www.googleapis.com/auth/analytics.readonly'
db:
host: process.env.DB_PROD_HOST
port: process.env.DB_PROD_PORT
username: process.env.DB_PROD_USER
password: <PASSWORD>
database: process.env.DB_PROD_DATABASE
dialect: process.env.DB_PROD_DIALECT
cache: url.parse process.env.REDISCLOUD_URL
module.exports = config
| true | url = require 'url'
# ==========
# ask repo owner for GA Service Account key.pem & foreman .env file; place into project root
config =
development:
port: 3000
apiBaseUri: '/api/1'
ga:
clientEmail: process.env.APP_GA_CLIENT_EMAIL
privateKeyPath: "../gaServiceAcctKeyDev.pem"
profile: '75972512'
scopeUri: 'https://www.googleapis.com/auth/analytics.readonly'
db:
host: process.env.DB_DEV_HOST
port: process.env.DB_DEV_PORT
username: process.env.DB_DEV_USER
password: PI:PASSWORD:<PASSWORD>END_PI
database: process.env.DB_DEV_DATABASE
dialect: process.env.DB_DEV_DIALECT
cache: '/tmp/redis-stats.bower.io.sock'
production:
port: 3000
apiBaseUri: '/api/1'
ga:
clientEmail: process.env.APP_GA_CLIENT_EMAIL
privateKeyContent: process.env.APP_GA_KEY_CONTENT
profile: '75972512'
scopeUri: 'https://www.googleapis.com/auth/analytics.readonly'
db:
host: process.env.DB_PROD_HOST
port: process.env.DB_PROD_PORT
username: process.env.DB_PROD_USER
password: PI:PASSWORD:<PASSWORD>END_PI
database: process.env.DB_PROD_DATABASE
dialect: process.env.DB_PROD_DIALECT
cache: url.parse process.env.REDISCLOUD_URL
module.exports = config
|
[
{
"context": "st from the Uber API\nuberInfo = () ->\n\tAPI_key = '1TTcGJNB_ltPhjaH0Lp1oHjypAYSFFxrwmhncRDi'\n\tlat = '40.4406'\n\tlng = '-79.9959'\n\tproxy = 'htt",
"end": 135,
"score": 0.9997354745864868,
"start": 95,
"tag": "KEY",
"value": "1TTcGJNB_ltPhjaH0Lp1oHjypAYSFFxrwmhncRDi"
}
] | public/js/uber.coffee | pschfr/dashboard | 1 | # Gets surge pricing, wait times, and est. cost from the Uber API
uberInfo = () ->
API_key = '1TTcGJNB_ltPhjaH0Lp1oHjypAYSFFxrwmhncRDi'
lat = '40.4406'
lng = '-79.9959'
proxy = 'https://paulmakesthe.net/ba-simple-proxy.php'
uberURL = 'https://api.uber.com/v1.2/estimates/time?start_latitude=' + lat + '&start_longitude=' + lng
xhr = new XMLHttpRequest()
xhr.open('GET', proxy + '?url=' + uberURL, true)
# xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
xhr.setRequestHeader('Authorization', 'Token ' + API_key)
# xhr.send()
xhr.onreadystatechange = () ->
if (xhr.readyState == 4 && xhr.status == 200)
times = JSON.parse(xhr.responseText)
# console.log(times)
xhr.send(null)
uberInfo()
| 25214 | # Gets surge pricing, wait times, and est. cost from the Uber API
uberInfo = () ->
API_key = '<KEY>'
lat = '40.4406'
lng = '-79.9959'
proxy = 'https://paulmakesthe.net/ba-simple-proxy.php'
uberURL = 'https://api.uber.com/v1.2/estimates/time?start_latitude=' + lat + '&start_longitude=' + lng
xhr = new XMLHttpRequest()
xhr.open('GET', proxy + '?url=' + uberURL, true)
# xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
xhr.setRequestHeader('Authorization', 'Token ' + API_key)
# xhr.send()
xhr.onreadystatechange = () ->
if (xhr.readyState == 4 && xhr.status == 200)
times = JSON.parse(xhr.responseText)
# console.log(times)
xhr.send(null)
uberInfo()
| true | # Gets surge pricing, wait times, and est. cost from the Uber API
uberInfo = () ->
API_key = 'PI:KEY:<KEY>END_PI'
lat = '40.4406'
lng = '-79.9959'
proxy = 'https://paulmakesthe.net/ba-simple-proxy.php'
uberURL = 'https://api.uber.com/v1.2/estimates/time?start_latitude=' + lat + '&start_longitude=' + lng
xhr = new XMLHttpRequest()
xhr.open('GET', proxy + '?url=' + uberURL, true)
# xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
xhr.setRequestHeader('Authorization', 'Token ' + API_key)
# xhr.send()
xhr.onreadystatechange = () ->
if (xhr.readyState == 4 && xhr.status == 200)
times = JSON.parse(xhr.responseText)
# console.log(times)
xhr.send(null)
uberInfo()
|
[
{
"context": "\n type: false\n name: name\n actual: \"unknown\"\n ",
"end": 10592,
"score": 0.8656387329101562,
"start": 10588,
"tag": "NAME",
"value": "name"
}
] | src/5.test.1.coffee | zhanzhenzhen/wishlist | 0 | ###
In `wishlist.Test`, the `wishes` property contains only separated wishes
(i.e. not including those defined and checked in a test function), but
the `wishResults` property includes results for all wishes.
Test names can be duplicate. Wish names can also be duplicate.
Restriction: On browser it doesn't work well with exceptional tests.
###
class wishlist.Test
# `allCount` and `endedCount` refer to all descendant tests including itself.
# Both are redundant, but needed (for performance)
constructor: (@name = "") ->
@_children = []
@fun = =>
@afterFun = =>
@wishes = []
@async = false
@parent = null
@allCount = 1
@_resetContext()
_resetContext: ->
@env = {}
@wishResults = []
@result = null
@endedCount = 0
# syntax: set([name], fun, [wishes], [options])
set: ->
name = fun = wishes = rawWishes = options = undefined
normalizeWishes = (raw) =>
combined =
if Array.isArray(raw)
raw.join(";")
else if typeof raw == "string"
raw
else
""
wishlist.parseWishes(combined)
if typeof arguments[0] == "string"
name = arguments[0]
fun = arguments[1]
if typeof arguments[2] == "object" and arguments[2] != null and
not Array.isArray(arguments[2])
options = arguments[2]
else
rawWishes = arguments[2]
options = arguments[3]
else
fun = arguments[0]
if typeof arguments[1] == "object" and arguments[1] != null and
not Array.isArray(arguments[1])
options = arguments[1]
else
rawWishes = arguments[1]
options = arguments[2]
wishes = normalizeWishes(rawWishes)
options ?= {}
if name != undefined then @name = name
@fun = fun
if rawWishes != undefined then @wishes = wishes
if options.async != undefined then @async = options.async
@
setAsync: ->
args = []
for m in arguments
args.push(m)
lastArg = args[args.length - 1]
if typeof lastArg == "object" and lastArg != null and not Array.isArray(lastArg)
lastArg.async = true
else
args.push({async: true})
@set(args...)
after: (@afterFun) ->
@
add: ->
newChild = null
count = null
if arguments[0] instanceof wishlist.Test
newChild = arguments[0]
count = newChild.getAll().length
else
newChild = new wishlist.Test()
newChild.set(arguments...)
count = 1
newChild.parent = @
@_children.push(newChild)
@getAncestorsAndSelf().forEach((test) => test.allCount += count)
@
addAsync: ->
args = []
for m in arguments
args.push(m)
lastArg = args[args.length - 1]
if typeof lastArg == "object" and lastArg != null and not Array.isArray(lastArg)
lastArg.async = true
else
args.push({async: true})
@add(args...)
getChildren: ->
# use a shallow copy to encapsule `_children` to prevent direct operation on the array
@_children[..]
getAncestors: ->
test = @
r = []
while test.parent != null
r.push(test.parent)
test = test.parent
r
getAncestorsAndSelf: ->
[@].concat(@getAncestors())
# all descendant tests including itself
getAll: ->
r = []
r.push(@)
traverse = (test) =>
test.getChildren().forEach((m) =>
r.push(m)
traverse(m)
)
traverse(@)
r
run: (isRoot = true) ->
if isRoot
wishlist.currentRootTest = @
@_resetContext()
if @parent?
@env = wishlist.objectClone(@parent.env)
# We use `setTimeout(..., 0)` only to make all tests "unordered", at least theoretically.
setTimeout(=>
if wishlist.environmentType == "node"
domain = require("domain").create()
domain.on("error", (error) =>
@end(
type: false
errorMessage: """
Error Name: #{error.name}
Error Message: #{error.message}
Error Stack: #{error.stack}
"""
)
)
domain.run(=> process.nextTick(=>
@fun(@env, @)
if not @result? and not @async
@end({type: true})
))
else
try
@fun(@env, @)
if not @result? and not @async
@end({type: true})
catch
@end({type: false})
, 0)
if isRoot
allTests = @getAll()
console.log()
# TODO: Scanning for timeout is now also in this function. It's inaccurate because interval
# is 1 sec. We may need to create another timer with shorter interval for that.
timerJob = =>
okTests = allTests.filter((m) => m.result? and m.result.type == true)
exceptionTests = allTests.filter((m) => m.result? and m.result.type == false)
pendingTests = allTests.filter((m) => not m.result?)
console.log("#{new Date().toISOString()} OK: #{okTests.length}, " +
"Exception: #{exceptionTests.length}, Pending: #{pendingTests.length}")
if pendingTests.length == 0
clearInterval(timer)
exceptionTests.forEach((m) =>
console.log("\n********** Exceptional Test **********")
console.log("Test: #{m.name}")
console.log("Function: #{m.fun.toString()}")
console.log(m.result.errorMessage) if m.result.errorMessage?
)
failureCount = 0
successCount = 0
markString = ""
allTests.forEach((m) => m.wishResults.forEach((n) =>
markString += " " + n.type.toString()
if n.type == false
failureCount++
ancestors = m.getAncestors()
ancestors.reverse()
longName = ancestors.concat([m]).map((m) => m.name).join(" --> ")
console.log("\n********** Broken Wish **********")
console.log(" Test: #{longName}")
console.log(" Wish: #{n.name}")
console.log("Expected: #{n.expected}")
console.log(" Actual: #{n.actual}")
else
successCount++
))
markString = markString.trim()
mark = wishlist.sha256(markString).substr(0, 5)
console.log("\n" + (
(
if exceptionTests.length == 0
"Tests OK."
else
"#{exceptionTests.length} tests of #{allTests.length} exceptional."
) + " " +
(
if failureCount == 0
"Wishes fulfilled."
else
"#{failureCount} wishes of #{failureCount + successCount} broken."
) + " " +
"Mark: #{mark}"
) + "\n")
wishlist.currentRootTest = null
timer = setInterval(timerJob, 1000)
# a delay slightly greater than 0 is useful for preventing a useless heartbeat
# while there's no async test and computation takes very little time.
setTimeout(timerJob, 10)
@
end: (result) ->
if not @result?
@result = result ? {type: true}
@wishes.forEach((m) =>
@_checkWish(m)
)
@getAncestorsAndSelf().forEach((test) =>
test.endedCount++
if test.endedCount == test.allCount
test._tryCallFun(=> test.afterFun(test.env))
)
@getChildren().forEach((m) =>
m.run(false)
)
@
_tryCallFun: (fun) ->
if wishlist.environmentType == "node"
domain = require("domain").create()
domain.on("error", (error) =>
console.log(error.stack)
)
domain.run(=> process.nextTick(fun))
else
try
fun()
catch
console.log("Error!")
_checkWish: (wishStr) ->
# Reason for `that`: CoffeeScript cannot detect `this` keyword in `eval` string,
# so in `eval` in fat arrow functions we must use `that`.
that = this
interpret = (s) =>
wishlist.parseExpression(s, Object.keys(@env)).forEach((m, index) =>
insertedString = "that.env."
pos = m + insertedString.length * index
s = s.substr(0, pos) + insertedString + s.substr(pos)
)
s
parsed = wishlist.parseWish(wishStr)
args = parsed.components.map((m, index) =>
if index == parsed.components.length - 1
m
else
interpret(m)
)
name = JSON.parse(args[args.length - 1])
result =
try
# Must enclose it by "()", otherwise object literals can't be evaluated.
# Note: Ideally a single "()" pair is enough, but Safari has a strange bug
# that makes `eval("(-0)")` return +0. So we must use "(())" to workaround it.
args = args.map((m) => eval("((#{m}))"))
@["_check_" + parsed.type](args...)
catch
type: false
name: name
actual: "unknown"
expected: "unknown"
@wishResults.push(result)
wish: (wishesStr) ->
wishlist.parseWishes(wishesStr).forEach((wishStr) =>
@_checkWish(wishStr)
)
| 185557 | ###
In `wishlist.Test`, the `wishes` property contains only separated wishes
(i.e. not including those defined and checked in a test function), but
the `wishResults` property includes results for all wishes.
Test names can be duplicate. Wish names can also be duplicate.
Restriction: On browser it doesn't work well with exceptional tests.
###
class wishlist.Test
# `allCount` and `endedCount` refer to all descendant tests including itself.
# Both are redundant, but needed (for performance)
constructor: (@name = "") ->
@_children = []
@fun = =>
@afterFun = =>
@wishes = []
@async = false
@parent = null
@allCount = 1
@_resetContext()
_resetContext: ->
@env = {}
@wishResults = []
@result = null
@endedCount = 0
# syntax: set([name], fun, [wishes], [options])
set: ->
name = fun = wishes = rawWishes = options = undefined
normalizeWishes = (raw) =>
combined =
if Array.isArray(raw)
raw.join(";")
else if typeof raw == "string"
raw
else
""
wishlist.parseWishes(combined)
if typeof arguments[0] == "string"
name = arguments[0]
fun = arguments[1]
if typeof arguments[2] == "object" and arguments[2] != null and
not Array.isArray(arguments[2])
options = arguments[2]
else
rawWishes = arguments[2]
options = arguments[3]
else
fun = arguments[0]
if typeof arguments[1] == "object" and arguments[1] != null and
not Array.isArray(arguments[1])
options = arguments[1]
else
rawWishes = arguments[1]
options = arguments[2]
wishes = normalizeWishes(rawWishes)
options ?= {}
if name != undefined then @name = name
@fun = fun
if rawWishes != undefined then @wishes = wishes
if options.async != undefined then @async = options.async
@
setAsync: ->
args = []
for m in arguments
args.push(m)
lastArg = args[args.length - 1]
if typeof lastArg == "object" and lastArg != null and not Array.isArray(lastArg)
lastArg.async = true
else
args.push({async: true})
@set(args...)
after: (@afterFun) ->
@
add: ->
newChild = null
count = null
if arguments[0] instanceof wishlist.Test
newChild = arguments[0]
count = newChild.getAll().length
else
newChild = new wishlist.Test()
newChild.set(arguments...)
count = 1
newChild.parent = @
@_children.push(newChild)
@getAncestorsAndSelf().forEach((test) => test.allCount += count)
@
addAsync: ->
args = []
for m in arguments
args.push(m)
lastArg = args[args.length - 1]
if typeof lastArg == "object" and lastArg != null and not Array.isArray(lastArg)
lastArg.async = true
else
args.push({async: true})
@add(args...)
getChildren: ->
# use a shallow copy to encapsule `_children` to prevent direct operation on the array
@_children[..]
getAncestors: ->
test = @
r = []
while test.parent != null
r.push(test.parent)
test = test.parent
r
getAncestorsAndSelf: ->
[@].concat(@getAncestors())
# all descendant tests including itself
getAll: ->
r = []
r.push(@)
traverse = (test) =>
test.getChildren().forEach((m) =>
r.push(m)
traverse(m)
)
traverse(@)
r
run: (isRoot = true) ->
if isRoot
wishlist.currentRootTest = @
@_resetContext()
if @parent?
@env = wishlist.objectClone(@parent.env)
# We use `setTimeout(..., 0)` only to make all tests "unordered", at least theoretically.
setTimeout(=>
if wishlist.environmentType == "node"
domain = require("domain").create()
domain.on("error", (error) =>
@end(
type: false
errorMessage: """
Error Name: #{error.name}
Error Message: #{error.message}
Error Stack: #{error.stack}
"""
)
)
domain.run(=> process.nextTick(=>
@fun(@env, @)
if not @result? and not @async
@end({type: true})
))
else
try
@fun(@env, @)
if not @result? and not @async
@end({type: true})
catch
@end({type: false})
, 0)
if isRoot
allTests = @getAll()
console.log()
# TODO: Scanning for timeout is now also in this function. It's inaccurate because interval
# is 1 sec. We may need to create another timer with shorter interval for that.
timerJob = =>
okTests = allTests.filter((m) => m.result? and m.result.type == true)
exceptionTests = allTests.filter((m) => m.result? and m.result.type == false)
pendingTests = allTests.filter((m) => not m.result?)
console.log("#{new Date().toISOString()} OK: #{okTests.length}, " +
"Exception: #{exceptionTests.length}, Pending: #{pendingTests.length}")
if pendingTests.length == 0
clearInterval(timer)
exceptionTests.forEach((m) =>
console.log("\n********** Exceptional Test **********")
console.log("Test: #{m.name}")
console.log("Function: #{m.fun.toString()}")
console.log(m.result.errorMessage) if m.result.errorMessage?
)
failureCount = 0
successCount = 0
markString = ""
allTests.forEach((m) => m.wishResults.forEach((n) =>
markString += " " + n.type.toString()
if n.type == false
failureCount++
ancestors = m.getAncestors()
ancestors.reverse()
longName = ancestors.concat([m]).map((m) => m.name).join(" --> ")
console.log("\n********** Broken Wish **********")
console.log(" Test: #{longName}")
console.log(" Wish: #{n.name}")
console.log("Expected: #{n.expected}")
console.log(" Actual: #{n.actual}")
else
successCount++
))
markString = markString.trim()
mark = wishlist.sha256(markString).substr(0, 5)
console.log("\n" + (
(
if exceptionTests.length == 0
"Tests OK."
else
"#{exceptionTests.length} tests of #{allTests.length} exceptional."
) + " " +
(
if failureCount == 0
"Wishes fulfilled."
else
"#{failureCount} wishes of #{failureCount + successCount} broken."
) + " " +
"Mark: #{mark}"
) + "\n")
wishlist.currentRootTest = null
timer = setInterval(timerJob, 1000)
# a delay slightly greater than 0 is useful for preventing a useless heartbeat
# while there's no async test and computation takes very little time.
setTimeout(timerJob, 10)
@
end: (result) ->
if not @result?
@result = result ? {type: true}
@wishes.forEach((m) =>
@_checkWish(m)
)
@getAncestorsAndSelf().forEach((test) =>
test.endedCount++
if test.endedCount == test.allCount
test._tryCallFun(=> test.afterFun(test.env))
)
@getChildren().forEach((m) =>
m.run(false)
)
@
_tryCallFun: (fun) ->
if wishlist.environmentType == "node"
domain = require("domain").create()
domain.on("error", (error) =>
console.log(error.stack)
)
domain.run(=> process.nextTick(fun))
else
try
fun()
catch
console.log("Error!")
_checkWish: (wishStr) ->
# Reason for `that`: CoffeeScript cannot detect `this` keyword in `eval` string,
# so in `eval` in fat arrow functions we must use `that`.
that = this
interpret = (s) =>
wishlist.parseExpression(s, Object.keys(@env)).forEach((m, index) =>
insertedString = "that.env."
pos = m + insertedString.length * index
s = s.substr(0, pos) + insertedString + s.substr(pos)
)
s
parsed = wishlist.parseWish(wishStr)
args = parsed.components.map((m, index) =>
if index == parsed.components.length - 1
m
else
interpret(m)
)
name = JSON.parse(args[args.length - 1])
result =
try
# Must enclose it by "()", otherwise object literals can't be evaluated.
# Note: Ideally a single "()" pair is enough, but Safari has a strange bug
# that makes `eval("(-0)")` return +0. So we must use "(())" to workaround it.
args = args.map((m) => eval("((#{m}))"))
@["_check_" + parsed.type](args...)
catch
type: false
name: <NAME>
actual: "unknown"
expected: "unknown"
@wishResults.push(result)
wish: (wishesStr) ->
wishlist.parseWishes(wishesStr).forEach((wishStr) =>
@_checkWish(wishStr)
)
| true | ###
In `wishlist.Test`, the `wishes` property contains only separated wishes
(i.e. not including those defined and checked in a test function), but
the `wishResults` property includes results for all wishes.
Test names can be duplicate. Wish names can also be duplicate.
Restriction: On browser it doesn't work well with exceptional tests.
###
class wishlist.Test
# `allCount` and `endedCount` refer to all descendant tests including itself.
# Both are redundant, but needed (for performance)
constructor: (@name = "") ->
@_children = []
@fun = =>
@afterFun = =>
@wishes = []
@async = false
@parent = null
@allCount = 1
@_resetContext()
_resetContext: ->
@env = {}
@wishResults = []
@result = null
@endedCount = 0
# syntax: set([name], fun, [wishes], [options])
set: ->
name = fun = wishes = rawWishes = options = undefined
normalizeWishes = (raw) =>
combined =
if Array.isArray(raw)
raw.join(";")
else if typeof raw == "string"
raw
else
""
wishlist.parseWishes(combined)
if typeof arguments[0] == "string"
name = arguments[0]
fun = arguments[1]
if typeof arguments[2] == "object" and arguments[2] != null and
not Array.isArray(arguments[2])
options = arguments[2]
else
rawWishes = arguments[2]
options = arguments[3]
else
fun = arguments[0]
if typeof arguments[1] == "object" and arguments[1] != null and
not Array.isArray(arguments[1])
options = arguments[1]
else
rawWishes = arguments[1]
options = arguments[2]
wishes = normalizeWishes(rawWishes)
options ?= {}
if name != undefined then @name = name
@fun = fun
if rawWishes != undefined then @wishes = wishes
if options.async != undefined then @async = options.async
@
setAsync: ->
args = []
for m in arguments
args.push(m)
lastArg = args[args.length - 1]
if typeof lastArg == "object" and lastArg != null and not Array.isArray(lastArg)
lastArg.async = true
else
args.push({async: true})
@set(args...)
after: (@afterFun) ->
@
add: ->
newChild = null
count = null
if arguments[0] instanceof wishlist.Test
newChild = arguments[0]
count = newChild.getAll().length
else
newChild = new wishlist.Test()
newChild.set(arguments...)
count = 1
newChild.parent = @
@_children.push(newChild)
@getAncestorsAndSelf().forEach((test) => test.allCount += count)
@
addAsync: ->
args = []
for m in arguments
args.push(m)
lastArg = args[args.length - 1]
if typeof lastArg == "object" and lastArg != null and not Array.isArray(lastArg)
lastArg.async = true
else
args.push({async: true})
@add(args...)
getChildren: ->
# use a shallow copy to encapsule `_children` to prevent direct operation on the array
@_children[..]
getAncestors: ->
test = @
r = []
while test.parent != null
r.push(test.parent)
test = test.parent
r
getAncestorsAndSelf: ->
[@].concat(@getAncestors())
# all descendant tests including itself
getAll: ->
r = []
r.push(@)
traverse = (test) =>
test.getChildren().forEach((m) =>
r.push(m)
traverse(m)
)
traverse(@)
r
run: (isRoot = true) ->
if isRoot
wishlist.currentRootTest = @
@_resetContext()
if @parent?
@env = wishlist.objectClone(@parent.env)
# We use `setTimeout(..., 0)` only to make all tests "unordered", at least theoretically.
setTimeout(=>
if wishlist.environmentType == "node"
domain = require("domain").create()
domain.on("error", (error) =>
@end(
type: false
errorMessage: """
Error Name: #{error.name}
Error Message: #{error.message}
Error Stack: #{error.stack}
"""
)
)
domain.run(=> process.nextTick(=>
@fun(@env, @)
if not @result? and not @async
@end({type: true})
))
else
try
@fun(@env, @)
if not @result? and not @async
@end({type: true})
catch
@end({type: false})
, 0)
if isRoot
allTests = @getAll()
console.log()
# TODO: Scanning for timeout is now also in this function. It's inaccurate because interval
# is 1 sec. We may need to create another timer with shorter interval for that.
timerJob = =>
okTests = allTests.filter((m) => m.result? and m.result.type == true)
exceptionTests = allTests.filter((m) => m.result? and m.result.type == false)
pendingTests = allTests.filter((m) => not m.result?)
console.log("#{new Date().toISOString()} OK: #{okTests.length}, " +
"Exception: #{exceptionTests.length}, Pending: #{pendingTests.length}")
if pendingTests.length == 0
clearInterval(timer)
exceptionTests.forEach((m) =>
console.log("\n********** Exceptional Test **********")
console.log("Test: #{m.name}")
console.log("Function: #{m.fun.toString()}")
console.log(m.result.errorMessage) if m.result.errorMessage?
)
failureCount = 0
successCount = 0
markString = ""
allTests.forEach((m) => m.wishResults.forEach((n) =>
markString += " " + n.type.toString()
if n.type == false
failureCount++
ancestors = m.getAncestors()
ancestors.reverse()
longName = ancestors.concat([m]).map((m) => m.name).join(" --> ")
console.log("\n********** Broken Wish **********")
console.log(" Test: #{longName}")
console.log(" Wish: #{n.name}")
console.log("Expected: #{n.expected}")
console.log(" Actual: #{n.actual}")
else
successCount++
))
markString = markString.trim()
mark = wishlist.sha256(markString).substr(0, 5)
console.log("\n" + (
(
if exceptionTests.length == 0
"Tests OK."
else
"#{exceptionTests.length} tests of #{allTests.length} exceptional."
) + " " +
(
if failureCount == 0
"Wishes fulfilled."
else
"#{failureCount} wishes of #{failureCount + successCount} broken."
) + " " +
"Mark: #{mark}"
) + "\n")
wishlist.currentRootTest = null
timer = setInterval(timerJob, 1000)
# a delay slightly greater than 0 is useful for preventing a useless heartbeat
# while there's no async test and computation takes very little time.
setTimeout(timerJob, 10)
@
end: (result) ->
if not @result?
@result = result ? {type: true}
@wishes.forEach((m) =>
@_checkWish(m)
)
@getAncestorsAndSelf().forEach((test) =>
test.endedCount++
if test.endedCount == test.allCount
test._tryCallFun(=> test.afterFun(test.env))
)
@getChildren().forEach((m) =>
m.run(false)
)
@
_tryCallFun: (fun) ->
if wishlist.environmentType == "node"
domain = require("domain").create()
domain.on("error", (error) =>
console.log(error.stack)
)
domain.run(=> process.nextTick(fun))
else
try
fun()
catch
console.log("Error!")
_checkWish: (wishStr) ->
# Reason for `that`: CoffeeScript cannot detect `this` keyword in `eval` string,
# so in `eval` in fat arrow functions we must use `that`.
that = this
interpret = (s) =>
wishlist.parseExpression(s, Object.keys(@env)).forEach((m, index) =>
insertedString = "that.env."
pos = m + insertedString.length * index
s = s.substr(0, pos) + insertedString + s.substr(pos)
)
s
parsed = wishlist.parseWish(wishStr)
args = parsed.components.map((m, index) =>
if index == parsed.components.length - 1
m
else
interpret(m)
)
name = JSON.parse(args[args.length - 1])
result =
try
# Must enclose it by "()", otherwise object literals can't be evaluated.
# Note: Ideally a single "()" pair is enough, but Safari has a strange bug
# that makes `eval("(-0)")` return +0. So we must use "(())" to workaround it.
args = args.map((m) => eval("((#{m}))"))
@["_check_" + parsed.type](args...)
catch
type: false
name: PI:NAME:<NAME>END_PI
actual: "unknown"
expected: "unknown"
@wishResults.push(result)
wish: (wishesStr) ->
wishlist.parseWishes(wishesStr).forEach((wishStr) =>
@_checkWish(wishStr)
)
|
[
{
"context": " User\n\tconstructor: (options = {}) ->\n\t\t@email = \"acceptance-test-#{count}@example.com\"\n\t\t@password = \"acceptance-test-#{count}-password",
"end": 246,
"score": 0.9998282790184021,
"start": 210,
"tag": "EMAIL",
"value": "acceptance-test-#{count}@example.com"
},
{
... | test/acceptance/coffee/helpers/User.coffee | watercrossing/web-sharelatex | 0 | request = require("./request")
settings = require("settings-sharelatex")
{db, ObjectId} = require("../../../../app/js/infrastructure/mongojs")
count = 0
class User
constructor: (options = {}) ->
@email = "acceptance-test-#{count}@example.com"
@password = "acceptance-test-#{count}-password"
count++
@jar = request.jar()
@request = request.defaults({
jar: @jar
})
login: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.post {
url: "/register" # Register will log in, but also ensure user exists
json:
email: @email
password: @password
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
@id = user?._id?.toString()
@_id = user?._id?.toString()
@first_name = user?.first_name
@referal_id = user?.referal_id
callback()
logout: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.get {
url: "/logout"
json:
email: @email
password: @password
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
@id = user?._id?.toString()
@_id = user?._id?.toString()
callback()
ensure_admin: (callback = (error) ->) ->
db.users.update {_id: ObjectId(@id)}, { $set: { isAdmin: true }}, callback
createProject: (name, callback = (error, project_id) ->) ->
@request.post {
url: "/project/new",
json:
projectName: name
}, (error, response, body) ->
return callback(error) if error?
if !body?.project_id?
console.error "SOMETHING WENT WRONG CREATING PROJECT", response.statusCode, response.headers["location"], body
callback(null, body.project_id)
deleteProject: (project_id, callback=(error)) ->
@request.delete {
url: "/project/#{project_id}"
}, (error, response, body) ->
return callback(error) if error?
callback(null)
openProject: (project_id, callback=(error)) ->
@request.get {
url: "/project/#{project_id}"
}, (error, response, body) ->
return callback(error) if error?
if response.statusCode != 200
err = new Error("Non-success response when opening project: #{response.statusCode}")
return callback(err)
callback(null)
addUserToProject: (project_id, email, privileges, callback = (error, user) ->) ->
@request.post {
url: "/project/#{project_id}/users",
json: {email, privileges}
}, (error, response, body) ->
return callback(error) if error?
callback(null, body.user)
makePublic: (project_id, level, callback = (error) ->) ->
@request.post {
url: "/project/#{project_id}/settings/admin",
json:
publicAccessLevel: level
}, (error, response, body) ->
return callback(error) if error?
callback(null)
getCsrfToken: (callback = (error) ->) ->
@request.get {
url: "/register"
}, (err, response, body) =>
return callback(error) if error?
csrfMatches = body.match("window.csrfToken = \"(.*?)\";")
if !csrfMatches?
return callback(new Error("no csrf token found"))
@request = @request.defaults({
headers:
"x-csrf-token": csrfMatches[1]
})
callback()
changePassword: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.post {
url: "/user/password/update"
json:
currentPassword: @password
newPassword1: @password
newPassword2: @password
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
callback()
getUserSettingsPage: (callback = (error, statusCode) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.get {
url: "/user/settings"
}, (error, response, body) =>
return callback(error) if error?
callback(null, response.statusCode)
module.exports = User
| 195669 | request = require("./request")
settings = require("settings-sharelatex")
{db, ObjectId} = require("../../../../app/js/infrastructure/mongojs")
count = 0
class User
constructor: (options = {}) ->
@email = "<EMAIL>"
@password = "<PASSWORD>"
count++
@jar = request.jar()
@request = request.defaults({
jar: @jar
})
login: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.post {
url: "/register" # Register will log in, but also ensure user exists
json:
email: @email
password: <PASSWORD>
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
@id = user?._id?.toString()
@_id = user?._id?.toString()
@first_name = user?.first_name
@referal_id = user?.referal_id
callback()
logout: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.get {
url: "/logout"
json:
email: @email
password: <PASSWORD>
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
@id = user?._id?.toString()
@_id = user?._id?.toString()
callback()
ensure_admin: (callback = (error) ->) ->
db.users.update {_id: ObjectId(@id)}, { $set: { isAdmin: true }}, callback
createProject: (name, callback = (error, project_id) ->) ->
@request.post {
url: "/project/new",
json:
projectName: name
}, (error, response, body) ->
return callback(error) if error?
if !body?.project_id?
console.error "SOMETHING WENT WRONG CREATING PROJECT", response.statusCode, response.headers["location"], body
callback(null, body.project_id)
deleteProject: (project_id, callback=(error)) ->
@request.delete {
url: "/project/#{project_id}"
}, (error, response, body) ->
return callback(error) if error?
callback(null)
openProject: (project_id, callback=(error)) ->
@request.get {
url: "/project/#{project_id}"
}, (error, response, body) ->
return callback(error) if error?
if response.statusCode != 200
err = new Error("Non-success response when opening project: #{response.statusCode}")
return callback(err)
callback(null)
addUserToProject: (project_id, email, privileges, callback = (error, user) ->) ->
@request.post {
url: "/project/#{project_id}/users",
json: {email, privileges}
}, (error, response, body) ->
return callback(error) if error?
callback(null, body.user)
makePublic: (project_id, level, callback = (error) ->) ->
@request.post {
url: "/project/#{project_id}/settings/admin",
json:
publicAccessLevel: level
}, (error, response, body) ->
return callback(error) if error?
callback(null)
getCsrfToken: (callback = (error) ->) ->
@request.get {
url: "/register"
}, (err, response, body) =>
return callback(error) if error?
csrfMatches = body.match("window.csrfToken = \"(.*?)\";")
if !csrfMatches?
return callback(new Error("no csrf token found"))
@request = @request.defaults({
headers:
"x-csrf-token": csrfMatches[1]
})
callback()
changePassword: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.post {
url: "/user/password/update"
json:
currentPassword: <PASSWORD>
newPassword1: <PASSWORD>
newPassword2: <PASSWORD>
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
callback()
getUserSettingsPage: (callback = (error, statusCode) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.get {
url: "/user/settings"
}, (error, response, body) =>
return callback(error) if error?
callback(null, response.statusCode)
module.exports = User
| true | request = require("./request")
settings = require("settings-sharelatex")
{db, ObjectId} = require("../../../../app/js/infrastructure/mongojs")
count = 0
class User
constructor: (options = {}) ->
@email = "PI:EMAIL:<EMAIL>END_PI"
@password = "PI:PASSWORD:<PASSWORD>END_PI"
count++
@jar = request.jar()
@request = request.defaults({
jar: @jar
})
login: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.post {
url: "/register" # Register will log in, but also ensure user exists
json:
email: @email
password: PI:PASSWORD:<PASSWORD>END_PI
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
@id = user?._id?.toString()
@_id = user?._id?.toString()
@first_name = user?.first_name
@referal_id = user?.referal_id
callback()
logout: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.get {
url: "/logout"
json:
email: @email
password: PI:PASSWORD:<PASSWORD>END_PI
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
@id = user?._id?.toString()
@_id = user?._id?.toString()
callback()
ensure_admin: (callback = (error) ->) ->
db.users.update {_id: ObjectId(@id)}, { $set: { isAdmin: true }}, callback
createProject: (name, callback = (error, project_id) ->) ->
@request.post {
url: "/project/new",
json:
projectName: name
}, (error, response, body) ->
return callback(error) if error?
if !body?.project_id?
console.error "SOMETHING WENT WRONG CREATING PROJECT", response.statusCode, response.headers["location"], body
callback(null, body.project_id)
deleteProject: (project_id, callback=(error)) ->
@request.delete {
url: "/project/#{project_id}"
}, (error, response, body) ->
return callback(error) if error?
callback(null)
openProject: (project_id, callback=(error)) ->
@request.get {
url: "/project/#{project_id}"
}, (error, response, body) ->
return callback(error) if error?
if response.statusCode != 200
err = new Error("Non-success response when opening project: #{response.statusCode}")
return callback(err)
callback(null)
addUserToProject: (project_id, email, privileges, callback = (error, user) ->) ->
@request.post {
url: "/project/#{project_id}/users",
json: {email, privileges}
}, (error, response, body) ->
return callback(error) if error?
callback(null, body.user)
makePublic: (project_id, level, callback = (error) ->) ->
@request.post {
url: "/project/#{project_id}/settings/admin",
json:
publicAccessLevel: level
}, (error, response, body) ->
return callback(error) if error?
callback(null)
getCsrfToken: (callback = (error) ->) ->
@request.get {
url: "/register"
}, (err, response, body) =>
return callback(error) if error?
csrfMatches = body.match("window.csrfToken = \"(.*?)\";")
if !csrfMatches?
return callback(new Error("no csrf token found"))
@request = @request.defaults({
headers:
"x-csrf-token": csrfMatches[1]
})
callback()
changePassword: (callback = (error) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.post {
url: "/user/password/update"
json:
currentPassword: PI:PASSWORD:<PASSWORD>END_PI
newPassword1: PI:PASSWORD:<PASSWORD>END_PI
newPassword2: PI:PASSWORD:<PASSWORD>END_PI
}, (error, response, body) =>
return callback(error) if error?
db.users.findOne {email: @email}, (error, user) =>
return callback(error) if error?
callback()
getUserSettingsPage: (callback = (error, statusCode) ->) ->
@getCsrfToken (error) =>
return callback(error) if error?
@request.get {
url: "/user/settings"
}, (error, response, body) =>
return callback(error) if error?
callback(null, response.statusCode)
module.exports = User
|
[
{
"context": "# turn on stats\n\n model = new kb.Model({name: 'Bob'})\n instance = {}\n assert.equal(kb.utils.wr",
"end": 1011,
"score": 0.9989756345748901,
"start": 1008,
"tag": "NAME",
"value": "Bob"
},
{
"context": " view_model = kb.viewModel(new kb.Model({name: 'Bob'})... | test/spec/core/utils.tests.coffee | metacommunications/knockback | 160 | assert = assert or require?('chai').assert
describe 'knockback_core utils @quick @utils', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
done()
it 'kb.utils.wrappedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
observable = ko.observable()
instance = {}
kb.utils.wrappedObservable(instance, observable) # set
assert.equal(kb.utils.wrappedObservable(instance), observable, "observable was wrapped") # get
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.wrappedModel', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model({name: 'Bob'})
instance = {}
assert.equal(kb.utils.wrappedModel(instance), instance, "no model was wrapped so return the instance") # get
kb.utils.wrappedModel(instance, model) # set
assert.equal(kb.utils.wrappedModel(instance), model, "model was wrapped") # get
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.wrappedStore', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable(new kb.Collection())
assert.ok(!!kb.utils.wrappedStore(collection_observable), 'Store is available on a collection observable')
# can get and share store
collection_observable_shared = kb.collectionObservable(new kb.Collection(), {store: kb.utils.wrappedStore(collection_observable)})
assert.equal(kb.utils.wrappedStore(collection_observable), kb.utils.wrappedStore(collection_observable_shared), 'Store is shared between collection observables')
kb.release(collection_observable_shared) # clean up
view_model = kb.viewModel(new kb.Model({name: 'Bob'}))
assert.ok(!!kb.utils.wrappedStore(view_model), 'Store is available on a view model')
# can get and share store
collection_observable_shared = kb.collectionObservable(new kb.Collection(), {store: kb.utils.wrappedStore(view_model)})
assert.equal(kb.utils.wrappedStore(view_model), kb.utils.wrappedStore(collection_observable_shared), 'Store is shared between collection observable and view model')
# clean up
kb.release(collection_observable)
kb.release(collection_observable_shared)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.valueType', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
co = kb.collectionObservable(new kb.Collection())
assert.equal(kb.utils.valueType(co), kb.TYPE_COLLECTION, "kb.CollectionObservable is a collection type")
kb.release(co) # clean up
o = kb.observable(new kb.Model({name: 'name1'}), 'name')
assert.equal(kb.utils.valueType(o), kb.TYPE_SIMPLE, "kb.Observable is a kb.TYPE_SIMPLE")
kb.release(o) # clean up
model = new kb.Model({simple_type: 3, model_type: new kb.Model(), collection_type: new kb.Collection()})
view_model = kb.viewModel(model)
assert.equal(kb.utils.valueType(view_model.simple_type), kb.TYPE_SIMPLE, "simple is kb.TYPE_SIMPLE")
assert.equal(kb.utils.valueType(view_model.model_type), kb.TYPE_MODEL, "model is kb.TYPE_MODEL")
assert.equal(kb.utils.valueType(view_model.collection_type), kb.TYPE_COLLECTION, "collection is kb.TYPE_COLLECTION")
kb.release(view_model) # clean up
view_model = kb.viewModel(new kb.Model({simple_attr: null, model_attr: null}), {factories: model_attr: kb.ViewModel})
assert.equal(kb.utils.valueType(view_model.simple_attr), kb.TYPE_SIMPLE, 'simple_attr is kb.TYPE_SIMPLE')
assert.equal(kb.utils.valueType(view_model.model_attr), kb.TYPE_MODEL, 'model_attr is kb.TYPE_MODEL')
kb.release(view_model) # clean up
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.path', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
assert.equal(kb.utils.pathJoin(null, 'key'), 'key', "key path joined")
assert.equal(kb.utils.pathJoin('bob', 'key'), 'bob.key', "bob.key path joined")
assert.equal(kb.utils.pathJoin('bob.', 'key'), 'bob.key', "bob.key path joined")
assert.equal(kb.utils.pathJoin('bob.harry', 'key'), 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.pathJoin('bob.harry.', 'key'), 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.optionsPathJoin({}, 'key').path, 'key', "key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob'}, 'key').path, 'bob.key', "bob.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.'}, 'key').path, 'bob.key', "bob.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.harry'}, 'key').path, 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.harry.'}, 'key').path, 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/103
it 'kb.release handling type changes', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model()
model.set({foo: [1,2,3]})
observable = kb.viewModel(model)
model.set({foo: null})
kb.release(observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/101
it 'kb.release releases all events', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model({id: 1, name: "Zebra", age: 22, genus: "Equus"});
assert.ok(kb.Statistics.eventsStats(model).count is 0, 'No events yet')
view_model = {model: kb.viewModel(model)}
assert.ok(kb.Statistics.eventsStats(model).count is 1, "There is 1 event. Expected: 1. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
kb.release(view_model)
assert.ok(kb.Statistics.eventsStats(model).count is 0, "All events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| 132850 | assert = assert or require?('chai').assert
describe 'knockback_core utils @quick @utils', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
done()
it 'kb.utils.wrappedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
observable = ko.observable()
instance = {}
kb.utils.wrappedObservable(instance, observable) # set
assert.equal(kb.utils.wrappedObservable(instance), observable, "observable was wrapped") # get
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.wrappedModel', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model({name: '<NAME>'})
instance = {}
assert.equal(kb.utils.wrappedModel(instance), instance, "no model was wrapped so return the instance") # get
kb.utils.wrappedModel(instance, model) # set
assert.equal(kb.utils.wrappedModel(instance), model, "model was wrapped") # get
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.wrappedStore', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable(new kb.Collection())
assert.ok(!!kb.utils.wrappedStore(collection_observable), 'Store is available on a collection observable')
# can get and share store
collection_observable_shared = kb.collectionObservable(new kb.Collection(), {store: kb.utils.wrappedStore(collection_observable)})
assert.equal(kb.utils.wrappedStore(collection_observable), kb.utils.wrappedStore(collection_observable_shared), 'Store is shared between collection observables')
kb.release(collection_observable_shared) # clean up
view_model = kb.viewModel(new kb.Model({name: '<NAME>'}))
assert.ok(!!kb.utils.wrappedStore(view_model), 'Store is available on a view model')
# can get and share store
collection_observable_shared = kb.collectionObservable(new kb.Collection(), {store: kb.utils.wrappedStore(view_model)})
assert.equal(kb.utils.wrappedStore(view_model), kb.utils.wrappedStore(collection_observable_shared), 'Store is shared between collection observable and view model')
# clean up
kb.release(collection_observable)
kb.release(collection_observable_shared)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.valueType', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
co = kb.collectionObservable(new kb.Collection())
assert.equal(kb.utils.valueType(co), kb.TYPE_COLLECTION, "kb.CollectionObservable is a collection type")
kb.release(co) # clean up
o = kb.observable(new kb.Model({name: 'name1'}), 'name')
assert.equal(kb.utils.valueType(o), kb.TYPE_SIMPLE, "kb.Observable is a kb.TYPE_SIMPLE")
kb.release(o) # clean up
model = new kb.Model({simple_type: 3, model_type: new kb.Model(), collection_type: new kb.Collection()})
view_model = kb.viewModel(model)
assert.equal(kb.utils.valueType(view_model.simple_type), kb.TYPE_SIMPLE, "simple is kb.TYPE_SIMPLE")
assert.equal(kb.utils.valueType(view_model.model_type), kb.TYPE_MODEL, "model is kb.TYPE_MODEL")
assert.equal(kb.utils.valueType(view_model.collection_type), kb.TYPE_COLLECTION, "collection is kb.TYPE_COLLECTION")
kb.release(view_model) # clean up
view_model = kb.viewModel(new kb.Model({simple_attr: null, model_attr: null}), {factories: model_attr: kb.ViewModel})
assert.equal(kb.utils.valueType(view_model.simple_attr), kb.TYPE_SIMPLE, 'simple_attr is kb.TYPE_SIMPLE')
assert.equal(kb.utils.valueType(view_model.model_attr), kb.TYPE_MODEL, 'model_attr is kb.TYPE_MODEL')
kb.release(view_model) # clean up
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.path', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
assert.equal(kb.utils.pathJoin(null, 'key'), 'key', "key path joined")
assert.equal(kb.utils.pathJoin('bob', 'key'), 'bob.key', "bob.key path joined")
assert.equal(kb.utils.pathJoin('bob.', 'key'), 'bob.key', "bob.key path joined")
assert.equal(kb.utils.pathJoin('bob.harry', 'key'), 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.pathJoin('bob.harry.', 'key'), 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.optionsPathJoin({}, 'key').path, 'key', "key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob'}, 'key').path, 'bob.key', "bob.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.'}, 'key').path, 'bob.key', "bob.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.harry'}, 'key').path, 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.harry.'}, 'key').path, 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/103
it 'kb.release handling type changes', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model()
model.set({foo: [1,2,3]})
observable = kb.viewModel(model)
model.set({foo: null})
kb.release(observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/101
it 'kb.release releases all events', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model({id: 1, name: "<NAME>", age: 22, genus: "Equus"});
assert.ok(kb.Statistics.eventsStats(model).count is 0, 'No events yet')
view_model = {model: kb.viewModel(model)}
assert.ok(kb.Statistics.eventsStats(model).count is 1, "There is 1 event. Expected: 1. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
kb.release(view_model)
assert.ok(kb.Statistics.eventsStats(model).count is 0, "All events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| true | assert = assert or require?('chai').assert
describe 'knockback_core utils @quick @utils', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
done()
it 'kb.utils.wrappedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
observable = ko.observable()
instance = {}
kb.utils.wrappedObservable(instance, observable) # set
assert.equal(kb.utils.wrappedObservable(instance), observable, "observable was wrapped") # get
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.wrappedModel', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model({name: 'PI:NAME:<NAME>END_PI'})
instance = {}
assert.equal(kb.utils.wrappedModel(instance), instance, "no model was wrapped so return the instance") # get
kb.utils.wrappedModel(instance, model) # set
assert.equal(kb.utils.wrappedModel(instance), model, "model was wrapped") # get
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.wrappedStore', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable(new kb.Collection())
assert.ok(!!kb.utils.wrappedStore(collection_observable), 'Store is available on a collection observable')
# can get and share store
collection_observable_shared = kb.collectionObservable(new kb.Collection(), {store: kb.utils.wrappedStore(collection_observable)})
assert.equal(kb.utils.wrappedStore(collection_observable), kb.utils.wrappedStore(collection_observable_shared), 'Store is shared between collection observables')
kb.release(collection_observable_shared) # clean up
view_model = kb.viewModel(new kb.Model({name: 'PI:NAME:<NAME>END_PI'}))
assert.ok(!!kb.utils.wrappedStore(view_model), 'Store is available on a view model')
# can get and share store
collection_observable_shared = kb.collectionObservable(new kb.Collection(), {store: kb.utils.wrappedStore(view_model)})
assert.equal(kb.utils.wrappedStore(view_model), kb.utils.wrappedStore(collection_observable_shared), 'Store is shared between collection observable and view model')
# clean up
kb.release(collection_observable)
kb.release(collection_observable_shared)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.valueType', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
co = kb.collectionObservable(new kb.Collection())
assert.equal(kb.utils.valueType(co), kb.TYPE_COLLECTION, "kb.CollectionObservable is a collection type")
kb.release(co) # clean up
o = kb.observable(new kb.Model({name: 'name1'}), 'name')
assert.equal(kb.utils.valueType(o), kb.TYPE_SIMPLE, "kb.Observable is a kb.TYPE_SIMPLE")
kb.release(o) # clean up
model = new kb.Model({simple_type: 3, model_type: new kb.Model(), collection_type: new kb.Collection()})
view_model = kb.viewModel(model)
assert.equal(kb.utils.valueType(view_model.simple_type), kb.TYPE_SIMPLE, "simple is kb.TYPE_SIMPLE")
assert.equal(kb.utils.valueType(view_model.model_type), kb.TYPE_MODEL, "model is kb.TYPE_MODEL")
assert.equal(kb.utils.valueType(view_model.collection_type), kb.TYPE_COLLECTION, "collection is kb.TYPE_COLLECTION")
kb.release(view_model) # clean up
view_model = kb.viewModel(new kb.Model({simple_attr: null, model_attr: null}), {factories: model_attr: kb.ViewModel})
assert.equal(kb.utils.valueType(view_model.simple_attr), kb.TYPE_SIMPLE, 'simple_attr is kb.TYPE_SIMPLE')
assert.equal(kb.utils.valueType(view_model.model_attr), kb.TYPE_MODEL, 'model_attr is kb.TYPE_MODEL')
kb.release(view_model) # clean up
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.utils.path', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
assert.equal(kb.utils.pathJoin(null, 'key'), 'key', "key path joined")
assert.equal(kb.utils.pathJoin('bob', 'key'), 'bob.key', "bob.key path joined")
assert.equal(kb.utils.pathJoin('bob.', 'key'), 'bob.key', "bob.key path joined")
assert.equal(kb.utils.pathJoin('bob.harry', 'key'), 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.pathJoin('bob.harry.', 'key'), 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.optionsPathJoin({}, 'key').path, 'key', "key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob'}, 'key').path, 'bob.key', "bob.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.'}, 'key').path, 'bob.key', "bob.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.harry'}, 'key').path, 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.utils.optionsPathJoin({path: 'bob.harry.'}, 'key').path, 'bob.harry.key', "bob.harry.key path joined")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/103
it 'kb.release handling type changes', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model()
model.set({foo: [1,2,3]})
observable = kb.viewModel(model)
model.set({foo: null})
kb.release(observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/101
it 'kb.release releases all events', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new kb.Model({id: 1, name: "PI:NAME:<NAME>END_PI", age: 22, genus: "Equus"});
assert.ok(kb.Statistics.eventsStats(model).count is 0, 'No events yet')
view_model = {model: kb.viewModel(model)}
assert.ok(kb.Statistics.eventsStats(model).count is 1, "There is 1 event. Expected: 1. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
kb.release(view_model)
assert.ok(kb.Statistics.eventsStats(model).count is 0, "All events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
|
[
{
"context": "{\n name: 'SingleBaron'\n requires: ['Baron']\n gainPriority: (state, my",
"end": 22,
"score": 0.9801579117774963,
"start": 11,
"tag": "NAME",
"value": "SingleBaron"
}
] | strategies/SingleBaron.coffee | rspeer/dominiate | 65 | {
name: 'SingleBaron'
requires: ['Baron']
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6
"Duchy" if state.gainsToEndGame() <= 5
"Estate" if state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Baron" if my.countInDeck("Baron") == 0
"Silver"
"Copper" if state.gainsToEndGame() <= 2
]
discardPriority: (state, my) -> [
"Colony"
"Province"
"Duchy"
"Curse"
"Estate" if my.countInHand("Baron") == 0 \
or my.countInHand("Estate") > 1
"Copper"
"Baron" if my.countInHand("Estate") == 0
null
"Silver"
"Estate"
"Baron"
]
}
| 127495 | {
name: '<NAME>'
requires: ['Baron']
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6
"Duchy" if state.gainsToEndGame() <= 5
"Estate" if state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Baron" if my.countInDeck("Baron") == 0
"Silver"
"Copper" if state.gainsToEndGame() <= 2
]
discardPriority: (state, my) -> [
"Colony"
"Province"
"Duchy"
"Curse"
"Estate" if my.countInHand("Baron") == 0 \
or my.countInHand("Estate") > 1
"Copper"
"Baron" if my.countInHand("Estate") == 0
null
"Silver"
"Estate"
"Baron"
]
}
| true | {
name: 'PI:NAME:<NAME>END_PI'
requires: ['Baron']
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6
"Duchy" if state.gainsToEndGame() <= 5
"Estate" if state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Baron" if my.countInDeck("Baron") == 0
"Silver"
"Copper" if state.gainsToEndGame() <= 2
]
discardPriority: (state, my) -> [
"Colony"
"Province"
"Duchy"
"Curse"
"Estate" if my.countInHand("Baron") == 0 \
or my.countInHand("Estate") > 1
"Copper"
"Baron" if my.countInHand("Estate") == 0
null
"Silver"
"Estate"
"Baron"
]
}
|
[
{
"context": "Rest rsmq\n\nThe MIT License (MIT)\n\nCopyright © 2013 Patrick Liess, http://www.tcs.de\n\nPermission is hereby granted,",
"end": 68,
"score": 0.9997957348823547,
"start": 55,
"tag": "NAME",
"value": "Patrick Liess"
}
] | app.coffee | floleuerer/rest-rsmq | 45 | ###
Rest rsmq
The MIT License (MIT)
Copyright © 2013 Patrick Liess, http://www.tcs.de
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.
###
RSMQ = require "rsmq"
rsmq = new RSMQ()
express = require 'express'
app = express()
app.use (req, res, next) ->
res.header('Content-Type', "application/json")
res.removeHeader("X-Powered-By")
next()
return
app.configure ->
app.use( express.logger("dev") )
app.use(express.bodyParser())
return
app.get '/queues', (req, res) ->
rsmq.listQueues (err, resp) ->
if err
res.send(err, 500)
return
res.send({queues: resp})
return
app.get '/queues/:qname', (req, res) ->
rsmq.getQueueAttributes {qname: req.params.qname}, (err, resp) ->
if err
res.send(err, 500)
return
res.send(resp)
return
app.post '/queues/:qname', (req, res) ->
params = req.body
params.qname = req.params.qname
rsmq.createQueue params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
app.delete '/queues/:qname', (req, res) ->
rsmq.deleteQueue {qname: req.params.qname}, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
app.post '/messages/:qname', (req, res) ->
params = req.body
params.qname = req.params.qname
rsmq.sendMessage params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({id:resp})
return
return
app.get '/messages/:qname', (req, res) ->
rsmq.receiveMessage {qname: req.params.qname, vt: req.param("vt")}, (err, resp) ->
if err
res.send(err, 500)
return
res.send(resp)
return
return
app.put '/messages/:qname/:id', (req, res) ->
rsmq.changeMessageVisibility {qname: req.params.qname, id: req.params.id, vt: req.param("vt")}, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
app.delete '/messages/:qname/:id', (req, res) ->
rsmq.deleteMessage req.params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
module.exports = app
| 213663 | ###
Rest rsmq
The MIT License (MIT)
Copyright © 2013 <NAME>, http://www.tcs.de
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.
###
RSMQ = require "rsmq"
rsmq = new RSMQ()
express = require 'express'
app = express()
app.use (req, res, next) ->
res.header('Content-Type', "application/json")
res.removeHeader("X-Powered-By")
next()
return
app.configure ->
app.use( express.logger("dev") )
app.use(express.bodyParser())
return
app.get '/queues', (req, res) ->
rsmq.listQueues (err, resp) ->
if err
res.send(err, 500)
return
res.send({queues: resp})
return
app.get '/queues/:qname', (req, res) ->
rsmq.getQueueAttributes {qname: req.params.qname}, (err, resp) ->
if err
res.send(err, 500)
return
res.send(resp)
return
app.post '/queues/:qname', (req, res) ->
params = req.body
params.qname = req.params.qname
rsmq.createQueue params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
app.delete '/queues/:qname', (req, res) ->
rsmq.deleteQueue {qname: req.params.qname}, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
app.post '/messages/:qname', (req, res) ->
params = req.body
params.qname = req.params.qname
rsmq.sendMessage params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({id:resp})
return
return
app.get '/messages/:qname', (req, res) ->
rsmq.receiveMessage {qname: req.params.qname, vt: req.param("vt")}, (err, resp) ->
if err
res.send(err, 500)
return
res.send(resp)
return
return
app.put '/messages/:qname/:id', (req, res) ->
rsmq.changeMessageVisibility {qname: req.params.qname, id: req.params.id, vt: req.param("vt")}, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
app.delete '/messages/:qname/:id', (req, res) ->
rsmq.deleteMessage req.params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
module.exports = app
| true | ###
Rest rsmq
The MIT License (MIT)
Copyright © 2013 PI:NAME:<NAME>END_PI, http://www.tcs.de
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.
###
RSMQ = require "rsmq"
rsmq = new RSMQ()
express = require 'express'
app = express()
app.use (req, res, next) ->
res.header('Content-Type', "application/json")
res.removeHeader("X-Powered-By")
next()
return
app.configure ->
app.use( express.logger("dev") )
app.use(express.bodyParser())
return
app.get '/queues', (req, res) ->
rsmq.listQueues (err, resp) ->
if err
res.send(err, 500)
return
res.send({queues: resp})
return
app.get '/queues/:qname', (req, res) ->
rsmq.getQueueAttributes {qname: req.params.qname}, (err, resp) ->
if err
res.send(err, 500)
return
res.send(resp)
return
app.post '/queues/:qname', (req, res) ->
params = req.body
params.qname = req.params.qname
rsmq.createQueue params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
app.delete '/queues/:qname', (req, res) ->
rsmq.deleteQueue {qname: req.params.qname}, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
app.post '/messages/:qname', (req, res) ->
params = req.body
params.qname = req.params.qname
rsmq.sendMessage params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({id:resp})
return
return
app.get '/messages/:qname', (req, res) ->
rsmq.receiveMessage {qname: req.params.qname, vt: req.param("vt")}, (err, resp) ->
if err
res.send(err, 500)
return
res.send(resp)
return
return
app.put '/messages/:qname/:id', (req, res) ->
rsmq.changeMessageVisibility {qname: req.params.qname, id: req.params.id, vt: req.param("vt")}, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
app.delete '/messages/:qname/:id', (req, res) ->
rsmq.deleteMessage req.params, (err, resp) ->
if err
res.send(err, 500)
return
res.send({result:resp})
return
return
module.exports = app
|
[
{
"context": " : \"email\"\n \"#password\" : \"password\"\n \"#twitter_handle\" : \"twitter_handle\"\n ",
"end": 599,
"score": 0.999453067779541,
"start": 591,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " : \"password\"\n \"#twit... | frontend/app/modules/person/create/PersonCreate.coffee | ry-battuta/battuta-book | 0 | @App.module "PersonApp.New", (New, App, Backbone, Marionette, $, _) ->
Controller =
new: (region) ->
console.log("person:create called")
person = App.request("person:entities:create")
personView = new Person(
model: person
)
region.show personView
class Person extends Marionette.ItemView
template: require './templates/person'
events:
'click #save' : 'save',
bindings:
"#first_name" : "first_name"
"#last_name" : "last_name"
"#email" : "email"
"#password" : "password"
"#twitter_handle" : "twitter_handle"
"#avatar" : "avatar"
"#homebase" : "homebase"
"#profession" : "profession"
"#passions" : "passions"
"#skills" : "skills"
"#current_location" : "current_location"
"#blurb" : "blurb"
save: () =>
@model.save()
onRender: () =>
@stickit()
onDestroy: () =>
@unstickit()
App.reqres.setHandler "person:create", (region) -> Controller.new(region)
| 143684 | @App.module "PersonApp.New", (New, App, Backbone, Marionette, $, _) ->
Controller =
new: (region) ->
console.log("person:create called")
person = App.request("person:entities:create")
personView = new Person(
model: person
)
region.show personView
class Person extends Marionette.ItemView
template: require './templates/person'
events:
'click #save' : 'save',
bindings:
"#first_name" : "first_name"
"#last_name" : "last_name"
"#email" : "email"
"#password" : "<PASSWORD>"
"#twitter_handle" : "twitter_handle"
"#avatar" : "avatar"
"#homebase" : "homebase"
"#profession" : "profession"
"#passions" : "passions"
"#skills" : "skills"
"#current_location" : "current_location"
"#blurb" : "blurb"
save: () =>
@model.save()
onRender: () =>
@stickit()
onDestroy: () =>
@unstickit()
App.reqres.setHandler "person:create", (region) -> Controller.new(region)
| true | @App.module "PersonApp.New", (New, App, Backbone, Marionette, $, _) ->
Controller =
new: (region) ->
console.log("person:create called")
person = App.request("person:entities:create")
personView = new Person(
model: person
)
region.show personView
class Person extends Marionette.ItemView
template: require './templates/person'
events:
'click #save' : 'save',
bindings:
"#first_name" : "first_name"
"#last_name" : "last_name"
"#email" : "email"
"#password" : "PI:PASSWORD:<PASSWORD>END_PI"
"#twitter_handle" : "twitter_handle"
"#avatar" : "avatar"
"#homebase" : "homebase"
"#profession" : "profession"
"#passions" : "passions"
"#skills" : "skills"
"#current_location" : "current_location"
"#blurb" : "blurb"
save: () =>
@model.save()
onRender: () =>
@stickit()
onDestroy: () =>
@unstickit()
App.reqres.setHandler "person:create", (region) -> Controller.new(region)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9980575442314148,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-upgrade-client2.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
CRLF = "\r\n"
server = http.createServer()
server.on "upgrade", (req, socket, head) ->
socket.write "HTTP/1.1 101 Ok" + CRLF + "Connection: Upgrade" + CRLF + "Upgrade: Test" + CRLF + CRLF + "head"
socket.on "end", ->
socket.end()
return
return
successCount = 0
server.listen common.PORT, ->
upgradeRequest = (fn) ->
onUpgrade = (res, socket, head) ->
console.log "client upgraded"
wasUpgrade = true
request.removeListener "upgrade", onUpgrade
socket.end()
return
onEnd = ->
console.log "client end"
request.removeListener "end", onEnd
unless wasUpgrade
throw new Error("hasn't received upgrade event")
else
fn and process.nextTick(fn)
return
console.log "req"
header =
Connection: "Upgrade"
Upgrade: "Test"
request = http.request(
port: common.PORT
headers: header
)
wasUpgrade = false
request.on "upgrade", onUpgrade
request.on "close", onEnd
request.write "head"
return
upgradeRequest ->
successCount++
upgradeRequest ->
successCount++
# Test pass
console.log "Pass!"
server.close()
return
return
return
process.on "exit", ->
assert.equal 2, successCount
return
| 25739 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
CRLF = "\r\n"
server = http.createServer()
server.on "upgrade", (req, socket, head) ->
socket.write "HTTP/1.1 101 Ok" + CRLF + "Connection: Upgrade" + CRLF + "Upgrade: Test" + CRLF + CRLF + "head"
socket.on "end", ->
socket.end()
return
return
successCount = 0
server.listen common.PORT, ->
upgradeRequest = (fn) ->
onUpgrade = (res, socket, head) ->
console.log "client upgraded"
wasUpgrade = true
request.removeListener "upgrade", onUpgrade
socket.end()
return
onEnd = ->
console.log "client end"
request.removeListener "end", onEnd
unless wasUpgrade
throw new Error("hasn't received upgrade event")
else
fn and process.nextTick(fn)
return
console.log "req"
header =
Connection: "Upgrade"
Upgrade: "Test"
request = http.request(
port: common.PORT
headers: header
)
wasUpgrade = false
request.on "upgrade", onUpgrade
request.on "close", onEnd
request.write "head"
return
upgradeRequest ->
successCount++
upgradeRequest ->
successCount++
# Test pass
console.log "Pass!"
server.close()
return
return
return
process.on "exit", ->
assert.equal 2, successCount
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
CRLF = "\r\n"
server = http.createServer()
server.on "upgrade", (req, socket, head) ->
socket.write "HTTP/1.1 101 Ok" + CRLF + "Connection: Upgrade" + CRLF + "Upgrade: Test" + CRLF + CRLF + "head"
socket.on "end", ->
socket.end()
return
return
successCount = 0
server.listen common.PORT, ->
upgradeRequest = (fn) ->
onUpgrade = (res, socket, head) ->
console.log "client upgraded"
wasUpgrade = true
request.removeListener "upgrade", onUpgrade
socket.end()
return
onEnd = ->
console.log "client end"
request.removeListener "end", onEnd
unless wasUpgrade
throw new Error("hasn't received upgrade event")
else
fn and process.nextTick(fn)
return
console.log "req"
header =
Connection: "Upgrade"
Upgrade: "Test"
request = http.request(
port: common.PORT
headers: header
)
wasUpgrade = false
request.on "upgrade", onUpgrade
request.on "close", onEnd
request.write "head"
return
upgradeRequest ->
successCount++
upgradeRequest ->
successCount++
# Test pass
console.log "Pass!"
server.close()
return
return
return
process.on "exit", ->
assert.equal 2, successCount
return
|
[
{
"context": "spired net server echo server example\n#\n# (C) 2011 Tristan Slominski\n#\nanode = require '../lib/anode'\n\n# create a new ",
"end": 110,
"score": 0.9997758269309998,
"start": 93,
"tag": "NAME",
"value": "Tristan Slominski"
}
] | examples/echoserver.example.coffee | tristanls/anodejs | 3 | #
# echoserver.example.coffee : Node.js inspired net server echo server example
#
# (C) 2011 Tristan Slominski
#
anode = require '../lib/anode'
# create a new actor configuration
cnf = new anode.Configuration debug : true
# create the net actor
netServer = cnf.actor 'netServer', anode.net.server_beh()
# create the echo server application actor
echoServer = cnf.actor 'echoServer', anode.beh( 'netServer'
'#start' : ->
@send( @, '#listen', 8124 ).to @netServer
'$netServer, #listen' : ->
@send( 'server bound' ).to cnf.console.log
'$netServer, #connection, socket' : ->
@send( 'server connected' ).to cnf.console.log
# request ack after #write completes by including self (@)
@send( @, '#write', 'hello\r\n' ).to @socket
'socket, #end' : ->
@send( 'server disconnected' ).to cnf.console.log
# once socket gives us its socket object
'socket, #socket, socketObj' : ->
# pipe the socket to itself to echo
@send( null, '#pipe', @socketObj ).to @socket
# write ack
'socket, #write, _' : ->
# request the actual socket object so we can pipe to it
@send( @, '#socket' ).to @socket
)( netServer ) # echoServer
cnf.send( '#start' ).to echoServer | 143146 | #
# echoserver.example.coffee : Node.js inspired net server echo server example
#
# (C) 2011 <NAME>
#
anode = require '../lib/anode'
# create a new actor configuration
cnf = new anode.Configuration debug : true
# create the net actor
netServer = cnf.actor 'netServer', anode.net.server_beh()
# create the echo server application actor
echoServer = cnf.actor 'echoServer', anode.beh( 'netServer'
'#start' : ->
@send( @, '#listen', 8124 ).to @netServer
'$netServer, #listen' : ->
@send( 'server bound' ).to cnf.console.log
'$netServer, #connection, socket' : ->
@send( 'server connected' ).to cnf.console.log
# request ack after #write completes by including self (@)
@send( @, '#write', 'hello\r\n' ).to @socket
'socket, #end' : ->
@send( 'server disconnected' ).to cnf.console.log
# once socket gives us its socket object
'socket, #socket, socketObj' : ->
# pipe the socket to itself to echo
@send( null, '#pipe', @socketObj ).to @socket
# write ack
'socket, #write, _' : ->
# request the actual socket object so we can pipe to it
@send( @, '#socket' ).to @socket
)( netServer ) # echoServer
cnf.send( '#start' ).to echoServer | true | #
# echoserver.example.coffee : Node.js inspired net server echo server example
#
# (C) 2011 PI:NAME:<NAME>END_PI
#
anode = require '../lib/anode'
# create a new actor configuration
cnf = new anode.Configuration debug : true
# create the net actor
netServer = cnf.actor 'netServer', anode.net.server_beh()
# create the echo server application actor
echoServer = cnf.actor 'echoServer', anode.beh( 'netServer'
'#start' : ->
@send( @, '#listen', 8124 ).to @netServer
'$netServer, #listen' : ->
@send( 'server bound' ).to cnf.console.log
'$netServer, #connection, socket' : ->
@send( 'server connected' ).to cnf.console.log
# request ack after #write completes by including self (@)
@send( @, '#write', 'hello\r\n' ).to @socket
'socket, #end' : ->
@send( 'server disconnected' ).to cnf.console.log
# once socket gives us its socket object
'socket, #socket, socketObj' : ->
# pipe the socket to itself to echo
@send( null, '#pipe', @socketObj ).to @socket
# write ack
'socket, #write, _' : ->
# request the actual socket object so we can pipe to it
@send( @, '#socket' ).to @socket
)( netServer ) # echoServer
cnf.send( '#start' ).to echoServer |
[
{
"context": "tion module unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\nTest.set \"/n",
"end": 86,
"score": 0.9998843669891357,
"start": 69,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/dom/test/element/navigation_test.coffee | lovely-io/lovely.io-stl | 2 | #
# Element navigation module unit tests
#
# Copyright (C) 2011-2013 Nikolay Nemshilov
#
{Test,should} = require('lovely')
Test.set "/navigation.html", """
<html>
<head>
<script src="/core.js"></script>
<script src="/dom.js"></script>
</head>
<body>
<div id="one">
<div class="one">#one .one</div>
<div class="two">#one .two</div>
</div>
<div id="two">
<div class="one">#two .one</div>
<div class="two">#two .two</div>
</div>
<div id="three">
<div class="one">#three .one</div>
<div class="two">#three .two</div>
<div class="three">#three .three</div>
</div>
</body>
</html>
"""
describe "Element Navigation", ->
$ = window = document = element = null
get = (css_rule)->
before Test.load "/navigation.html", (dom, win)->
$ = dom
window = win
document = win.document
element = new $.Element(window.document.querySelector(css_rule))
describe "#match('css_rule')", ->
element = get('#one .one')
it "should say 'true' if it match the rule", ->
element.match('#one .one').should.be.true
it "should say 'false' if it doesn't match the rule", ->
element.match('#one .two').should.be.false
describe "#find('css_rule')", ->
element = get('#one')
it "should search in the element", ->
search = element.find('.one')
search.should.be.instanceOf $.NodeList
search.should.have.length 1
search[0].should.be.instanceOf $.Element
search[0]._.should.equal document.querySelector('#one .one')
it "should return an empty list if nothing found", ->
search = element.find('.non-existing')
search.should.be.instanceOf $.NodeList
search.should.have.length 0
it "should allow a raw DOM elements search", ->
search = element.find('.one, .two', true)
search.should.not.be.instanceOf $.NodeList
search.should.have.length 2
search[0].should.equal document.querySelector('#one .one')
search[1].should.equal document.querySelector('#one .two')
describe "#first('css_rule')", ->
element = get('#one')
it "should find the first matching element", ->
first = element.first('.two')
first.should.be.instanceOf $.Element
first._.should.equal document.querySelector('#one .two')
it "should find the very first element when called without a css-rule", ->
first = element.first()
first.should.be.instanceOf $.Element
first._.should.equal document.querySelector('#one .one')
describe "#parent('css-rule')", ->
element = get('#one .one')
it "should return the first parent when called without a css-rule", ->
parent = element.parent()
parent.should.be.instanceOf $.Element
parent._.should.equal document.querySelector('#one')
it "should return the first matching parent when called with a css-rule", ->
parent = element.parent('body')
parent.should.be.instanceOf $.Element
parent._.should.equal document.body
describe "#parents('css-rule')", ->
element = get('#one .one')
it "should return the list of all parents when called with a css-rule", ->
parents = element.parents()
parents.should.be.instanceOf $.NodeList
parents.should.have.length 3
parents[0]._.should.equal document.querySelector('#one')
parents[1]._.should.equal document.body
parents[2]._.should.equal document.documentElement
it "should filter the list by a given css-rule", ->
parents = element.parents('body')
parents.should.be.instanceOf $.NodeList
parents.should.have.length 1
parents[0]._.should.equal document.body
describe "#children('css_rule')", ->
element = get('#one')
it "should return all child elements when called without a css-rule", ->
result = element.children()
result.should.be.instanceOf $.NodeList
result.should.have.length 2
result[0].should.be.instanceOf $.Element
result[1].should.be.instanceOf $.Element
result[0]._.should.equal document.querySelector('#one .one')
result[1]._.should.equal document.querySelector('#one .two')
it "should filter the result by the css-rule", ->
result = element.children('.one')
result.should.have.length 1
result[0]._.should.equal document.querySelector('#one .one')
describe "#siblings('css-rule')", ->
element = get('#three .two')
it "should return the list of all siblings when called without a css-rule", ->
siblings = element.siblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .one')
siblings[1]._.should.equal document.querySelector('#three .three')
it "should return the list of matching siblings only when called with a css-rule", ->
siblings = element.siblings('.one')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .one')
describe "#nextSiblings('css-rule')", ->
element = get('#three .one')
it "should return a list of all the next siblings when called without a css-rule", ->
siblings = element.nextSiblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
siblings[1]._.should.equal document.querySelector('#three .three')
it "should return only matching siblings when called with a css-rule", ->
siblings = element.nextSiblings('.two')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
describe "#previousSiblings('css-rule')", ->
element = get('#three .three')
it "should return a list of all the next siblings when called without a css-rule", ->
siblings = element.previousSiblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
siblings[1]._.should.equal document.querySelector('#three .one')
it "should return only matching siblings when called with a css-rule", ->
siblings = element.previousSiblings('.two')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
describe "#nextSibling('css-rule')", ->
element = get('#three .one')
it "should return the very next sibling element when called without a css-rule", ->
sibling = element.nextSibling()
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .two')
it "should return a matching next sibling when called with a css-rule", ->
sibling = element.nextSibling('.three')
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .three')
describe "#previousSibling('css-rule')", ->
element = get('#three .three')
it "should return the very previous sibling element when called without a css-rule", ->
sibling = element.previousSibling()
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .two')
it "should return a matching previous sibling when called with a css-rule", ->
sibling = element.previousSibling('.one')
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .one')
| 116695 | #
# Element navigation module unit tests
#
# Copyright (C) 2011-2013 <NAME>
#
{Test,should} = require('lovely')
Test.set "/navigation.html", """
<html>
<head>
<script src="/core.js"></script>
<script src="/dom.js"></script>
</head>
<body>
<div id="one">
<div class="one">#one .one</div>
<div class="two">#one .two</div>
</div>
<div id="two">
<div class="one">#two .one</div>
<div class="two">#two .two</div>
</div>
<div id="three">
<div class="one">#three .one</div>
<div class="two">#three .two</div>
<div class="three">#three .three</div>
</div>
</body>
</html>
"""
describe "Element Navigation", ->
$ = window = document = element = null
get = (css_rule)->
before Test.load "/navigation.html", (dom, win)->
$ = dom
window = win
document = win.document
element = new $.Element(window.document.querySelector(css_rule))
describe "#match('css_rule')", ->
element = get('#one .one')
it "should say 'true' if it match the rule", ->
element.match('#one .one').should.be.true
it "should say 'false' if it doesn't match the rule", ->
element.match('#one .two').should.be.false
describe "#find('css_rule')", ->
element = get('#one')
it "should search in the element", ->
search = element.find('.one')
search.should.be.instanceOf $.NodeList
search.should.have.length 1
search[0].should.be.instanceOf $.Element
search[0]._.should.equal document.querySelector('#one .one')
it "should return an empty list if nothing found", ->
search = element.find('.non-existing')
search.should.be.instanceOf $.NodeList
search.should.have.length 0
it "should allow a raw DOM elements search", ->
search = element.find('.one, .two', true)
search.should.not.be.instanceOf $.NodeList
search.should.have.length 2
search[0].should.equal document.querySelector('#one .one')
search[1].should.equal document.querySelector('#one .two')
describe "#first('css_rule')", ->
element = get('#one')
it "should find the first matching element", ->
first = element.first('.two')
first.should.be.instanceOf $.Element
first._.should.equal document.querySelector('#one .two')
it "should find the very first element when called without a css-rule", ->
first = element.first()
first.should.be.instanceOf $.Element
first._.should.equal document.querySelector('#one .one')
describe "#parent('css-rule')", ->
element = get('#one .one')
it "should return the first parent when called without a css-rule", ->
parent = element.parent()
parent.should.be.instanceOf $.Element
parent._.should.equal document.querySelector('#one')
it "should return the first matching parent when called with a css-rule", ->
parent = element.parent('body')
parent.should.be.instanceOf $.Element
parent._.should.equal document.body
describe "#parents('css-rule')", ->
element = get('#one .one')
it "should return the list of all parents when called with a css-rule", ->
parents = element.parents()
parents.should.be.instanceOf $.NodeList
parents.should.have.length 3
parents[0]._.should.equal document.querySelector('#one')
parents[1]._.should.equal document.body
parents[2]._.should.equal document.documentElement
it "should filter the list by a given css-rule", ->
parents = element.parents('body')
parents.should.be.instanceOf $.NodeList
parents.should.have.length 1
parents[0]._.should.equal document.body
describe "#children('css_rule')", ->
element = get('#one')
it "should return all child elements when called without a css-rule", ->
result = element.children()
result.should.be.instanceOf $.NodeList
result.should.have.length 2
result[0].should.be.instanceOf $.Element
result[1].should.be.instanceOf $.Element
result[0]._.should.equal document.querySelector('#one .one')
result[1]._.should.equal document.querySelector('#one .two')
it "should filter the result by the css-rule", ->
result = element.children('.one')
result.should.have.length 1
result[0]._.should.equal document.querySelector('#one .one')
describe "#siblings('css-rule')", ->
element = get('#three .two')
it "should return the list of all siblings when called without a css-rule", ->
siblings = element.siblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .one')
siblings[1]._.should.equal document.querySelector('#three .three')
it "should return the list of matching siblings only when called with a css-rule", ->
siblings = element.siblings('.one')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .one')
describe "#nextSiblings('css-rule')", ->
element = get('#three .one')
it "should return a list of all the next siblings when called without a css-rule", ->
siblings = element.nextSiblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
siblings[1]._.should.equal document.querySelector('#three .three')
it "should return only matching siblings when called with a css-rule", ->
siblings = element.nextSiblings('.two')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
describe "#previousSiblings('css-rule')", ->
element = get('#three .three')
it "should return a list of all the next siblings when called without a css-rule", ->
siblings = element.previousSiblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
siblings[1]._.should.equal document.querySelector('#three .one')
it "should return only matching siblings when called with a css-rule", ->
siblings = element.previousSiblings('.two')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
describe "#nextSibling('css-rule')", ->
element = get('#three .one')
it "should return the very next sibling element when called without a css-rule", ->
sibling = element.nextSibling()
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .two')
it "should return a matching next sibling when called with a css-rule", ->
sibling = element.nextSibling('.three')
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .three')
describe "#previousSibling('css-rule')", ->
element = get('#three .three')
it "should return the very previous sibling element when called without a css-rule", ->
sibling = element.previousSibling()
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .two')
it "should return a matching previous sibling when called with a css-rule", ->
sibling = element.previousSibling('.one')
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .one')
| true | #
# Element navigation module unit tests
#
# Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI
#
{Test,should} = require('lovely')
Test.set "/navigation.html", """
<html>
<head>
<script src="/core.js"></script>
<script src="/dom.js"></script>
</head>
<body>
<div id="one">
<div class="one">#one .one</div>
<div class="two">#one .two</div>
</div>
<div id="two">
<div class="one">#two .one</div>
<div class="two">#two .two</div>
</div>
<div id="three">
<div class="one">#three .one</div>
<div class="two">#three .two</div>
<div class="three">#three .three</div>
</div>
</body>
</html>
"""
describe "Element Navigation", ->
$ = window = document = element = null
get = (css_rule)->
before Test.load "/navigation.html", (dom, win)->
$ = dom
window = win
document = win.document
element = new $.Element(window.document.querySelector(css_rule))
describe "#match('css_rule')", ->
element = get('#one .one')
it "should say 'true' if it match the rule", ->
element.match('#one .one').should.be.true
it "should say 'false' if it doesn't match the rule", ->
element.match('#one .two').should.be.false
describe "#find('css_rule')", ->
element = get('#one')
it "should search in the element", ->
search = element.find('.one')
search.should.be.instanceOf $.NodeList
search.should.have.length 1
search[0].should.be.instanceOf $.Element
search[0]._.should.equal document.querySelector('#one .one')
it "should return an empty list if nothing found", ->
search = element.find('.non-existing')
search.should.be.instanceOf $.NodeList
search.should.have.length 0
it "should allow a raw DOM elements search", ->
search = element.find('.one, .two', true)
search.should.not.be.instanceOf $.NodeList
search.should.have.length 2
search[0].should.equal document.querySelector('#one .one')
search[1].should.equal document.querySelector('#one .two')
describe "#first('css_rule')", ->
element = get('#one')
it "should find the first matching element", ->
first = element.first('.two')
first.should.be.instanceOf $.Element
first._.should.equal document.querySelector('#one .two')
it "should find the very first element when called without a css-rule", ->
first = element.first()
first.should.be.instanceOf $.Element
first._.should.equal document.querySelector('#one .one')
describe "#parent('css-rule')", ->
element = get('#one .one')
it "should return the first parent when called without a css-rule", ->
parent = element.parent()
parent.should.be.instanceOf $.Element
parent._.should.equal document.querySelector('#one')
it "should return the first matching parent when called with a css-rule", ->
parent = element.parent('body')
parent.should.be.instanceOf $.Element
parent._.should.equal document.body
describe "#parents('css-rule')", ->
element = get('#one .one')
it "should return the list of all parents when called with a css-rule", ->
parents = element.parents()
parents.should.be.instanceOf $.NodeList
parents.should.have.length 3
parents[0]._.should.equal document.querySelector('#one')
parents[1]._.should.equal document.body
parents[2]._.should.equal document.documentElement
it "should filter the list by a given css-rule", ->
parents = element.parents('body')
parents.should.be.instanceOf $.NodeList
parents.should.have.length 1
parents[0]._.should.equal document.body
describe "#children('css_rule')", ->
element = get('#one')
it "should return all child elements when called without a css-rule", ->
result = element.children()
result.should.be.instanceOf $.NodeList
result.should.have.length 2
result[0].should.be.instanceOf $.Element
result[1].should.be.instanceOf $.Element
result[0]._.should.equal document.querySelector('#one .one')
result[1]._.should.equal document.querySelector('#one .two')
it "should filter the result by the css-rule", ->
result = element.children('.one')
result.should.have.length 1
result[0]._.should.equal document.querySelector('#one .one')
describe "#siblings('css-rule')", ->
element = get('#three .two')
it "should return the list of all siblings when called without a css-rule", ->
siblings = element.siblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .one')
siblings[1]._.should.equal document.querySelector('#three .three')
it "should return the list of matching siblings only when called with a css-rule", ->
siblings = element.siblings('.one')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .one')
describe "#nextSiblings('css-rule')", ->
element = get('#three .one')
it "should return a list of all the next siblings when called without a css-rule", ->
siblings = element.nextSiblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
siblings[1]._.should.equal document.querySelector('#three .three')
it "should return only matching siblings when called with a css-rule", ->
siblings = element.nextSiblings('.two')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
describe "#previousSiblings('css-rule')", ->
element = get('#three .three')
it "should return a list of all the next siblings when called without a css-rule", ->
siblings = element.previousSiblings()
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 2
siblings[0].should.be.instanceOf $.Element
siblings[1].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
siblings[1]._.should.equal document.querySelector('#three .one')
it "should return only matching siblings when called with a css-rule", ->
siblings = element.previousSiblings('.two')
siblings.should.be.instanceOf $.NodeList
siblings.should.have.length 1
siblings[0].should.be.instanceOf $.Element
siblings[0]._.should.equal document.querySelector('#three .two')
describe "#nextSibling('css-rule')", ->
element = get('#three .one')
it "should return the very next sibling element when called without a css-rule", ->
sibling = element.nextSibling()
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .two')
it "should return a matching next sibling when called with a css-rule", ->
sibling = element.nextSibling('.three')
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .three')
describe "#previousSibling('css-rule')", ->
element = get('#three .three')
it "should return the very previous sibling element when called without a css-rule", ->
sibling = element.previousSibling()
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .two')
it "should return a matching previous sibling when called with a css-rule", ->
sibling = element.previousSibling('.one')
sibling.should.be.instanceOf $.Element
sibling._.should.equal document.querySelector('#three .one')
|
[
{
"context": "etted entry.\n\n Have a look at https://github.com/loveencounterflow/guy-test to see how to use the BNP caller info\n ",
"end": 14734,
"score": 0.9994118809700012,
"start": 14717,
"tag": "USERNAME",
"value": "loveencounterflow"
},
{
"context": "ee different user IDs:\... | src/BITSNPIECES.coffee | loveencounterflow/cnd | 0 |
############################################################################################################
njs_path = require 'path'
njs_fs = require 'fs'
njs_util = require 'util'
rpr = njs_util.inspect
CND = require './main'
PATH = require 'path'
{ NumberFormat } = require 'jsx-number-format'
@flatten = ( x, depth = Infinity ) -> x.flat depth
#-----------------------------------------------------------------------------------------------------------
@jr = JSON.stringify
@assign = Object.assign
#-----------------------------------------------------------------------------------------------------------
@here_abspath = ( dirname, P... ) -> PATH.resolve dirname, P...
@cwd_abspath = ( P... ) -> PATH.resolve process.cwd(), P...
@cwd_relpath = ( P... ) -> PATH.relative process.cwd(), P...
#-----------------------------------------------------------------------------------------------------------
@deep_copy = ( P... ) -> ( require './universal-copy' ) P...
#-----------------------------------------------------------------------------------------------------------
# number_formatter = new Intl.NumberFormat 'en-US'
# @format_number = ( x ) -> number_formatter.format x
@format_number = ( n ) ->
R = NumberFormat n, 3
return R.replace /\.000/, ''
#-----------------------------------------------------------------------------------------------------------
@escape_regex = ( text ) ->
### Given a `text`, return the same with all regular expression metacharacters properly escaped. Escaped
characters are `[]{}()*+?-.,\^$|#` plus whitespace. ###
#.........................................................................................................
return text.replace /[-[\]{}()*+?.,\\\/^$|#\s]/g, "\\$&"
#-----------------------------------------------------------------------------------------------------------
@escape_html = ( text ) ->
### Given a `text`, return the same with all characters critical in HTML (`&`, `<`, `>`) properly
escaped. ###
R = text
R = R.replace /&/g, '&'
R = R.replace /</g, '<'
R = R.replace />/g, '>'
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@find_all = ( text, matcher ) ->
### `CND.find_all` expects a `text` and a `matcher` (which must be a RegExp object); it returns a
(possibly empty) list of all matching parts in the text. If `matcher` does not have the `g` (global) flag
set, a new RegExp object will be cloned behind the scenes, so passsing in a regular expression with `g`
turned on may improve performance.
With thanks to http://www.2ality.com/2013/08/regexp-g.html,
http://www.2ality.com/2011/04/javascript-overview-of-regular.html.
###
unless ( Object::toString.call matcher is '[object RegExp]' ) and matcher.global
flags = if matcher.multiline then 'gm' else 'g'
flags += 'i' if matcher.ignoreCase
flags += 'y' if matcher.sticky
matcher = ( new RegExp matcher.source, flags )
throw new Error "matcher must be a RegExp object with global flag set" unless matcher.global
matcher.lastIndex = 0
return ( text.match matcher ) ? []
#===========================================================================================================
# UNSORTING
#-----------------------------------------------------------------------------------------------------------
@shuffle = ( list, ratio = 1 ) ->
### Shuffles the elements of a list randomly. After the call, the elements of will be—most of the time—
be reordered (but this is not guaranteed, as there is a realistic probability for recurrence of orderings
with short lists).
This is an implementation of the renowned Fisher-Yates algorithm, but with a twist: You may pass in a
`ratio` as second argument (which should be a float in the range `0 <= ratio <= 1`); if set to a value
less than one, a random number will be used to decide whether or not to perform a given step in the
shuffling process, so lists shuffled with zero-ish ratios will show less disorder than lists shuffled with
a one-ish ratio.
Implementation gleaned from http://stackoverflow.com/a/962890/256361. ###
#.........................................................................................................
return list if ( this_idx = list.length ) < 2
return @_shuffle list, ratio, Math.random, @random_integer.bind @
#-----------------------------------------------------------------------------------------------------------
@get_shuffle = ( seed_0 = 0, seed_1 = 1 ) ->
### This method works similar to `get_rnd`; it accepts two `seed`s which are used to produce random number
generators and returns a predictable shuffling function that accepts arguments like Bits'N'Pieces
`shuffle`. ###
rnd = @get_rnd seed_0
random_integer = @get_rnd_int seed_1
return ( list, ratio = 1 ) => @_shuffle list, ratio, rnd, random_integer
#-----------------------------------------------------------------------------------------------------------
@_shuffle = ( list, ratio, rnd, random_integer ) ->
#.........................................................................................................
return list if ( this_idx = list.length ) < 2
#.........................................................................................................
loop
this_idx += -1
return list if this_idx < 1
if ratio >= 1 or rnd() <= ratio
# return list if this_idx < 1
that_idx = random_integer 0, this_idx
[ list[ that_idx ], list[ this_idx ] ] = [ list[ this_idx ], list[ that_idx ] ]
#.........................................................................................................
return list
#===========================================================================================================
# RANDOM NUMBERS
#-----------------------------------------------------------------------------------------------------------
### see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number ###
@MIN_SAFE_INTEGER = -( 2 ** 53 ) - 1
@MAX_SAFE_INTEGER = +( 2 ** 53 ) - 1
#-----------------------------------------------------------------------------------------------------------
@random_number = ( min = 0, max = 1 ) ->
### Return a random number between min (inclusive) and max (exclusive).
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
via http://stackoverflow.com/a/1527820/256361. ###
return Math.random() * ( max - min ) + min
#-----------------------------------------------------------------------------------------------------------
@integer_from_normal_float = ( x, min = 0, max = 2 ) ->
### Given a 'normal' float `x` so that `0 <= x < 1`, return an integer `n` so that `min <= n < min`. ###
return ( Math.floor x * ( max - min ) ) + min
#-----------------------------------------------------------------------------------------------------------
@random_integer = ( min = 0, max = 2 ) ->
### Return a random integer between min (inclusive) and max (exclusive).
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
via http://stackoverflow.com/a/1527820/256361. ###
return @integer_from_normal_float Math.random(), min, max
#-----------------------------------------------------------------------------------------------------------
@get_rnd_int = ( seed = 1, delta = 1 ) ->
### Like `get_rnd`, but returns a predictable random integer generator. ###
rnd = @get_rnd seed, delta
return ( min = 0, max = 1 ) => @integer_from_normal_float rnd(), min, max
#-----------------------------------------------------------------------------------------------------------
@get_rnd = ( seed = 1, delta = 1 ) ->
### This method returns a simple deterministic pseudo-random number generator—basically like
`Math.random`, but (1) very probably with a much worse distribution of results, and (2) with predictable
series of numbers, which is good for some testing scenarios. You may seed this method by passing in a
`seed` and a `delta`, both of which must be non-zero numbers; the ensuing series of calls to the returned
method will then always result in the same series of numbers. Here is a usage example that also shows how
to reset the generator:
CND = require 'cnd'
rnd = CND.get_rnd() # or, say, `rnd = CND.get_rnd 123, 0.5`
log rnd() for idx in [ 0 .. 5 ]
log()
rnd.reset()
log rnd() for idx in [ 0 .. 5 ]
Please note that there are no strong guarantees made about the quality of the generated values except the
(1) deterministic repeatability, (2) boundedness, and (3) 'apparent randomness'. Do **not** use this for
cryptographic purposes. ###
#.........................................................................................................
R = ->
R._idx += 1
x = ( Math.sin R._s ) * 10000
R._s += R._delta
return x - Math.floor x
#.........................................................................................................
R.reset = ( seed, delta ) ->
### Reset the generator. After calling `rnd.reset` (or `rnd.seed` with the same arguments), ensuing calls
to `rnd` will always result in the same sequence of pseudo-random numbers. ###
seed ?= @._seed
delta ?= @._delta
#.......................................................................................................
unless ( typeof seed ) is 'number' and ( Number.isFinite seed ) then throw new Error "^3397^ expected a number, got #{rpr seed}"
unless ( typeof delta ) is 'number' and ( Number.isFinite delta ) then throw new Error "^3398^ expected a number, got #{rpr delta}"
#.......................................................................................................
throw new Error "seed should not be zero" unless seed != 0
throw new Error "delta should not be zero" unless delta != 0
#.......................................................................................................
R._s = seed
R._seed = seed
R._delta = delta
R._idx = -1
return null
#.........................................................................................................
R.reset seed, delta
#.........................................................................................................
return R
#===========================================================================================================
# PODs
#-----------------------------------------------------------------------------------------------------------
@pluck = ( x, name, fallback ) ->
### Given some object `x`, a `name` and a `fallback`, return the value of `x[ name ]`, or, if it does not
exist, `fallback`. When the method returns, `x[ name ]` has been deleted. ###
if x[ name ]?
R = x[ name ]
delete x[ name ]
else
R = fallback
return R
#===========================================================================================================
# ROUTES
#-----------------------------------------------------------------------------------------------------------
@get_parent_routes = ( route ) ->
R = []
#.........................................................................................................
loop
R.push route
break if route.length is 0 or route is '/'
route = njs_path.dirname route
#.........................................................................................................
return R
#===========================================================================================================
# CALLER LOCATION
#-----------------------------------------------------------------------------------------------------------
@get_V8_CallSite_objects = ( error = null ) ->
### Save original Error.prepareStackTrace ###
prepareStackTrace_original = Error.prepareStackTrace
#.........................................................................................................
Error.prepareStackTrace = ( ignored, stack ) -> return stack
error ?= new Error()
R = error.stack
#.........................................................................................................
### Restore original Error.prepareStackTrace ###
Error.prepareStackTrace = prepareStackTrace_original
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@get_caller_info_stack = ( delta = 0, error = null, limit = Infinity, include_source = no ) ->
### Return a list of PODs representing information about the call stack; newest items will be closer
to the start ('top') of the list.
`delta` represents the call distance of the site the inquirer is interested about, relative to the
*inquirer*; this will be `0` if that is the very line where the call originated from, `1` in case another
function is called to collect this information, and so on.
A custom error will be produced and analyzed (with a suitably adjusted value for `delta`) in case no
`error` has been given. Often, one will want to use this facility to see what the source for a caught
error looks like; in that case, just pass in the caught `error` object along with a `delta` of (typically)
`0` (because the error really originated where the problem occurred).
It is further possible to cut down on the amount of data returned by setting `limit` to a smallish
number; entries too close (with a stack index smaller than `delta`) or too far from the interesting
point will be omitted.
When `include_source` is `true`, an attempt will be made to open each source file, read its contents,
split it into lines, and include the indicated line in the respective entry. Note that this is currently
done in a very stupid, blocking, and non-memoizing way, so try not to do that if your stack trace is
hundreds of lines long and includes megabyte-sized sources.
Also see `get_caller_info`, which should be handy if you do not need an entire stack but just a single
targetted entry.
Have a look at https://github.com/loveencounterflow/guy-test to see how to use the BNP caller info
methods to copy with error locations in an asynchronous world. ###
#.........................................................................................................
delta += +2 unless error?
call_sites = @get_V8_CallSite_objects error
R = []
#.........................................................................................................
for cs, idx in call_sites
continue if delta? and idx < delta
break if R.length >= limit
entry =
'function-name': cs.getFunctionName()
'method-name': cs.getMethodName()
'route': cs.getFileName()
'line-nr': cs.getLineNumber()
'column-nr': cs.getColumnNumber()
entry[ 'source' ] = @_source_line_from_caller_info entry if include_source
R.push entry
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@get_caller_info = ( delta = 0, error = null, include_source = no ) ->
R = null
while delta >= 0 and not R?
R = ( @get_caller_info_stack delta, error, 1, include_source )[ 0 ]
delta += -1
# console.log '©3cc0i', rpr R
return R
#-----------------------------------------------------------------------------------------------------------
@_source_line_from_caller_info = ( info ) ->
route = info[ 'route' ]
line_nr = info[ 'line-nr' ]
try
source_lines = ( njs_fs.readFileSync route, encoding: 'utf-8' ).split /\r?\n/
R = source_lines[ line_nr - 1 ]
catch error
R = null
return R
#===========================================================================================================
# ID CREATION
#-----------------------------------------------------------------------------------------------------------
@create_id = ( values, length ) ->
### Given a number of `values` and a `length`, return an ID with `length` hexadecimal digits (`[0-9a-f]`)
that deterministically depends on the input but can probably not reverse-engeneered to yield the input
values. This is in no way meant to be cryptographically strong, just arbitrary enough so that we have a
convenient method to derive an ID with little chance of overlap given different inputs. **Note** It is
certainly possible to use this method (or `id_from_text`) to create a hash from a password to be stored in
a DB. Don't do this. Use `bcrypt` or similar best-practices for password storage. Again, the intent of
the BITSNPIECES ID utilities is *not* to be 'crypto-safe'; its intent is to give you a tool for generating
repetition-free IDs. ###
return @id_from_text ( ( rpr value for value in values ).join '-' ), length
#-----------------------------------------------------------------------------------------------------------
@create_random_id = ( values, length ) ->
### Like `create_id`, but with an extra random factor built in that should exclude that two identical
outputs are ever returned for any two identical inputs. Under the assumption that two calls to this
method are highly unlikely two produce an identical pair `( 1 * new Date(), Math.random() )` (which could
only happen if `Math.random()` returned the same number again *within the same clock millisecond*), and
assuming you are using a reasonable value for `length` (i.e., say, `7 < length < 20`), you should never
see the same ID twice. ###
values.push 1 * new Date() * Math.random()
return @create_id values, length
#-----------------------------------------------------------------------------------------------------------
@get_create_rnd_id = ( seed, delta ) ->
### Given an optional `seed` and `delta`, returns a function that will create pseudo-random IDs similar to
the ones `create_random_id` returns; however, the Bits'n'Pieces `get_rnd` method is used to obtain a
repeatable random number generator so that ID sequences are repeatable. The underlying PRNG is exposed as
`fn.rnd`, so `fn.rnd.reset` may be used to start over.
**Use Case Example**: The below code demonstrates the interesting properties of the method returned by
`get_create_rnd_id`: **(1)** we can seed the PRNG with numbers of our choice, so we get a chance to create
IDs that are unlikely to be repeated by other people using the same software, even when later inputs (such
as the email adresses shown here) happen to be the same. **(2)** Calling the ID generator with three
diffferent user-specific inputs, we get three different IDs, as expected. **(3)** Repeating the ID
generation calls with the *same* arguments will yield *different* IDs. **(4)** After calling
`create_rnd_id.rnd.reset()` and feeding `create_rnd_id` with the *same* user-specific inputs, we can still
see the identical *same* IDs generated—which is great for testing.
create_rnd_id = CND.get_create_rnd_id 1234, 87.23
# three different user IDs:
log create_rnd_id [ 'foo@example.com' ], 12
log create_rnd_id [ 'alice@nosuchname.com' ], 12
log create_rnd_id [ 'tim@cern.ch' ], 12
# the same repeated, but yielding random other IDs:
log()
log create_rnd_id [ 'foo@example.com' ], 12
log create_rnd_id [ 'alice@nosuchname.com' ], 12
log create_rnd_id [ 'tim@cern.ch' ], 12
# the same repeated, but yielding the same IDs as in the first run:
log()
create_rnd_id.rnd.reset()
log create_rnd_id [ 'foo@example.com' ], 12
log create_rnd_id [ 'alice@nosuchname.com' ], 12
log create_rnd_id [ 'tim@cern.ch' ], 12
The output you should see is
c40f774fce65
9d44f31f9a55
1b26e6e3e736
a0e11f616685
d7242f6935c7
976f26d1b25b
c40f774fce65
9d44f31f9a55
1b26e6e3e736
Note the last three IDs exactly match the first three IDs. The upshot of this is that we get reasonably
hard-to-guess, yet on-demand replayable IDs. Apart from weaknesses in the PRNG itself (for which see the
caveats in the description to `get_rnd`), the obvious way to cheat the system is by making it so that
a given piece of case-specific data is fed into the ID generator as the n-th call a second time. In
theory, we could make it so that each call constributes to the state change inside of `create_rnd_id`;
a replay would then need to provide all of the case-specific pieces of data a second time, in the right
order. ###
#.........................................................................................................
R = ( values, length ) =>
values.push R.rnd()
return @create_id values, length
#.........................................................................................................
R.rnd = @get_rnd seed, delta
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@id_from_text = ( text, length ) ->
### Given a `text` and a `length`, return an ID with `length` hexadecimal digits (`[0-9a-f]`)—this is like
`create_id`, but working on a text rather than a number of arbitrary values. The hash algorithm currently
used is SHA-1, which returns 40 hex digits; it should be good enough for the task at hand and has the
advantage of being widely implemented. ###
### TAINT should be a user option, or take 'good' algorithm universally available ###
R = ( ( ( require 'crypto' ).createHash 'sha1' ).update text, 'utf-8' ).digest 'hex'
return if length? then R[ 0 ... length ] else R
#-----------------------------------------------------------------------------------------------------------
@id_from_route = ( route, length, handler ) ->
### Like `id_from_text`, but accepting a file route instead of a text. ###
throw new Error "asynchronous `id_from_route` not yet supported" if handler?
content = njs_fs.readFileSync route
R = ( ( ( require 'crypto' ).createHash 'sha1' ).update content ).digest 'hex'
return if length? then R[ 0 ... length ] else R
#===========================================================================================================
# APP INFO
#-----------------------------------------------------------------------------------------------------------
@get_app_home = ( routes = null ) ->
### Return the file system route to the current (likely) application folder. This works by traversing all
the routes in `require[ 'main' ][ 'paths' ]` and checking whether one of the `node_modules` folders
listed there exists and is a folder; the first match is accepted and returned. If no matching existing
route is found, an error is thrown.
NB that the algorithm works even if the CoffeeNode Options module has been symlinked from another location
(rather than 'physically' installed) and even if the application main file has been executed from outside
the application folder (i.e. this obviates the need to `cd ~/route/to/my/app` before doing `node ./start`
or whatever—you can simply do `node ~/route/to/my/app/start`), but it does presuppose that (1) there *is*
a `node_modules` folder in your app folder; (2) there is *no* `node_modules` folder in the subfolder or
any of the intervening levels (if any) that contains your startup file. Most modules that follow the
established NodeJS / npm way of structuring modules should naturally comply with these assumptions. ###
njs_fs = require 'fs'
routes ?= require[ 'main' ][ 'paths' ]
#.........................................................................................................
for route in routes
try
return njs_path.dirname route if ( njs_fs.statSync route ).isDirectory()
#.......................................................................................................
catch error
### silently ignore missing routes: ###
continue if error[ 'code' ] is 'ENOENT'
throw error
#.........................................................................................................
throw new Error "unable to determine application home; tested routes: \n\n #{routes.join '\n '}\n"
#===========================================================================================================
# FS ROUTES
#-----------------------------------------------------------------------------------------------------------
@swap_extension = ( route, extension ) ->
extension = '.' + extension unless extension[ 0 ] is '.'
extname = njs_path.extname route
return route[ 0 ... route.length - extname.length ] + extension
#===========================================================================================================
# NETWORK
#-----------------------------------------------------------------------------------------------------------
@get_local_ips = ->
### thx to http://stackoverflow.com/a/10756441/256361 ###
R = []
for _, interface_ of ( require 'os' ).networkInterfaces()
for description in interface_
if description[ 'family' ] is 'IPv4' and not description[ 'internal' ]
R.push description[ 'address' ]
return R
#===========================================================================================================
# ESCAPE FOR COMMAND LINE
#-----------------------------------------------------------------------------------------------------------
```
// thx to https://github.com/xxorax/node-shell-escape/blob/master/shell-escape.js
this.shellescape = function shellescape(a) {
var ret = [];
a.forEach(function(s) {
if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
s = "'"+s.replace(/'/g,"'\\''")+"'";
s = s.replace(/^(?:'')+/g, '') // unduplicate single-quote at the beginning
.replace(/\\'''/g, "\\'" ); // remove non-escaped single-quote if there are enclosed between 2 escaped
}
ret.push(s);
});
return ret.join(' ');
}
```
| 169165 |
############################################################################################################
njs_path = require 'path'
njs_fs = require 'fs'
njs_util = require 'util'
rpr = njs_util.inspect
CND = require './main'
PATH = require 'path'
{ NumberFormat } = require 'jsx-number-format'
@flatten = ( x, depth = Infinity ) -> x.flat depth
#-----------------------------------------------------------------------------------------------------------
@jr = JSON.stringify
@assign = Object.assign
#-----------------------------------------------------------------------------------------------------------
@here_abspath = ( dirname, P... ) -> PATH.resolve dirname, P...
@cwd_abspath = ( P... ) -> PATH.resolve process.cwd(), P...
@cwd_relpath = ( P... ) -> PATH.relative process.cwd(), P...
#-----------------------------------------------------------------------------------------------------------
@deep_copy = ( P... ) -> ( require './universal-copy' ) P...
#-----------------------------------------------------------------------------------------------------------
# number_formatter = new Intl.NumberFormat 'en-US'
# @format_number = ( x ) -> number_formatter.format x
@format_number = ( n ) ->
R = NumberFormat n, 3
return R.replace /\.000/, ''
#-----------------------------------------------------------------------------------------------------------
@escape_regex = ( text ) ->
### Given a `text`, return the same with all regular expression metacharacters properly escaped. Escaped
characters are `[]{}()*+?-.,\^$|#` plus whitespace. ###
#.........................................................................................................
return text.replace /[-[\]{}()*+?.,\\\/^$|#\s]/g, "\\$&"
#-----------------------------------------------------------------------------------------------------------
@escape_html = ( text ) ->
### Given a `text`, return the same with all characters critical in HTML (`&`, `<`, `>`) properly
escaped. ###
R = text
R = R.replace /&/g, '&'
R = R.replace /</g, '<'
R = R.replace />/g, '>'
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@find_all = ( text, matcher ) ->
### `CND.find_all` expects a `text` and a `matcher` (which must be a RegExp object); it returns a
(possibly empty) list of all matching parts in the text. If `matcher` does not have the `g` (global) flag
set, a new RegExp object will be cloned behind the scenes, so passsing in a regular expression with `g`
turned on may improve performance.
With thanks to http://www.2ality.com/2013/08/regexp-g.html,
http://www.2ality.com/2011/04/javascript-overview-of-regular.html.
###
unless ( Object::toString.call matcher is '[object RegExp]' ) and matcher.global
flags = if matcher.multiline then 'gm' else 'g'
flags += 'i' if matcher.ignoreCase
flags += 'y' if matcher.sticky
matcher = ( new RegExp matcher.source, flags )
throw new Error "matcher must be a RegExp object with global flag set" unless matcher.global
matcher.lastIndex = 0
return ( text.match matcher ) ? []
#===========================================================================================================
# UNSORTING
#-----------------------------------------------------------------------------------------------------------
@shuffle = ( list, ratio = 1 ) ->
### Shuffles the elements of a list randomly. After the call, the elements of will be—most of the time—
be reordered (but this is not guaranteed, as there is a realistic probability for recurrence of orderings
with short lists).
This is an implementation of the renowned Fisher-Yates algorithm, but with a twist: You may pass in a
`ratio` as second argument (which should be a float in the range `0 <= ratio <= 1`); if set to a value
less than one, a random number will be used to decide whether or not to perform a given step in the
shuffling process, so lists shuffled with zero-ish ratios will show less disorder than lists shuffled with
a one-ish ratio.
Implementation gleaned from http://stackoverflow.com/a/962890/256361. ###
#.........................................................................................................
return list if ( this_idx = list.length ) < 2
return @_shuffle list, ratio, Math.random, @random_integer.bind @
#-----------------------------------------------------------------------------------------------------------
@get_shuffle = ( seed_0 = 0, seed_1 = 1 ) ->
### This method works similar to `get_rnd`; it accepts two `seed`s which are used to produce random number
generators and returns a predictable shuffling function that accepts arguments like Bits'N'Pieces
`shuffle`. ###
rnd = @get_rnd seed_0
random_integer = @get_rnd_int seed_1
return ( list, ratio = 1 ) => @_shuffle list, ratio, rnd, random_integer
#-----------------------------------------------------------------------------------------------------------
@_shuffle = ( list, ratio, rnd, random_integer ) ->
#.........................................................................................................
return list if ( this_idx = list.length ) < 2
#.........................................................................................................
loop
this_idx += -1
return list if this_idx < 1
if ratio >= 1 or rnd() <= ratio
# return list if this_idx < 1
that_idx = random_integer 0, this_idx
[ list[ that_idx ], list[ this_idx ] ] = [ list[ this_idx ], list[ that_idx ] ]
#.........................................................................................................
return list
#===========================================================================================================
# RANDOM NUMBERS
#-----------------------------------------------------------------------------------------------------------
### see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number ###
@MIN_SAFE_INTEGER = -( 2 ** 53 ) - 1
@MAX_SAFE_INTEGER = +( 2 ** 53 ) - 1
#-----------------------------------------------------------------------------------------------------------
@random_number = ( min = 0, max = 1 ) ->
### Return a random number between min (inclusive) and max (exclusive).
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
via http://stackoverflow.com/a/1527820/256361. ###
return Math.random() * ( max - min ) + min
#-----------------------------------------------------------------------------------------------------------
@integer_from_normal_float = ( x, min = 0, max = 2 ) ->
### Given a 'normal' float `x` so that `0 <= x < 1`, return an integer `n` so that `min <= n < min`. ###
return ( Math.floor x * ( max - min ) ) + min
#-----------------------------------------------------------------------------------------------------------
@random_integer = ( min = 0, max = 2 ) ->
### Return a random integer between min (inclusive) and max (exclusive).
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
via http://stackoverflow.com/a/1527820/256361. ###
return @integer_from_normal_float Math.random(), min, max
#-----------------------------------------------------------------------------------------------------------
@get_rnd_int = ( seed = 1, delta = 1 ) ->
### Like `get_rnd`, but returns a predictable random integer generator. ###
rnd = @get_rnd seed, delta
return ( min = 0, max = 1 ) => @integer_from_normal_float rnd(), min, max
#-----------------------------------------------------------------------------------------------------------
@get_rnd = ( seed = 1, delta = 1 ) ->
### This method returns a simple deterministic pseudo-random number generator—basically like
`Math.random`, but (1) very probably with a much worse distribution of results, and (2) with predictable
series of numbers, which is good for some testing scenarios. You may seed this method by passing in a
`seed` and a `delta`, both of which must be non-zero numbers; the ensuing series of calls to the returned
method will then always result in the same series of numbers. Here is a usage example that also shows how
to reset the generator:
CND = require 'cnd'
rnd = CND.get_rnd() # or, say, `rnd = CND.get_rnd 123, 0.5`
log rnd() for idx in [ 0 .. 5 ]
log()
rnd.reset()
log rnd() for idx in [ 0 .. 5 ]
Please note that there are no strong guarantees made about the quality of the generated values except the
(1) deterministic repeatability, (2) boundedness, and (3) 'apparent randomness'. Do **not** use this for
cryptographic purposes. ###
#.........................................................................................................
R = ->
R._idx += 1
x = ( Math.sin R._s ) * 10000
R._s += R._delta
return x - Math.floor x
#.........................................................................................................
R.reset = ( seed, delta ) ->
### Reset the generator. After calling `rnd.reset` (or `rnd.seed` with the same arguments), ensuing calls
to `rnd` will always result in the same sequence of pseudo-random numbers. ###
seed ?= @._seed
delta ?= @._delta
#.......................................................................................................
unless ( typeof seed ) is 'number' and ( Number.isFinite seed ) then throw new Error "^3397^ expected a number, got #{rpr seed}"
unless ( typeof delta ) is 'number' and ( Number.isFinite delta ) then throw new Error "^3398^ expected a number, got #{rpr delta}"
#.......................................................................................................
throw new Error "seed should not be zero" unless seed != 0
throw new Error "delta should not be zero" unless delta != 0
#.......................................................................................................
R._s = seed
R._seed = seed
R._delta = delta
R._idx = -1
return null
#.........................................................................................................
R.reset seed, delta
#.........................................................................................................
return R
#===========================================================================================================
# PODs
#-----------------------------------------------------------------------------------------------------------
@pluck = ( x, name, fallback ) ->
### Given some object `x`, a `name` and a `fallback`, return the value of `x[ name ]`, or, if it does not
exist, `fallback`. When the method returns, `x[ name ]` has been deleted. ###
if x[ name ]?
R = x[ name ]
delete x[ name ]
else
R = fallback
return R
#===========================================================================================================
# ROUTES
#-----------------------------------------------------------------------------------------------------------
@get_parent_routes = ( route ) ->
R = []
#.........................................................................................................
loop
R.push route
break if route.length is 0 or route is '/'
route = njs_path.dirname route
#.........................................................................................................
return R
#===========================================================================================================
# CALLER LOCATION
#-----------------------------------------------------------------------------------------------------------
@get_V8_CallSite_objects = ( error = null ) ->
### Save original Error.prepareStackTrace ###
prepareStackTrace_original = Error.prepareStackTrace
#.........................................................................................................
Error.prepareStackTrace = ( ignored, stack ) -> return stack
error ?= new Error()
R = error.stack
#.........................................................................................................
### Restore original Error.prepareStackTrace ###
Error.prepareStackTrace = prepareStackTrace_original
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@get_caller_info_stack = ( delta = 0, error = null, limit = Infinity, include_source = no ) ->
### Return a list of PODs representing information about the call stack; newest items will be closer
to the start ('top') of the list.
`delta` represents the call distance of the site the inquirer is interested about, relative to the
*inquirer*; this will be `0` if that is the very line where the call originated from, `1` in case another
function is called to collect this information, and so on.
A custom error will be produced and analyzed (with a suitably adjusted value for `delta`) in case no
`error` has been given. Often, one will want to use this facility to see what the source for a caught
error looks like; in that case, just pass in the caught `error` object along with a `delta` of (typically)
`0` (because the error really originated where the problem occurred).
It is further possible to cut down on the amount of data returned by setting `limit` to a smallish
number; entries too close (with a stack index smaller than `delta`) or too far from the interesting
point will be omitted.
When `include_source` is `true`, an attempt will be made to open each source file, read its contents,
split it into lines, and include the indicated line in the respective entry. Note that this is currently
done in a very stupid, blocking, and non-memoizing way, so try not to do that if your stack trace is
hundreds of lines long and includes megabyte-sized sources.
Also see `get_caller_info`, which should be handy if you do not need an entire stack but just a single
targetted entry.
Have a look at https://github.com/loveencounterflow/guy-test to see how to use the BNP caller info
methods to copy with error locations in an asynchronous world. ###
#.........................................................................................................
delta += +2 unless error?
call_sites = @get_V8_CallSite_objects error
R = []
#.........................................................................................................
for cs, idx in call_sites
continue if delta? and idx < delta
break if R.length >= limit
entry =
'function-name': cs.getFunctionName()
'method-name': cs.getMethodName()
'route': cs.getFileName()
'line-nr': cs.getLineNumber()
'column-nr': cs.getColumnNumber()
entry[ 'source' ] = @_source_line_from_caller_info entry if include_source
R.push entry
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@get_caller_info = ( delta = 0, error = null, include_source = no ) ->
R = null
while delta >= 0 and not R?
R = ( @get_caller_info_stack delta, error, 1, include_source )[ 0 ]
delta += -1
# console.log '©3cc0i', rpr R
return R
#-----------------------------------------------------------------------------------------------------------
@_source_line_from_caller_info = ( info ) ->
route = info[ 'route' ]
line_nr = info[ 'line-nr' ]
try
source_lines = ( njs_fs.readFileSync route, encoding: 'utf-8' ).split /\r?\n/
R = source_lines[ line_nr - 1 ]
catch error
R = null
return R
#===========================================================================================================
# ID CREATION
#-----------------------------------------------------------------------------------------------------------
@create_id = ( values, length ) ->
### Given a number of `values` and a `length`, return an ID with `length` hexadecimal digits (`[0-9a-f]`)
that deterministically depends on the input but can probably not reverse-engeneered to yield the input
values. This is in no way meant to be cryptographically strong, just arbitrary enough so that we have a
convenient method to derive an ID with little chance of overlap given different inputs. **Note** It is
certainly possible to use this method (or `id_from_text`) to create a hash from a password to be stored in
a DB. Don't do this. Use `bcrypt` or similar best-practices for password storage. Again, the intent of
the BITSNPIECES ID utilities is *not* to be 'crypto-safe'; its intent is to give you a tool for generating
repetition-free IDs. ###
return @id_from_text ( ( rpr value for value in values ).join '-' ), length
#-----------------------------------------------------------------------------------------------------------
@create_random_id = ( values, length ) ->
### Like `create_id`, but with an extra random factor built in that should exclude that two identical
outputs are ever returned for any two identical inputs. Under the assumption that two calls to this
method are highly unlikely two produce an identical pair `( 1 * new Date(), Math.random() )` (which could
only happen if `Math.random()` returned the same number again *within the same clock millisecond*), and
assuming you are using a reasonable value for `length` (i.e., say, `7 < length < 20`), you should never
see the same ID twice. ###
values.push 1 * new Date() * Math.random()
return @create_id values, length
#-----------------------------------------------------------------------------------------------------------
@get_create_rnd_id = ( seed, delta ) ->
### Given an optional `seed` and `delta`, returns a function that will create pseudo-random IDs similar to
the ones `create_random_id` returns; however, the Bits'n'Pieces `get_rnd` method is used to obtain a
repeatable random number generator so that ID sequences are repeatable. The underlying PRNG is exposed as
`fn.rnd`, so `fn.rnd.reset` may be used to start over.
**Use Case Example**: The below code demonstrates the interesting properties of the method returned by
`get_create_rnd_id`: **(1)** we can seed the PRNG with numbers of our choice, so we get a chance to create
IDs that are unlikely to be repeated by other people using the same software, even when later inputs (such
as the email adresses shown here) happen to be the same. **(2)** Calling the ID generator with three
diffferent user-specific inputs, we get three different IDs, as expected. **(3)** Repeating the ID
generation calls with the *same* arguments will yield *different* IDs. **(4)** After calling
`create_rnd_id.rnd.reset()` and feeding `create_rnd_id` with the *same* user-specific inputs, we can still
see the identical *same* IDs generated—which is great for testing.
create_rnd_id = CND.get_create_rnd_id 1234, 87.23
# three different user IDs:
log create_rnd_id [ '<EMAIL>' ], 12
log create_rnd_id [ '<EMAIL>' ], 12
log create_rnd_id [ '<EMAIL>' ], 12
# the same repeated, but yielding random other IDs:
log()
log create_rnd_id [ '<EMAIL>' ], 12
log create_rnd_id [ '<EMAIL>' ], 12
log create_rnd_id [ '<EMAIL>' ], 12
# the same repeated, but yielding the same IDs as in the first run:
log()
create_rnd_id.rnd.reset()
log create_rnd_id [ '<EMAIL>' ], 12
log create_rnd_id [ '<EMAIL>' ], 12
log create_rnd_id [ '<EMAIL>' ], 12
The output you should see is
c40f774fce65
9d44f31f9a55
1b26e6e3e736
a0e11f616685
d7242f6935c7
976f26d1b25b
c40f774fce65
9d44f31f9a55
1b26e6e3e736
Note the last three IDs exactly match the first three IDs. The upshot of this is that we get reasonably
hard-to-guess, yet on-demand replayable IDs. Apart from weaknesses in the PRNG itself (for which see the
caveats in the description to `get_rnd`), the obvious way to cheat the system is by making it so that
a given piece of case-specific data is fed into the ID generator as the n-th call a second time. In
theory, we could make it so that each call constributes to the state change inside of `create_rnd_id`;
a replay would then need to provide all of the case-specific pieces of data a second time, in the right
order. ###
#.........................................................................................................
R = ( values, length ) =>
values.push R.rnd()
return @create_id values, length
#.........................................................................................................
R.rnd = @get_rnd seed, delta
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@id_from_text = ( text, length ) ->
### Given a `text` and a `length`, return an ID with `length` hexadecimal digits (`[0-9a-f]`)—this is like
`create_id`, but working on a text rather than a number of arbitrary values. The hash algorithm currently
used is SHA-1, which returns 40 hex digits; it should be good enough for the task at hand and has the
advantage of being widely implemented. ###
### TAINT should be a user option, or take 'good' algorithm universally available ###
R = ( ( ( require 'crypto' ).createHash 'sha1' ).update text, 'utf-8' ).digest 'hex'
return if length? then R[ 0 ... length ] else R
#-----------------------------------------------------------------------------------------------------------
@id_from_route = ( route, length, handler ) ->
### Like `id_from_text`, but accepting a file route instead of a text. ###
throw new Error "asynchronous `id_from_route` not yet supported" if handler?
content = njs_fs.readFileSync route
R = ( ( ( require 'crypto' ).createHash 'sha1' ).update content ).digest 'hex'
return if length? then R[ 0 ... length ] else R
#===========================================================================================================
# APP INFO
#-----------------------------------------------------------------------------------------------------------
@get_app_home = ( routes = null ) ->
### Return the file system route to the current (likely) application folder. This works by traversing all
the routes in `require[ 'main' ][ 'paths' ]` and checking whether one of the `node_modules` folders
listed there exists and is a folder; the first match is accepted and returned. If no matching existing
route is found, an error is thrown.
NB that the algorithm works even if the CoffeeNode Options module has been symlinked from another location
(rather than 'physically' installed) and even if the application main file has been executed from outside
the application folder (i.e. this obviates the need to `cd ~/route/to/my/app` before doing `node ./start`
or whatever—you can simply do `node ~/route/to/my/app/start`), but it does presuppose that (1) there *is*
a `node_modules` folder in your app folder; (2) there is *no* `node_modules` folder in the subfolder or
any of the intervening levels (if any) that contains your startup file. Most modules that follow the
established NodeJS / npm way of structuring modules should naturally comply with these assumptions. ###
njs_fs = require 'fs'
routes ?= require[ 'main' ][ 'paths' ]
#.........................................................................................................
for route in routes
try
return njs_path.dirname route if ( njs_fs.statSync route ).isDirectory()
#.......................................................................................................
catch error
### silently ignore missing routes: ###
continue if error[ 'code' ] is 'ENOENT'
throw error
#.........................................................................................................
throw new Error "unable to determine application home; tested routes: \n\n #{routes.join '\n '}\n"
#===========================================================================================================
# FS ROUTES
#-----------------------------------------------------------------------------------------------------------
@swap_extension = ( route, extension ) ->
extension = '.' + extension unless extension[ 0 ] is '.'
extname = njs_path.extname route
return route[ 0 ... route.length - extname.length ] + extension
#===========================================================================================================
# NETWORK
#-----------------------------------------------------------------------------------------------------------
@get_local_ips = ->
### thx to http://stackoverflow.com/a/10756441/256361 ###
R = []
for _, interface_ of ( require 'os' ).networkInterfaces()
for description in interface_
if description[ 'family' ] is 'IPv4' and not description[ 'internal' ]
R.push description[ 'address' ]
return R
#===========================================================================================================
# ESCAPE FOR COMMAND LINE
#-----------------------------------------------------------------------------------------------------------
```
// thx to https://github.com/xxorax/node-shell-escape/blob/master/shell-escape.js
this.shellescape = function shellescape(a) {
var ret = [];
a.forEach(function(s) {
if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
s = "'"+s.replace(/'/g,"'\\''")+"'";
s = s.replace(/^(?:'')+/g, '') // unduplicate single-quote at the beginning
.replace(/\\'''/g, "\\'" ); // remove non-escaped single-quote if there are enclosed between 2 escaped
}
ret.push(s);
});
return ret.join(' ');
}
```
| true |
############################################################################################################
njs_path = require 'path'
njs_fs = require 'fs'
njs_util = require 'util'
rpr = njs_util.inspect
CND = require './main'
PATH = require 'path'
{ NumberFormat } = require 'jsx-number-format'
@flatten = ( x, depth = Infinity ) -> x.flat depth
#-----------------------------------------------------------------------------------------------------------
@jr = JSON.stringify
@assign = Object.assign
#-----------------------------------------------------------------------------------------------------------
@here_abspath = ( dirname, P... ) -> PATH.resolve dirname, P...
@cwd_abspath = ( P... ) -> PATH.resolve process.cwd(), P...
@cwd_relpath = ( P... ) -> PATH.relative process.cwd(), P...
#-----------------------------------------------------------------------------------------------------------
@deep_copy = ( P... ) -> ( require './universal-copy' ) P...
#-----------------------------------------------------------------------------------------------------------
# number_formatter = new Intl.NumberFormat 'en-US'
# @format_number = ( x ) -> number_formatter.format x
@format_number = ( n ) ->
R = NumberFormat n, 3
return R.replace /\.000/, ''
#-----------------------------------------------------------------------------------------------------------
@escape_regex = ( text ) ->
### Given a `text`, return the same with all regular expression metacharacters properly escaped. Escaped
characters are `[]{}()*+?-.,\^$|#` plus whitespace. ###
#.........................................................................................................
return text.replace /[-[\]{}()*+?.,\\\/^$|#\s]/g, "\\$&"
#-----------------------------------------------------------------------------------------------------------
@escape_html = ( text ) ->
### Given a `text`, return the same with all characters critical in HTML (`&`, `<`, `>`) properly
escaped. ###
R = text
R = R.replace /&/g, '&'
R = R.replace /</g, '<'
R = R.replace />/g, '>'
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@find_all = ( text, matcher ) ->
### `CND.find_all` expects a `text` and a `matcher` (which must be a RegExp object); it returns a
(possibly empty) list of all matching parts in the text. If `matcher` does not have the `g` (global) flag
set, a new RegExp object will be cloned behind the scenes, so passsing in a regular expression with `g`
turned on may improve performance.
With thanks to http://www.2ality.com/2013/08/regexp-g.html,
http://www.2ality.com/2011/04/javascript-overview-of-regular.html.
###
unless ( Object::toString.call matcher is '[object RegExp]' ) and matcher.global
flags = if matcher.multiline then 'gm' else 'g'
flags += 'i' if matcher.ignoreCase
flags += 'y' if matcher.sticky
matcher = ( new RegExp matcher.source, flags )
throw new Error "matcher must be a RegExp object with global flag set" unless matcher.global
matcher.lastIndex = 0
return ( text.match matcher ) ? []
#===========================================================================================================
# UNSORTING
#-----------------------------------------------------------------------------------------------------------
@shuffle = ( list, ratio = 1 ) ->
### Shuffles the elements of a list randomly. After the call, the elements of will be—most of the time—
be reordered (but this is not guaranteed, as there is a realistic probability for recurrence of orderings
with short lists).
This is an implementation of the renowned Fisher-Yates algorithm, but with a twist: You may pass in a
`ratio` as second argument (which should be a float in the range `0 <= ratio <= 1`); if set to a value
less than one, a random number will be used to decide whether or not to perform a given step in the
shuffling process, so lists shuffled with zero-ish ratios will show less disorder than lists shuffled with
a one-ish ratio.
Implementation gleaned from http://stackoverflow.com/a/962890/256361. ###
#.........................................................................................................
return list if ( this_idx = list.length ) < 2
return @_shuffle list, ratio, Math.random, @random_integer.bind @
#-----------------------------------------------------------------------------------------------------------
@get_shuffle = ( seed_0 = 0, seed_1 = 1 ) ->
### This method works similar to `get_rnd`; it accepts two `seed`s which are used to produce random number
generators and returns a predictable shuffling function that accepts arguments like Bits'N'Pieces
`shuffle`. ###
rnd = @get_rnd seed_0
random_integer = @get_rnd_int seed_1
return ( list, ratio = 1 ) => @_shuffle list, ratio, rnd, random_integer
#-----------------------------------------------------------------------------------------------------------
@_shuffle = ( list, ratio, rnd, random_integer ) ->
#.........................................................................................................
return list if ( this_idx = list.length ) < 2
#.........................................................................................................
loop
this_idx += -1
return list if this_idx < 1
if ratio >= 1 or rnd() <= ratio
# return list if this_idx < 1
that_idx = random_integer 0, this_idx
[ list[ that_idx ], list[ this_idx ] ] = [ list[ this_idx ], list[ that_idx ] ]
#.........................................................................................................
return list
#===========================================================================================================
# RANDOM NUMBERS
#-----------------------------------------------------------------------------------------------------------
### see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number ###
@MIN_SAFE_INTEGER = -( 2 ** 53 ) - 1
@MAX_SAFE_INTEGER = +( 2 ** 53 ) - 1
#-----------------------------------------------------------------------------------------------------------
@random_number = ( min = 0, max = 1 ) ->
### Return a random number between min (inclusive) and max (exclusive).
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
via http://stackoverflow.com/a/1527820/256361. ###
return Math.random() * ( max - min ) + min
#-----------------------------------------------------------------------------------------------------------
@integer_from_normal_float = ( x, min = 0, max = 2 ) ->
### Given a 'normal' float `x` so that `0 <= x < 1`, return an integer `n` so that `min <= n < min`. ###
return ( Math.floor x * ( max - min ) ) + min
#-----------------------------------------------------------------------------------------------------------
@random_integer = ( min = 0, max = 2 ) ->
### Return a random integer between min (inclusive) and max (exclusive).
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
via http://stackoverflow.com/a/1527820/256361. ###
return @integer_from_normal_float Math.random(), min, max
#-----------------------------------------------------------------------------------------------------------
@get_rnd_int = ( seed = 1, delta = 1 ) ->
### Like `get_rnd`, but returns a predictable random integer generator. ###
rnd = @get_rnd seed, delta
return ( min = 0, max = 1 ) => @integer_from_normal_float rnd(), min, max
#-----------------------------------------------------------------------------------------------------------
@get_rnd = ( seed = 1, delta = 1 ) ->
### This method returns a simple deterministic pseudo-random number generator—basically like
`Math.random`, but (1) very probably with a much worse distribution of results, and (2) with predictable
series of numbers, which is good for some testing scenarios. You may seed this method by passing in a
`seed` and a `delta`, both of which must be non-zero numbers; the ensuing series of calls to the returned
method will then always result in the same series of numbers. Here is a usage example that also shows how
to reset the generator:
CND = require 'cnd'
rnd = CND.get_rnd() # or, say, `rnd = CND.get_rnd 123, 0.5`
log rnd() for idx in [ 0 .. 5 ]
log()
rnd.reset()
log rnd() for idx in [ 0 .. 5 ]
Please note that there are no strong guarantees made about the quality of the generated values except the
(1) deterministic repeatability, (2) boundedness, and (3) 'apparent randomness'. Do **not** use this for
cryptographic purposes. ###
#.........................................................................................................
R = ->
R._idx += 1
x = ( Math.sin R._s ) * 10000
R._s += R._delta
return x - Math.floor x
#.........................................................................................................
R.reset = ( seed, delta ) ->
### Reset the generator. After calling `rnd.reset` (or `rnd.seed` with the same arguments), ensuing calls
to `rnd` will always result in the same sequence of pseudo-random numbers. ###
seed ?= @._seed
delta ?= @._delta
#.......................................................................................................
unless ( typeof seed ) is 'number' and ( Number.isFinite seed ) then throw new Error "^3397^ expected a number, got #{rpr seed}"
unless ( typeof delta ) is 'number' and ( Number.isFinite delta ) then throw new Error "^3398^ expected a number, got #{rpr delta}"
#.......................................................................................................
throw new Error "seed should not be zero" unless seed != 0
throw new Error "delta should not be zero" unless delta != 0
#.......................................................................................................
R._s = seed
R._seed = seed
R._delta = delta
R._idx = -1
return null
#.........................................................................................................
R.reset seed, delta
#.........................................................................................................
return R
#===========================================================================================================
# PODs
#-----------------------------------------------------------------------------------------------------------
@pluck = ( x, name, fallback ) ->
### Given some object `x`, a `name` and a `fallback`, return the value of `x[ name ]`, or, if it does not
exist, `fallback`. When the method returns, `x[ name ]` has been deleted. ###
if x[ name ]?
R = x[ name ]
delete x[ name ]
else
R = fallback
return R
#===========================================================================================================
# ROUTES
#-----------------------------------------------------------------------------------------------------------
@get_parent_routes = ( route ) ->
R = []
#.........................................................................................................
loop
R.push route
break if route.length is 0 or route is '/'
route = njs_path.dirname route
#.........................................................................................................
return R
#===========================================================================================================
# CALLER LOCATION
#-----------------------------------------------------------------------------------------------------------
@get_V8_CallSite_objects = ( error = null ) ->
### Save original Error.prepareStackTrace ###
prepareStackTrace_original = Error.prepareStackTrace
#.........................................................................................................
Error.prepareStackTrace = ( ignored, stack ) -> return stack
error ?= new Error()
R = error.stack
#.........................................................................................................
### Restore original Error.prepareStackTrace ###
Error.prepareStackTrace = prepareStackTrace_original
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@get_caller_info_stack = ( delta = 0, error = null, limit = Infinity, include_source = no ) ->
### Return a list of PODs representing information about the call stack; newest items will be closer
to the start ('top') of the list.
`delta` represents the call distance of the site the inquirer is interested about, relative to the
*inquirer*; this will be `0` if that is the very line where the call originated from, `1` in case another
function is called to collect this information, and so on.
A custom error will be produced and analyzed (with a suitably adjusted value for `delta`) in case no
`error` has been given. Often, one will want to use this facility to see what the source for a caught
error looks like; in that case, just pass in the caught `error` object along with a `delta` of (typically)
`0` (because the error really originated where the problem occurred).
It is further possible to cut down on the amount of data returned by setting `limit` to a smallish
number; entries too close (with a stack index smaller than `delta`) or too far from the interesting
point will be omitted.
When `include_source` is `true`, an attempt will be made to open each source file, read its contents,
split it into lines, and include the indicated line in the respective entry. Note that this is currently
done in a very stupid, blocking, and non-memoizing way, so try not to do that if your stack trace is
hundreds of lines long and includes megabyte-sized sources.
Also see `get_caller_info`, which should be handy if you do not need an entire stack but just a single
targetted entry.
Have a look at https://github.com/loveencounterflow/guy-test to see how to use the BNP caller info
methods to copy with error locations in an asynchronous world. ###
#.........................................................................................................
delta += +2 unless error?
call_sites = @get_V8_CallSite_objects error
R = []
#.........................................................................................................
for cs, idx in call_sites
continue if delta? and idx < delta
break if R.length >= limit
entry =
'function-name': cs.getFunctionName()
'method-name': cs.getMethodName()
'route': cs.getFileName()
'line-nr': cs.getLineNumber()
'column-nr': cs.getColumnNumber()
entry[ 'source' ] = @_source_line_from_caller_info entry if include_source
R.push entry
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@get_caller_info = ( delta = 0, error = null, include_source = no ) ->
R = null
while delta >= 0 and not R?
R = ( @get_caller_info_stack delta, error, 1, include_source )[ 0 ]
delta += -1
# console.log '©3cc0i', rpr R
return R
#-----------------------------------------------------------------------------------------------------------
@_source_line_from_caller_info = ( info ) ->
route = info[ 'route' ]
line_nr = info[ 'line-nr' ]
try
source_lines = ( njs_fs.readFileSync route, encoding: 'utf-8' ).split /\r?\n/
R = source_lines[ line_nr - 1 ]
catch error
R = null
return R
#===========================================================================================================
# ID CREATION
#-----------------------------------------------------------------------------------------------------------
@create_id = ( values, length ) ->
### Given a number of `values` and a `length`, return an ID with `length` hexadecimal digits (`[0-9a-f]`)
that deterministically depends on the input but can probably not reverse-engeneered to yield the input
values. This is in no way meant to be cryptographically strong, just arbitrary enough so that we have a
convenient method to derive an ID with little chance of overlap given different inputs. **Note** It is
certainly possible to use this method (or `id_from_text`) to create a hash from a password to be stored in
a DB. Don't do this. Use `bcrypt` or similar best-practices for password storage. Again, the intent of
the BITSNPIECES ID utilities is *not* to be 'crypto-safe'; its intent is to give you a tool for generating
repetition-free IDs. ###
return @id_from_text ( ( rpr value for value in values ).join '-' ), length
#-----------------------------------------------------------------------------------------------------------
@create_random_id = ( values, length ) ->
### Like `create_id`, but with an extra random factor built in that should exclude that two identical
outputs are ever returned for any two identical inputs. Under the assumption that two calls to this
method are highly unlikely two produce an identical pair `( 1 * new Date(), Math.random() )` (which could
only happen if `Math.random()` returned the same number again *within the same clock millisecond*), and
assuming you are using a reasonable value for `length` (i.e., say, `7 < length < 20`), you should never
see the same ID twice. ###
values.push 1 * new Date() * Math.random()
return @create_id values, length
#-----------------------------------------------------------------------------------------------------------
@get_create_rnd_id = ( seed, delta ) ->
### Given an optional `seed` and `delta`, returns a function that will create pseudo-random IDs similar to
the ones `create_random_id` returns; however, the Bits'n'Pieces `get_rnd` method is used to obtain a
repeatable random number generator so that ID sequences are repeatable. The underlying PRNG is exposed as
`fn.rnd`, so `fn.rnd.reset` may be used to start over.
**Use Case Example**: The below code demonstrates the interesting properties of the method returned by
`get_create_rnd_id`: **(1)** we can seed the PRNG with numbers of our choice, so we get a chance to create
IDs that are unlikely to be repeated by other people using the same software, even when later inputs (such
as the email adresses shown here) happen to be the same. **(2)** Calling the ID generator with three
diffferent user-specific inputs, we get three different IDs, as expected. **(3)** Repeating the ID
generation calls with the *same* arguments will yield *different* IDs. **(4)** After calling
`create_rnd_id.rnd.reset()` and feeding `create_rnd_id` with the *same* user-specific inputs, we can still
see the identical *same* IDs generated—which is great for testing.
create_rnd_id = CND.get_create_rnd_id 1234, 87.23
# three different user IDs:
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
# the same repeated, but yielding random other IDs:
log()
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
# the same repeated, but yielding the same IDs as in the first run:
log()
create_rnd_id.rnd.reset()
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
log create_rnd_id [ 'PI:EMAIL:<EMAIL>END_PI' ], 12
The output you should see is
c40f774fce65
9d44f31f9a55
1b26e6e3e736
a0e11f616685
d7242f6935c7
976f26d1b25b
c40f774fce65
9d44f31f9a55
1b26e6e3e736
Note the last three IDs exactly match the first three IDs. The upshot of this is that we get reasonably
hard-to-guess, yet on-demand replayable IDs. Apart from weaknesses in the PRNG itself (for which see the
caveats in the description to `get_rnd`), the obvious way to cheat the system is by making it so that
a given piece of case-specific data is fed into the ID generator as the n-th call a second time. In
theory, we could make it so that each call constributes to the state change inside of `create_rnd_id`;
a replay would then need to provide all of the case-specific pieces of data a second time, in the right
order. ###
#.........................................................................................................
R = ( values, length ) =>
values.push R.rnd()
return @create_id values, length
#.........................................................................................................
R.rnd = @get_rnd seed, delta
#.........................................................................................................
return R
#-----------------------------------------------------------------------------------------------------------
@id_from_text = ( text, length ) ->
### Given a `text` and a `length`, return an ID with `length` hexadecimal digits (`[0-9a-f]`)—this is like
`create_id`, but working on a text rather than a number of arbitrary values. The hash algorithm currently
used is SHA-1, which returns 40 hex digits; it should be good enough for the task at hand and has the
advantage of being widely implemented. ###
### TAINT should be a user option, or take 'good' algorithm universally available ###
R = ( ( ( require 'crypto' ).createHash 'sha1' ).update text, 'utf-8' ).digest 'hex'
return if length? then R[ 0 ... length ] else R
#-----------------------------------------------------------------------------------------------------------
@id_from_route = ( route, length, handler ) ->
### Like `id_from_text`, but accepting a file route instead of a text. ###
throw new Error "asynchronous `id_from_route` not yet supported" if handler?
content = njs_fs.readFileSync route
R = ( ( ( require 'crypto' ).createHash 'sha1' ).update content ).digest 'hex'
return if length? then R[ 0 ... length ] else R
#===========================================================================================================
# APP INFO
#-----------------------------------------------------------------------------------------------------------
@get_app_home = ( routes = null ) ->
### Return the file system route to the current (likely) application folder. This works by traversing all
the routes in `require[ 'main' ][ 'paths' ]` and checking whether one of the `node_modules` folders
listed there exists and is a folder; the first match is accepted and returned. If no matching existing
route is found, an error is thrown.
NB that the algorithm works even if the CoffeeNode Options module has been symlinked from another location
(rather than 'physically' installed) and even if the application main file has been executed from outside
the application folder (i.e. this obviates the need to `cd ~/route/to/my/app` before doing `node ./start`
or whatever—you can simply do `node ~/route/to/my/app/start`), but it does presuppose that (1) there *is*
a `node_modules` folder in your app folder; (2) there is *no* `node_modules` folder in the subfolder or
any of the intervening levels (if any) that contains your startup file. Most modules that follow the
established NodeJS / npm way of structuring modules should naturally comply with these assumptions. ###
njs_fs = require 'fs'
routes ?= require[ 'main' ][ 'paths' ]
#.........................................................................................................
for route in routes
try
return njs_path.dirname route if ( njs_fs.statSync route ).isDirectory()
#.......................................................................................................
catch error
### silently ignore missing routes: ###
continue if error[ 'code' ] is 'ENOENT'
throw error
#.........................................................................................................
throw new Error "unable to determine application home; tested routes: \n\n #{routes.join '\n '}\n"
#===========================================================================================================
# FS ROUTES
#-----------------------------------------------------------------------------------------------------------
@swap_extension = ( route, extension ) ->
extension = '.' + extension unless extension[ 0 ] is '.'
extname = njs_path.extname route
return route[ 0 ... route.length - extname.length ] + extension
#===========================================================================================================
# NETWORK
#-----------------------------------------------------------------------------------------------------------
@get_local_ips = ->
### thx to http://stackoverflow.com/a/10756441/256361 ###
R = []
for _, interface_ of ( require 'os' ).networkInterfaces()
for description in interface_
if description[ 'family' ] is 'IPv4' and not description[ 'internal' ]
R.push description[ 'address' ]
return R
#===========================================================================================================
# ESCAPE FOR COMMAND LINE
#-----------------------------------------------------------------------------------------------------------
```
// thx to https://github.com/xxorax/node-shell-escape/blob/master/shell-escape.js
this.shellescape = function shellescape(a) {
var ret = [];
a.forEach(function(s) {
if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
s = "'"+s.replace(/'/g,"'\\''")+"'";
s = s.replace(/^(?:'')+/g, '') // unduplicate single-quote at the beginning
.replace(/\\'''/g, "\\'" ); // remove non-escaped single-quote if there are enclosed between 2 escaped
}
ret.push(s);
});
return ret.join(' ');
}
```
|
[
{
"context": "arr = []\narr.push 'first'\narr.push 'second'\nconsole.log arr\n",
"end": 24,
"score": 0.9378702640533447,
"start": 19,
"tag": "NAME",
"value": "first"
},
{
"context": "arr = []\narr.push 'first'\narr.push 'second'\nconsole.log arr\n",
"end": 42,
"score": 0.8478... | code/coffeescript/array-add.coffee | evmorov/ruby-coffeescript | 29 | arr = []
arr.push 'first'
arr.push 'second'
console.log arr
| 27656 | arr = []
arr.push '<NAME>'
arr.push '<NAME>'
console.log arr
| true | arr = []
arr.push 'PI:NAME:<NAME>END_PI'
arr.push 'PI:NAME:<NAME>END_PI'
console.log arr
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.9998348355293274,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | src/material/material.coffee | OniDaito/pxljs | 1 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Contract} = require '../gl/contract'
# ## Material
# A base class for materials
class Material
# **@constructor**
constructor : () ->
@contract = new Contract()
# TODO - these are per class not instance so we can change that
@_uber0 = 0 # Settings to be OR'd with the ubershader uniform
@_uber_defines = [] # uber shader looks for this for the defines to add
@_override = false # if set, this material overides all these below it
_addToNode : (node) ->
node.material = @
# Called if we need to make any GL Calls before drawing with
#'this material'
_preDraw : () ->
@
_postDraw : () ->
@
module.exports =
Material : Material
| 208277 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Contract} = require '../gl/contract'
# ## Material
# A base class for materials
class Material
# **@constructor**
constructor : () ->
@contract = new Contract()
# TODO - these are per class not instance so we can change that
@_uber0 = 0 # Settings to be OR'd with the ubershader uniform
@_uber_defines = [] # uber shader looks for this for the defines to add
@_override = false # if set, this material overides all these below it
_addToNode : (node) ->
node.material = @
# Called if we need to make any GL Calls before drawing with
#'this material'
_preDraw : () ->
@
_postDraw : () ->
@
module.exports =
Material : Material
| true | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Contract} = require '../gl/contract'
# ## Material
# A base class for materials
class Material
# **@constructor**
constructor : () ->
@contract = new Contract()
# TODO - these are per class not instance so we can change that
@_uber0 = 0 # Settings to be OR'd with the ubershader uniform
@_uber_defines = [] # uber shader looks for this for the defines to add
@_override = false # if set, this material overides all these below it
_addToNode : (node) ->
node.material = @
# Called if we need to make any GL Calls before drawing with
#'this material'
_preDraw : () ->
@
_postDraw : () ->
@
module.exports =
Material : Material
|
[
{
"context": "rucigrama JS\n @version 0.1\n @date 2015\n @author Jonathan Montoya\n###\n\nCrucigram = do ->\n\n Crucigram = (props) ->\n",
"end": 74,
"score": 0.9998930096626282,
"start": 58,
"tag": "NAME",
"value": "Jonathan Montoya"
}
] | coffee/crucigram.coffee | jonathanxx/mango-crucigram | 1 | ###
Crucigrama JS
@version 0.1
@date 2015
@author Jonathan Montoya
###
Crucigram = do ->
Crucigram = (props) ->
@originWords = null
@updater = null
@arrWords = []
@score = 0
@mark = props.mark
@attrMark = props.attrMark or 'data-mark'
@clsMark = props.clsMark or 'textMark'
@words = props.words
@check = props.check
@press = props.press
@originBackground = props.originBackground
@pressBackground = props.pressBackground
@point = props.point or 1
@finishGame = props.finishGame
@finishTime = props.finishTime
@minimum = props.minimum or this.size(this.words)
@minutes = props.minutes or 20
@time = props.time || false
@timerId = props.timerId or 'timer'
#Obtener indice del elemento
Crucigram::indexOf = (o, e) ->
[x, l, i] = [0, o.length, 0]
while x < l
if e is o[x] then i = x
x++
i
#Obtener longitud del
Crucigram::size = (o) ->
l = 0
for k,v of o then if o.hasOwnProperty k then ++l
l
#Organizar letras del crucigrama
Crucigram::organize = ->
@originWords = @words
for k,v of @words
if @words.hasOwnProperty (k) then @words[k].word = @words[k].word.split ''
#Acciones al presionar teclas
Crucigram::pressKey = ->
obj = @
press = document.getElementsByClassName @press
i = 0
l = press.length
while i < l
#Establecer background por defecto
press[i].style.backgroundColor = @originBackground
press[i].onclick = ->
_press = @;
@style.backgroundColor = obj.pressBackground
@tabIndex = obj.indexOf press, @
@focus()
#Cambiar color a activo
@onblur = -> _press.style.backgroundColor = obj.originBackground
#Insertar letra en crucigrama
@onkeydown = (e) ->
e = e or window.event
key = e.keyCode or e.chartCode or e.which
if key >= 65 and key <= 90
_press.innerHTML = String.fromCharCode key
else e.returnValue = false
i++
#Comprueba el crucigrama
Crucigram::checkWords = ->
obj = @
check = document.getElementsByClassName(@check)[0]
check.onclick = ->
obj.confirm()
#Iniciar crucigrama
Crucigram::start = ->
@organize()
@pressKey()
@checkWords()
if @time is true then @timer()
Crucigram::confirm = ->
obj = @
for k,v of obj.words
if obj.words.hasOwnProperty k
innerWord = document.getElementsByClassName k
word = obj.words[k].word
storeWord = []
#Guardar palabras que se han completado
x = 0
l = innerWord.length
while x < l
_x = innerWord[x].innerHTML
storeWord.push _x
x++
#Comprobar palabras
word = word.join ''
reverse = (arr) -> arr.slice().reverse()
reverseWord = reverse(storeWord).join ''
storeWord = storeWord.join ''
if (word is storeWord) or (word is reverseWord)
#Sumar puntaje
obj.score = obj.score + obj.point
obj.arrWords.push word
#Marcar palabras que se han completado
if obj.words[k].mark is true
m = document.getElementsByClassName obj.mark
j = 0
l = m.length
while j < l
mk = m[j].getAttribute obj.attrMark
if mk is k
m[j].className = m[j].className + ' ' + obj.clsMark
m[j].innerHTML = word
j++
#Elimina elementos para que no hayan repetidos
delete obj.words[k]
#Elimina eventos a palabras terminadas
cl = document.getElementsByClassName k
x = 0
l = cl.length
while x < l
cl[x].onkeydown = null
cl[x].onclick = null
x++
else
#Resetear estilo a la palabra
cl = document.getElementsByClassName k
x = 0
l = cl.length
while x < l
cl[x].style.backgroundColor = obj.originBackground
x++
#Terminar juego
if obj.arrWords.length >= obj.minimum
if obj.time is true
document.getElementById(obj.timerId).innerHTML = '00:00'
clearInterval obj.updater
obj.finishGame obj.score, obj.arrWords
Crucigram::timer = ->
if @minutes <= 59 and @minutes >= 1
obj = @
min = (60 * 1000) * @minutes
last = new Date();
last = last.getTime() + min
#Generar tiempo
generateTime = ->
now = new Date()
now = now.getTime()
#Generar tiempo
m = Math.floor (last - now) / 1000 / 60
s = Math.round ((last - now) / 1000) - (60 * m)
s = if s is 60 then 59 else s
#Tiempo a texto
seconds = if s is 0 then '00' else (if s < 10 then '0' + s.toString() else s.toString())
minutes = if m is 0 then '00' else (if m < 10 then '0' + m.toString() else m.toString())
timerText = minutes + ":" + seconds
return {
minutes: minutes
seconds: seconds
timerText: timerText
realSecond: s
realMinute: m
}
#Actualiza el contador
updateTime = ->
time = generateTime()
document.getElementById(obj.timerId).innerHTML = time.timerText
#Finalizar tiempo
if time.realMinute is 0 and time.realSecond is 1
#Finalizar juego
document.getElementById(obj.timerId).innerHTML = '00:00'
obj.confirm()
obj.finishTime obj.score, obj.arrWords
clearInterval obj.updater
obj.updater = setInterval updateTime, 1000
yes
Crucigram
window.Crucigram = Crucigram | 36807 | ###
Crucigrama JS
@version 0.1
@date 2015
@author <NAME>
###
Crucigram = do ->
Crucigram = (props) ->
@originWords = null
@updater = null
@arrWords = []
@score = 0
@mark = props.mark
@attrMark = props.attrMark or 'data-mark'
@clsMark = props.clsMark or 'textMark'
@words = props.words
@check = props.check
@press = props.press
@originBackground = props.originBackground
@pressBackground = props.pressBackground
@point = props.point or 1
@finishGame = props.finishGame
@finishTime = props.finishTime
@minimum = props.minimum or this.size(this.words)
@minutes = props.minutes or 20
@time = props.time || false
@timerId = props.timerId or 'timer'
#Obtener indice del elemento
Crucigram::indexOf = (o, e) ->
[x, l, i] = [0, o.length, 0]
while x < l
if e is o[x] then i = x
x++
i
#Obtener longitud del
Crucigram::size = (o) ->
l = 0
for k,v of o then if o.hasOwnProperty k then ++l
l
#Organizar letras del crucigrama
Crucigram::organize = ->
@originWords = @words
for k,v of @words
if @words.hasOwnProperty (k) then @words[k].word = @words[k].word.split ''
#Acciones al presionar teclas
Crucigram::pressKey = ->
obj = @
press = document.getElementsByClassName @press
i = 0
l = press.length
while i < l
#Establecer background por defecto
press[i].style.backgroundColor = @originBackground
press[i].onclick = ->
_press = @;
@style.backgroundColor = obj.pressBackground
@tabIndex = obj.indexOf press, @
@focus()
#Cambiar color a activo
@onblur = -> _press.style.backgroundColor = obj.originBackground
#Insertar letra en crucigrama
@onkeydown = (e) ->
e = e or window.event
key = e.keyCode or e.chartCode or e.which
if key >= 65 and key <= 90
_press.innerHTML = String.fromCharCode key
else e.returnValue = false
i++
#Comprueba el crucigrama
Crucigram::checkWords = ->
obj = @
check = document.getElementsByClassName(@check)[0]
check.onclick = ->
obj.confirm()
#Iniciar crucigrama
Crucigram::start = ->
@organize()
@pressKey()
@checkWords()
if @time is true then @timer()
Crucigram::confirm = ->
obj = @
for k,v of obj.words
if obj.words.hasOwnProperty k
innerWord = document.getElementsByClassName k
word = obj.words[k].word
storeWord = []
#Guardar palabras que se han completado
x = 0
l = innerWord.length
while x < l
_x = innerWord[x].innerHTML
storeWord.push _x
x++
#Comprobar palabras
word = word.join ''
reverse = (arr) -> arr.slice().reverse()
reverseWord = reverse(storeWord).join ''
storeWord = storeWord.join ''
if (word is storeWord) or (word is reverseWord)
#Sumar puntaje
obj.score = obj.score + obj.point
obj.arrWords.push word
#Marcar palabras que se han completado
if obj.words[k].mark is true
m = document.getElementsByClassName obj.mark
j = 0
l = m.length
while j < l
mk = m[j].getAttribute obj.attrMark
if mk is k
m[j].className = m[j].className + ' ' + obj.clsMark
m[j].innerHTML = word
j++
#Elimina elementos para que no hayan repetidos
delete obj.words[k]
#Elimina eventos a palabras terminadas
cl = document.getElementsByClassName k
x = 0
l = cl.length
while x < l
cl[x].onkeydown = null
cl[x].onclick = null
x++
else
#Resetear estilo a la palabra
cl = document.getElementsByClassName k
x = 0
l = cl.length
while x < l
cl[x].style.backgroundColor = obj.originBackground
x++
#Terminar juego
if obj.arrWords.length >= obj.minimum
if obj.time is true
document.getElementById(obj.timerId).innerHTML = '00:00'
clearInterval obj.updater
obj.finishGame obj.score, obj.arrWords
Crucigram::timer = ->
if @minutes <= 59 and @minutes >= 1
obj = @
min = (60 * 1000) * @minutes
last = new Date();
last = last.getTime() + min
#Generar tiempo
generateTime = ->
now = new Date()
now = now.getTime()
#Generar tiempo
m = Math.floor (last - now) / 1000 / 60
s = Math.round ((last - now) / 1000) - (60 * m)
s = if s is 60 then 59 else s
#Tiempo a texto
seconds = if s is 0 then '00' else (if s < 10 then '0' + s.toString() else s.toString())
minutes = if m is 0 then '00' else (if m < 10 then '0' + m.toString() else m.toString())
timerText = minutes + ":" + seconds
return {
minutes: minutes
seconds: seconds
timerText: timerText
realSecond: s
realMinute: m
}
#Actualiza el contador
updateTime = ->
time = generateTime()
document.getElementById(obj.timerId).innerHTML = time.timerText
#Finalizar tiempo
if time.realMinute is 0 and time.realSecond is 1
#Finalizar juego
document.getElementById(obj.timerId).innerHTML = '00:00'
obj.confirm()
obj.finishTime obj.score, obj.arrWords
clearInterval obj.updater
obj.updater = setInterval updateTime, 1000
yes
Crucigram
window.Crucigram = Crucigram | true | ###
Crucigrama JS
@version 0.1
@date 2015
@author PI:NAME:<NAME>END_PI
###
Crucigram = do ->
Crucigram = (props) ->
@originWords = null
@updater = null
@arrWords = []
@score = 0
@mark = props.mark
@attrMark = props.attrMark or 'data-mark'
@clsMark = props.clsMark or 'textMark'
@words = props.words
@check = props.check
@press = props.press
@originBackground = props.originBackground
@pressBackground = props.pressBackground
@point = props.point or 1
@finishGame = props.finishGame
@finishTime = props.finishTime
@minimum = props.minimum or this.size(this.words)
@minutes = props.minutes or 20
@time = props.time || false
@timerId = props.timerId or 'timer'
#Obtener indice del elemento
Crucigram::indexOf = (o, e) ->
[x, l, i] = [0, o.length, 0]
while x < l
if e is o[x] then i = x
x++
i
#Obtener longitud del
Crucigram::size = (o) ->
l = 0
for k,v of o then if o.hasOwnProperty k then ++l
l
#Organizar letras del crucigrama
Crucigram::organize = ->
@originWords = @words
for k,v of @words
if @words.hasOwnProperty (k) then @words[k].word = @words[k].word.split ''
#Acciones al presionar teclas
Crucigram::pressKey = ->
obj = @
press = document.getElementsByClassName @press
i = 0
l = press.length
while i < l
#Establecer background por defecto
press[i].style.backgroundColor = @originBackground
press[i].onclick = ->
_press = @;
@style.backgroundColor = obj.pressBackground
@tabIndex = obj.indexOf press, @
@focus()
#Cambiar color a activo
@onblur = -> _press.style.backgroundColor = obj.originBackground
#Insertar letra en crucigrama
@onkeydown = (e) ->
e = e or window.event
key = e.keyCode or e.chartCode or e.which
if key >= 65 and key <= 90
_press.innerHTML = String.fromCharCode key
else e.returnValue = false
i++
#Comprueba el crucigrama
Crucigram::checkWords = ->
obj = @
check = document.getElementsByClassName(@check)[0]
check.onclick = ->
obj.confirm()
#Iniciar crucigrama
Crucigram::start = ->
@organize()
@pressKey()
@checkWords()
if @time is true then @timer()
Crucigram::confirm = ->
obj = @
for k,v of obj.words
if obj.words.hasOwnProperty k
innerWord = document.getElementsByClassName k
word = obj.words[k].word
storeWord = []
#Guardar palabras que se han completado
x = 0
l = innerWord.length
while x < l
_x = innerWord[x].innerHTML
storeWord.push _x
x++
#Comprobar palabras
word = word.join ''
reverse = (arr) -> arr.slice().reverse()
reverseWord = reverse(storeWord).join ''
storeWord = storeWord.join ''
if (word is storeWord) or (word is reverseWord)
#Sumar puntaje
obj.score = obj.score + obj.point
obj.arrWords.push word
#Marcar palabras que se han completado
if obj.words[k].mark is true
m = document.getElementsByClassName obj.mark
j = 0
l = m.length
while j < l
mk = m[j].getAttribute obj.attrMark
if mk is k
m[j].className = m[j].className + ' ' + obj.clsMark
m[j].innerHTML = word
j++
#Elimina elementos para que no hayan repetidos
delete obj.words[k]
#Elimina eventos a palabras terminadas
cl = document.getElementsByClassName k
x = 0
l = cl.length
while x < l
cl[x].onkeydown = null
cl[x].onclick = null
x++
else
#Resetear estilo a la palabra
cl = document.getElementsByClassName k
x = 0
l = cl.length
while x < l
cl[x].style.backgroundColor = obj.originBackground
x++
#Terminar juego
if obj.arrWords.length >= obj.minimum
if obj.time is true
document.getElementById(obj.timerId).innerHTML = '00:00'
clearInterval obj.updater
obj.finishGame obj.score, obj.arrWords
Crucigram::timer = ->
if @minutes <= 59 and @minutes >= 1
obj = @
min = (60 * 1000) * @minutes
last = new Date();
last = last.getTime() + min
#Generar tiempo
generateTime = ->
now = new Date()
now = now.getTime()
#Generar tiempo
m = Math.floor (last - now) / 1000 / 60
s = Math.round ((last - now) / 1000) - (60 * m)
s = if s is 60 then 59 else s
#Tiempo a texto
seconds = if s is 0 then '00' else (if s < 10 then '0' + s.toString() else s.toString())
minutes = if m is 0 then '00' else (if m < 10 then '0' + m.toString() else m.toString())
timerText = minutes + ":" + seconds
return {
minutes: minutes
seconds: seconds
timerText: timerText
realSecond: s
realMinute: m
}
#Actualiza el contador
updateTime = ->
time = generateTime()
document.getElementById(obj.timerId).innerHTML = time.timerText
#Finalizar tiempo
if time.realMinute is 0 and time.realSecond is 1
#Finalizar juego
document.getElementById(obj.timerId).innerHTML = '00:00'
obj.confirm()
obj.finishTime obj.score, obj.arrWords
clearInterval obj.updater
obj.updater = setInterval updateTime, 1000
yes
Crucigram
window.Crucigram = Crucigram |
[
{
"context": "##\n##\n## Forked from Jeff Mott's CryptoJS\n##\n## https://code.google.com/p/cryp",
"end": 30,
"score": 0.9998633861541748,
"start": 21,
"tag": "NAME",
"value": "Jeff Mott"
},
{
"context": "n implementation of standard AES, forked from \n# [Jeff Mott's CryptoJS](http... | node_modules/triplesec/src/aes.iced | mazodan/mazodan.github.io | 0 | ##
##
## Forked from Jeff Mott's CryptoJS
##
## https://code.google.com/p/crypto-js/
##
{BlockCipher} = require './algbase'
{scrub_vec} = require './util'
#=======================================================================
#
# @private Global
#
# Global state used in all instances of AES, which is either
# immutable, or safe for one block only (if trampled by others).
#
#
class Global
constructor : ->
@SBOX = []
@INV_SBOX = []
@SUB_MIX = ([] for i in [0...4])
@INV_SUB_MIX = ([] for i in [0...4])
@init()
# Precomputed Rcon lookup
@RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
init : () ->
# Compute double table
d = for i in [0...256]
if (i < 128) then (i << 1) else ((i << 1) ^ 0x11b)
# Walk GF(2^8)
x = 0
xi = 0
for i in [0...256]
# Compute sbox
sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
@SBOX[x] = sx
@INV_SBOX[sx] = x
# Compute multiplication
x2 = d[x]
x4 = d[x2]
x8 = d[x4]
# Compute sub bytes, mix columns tables
t = (d[sx] * 0x101) ^ (sx * 0x1010100)
@SUB_MIX[0][x] = (t << 24) | (t >>> 8)
@SUB_MIX[1][x] = (t << 16) | (t >>> 16)
@SUB_MIX[2][x] = (t << 8) | (t >>> 24)
@SUB_MIX[3][x] = t
# Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
@INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
@INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
@INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
@INV_SUB_MIX[3][sx] = t
# Compute next counter
if x is 0 then x = xi = 1
else
x = x2 ^ d[d[d[x8 ^ x2]]]
xi ^= d[d[xi]]
true
#=======================================================================
G = new Global()
#=======================================================================
#
# ### Advanced Encyrption Standard (AES).
#
# An implementation of standard AES, forked from
# [Jeff Mott's CryptoJS](https://code.google.com/p/crypto-js/).
# See [Wikipedia](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
# for a high-level overview, and [FIPS 197](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf)
# for more information on the standard.
#
# Here, we have implemented AES-256, which takes a 256-bit key, block input
# of 128-bits, and outputs blocks of 128-bits.
#
class AES extends BlockCipher
# Blocksize in bytes --- Each round transforms 4 32-bit
# words, so 16 bytes in total
@blockSize : 4*4
blockSize : AES.blockSize
@keySize : 256/8
keySize : AES.keySize
@ivSize : AES.blockSize
ivSize : AES.ivSize
#-------------------------
#
# Create a new AES encryption engine
#
# @param {WordArray} key The encryption key
#
constructor : (key) ->
@_key = key.clone()
@_doReset()
#-------------------------
# @private method _doReset
#
# Resets the internal state of the AES cipher
_doReset : ->
# Shortcuts
keyWords = @_key.words
keySize = @_key.sigBytes / 4
# Compute number of rounds
@_nRounds = keySize + 6
# Compute number of key schedule rows
ksRows = (@_nRounds + 1) * 4
# Compute key schedule
@_keySchedule = []
for ksRow in [0...ksRows]
@_keySchedule[ksRow] = if ksRow < keySize then keyWords[ksRow]
else
t = @_keySchedule[ksRow - 1]
if (ksRow % keySize) is 0
# Rot word
t = (t << 8) | (t >>> 24)
# Sub word
t = ((G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff])
# Mix Rcon
t ^= G.RCON[(ksRow / keySize) | 0] << 24
else if (keySize > 6 && ksRow % keySize == 4)
# Sub word
t = ((G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff])
@_keySchedule[ksRow - keySize] ^ t
# Compute inv key schedule
@_invKeySchedule = []
for invKsRow in [0...ksRows]
ksRow = ksRows - invKsRow
t = @_keySchedule[ksRow - (if (invKsRow % 4) then 0 else 4)]
@_invKeySchedule[invKsRow] = if (invKsRow < 4 || ksRow <= 4) then t
else (G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^
G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^
G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^
G.INV_SUB_MIX[3][G.SBOX[t & 0xff]])
true
#-------------------------
# @method encryptBlock
#
# Encrypt one AES-block of input ciphertext *in place*. Replace the
# plaintext with the output ciphertext.
#
# This is a lower-level function that should not be called directly, but only by
# higher-level routines.
#
# @param {Array<uint32>} M An array of uint32s, that can be way longer than an AES block
# @param {Number} offset The offset into M, in # of words.
#
encryptBlock : (M, offset = 0) ->
@_doCryptBlock M, offset, @_keySchedule, G.SUB_MIX, G.SBOX
#-------------------------
# @method decryptBlock
#
# Decrypt one AES-block of input ciphertext *in place*. Replace the
# ciphertext with the output plaintext.
#
# This is a lower-level function that should not be called directly, but only by
# higher-level routines.
#
# @param {Array<uint32>} M An array of uint32s, that can be way longer than an AES block
# @param {Number} offset The offset into M, in # of words.
#
decryptBlock: (M, offset = 0) ->
# Swap 2nd and 4th rows
[ M[offset + 1], M[offset + 3] ] = [ M[offset + 3], M[offset + 1] ]
@_doCryptBlock M, offset, @_invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX
# Inv swap 2nd and 4th rows
[ M[offset + 1], M[offset + 3] ] = [ M[offset + 3], M[offset + 1] ]
#-------------------------
# @method scrub
#
# Zero-out all internal state that's sensitive.
scrub : () ->
scrub_vec @_keySchedule
scrub_vec @_invKeySchedule
@_key.scrub()
#-------------------------
# @private _doCryptBlock
#
# The internal workhouse of the algorithm.
#
_doCryptBlock: (M, offset, keySchedule, SUB_MIX, SBOX) ->
# Get input, add round key
s0 = M[offset] ^ keySchedule[0]
s1 = M[offset + 1] ^ keySchedule[1]
s2 = M[offset + 2] ^ keySchedule[2]
s3 = M[offset + 3] ^ keySchedule[3]
# Key schedule row counter
ksRow = 4
# Rounds
for round in [1...@_nRounds]
# Shift rows, sub bytes, mix columns, add round key
t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++]
t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++]
t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++]
t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++]
#Update state
s0 = t0
s1 = t1
s2 = t2
s3 = t3
# Shift rows, sub bytes, add round key
t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
# Set output
M[offset] = t0
M[offset + 1] = t1
M[offset + 2] = t2
M[offset + 3] = t3
#=======================================================================
exports.AES = AES
#=======================================================================
| 148032 | ##
##
## Forked from <NAME>'s CryptoJS
##
## https://code.google.com/p/crypto-js/
##
{BlockCipher} = require './algbase'
{scrub_vec} = require './util'
#=======================================================================
#
# @private Global
#
# Global state used in all instances of AES, which is either
# immutable, or safe for one block only (if trampled by others).
#
#
class Global
constructor : ->
@SBOX = []
@INV_SBOX = []
@SUB_MIX = ([] for i in [0...4])
@INV_SUB_MIX = ([] for i in [0...4])
@init()
# Precomputed Rcon lookup
@RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
init : () ->
# Compute double table
d = for i in [0...256]
if (i < 128) then (i << 1) else ((i << 1) ^ 0x11b)
# Walk GF(2^8)
x = 0
xi = 0
for i in [0...256]
# Compute sbox
sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
@SBOX[x] = sx
@INV_SBOX[sx] = x
# Compute multiplication
x2 = d[x]
x4 = d[x2]
x8 = d[x4]
# Compute sub bytes, mix columns tables
t = (d[sx] * 0x101) ^ (sx * 0x1010100)
@SUB_MIX[0][x] = (t << 24) | (t >>> 8)
@SUB_MIX[1][x] = (t << 16) | (t >>> 16)
@SUB_MIX[2][x] = (t << 8) | (t >>> 24)
@SUB_MIX[3][x] = t
# Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
@INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
@INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
@INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
@INV_SUB_MIX[3][sx] = t
# Compute next counter
if x is 0 then x = xi = 1
else
x = x2 ^ d[d[d[x8 ^ x2]]]
xi ^= d[d[xi]]
true
#=======================================================================
G = new Global()
#=======================================================================
#
# ### Advanced Encyrption Standard (AES).
#
# An implementation of standard AES, forked from
# [<NAME>'s CryptoJS](https://code.google.com/p/crypto-js/).
# See [Wikipedia](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
# for a high-level overview, and [FIPS 197](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf)
# for more information on the standard.
#
# Here, we have implemented AES-256, which takes a 256-bit key, block input
# of 128-bits, and outputs blocks of 128-bits.
#
class AES extends BlockCipher
# Blocksize in bytes --- Each round transforms 4 32-bit
# words, so 16 bytes in total
@blockSize : 4*4
blockSize : AES.blockSize
@keySize : 256/8
keySize : AES.keySize
@ivSize : AES.blockSize
ivSize : AES.ivSize
#-------------------------
#
# Create a new AES encryption engine
#
# @param {WordArray} key The encryption key
#
constructor : (key) ->
@_key = key.clone()
@_doReset()
#-------------------------
# @private method _doReset
#
# Resets the internal state of the AES cipher
_doReset : ->
# Shortcuts
keyWords = @_key.words
keySize = @_key.sigBytes / 4
# Compute number of rounds
@_nRounds = keySize + 6
# Compute number of key schedule rows
ksRows = (@_nRounds + 1) * 4
# Compute key schedule
@_keySchedule = []
for ksRow in [0...ksRows]
@_keySchedule[ksRow] = if ksRow < keySize then keyWords[ksRow]
else
t = @_keySchedule[ksRow - 1]
if (ksRow % keySize) is 0
# Rot word
t = (t << 8) | (t >>> 24)
# Sub word
t = ((G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff])
# Mix Rcon
t ^= G.RCON[(ksRow / keySize) | 0] << 24
else if (keySize > 6 && ksRow % keySize == 4)
# Sub word
t = ((G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff])
@_keySchedule[ksRow - keySize] ^ t
# Compute inv key schedule
@_invKeySchedule = []
for invKsRow in [0...ksRows]
ksRow = ksRows - invKsRow
t = @_keySchedule[ksRow - (if (invKsRow % 4) then 0 else 4)]
@_invKeySchedule[invKsRow] = if (invKsRow < 4 || ksRow <= 4) then t
else (G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^
G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^
G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^
G.INV_SUB_MIX[3][G.SBOX[t & 0xff]])
true
#-------------------------
# @method encryptBlock
#
# Encrypt one AES-block of input ciphertext *in place*. Replace the
# plaintext with the output ciphertext.
#
# This is a lower-level function that should not be called directly, but only by
# higher-level routines.
#
# @param {Array<uint32>} M An array of uint32s, that can be way longer than an AES block
# @param {Number} offset The offset into M, in # of words.
#
encryptBlock : (M, offset = 0) ->
@_doCryptBlock M, offset, @_keySchedule, G.SUB_MIX, G.SBOX
#-------------------------
# @method decryptBlock
#
# Decrypt one AES-block of input ciphertext *in place*. Replace the
# ciphertext with the output plaintext.
#
# This is a lower-level function that should not be called directly, but only by
# higher-level routines.
#
# @param {Array<uint32>} M An array of uint32s, that can be way longer than an AES block
# @param {Number} offset The offset into M, in # of words.
#
decryptBlock: (M, offset = 0) ->
# Swap 2nd and 4th rows
[ M[offset + 1], M[offset + 3] ] = [ M[offset + 3], M[offset + 1] ]
@_doCryptBlock M, offset, @_invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX
# Inv swap 2nd and 4th rows
[ M[offset + 1], M[offset + 3] ] = [ M[offset + 3], M[offset + 1] ]
#-------------------------
# @method scrub
#
# Zero-out all internal state that's sensitive.
scrub : () ->
scrub_vec @_keySchedule
scrub_vec @_invKeySchedule
@_key.scrub()
#-------------------------
# @private _doCryptBlock
#
# The internal workhouse of the algorithm.
#
_doCryptBlock: (M, offset, keySchedule, SUB_MIX, SBOX) ->
# Get input, add round key
s0 = M[offset] ^ keySchedule[0]
s1 = M[offset + 1] ^ keySchedule[1]
s2 = M[offset + 2] ^ keySchedule[2]
s3 = M[offset + 3] ^ keySchedule[3]
# Key schedule row counter
ksRow = 4
# Rounds
for round in [1...@_nRounds]
# Shift rows, sub bytes, mix columns, add round key
t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++]
t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++]
t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++]
t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++]
#Update state
s0 = t0
s1 = t1
s2 = t2
s3 = t3
# Shift rows, sub bytes, add round key
t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
# Set output
M[offset] = t0
M[offset + 1] = t1
M[offset + 2] = t2
M[offset + 3] = t3
#=======================================================================
exports.AES = AES
#=======================================================================
| true | ##
##
## Forked from PI:NAME:<NAME>END_PI's CryptoJS
##
## https://code.google.com/p/crypto-js/
##
{BlockCipher} = require './algbase'
{scrub_vec} = require './util'
#=======================================================================
#
# @private Global
#
# Global state used in all instances of AES, which is either
# immutable, or safe for one block only (if trampled by others).
#
#
class Global
constructor : ->
@SBOX = []
@INV_SBOX = []
@SUB_MIX = ([] for i in [0...4])
@INV_SUB_MIX = ([] for i in [0...4])
@init()
# Precomputed Rcon lookup
@RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
init : () ->
# Compute double table
d = for i in [0...256]
if (i < 128) then (i << 1) else ((i << 1) ^ 0x11b)
# Walk GF(2^8)
x = 0
xi = 0
for i in [0...256]
# Compute sbox
sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
@SBOX[x] = sx
@INV_SBOX[sx] = x
# Compute multiplication
x2 = d[x]
x4 = d[x2]
x8 = d[x4]
# Compute sub bytes, mix columns tables
t = (d[sx] * 0x101) ^ (sx * 0x1010100)
@SUB_MIX[0][x] = (t << 24) | (t >>> 8)
@SUB_MIX[1][x] = (t << 16) | (t >>> 16)
@SUB_MIX[2][x] = (t << 8) | (t >>> 24)
@SUB_MIX[3][x] = t
# Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
@INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
@INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
@INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
@INV_SUB_MIX[3][sx] = t
# Compute next counter
if x is 0 then x = xi = 1
else
x = x2 ^ d[d[d[x8 ^ x2]]]
xi ^= d[d[xi]]
true
#=======================================================================
G = new Global()
#=======================================================================
#
# ### Advanced Encyrption Standard (AES).
#
# An implementation of standard AES, forked from
# [PI:NAME:<NAME>END_PI's CryptoJS](https://code.google.com/p/crypto-js/).
# See [Wikipedia](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
# for a high-level overview, and [FIPS 197](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf)
# for more information on the standard.
#
# Here, we have implemented AES-256, which takes a 256-bit key, block input
# of 128-bits, and outputs blocks of 128-bits.
#
class AES extends BlockCipher
# Blocksize in bytes --- Each round transforms 4 32-bit
# words, so 16 bytes in total
@blockSize : 4*4
blockSize : AES.blockSize
@keySize : 256/8
keySize : AES.keySize
@ivSize : AES.blockSize
ivSize : AES.ivSize
#-------------------------
#
# Create a new AES encryption engine
#
# @param {WordArray} key The encryption key
#
constructor : (key) ->
@_key = key.clone()
@_doReset()
#-------------------------
# @private method _doReset
#
# Resets the internal state of the AES cipher
_doReset : ->
# Shortcuts
keyWords = @_key.words
keySize = @_key.sigBytes / 4
# Compute number of rounds
@_nRounds = keySize + 6
# Compute number of key schedule rows
ksRows = (@_nRounds + 1) * 4
# Compute key schedule
@_keySchedule = []
for ksRow in [0...ksRows]
@_keySchedule[ksRow] = if ksRow < keySize then keyWords[ksRow]
else
t = @_keySchedule[ksRow - 1]
if (ksRow % keySize) is 0
# Rot word
t = (t << 8) | (t >>> 24)
# Sub word
t = ((G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff])
# Mix Rcon
t ^= G.RCON[(ksRow / keySize) | 0] << 24
else if (keySize > 6 && ksRow % keySize == 4)
# Sub word
t = ((G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff])
@_keySchedule[ksRow - keySize] ^ t
# Compute inv key schedule
@_invKeySchedule = []
for invKsRow in [0...ksRows]
ksRow = ksRows - invKsRow
t = @_keySchedule[ksRow - (if (invKsRow % 4) then 0 else 4)]
@_invKeySchedule[invKsRow] = if (invKsRow < 4 || ksRow <= 4) then t
else (G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^
G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^
G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^
G.INV_SUB_MIX[3][G.SBOX[t & 0xff]])
true
#-------------------------
# @method encryptBlock
#
# Encrypt one AES-block of input ciphertext *in place*. Replace the
# plaintext with the output ciphertext.
#
# This is a lower-level function that should not be called directly, but only by
# higher-level routines.
#
# @param {Array<uint32>} M An array of uint32s, that can be way longer than an AES block
# @param {Number} offset The offset into M, in # of words.
#
encryptBlock : (M, offset = 0) ->
@_doCryptBlock M, offset, @_keySchedule, G.SUB_MIX, G.SBOX
#-------------------------
# @method decryptBlock
#
# Decrypt one AES-block of input ciphertext *in place*. Replace the
# ciphertext with the output plaintext.
#
# This is a lower-level function that should not be called directly, but only by
# higher-level routines.
#
# @param {Array<uint32>} M An array of uint32s, that can be way longer than an AES block
# @param {Number} offset The offset into M, in # of words.
#
decryptBlock: (M, offset = 0) ->
# Swap 2nd and 4th rows
[ M[offset + 1], M[offset + 3] ] = [ M[offset + 3], M[offset + 1] ]
@_doCryptBlock M, offset, @_invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX
# Inv swap 2nd and 4th rows
[ M[offset + 1], M[offset + 3] ] = [ M[offset + 3], M[offset + 1] ]
#-------------------------
# @method scrub
#
# Zero-out all internal state that's sensitive.
scrub : () ->
scrub_vec @_keySchedule
scrub_vec @_invKeySchedule
@_key.scrub()
#-------------------------
# @private _doCryptBlock
#
# The internal workhouse of the algorithm.
#
_doCryptBlock: (M, offset, keySchedule, SUB_MIX, SBOX) ->
# Get input, add round key
s0 = M[offset] ^ keySchedule[0]
s1 = M[offset + 1] ^ keySchedule[1]
s2 = M[offset + 2] ^ keySchedule[2]
s3 = M[offset + 3] ^ keySchedule[3]
# Key schedule row counter
ksRow = 4
# Rounds
for round in [1...@_nRounds]
# Shift rows, sub bytes, mix columns, add round key
t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++]
t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++]
t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++]
t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++]
#Update state
s0 = t0
s1 = t1
s2 = t2
s3 = t3
# Shift rows, sub bytes, add round key
t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
# Set output
M[offset] = t0
M[offset + 1] = t1
M[offset + 2] = t2
M[offset + 3] = t3
#=======================================================================
exports.AES = AES
#=======================================================================
|
[
{
"context": "Title\n\n message = \"\"\"\n Username : #{user.username}\n User Agent : #{req.headers['user-agent']",
"end": 1041,
"score": 0.7880478501319885,
"start": 1028,
"tag": "USERNAME",
"value": "user.username"
},
{
"context": " user : key\n ... | servers/lib/server/helpscout.coffee | ezgikaysi/koding | 1 | request = require 'request'
KONFIG = require 'koding-config-manager'
module.exports = (account, req, res) ->
Payment = require '../../../workers/social/lib/social/models/payment'
{ apiKey, baseUrl } = KONFIG.helpscout if KONFIG.helpscout
if not apiKey or not baseUrl
errorText = 'HelpScout is disabled because of missing configuration'
console.warn errorText
return res.status(400).send
description : errorText
error : 'bad_request'
account.fetchUser (err, user) ->
if err? or not user?
return res.status(401).end()
{ message, subject } = req.body
if not message or not subject
return res.status(400).send
description : 'message and subject required'
error : 'bad_request'
client = { connection: { delegate: account } }
Payment.subscriptions client, {}, (err, subscription) ->
if err? or not subscription?
then plan = 'free'
else plan = subscription.planTitle
message = """
Username : #{user.username}
User Agent : #{req.headers['user-agent']}
User Plan : #{plan}
----------------------------------------
""" + message
request
url : "#{baseUrl}/conversations.json"
method : 'POST'
auth :
user : key
pass : 'x'
json :
type : 'email'
customer :
email : user.email
type : 'customer'
subject : subject
mailbox :
id : 19295
name : 'Support'
,
tags : ["Plan->#{plan}"]
,
threads : [
type : 'customer'
createdBy :
email : user.email
type : 'customer'
,
body : message
]
, (error, response, body) ->
if error or body
console.error error, body
res.status(400).send { ok: 0 }
else
res.status(200).send { ok: 1 }
| 144493 | request = require 'request'
KONFIG = require 'koding-config-manager'
module.exports = (account, req, res) ->
Payment = require '../../../workers/social/lib/social/models/payment'
{ apiKey, baseUrl } = KONFIG.helpscout if KONFIG.helpscout
if not apiKey or not baseUrl
errorText = 'HelpScout is disabled because of missing configuration'
console.warn errorText
return res.status(400).send
description : errorText
error : 'bad_request'
account.fetchUser (err, user) ->
if err? or not user?
return res.status(401).end()
{ message, subject } = req.body
if not message or not subject
return res.status(400).send
description : 'message and subject required'
error : 'bad_request'
client = { connection: { delegate: account } }
Payment.subscriptions client, {}, (err, subscription) ->
if err? or not subscription?
then plan = 'free'
else plan = subscription.planTitle
message = """
Username : #{user.username}
User Agent : #{req.headers['user-agent']}
User Plan : #{plan}
----------------------------------------
""" + message
request
url : "#{baseUrl}/conversations.json"
method : 'POST'
auth :
user : key
pass : '<PASSWORD>'
json :
type : 'email'
customer :
email : user.email
type : 'customer'
subject : subject
mailbox :
id : 19295
name : 'Support'
,
tags : ["Plan->#{plan}"]
,
threads : [
type : 'customer'
createdBy :
email : user.email
type : 'customer'
,
body : message
]
, (error, response, body) ->
if error or body
console.error error, body
res.status(400).send { ok: 0 }
else
res.status(200).send { ok: 1 }
| true | request = require 'request'
KONFIG = require 'koding-config-manager'
module.exports = (account, req, res) ->
Payment = require '../../../workers/social/lib/social/models/payment'
{ apiKey, baseUrl } = KONFIG.helpscout if KONFIG.helpscout
if not apiKey or not baseUrl
errorText = 'HelpScout is disabled because of missing configuration'
console.warn errorText
return res.status(400).send
description : errorText
error : 'bad_request'
account.fetchUser (err, user) ->
if err? or not user?
return res.status(401).end()
{ message, subject } = req.body
if not message or not subject
return res.status(400).send
description : 'message and subject required'
error : 'bad_request'
client = { connection: { delegate: account } }
Payment.subscriptions client, {}, (err, subscription) ->
if err? or not subscription?
then plan = 'free'
else plan = subscription.planTitle
message = """
Username : #{user.username}
User Agent : #{req.headers['user-agent']}
User Plan : #{plan}
----------------------------------------
""" + message
request
url : "#{baseUrl}/conversations.json"
method : 'POST'
auth :
user : key
pass : 'PI:PASSWORD:<PASSWORD>END_PI'
json :
type : 'email'
customer :
email : user.email
type : 'customer'
subject : subject
mailbox :
id : 19295
name : 'Support'
,
tags : ["Plan->#{plan}"]
,
threads : [
type : 'customer'
createdBy :
email : user.email
type : 'customer'
,
body : message
]
, (error, response, body) ->
if error or body
console.error error, body
res.status(400).send { ok: 0 }
else
res.status(200).send { ok: 1 }
|
[
{
"context": "()\n return @rowKeys\n\n flattenKey: (x) => x.join(String.fromCharCode(0))\n\n processRecord: (reco",
"end": 9167,
"score": 0.8009117245674133,
"start": 9161,
"tag": "KEY",
"value": "x.join"
},
{
"context": "rowKeys\n\n flattenKey: (x) => x.join(String.f... | pivot.coffee | faheydesign/pivottable | 1 | $ = jQuery
###
Utilities
###
addSeparators = (nStr, thousandsSep, decimalSep) ->
nStr += ''
x = nStr.split('.')
x1 = x[0]
x2 = if x.length > 1 then decimalSep + x[1] else ''
rgx = /(\d+)(\d{3})/
x1 = x1.replace(rgx, '$1' + thousandsSep + '$2') while rgx.test(x1)
return x1 + x2
numberFormat = (sigfig=3, scaler=1, thousandsSep=",", decimalSep=".") ->
(x) ->
if x==0 or isNaN(x) or not isFinite(x) then ""
else addSeparators (scaler*x).toFixed(sigfig), thousandsSep, decimalSep
#technically these are aggregator constructor generator generators (!)
aggregatorTemplates =
sum: (sigfig=3, scaler=1) -> ([attr]) -> ->
sum: 0
push: (record) -> @sum += parseFloat(record[attr]) if not isNaN parseFloat(record[attr])
value: -> @sum
format: numberFormat(sigfig, scaler)
label: "Sum of #{attr}"
average: (sigfig=3, scaler=1) -> ([attr]) -> ->
sum: 0
len: 0
push: (record) ->
if not isNaN parseFloat(record[attr])
@sum += parseFloat(record[attr])
@len++
value: -> @sum/@len
format: numberFormat(sigfig, scaler)
label: "Average of #{attr}"
sumOverSum: (sigfig=3, scaler=1) -> ([num, denom]) -> ->
sumNum: 0
sumDenom: 0
push: (record) ->
@sumNum += parseFloat(record[num]) if not isNaN parseFloat(record[num])
@sumDenom += parseFloat(record[denom]) if not isNaN parseFloat(record[denom])
value: -> @sumNum/@sumDenom
format: numberFormat(sigfig, scaler)
label: "#{num}/#{denom}"
sumOverSumBound80: (sigfig=3, scaler=1, upper=true) -> ([num, denom]) -> ->
sumNum: 0
sumDenom: 0
push: (record) ->
@sumNum += parseFloat(record[num]) if not isNaN parseFloat(record[num])
@sumDenom += parseFloat(record[denom]) if not isNaN parseFloat(record[denom])
value: ->
sign = if upper then 1 else -1
(0.821187207574908/@sumDenom + @sumNum/@sumDenom + 1.2815515655446004*sign*
Math.sqrt(0.410593603787454/ (@sumDenom*@sumDenom) + (@sumNum*(1 - @sumNum/ @sumDenom))/ (@sumDenom*@sumDenom)))/
(1 + 1.642374415149816/@sumDenom)
format: numberFormat(sigfig, scaler)
label: "#{if upper then "Upper" else "Lower"} Bound of #{num}/#{denom}"
fractionOf: (wrapped, type="total") -> (x...) -> (data, rowKey, colKey) ->
selector: {total:[[],[]],row:[rowKey,[]],col:[[],colKey]}[type]
inner: wrapped(x...)(data, rowKey, colKey)
push: (record) -> @inner.push record
format: (v) -> numberFormat(2)(100*v)+"%"
label: wrapped(x...)(data, rowKey, colKey).label+" % of "+type
value: -> @inner.value() / data.getAggregator(@selector...).inner.value()
l10nWrapper: ( wrapped, formatter, labelFn) -> (x...) -> (data, rowKey, colKey) ->
inner: wrapped(x...)(data, rowKey, colKey)
push: (record) -> @inner.push record
format: formatter
label: labelFn(data)
value: -> @inner.value()
#technically these are aggregator constructor generators (!)
aggregators =
count: -> ->
count: 0
push: -> @count++
value: -> @count
format: numberFormat(0)
label: "Count"
countUnique: ([attr]) -> ->
uniq: []
push: (record) -> @uniq.push(record[attr]) if record[attr] not in @uniq
value: -> @uniq.length
format: numberFormat(0)
label: "Count Unique #{attr}"
listUnique: ([attr]) -> ->
uniq: []
push: (record) -> @uniq.push(record[attr]) if record[attr] not in @uniq
value: -> @uniq.join ", "
format: (x) -> x
label: "List Unique #{attr}"
intSum: aggregatorTemplates.sum(0)
sum: aggregatorTemplates.sum(3)
average: aggregatorTemplates.average(3)
sumOverSum: aggregatorTemplates.sumOverSum(3)
ub80: aggregatorTemplates.sumOverSumBound80(3, 1, true)
lb80: aggregatorTemplates.sumOverSumBound80(3, 1, false)
aggregators.sumAsFractionOfTotal= aggregatorTemplates.fractionOf(aggregators.sum)
aggregators.sumAsFractionOfRow= aggregatorTemplates.fractionOf(aggregators.sum, "row")
aggregators.sumAsFractionOfCol= aggregatorTemplates.fractionOf(aggregators.sum, "col")
aggregators.countAsFractionOfTotal= aggregatorTemplates.fractionOf(aggregators.count)
aggregators.countAsFractionOfRow= aggregatorTemplates.fractionOf(aggregators.count, "row")
aggregators.countAsFractionOfCol= aggregatorTemplates.fractionOf(aggregators.count, "col")
renderers =
"Table": (pvtData, opts) -> pivotTableRenderer(pvtData, opts)
"Table Barchart": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).barchart()
"Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap()
"Row Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap("rowheatmap")
"Col Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap("colheatmap")
mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
zeroPad = (number) -> ("0"+number).substr(-2,2)
derivers =
bin: (col, binWidth) -> (record) -> record[col] - record[col] % binWidth
dateFormat: (col, formatString) ->
#thanks http://stackoverflow.com/a/12213072/112871
(record) ->
date = new Date(Date.parse(record[col]))
if isNaN(date) then return ""
formatString.replace /%(.)/g, (m, p) ->
switch p
when "y" then date.getFullYear()
when "m" then zeroPad(date.getMonth()+1)
when "n" then mthNames[date.getMonth()]
when "d" then zeroPad(date.getDate())
when "w" then dayNames[date.getDay()]
when "x" then date.getDay()
when "H" then zeroPad(date.getHours())
when "M" then zeroPad(date.getMinutes())
when "S" then zeroPad(date.getSeconds())
else "%" + p
naturalSort = (as, bs) => #from http://stackoverflow.com/a/4373421/112871
rx = /(\d+)|(\D+)/g
rd = /\d/
rz = /^0/
if typeof as is "number" or typeof bs is "number"
return 1 if isNaN(as)
return -1 if isNaN(bs)
return as - bs
a = String(as).toLowerCase()
b = String(bs).toLowerCase()
return 0 if a is b
return (if a > b then 1 else -1) unless rd.test(a) and rd.test(b)
a = a.match(rx)
b = b.match(rx)
while a.length and b.length
a1 = a.shift()
b1 = b.shift()
if a1 isnt b1
if rd.test(a1) and rd.test(b1)
return a1.replace(rz, ".0") - b1.replace(rz, ".0")
else
return (if a1 > b1 then 1 else -1)
a.length - b.length
$.pivotUtilities = {aggregatorTemplates, aggregators, renderers, derivers, naturalSort, numberFormat}
###
functions for accessing input
###
deriveAttributes = (record, derivedAttributes, f) ->
record[k] = v(record) ? record[k] for k, v of derivedAttributes
record[k] ?= "null" for own k of record
f(record)
#can handle arrays or jQuery selections of tables
forEachRecord = (input, derivedAttributes, f) ->
addRecord = (record) -> deriveAttributes(record, derivedAttributes, f)
#if it's a function, have it call us back
if $.isFunction(input)
input(addRecord)
else if $.isArray(input)
if $.isArray(input[0]) #array of arrays
for own i, compactRecord of input when i > 0
record = {}
record[k] = compactRecord[j] for own j, k of input[0]
addRecord(record)
else #array of objects
addRecord(record) for record in input
else if input instanceof jQuery
tblCols = []
$("thead > tr > th", input).each (i) -> tblCols.push $(this).text()
$("tbody > tr", input).each (i) ->
record = {}
$("td", this).each (j) -> record[tblCols[j]] = $(this).text()
addRecord(record)
else
throw new Error("unknown input format")
#converts to [{attr:val, attr:val},{attr:val, attr:val}] using method above
convertToArray = (input) ->
result = []
forEachRecord input, {}, (record) -> result.push record
return result
class PivotData
constructor: (@aggregator, @colAttrs, @rowAttrs) ->
@tree = {}
@rowKeys = []
@colKeys = []
@flatRowKeys = []
@flatColKeys = []
@rowTotals = {}
@colTotals = {}
@allTotal = @aggregator(this, [], [])
@sorted = false
natSort: (as, bs) => naturalSort(as, bs)
arrSort: (a,b) => @natSort a.join(), b.join()
sortKeys: () =>
if not @sorted
@rowKeys.sort @arrSort
@colKeys.sort @arrSort
@sorted = true
getColKeys: () =>
@sortKeys()
return @colKeys
getRowKeys: () =>
@sortKeys()
return @rowKeys
flattenKey: (x) => x.join(String.fromCharCode(0))
processRecord: (record) ->
colKey = (record[x] for x in @colAttrs)
rowKey = (record[x] for x in @rowAttrs)
flatRowKey = @flattenKey rowKey
flatColKey = @flattenKey colKey
@allTotal.push record
if rowKey.length != 0
if flatRowKey not in @flatRowKeys
@rowKeys.push rowKey
@flatRowKeys.push flatRowKey
if not @rowTotals[flatRowKey]
@rowTotals[flatRowKey] = @aggregator(this, rowKey, [])
@rowTotals[flatRowKey].push record
if colKey.length != 0
if flatColKey not in @flatColKeys
@colKeys.push colKey
@flatColKeys.push flatColKey
if not @colTotals[flatColKey]
@colTotals[flatColKey] = @aggregator(this, [], colKey)
@colTotals[flatColKey].push record
if colKey.length != 0 and rowKey.length != 0
if flatRowKey not of @tree
@tree[flatRowKey] = {}
if flatColKey not of @tree[flatRowKey]
@tree[flatRowKey][flatColKey] = @aggregator(this, rowKey, colKey)
@tree[flatRowKey][flatColKey].push record
getAggregator: (rowKey, colKey) =>
flatRowKey = @flattenKey rowKey
flatColKey = @flattenKey colKey
if rowKey.length == 0 and colKey.length == 0
agg = @allTotal
else if rowKey.length == 0
agg = @colTotals[flatColKey]
else if colKey.length == 0
agg = @rowTotals[flatRowKey]
else
agg = @tree[flatRowKey][flatColKey]
return agg ? {value: (-> null), format: -> ""}
getPivotData = (input, cols, rows, aggregator, filter, derivedAttributes) ->
# iterate through input, accumulating data for cells
pivotData = new PivotData(aggregator, cols, rows)
forEachRecord input, derivedAttributes, (record) ->
pivotData.processRecord(record) if filter(record)
return pivotData
#helper function for setting row/col-span
spanSize = (arr, i, j) ->
if i != 0
noDraw = true
for x in [0..j]
if arr[i-1][x] != arr[i][x]
noDraw = false
if noDraw
return -1 #do not draw cell
len = 0
while i+len < arr.length
stop = false
for x in [0..j]
stop = true if arr[i][x] != arr[i+len][x]
break if stop
len++
return len
pivotTableRenderer = (pivotData, opts) ->
defaults =
localeStrings:
totals: "Totals"
opts = $.extend defaults, opts
colAttrs = pivotData.colAttrs
rowAttrs = pivotData.rowAttrs
rowKeys = pivotData.getRowKeys()
colKeys = pivotData.getColKeys()
#now actually build the output
result = $("<table class='table table-bordered pvtTable'>")
#the first few rows are for col headers
for own j, c of colAttrs
tr = $("<tr>")
if parseInt(j) == 0 and rowAttrs.length != 0
tr.append $("<th>")
.attr("colspan", rowAttrs.length)
.attr("rowspan", colAttrs.length)
tr.append $("<th class='pvtAxisLabel'>").text(c)
for own i, colKey of colKeys
x = spanSize(colKeys, parseInt(i), parseInt(j))
if x != -1
th = $("<th class='pvtColLabel'>").text(colKey[j]).attr("colspan", x)
if parseInt(j) == colAttrs.length-1 and rowAttrs.length != 0
th.attr("rowspan", 2)
tr.append th
if parseInt(j) == 0
tr.append $("<th class='pvtTotalLabel'>").text(opts.localeStrings.totals)
.attr("rowspan", colAttrs.length + (if rowAttrs.length ==0 then 0 else 1))
result.append tr
#then a row for row header headers
if rowAttrs.length !=0
tr = $("<tr>")
for own i, r of rowAttrs
tr.append $("<th class='pvtAxisLabel'>").text(r)
th = $("<th>")
if colAttrs.length ==0
th.addClass("pvtTotalLabel").text(opts.localeStrings.totals)
tr.append th
result.append tr
#now the actual data rows, with their row headers and totals
for own i, rowKey of rowKeys
tr = $("<tr>")
for own j, txt of rowKey
x = spanSize(rowKeys, parseInt(i), parseInt(j))
if x != -1
th = $("<th class='pvtRowLabel'>").text(txt).attr("rowspan", x)
if parseInt(j) == rowAttrs.length-1 and colAttrs.length !=0
th.attr("colspan",2)
tr.append th
for own j, colKey of colKeys
aggregator = pivotData.getAggregator(rowKey, colKey)
val = aggregator.value()
tr.append $("<td class='pvtVal row#{i} col#{j}'>")
.html(aggregator.format val)
.data("value", val)
totalAggregator = pivotData.getAggregator(rowKey, [])
val = totalAggregator.value()
tr.append $("<td class='pvtTotal rowTotal'>")
.html(totalAggregator.format val)
.data("value", val)
.data("for", "row"+i)
result.append tr
#finally, the row for col totals, and a grand total
tr = $("<tr>")
th = $("<th class='pvtTotalLabel'>").text(opts.localeStrings.totals)
th.attr("colspan", rowAttrs.length + (if colAttrs.length == 0 then 0 else 1))
tr.append th
for own j, colKey of colKeys
totalAggregator = pivotData.getAggregator([], colKey)
val = totalAggregator.value()
tr.append $("<td class='pvtTotal colTotal'>")
.html(totalAggregator.format val)
.data("value", val)
.data("for", "col"+j)
totalAggregator = pivotData.getAggregator([], [])
val = totalAggregator.value()
tr.append $("<td class='pvtGrandTotal'>")
.html(totalAggregator.format val)
.data("value", val)
result.append tr
#squirrel this away for later
result.data "dimensions", [rowKeys.length, colKeys.length]
return result
###
Pivot Table
###
$.fn.pivot = (input, opts) ->
defaults =
cols : []
rows: []
filter: -> true
aggregator: aggregators.count()
derivedAttributes: {},
renderer: pivotTableRenderer
rendererOptions: null
localeStrings:
renderError: "An error occurred rendering the PivotTable results."
computeError: "An error occurred computing the PivotTable results."
opts = $.extend defaults, opts
result = null
try
pivotData = getPivotData(input, opts.cols, opts.rows,
opts.aggregator, opts.filter,
opts.derivedAttributes)
try
result = opts.renderer(pivotData, opts.rendererOptions)
catch e
console.error(e.stack) if console?
result = opts.localeStrings.renderError
catch e
console.error(e.stack) if console?
result = opts.localeStrings.computeError
@html result
return this
###
UI code, calls pivot table above
###
$.fn.pivotUI = (input, inputOpts, overwrite = false) ->
defaults =
derivedAttributes: {}
aggregators: aggregators
renderers: renderers
hiddenAttributes: []
menuLimit: 200
cols: [], rows: [], vals: []
exclusions: {}
unusedAttrsVertical: false
autoSortUnusedAttrs: false
rendererOptions: null
onRefresh: null
filter: -> true
localeStrings:
renderError: "An error occurred rendering the PivotTable results."
computeError: "An error occurred computing the PivotTable results."
uiRenderError: "An error occurred rendering the PivotTable UI."
selectAll: "Select <span>All</span>"
selectNone: "Select <span>None</span>"
tooMany: "(too many to list)"
filterResults: "Filter results"
btnSubmit: "Update"
existingOpts = @data "pivotUIOptions"
if not existingOpts? or overwrite
opts = $.extend defaults, inputOpts
else
opts = existingOpts
try
#cache the input in some useful form
input = convertToArray(input)
tblCols = (k for own k of input[0])
tblCols.push c for own c of opts.derivedAttributes when (c not in tblCols)
#figure out the cardinality and some stats
axisValues = {}
axisValues[x] = {} for x in tblCols
forEachRecord input, opts.derivedAttributes, (record) ->
for own k, v of record when opts.filter(record)
v ?= "null"
axisValues[k][v] ?= 0
axisValues[k][v]++
#start building the output
uiTable = $("<table class='table table-bordered' cellpadding='5'>")
#renderer control
rendererControl = $("<td>")
renderer = $("<select class='pvtRenderer'>")
.bind "change", -> refresh() #capture reference
for own x of opts.renderers
renderer.append $("<option>").val(x).text(x)
rendererControl.append renderer
#axis list, including the double-click menu
colList = $("<td class='pvtAxisContainer pvtUnused'>")
if opts.unusedAttrsVertical
colList.addClass('pvtVertList')
else
colList.addClass('pvtHorizList')
shownAttributes = (c for c in tblCols when c not in opts.hiddenAttributes)
for i, c of shownAttributes
do (c) ->
keys = (k for k of axisValues[c])
hasExcludedItem = false
valueList = $("<div>").addClass('pvtFilterBox').hide()
clearSearch = ->
$('.pvtSearch').val('').removeClass("nobkgd")
$('label').show()
$(".clear-search").hide()
$(".checkContainer").css("border-color","hsl(0, 0%, 87%)")
$(".none").remove()
hideFilterList = ->
$(".pvtFilterBox").hide();
$("nobr").removeClass();
updateSelected = ->
checked = $(valueList).find("[type='checkbox']:checked").length
$(".selected-val em").html(checked)
return checked
valueList.append $("<h4>")
.text("#{c} (#{keys.length})")
if keys.length > opts.menuLimit
valueList.append $("<p>")
.text(opts.localeStrings.tooMany)
else
btns = $("<p>").addClass("btns-search")
btns.append $("<button>").html(opts.localeStrings.selectAll).bind "click", ->
valueList.find("input").each ->
if $(this).is(':visible')
$(this).prop "checked", true
updateSelected()
btns.append $("<button>").html(opts.localeStrings.selectNone).bind "click", ->
valueList.find("input").each ->
if $(this).is(':visible')
$(this).prop "checked", false
updateSelected()
btns.append $("<span>").addClass("clear-search").bind "click", clearSearch
btns.append $("<div>").addClass("close-btn").bind "click", hideFilterList
btns.append $("<input>").addClass("pvtSearch").attr("placeholder", opts.localeStrings.filterResults).bind "keyup", ->
filter = $(this).val().toLowerCase()
if filter
$(".clear-search").css('display', 'inline-block')
$(".pvtSearch").addClass("nobkgd")
else
$(".clear-search").hide()
$(".pvtSearch").removeClass("nobkgd")
count = 0
$(this).parents(".pvtFilterBox").find('label span').each ->
testString = this.innerText.toLowerCase().indexOf(filter)
if testString isnt -1
$(this).parent().show()
count++
else
$(this).parent().hide()
if count is 0 and $('.none').length <= 0
$(".checkContainer").css("border-color","#fffff")
$(".checkContainer").append("<p class='none'>No results. <a href='#'>Clear filter?</a></p>").bind "click", clearSearch
else if count >= 1
clearSearch()
valueList.append btns
checkContainer = $("<div>").addClass("checkContainer")
for k in keys.sort(naturalSort)
v = axisValues[c][k]
filterItem = $("<label>")
filterItemExcluded = if opts.exclusions[c] then (k in opts.exclusions[c]) else false
hasExcludedItem ||= filterItemExcluded
filterItem.append $("<input type='checkbox' class='pvtFilter'>")
.attr("checked", !filterItemExcluded).data("filter", [c,k]).bind "change", updateSelected
filterItem.append $("<span>").text "#{k} (#{v})"
checkContainer.append $("<p>").append(filterItem)
valueList.append checkContainer
updateFilter = ->
unselectedCount = $(valueList).find("[type='checkbox']").length -
$(valueList).find("[type='checkbox']:checked").length
if unselectedCount > 0
attrElem.addClass "pvtFilteredAttribute"
else
attrElem.removeClass "pvtFilteredAttribute"
if keys.length > opts.menuLimit
valueList.toggle()
else
valueList.toggle(0, refresh)
$("nobr").removeClass("active_filter")
btn_submit = $("<p>").addClass("submit-btn")
valueList.append btn_submit
.append $("<button>").text(opts.localeStrings.btnSubmit).bind "click", updateFilter
btn_submit.append $("<span>").html('<em>' + updateSelected() + '</em>' + " selected of #{keys.length} total values").addClass("selected-val")
showFilterList = (e) ->
pvtFilterBox = $(".pvtFilterBox")
hideFilterList()
nobr = $(this).parents("nobr")
nobr.toggleClass("active_filter")
position = nobr.offset()
bottom = position.top + nobr.height() + 8
valueList.css(left: position.left, top: bottom).toggle()
clearSearch()
$(document).mouseup (e) ->
if (!pvtFilterBox.is(e.target) && pvtFilterBox.has(e.target).length is 0)
hideFilterList()
triangleLink = $("<span class='pvtTriangle'>").html(" ▾")
.bind "click", showFilterList
attrElem = $("<li class='label label-info axis_#{i}'>")
.append $("<nobr>").text(c).data("attrName", c).append(triangleLink)
attrElem.addClass('pvtFilteredAttribute') if hasExcludedItem
colList.append(attrElem).append(valueList)
attrElem.bind "dblclick", showFilterList
tr1 = $("<tr>")
#aggregator menu and value area
aggregator = $("<select class='pvtAggregator'>")
.bind "change", -> refresh() #capture reference
for own x of opts.aggregators
aggregator.append $("<option>").val(x).text(x)
tr1.append $("<td class='pvtAxisContainer pvtHorizList pvtVals'>")
.append(aggregator).append($("<br>"))
#column axes
tr1.append $("<td class='pvtAxisContainer pvtHorizList pvtCols'>")
uiTable.append tr1
tr2 = $("<tr>")
#row axes
tr2.append $("<td valign='top' class='pvtAxisContainer pvtRows'>")
#the actual pivot table container
pivotTable = $("<td valign='top' class='pvtRendererArea'>")
tr2.append pivotTable
uiTable.append tr2
#finally the renderer dropdown and unused attribs are inserted at the requested location
if opts.unusedAttrsVertical
uiTable.find('tr:nth-child(1)').prepend rendererControl
uiTable.find('tr:nth-child(2)').prepend colList
else
uiTable.prepend $("<tr>").append(rendererControl).append(colList)
#render the UI in its default state
@html uiTable
#set up the UI initial state as requested by moving elements around
for x in opts.cols
@find(".pvtCols").append @find(".axis_#{shownAttributes.indexOf(x)}")
for x in opts.rows
@find(".pvtRows").append @find(".axis_#{shownAttributes.indexOf(x)}")
for x in opts.vals
@find(".pvtVals").append @find(".axis_#{shownAttributes.indexOf(x)}")
if opts.aggregatorName?
@find(".pvtAggregator").val opts.aggregatorName
if opts.rendererName?
@find(".pvtRenderer").val opts.rendererName
#set up for refreshing
refreshDelayed = =>
subopts =
derivedAttributes: opts.derivedAttributes
localeStrings: opts.localeStrings
rendererOptions: opts.rendererOptions
cols: [], rows: []
vals = []
@find(".pvtRows li nobr").each -> subopts.rows.push $(this).data("attrName")
@find(".pvtCols li nobr").each -> subopts.cols.push $(this).data("attrName")
@find(".pvtVals li nobr").each -> vals.push $(this).data("attrName")
subopts.aggregator = opts.aggregators[aggregator.val()](vals)
subopts.renderer = opts.renderers[renderer.val()]
#construct filter here
exclusions = {}
@find('input.pvtFilter').not(':checked').each ->
filter = $(this).data("filter")
if exclusions[filter[0]]?
exclusions[filter[0]].push( filter[1] )
else
exclusions[filter[0]] = [ filter[1] ]
subopts.filter = (record) ->
return false if not opts.filter(record)
for k,excludedItems of exclusions
return false if ""+record[k] in excludedItems
return true
pivotTable.pivot(input,subopts)
pivotUIOptions =
cols: subopts.cols
rows: subopts.rows
vals: vals
exclusions: exclusions
hiddenAttributes: opts.hiddenAttributes
renderers: opts.renderers
aggregators: opts.aggregators
filter: opts.filter
derivedAttributes: opts.derivedAttributes
aggregatorName: aggregator.val()
rendererName: renderer.val()
localeStrings: opts.localeStrings
rendererOptions: opts.rendererOptions
@data "pivotUIOptions", pivotUIOptions
# if requested make sure unused columns are in alphabetical order
if opts.autoSortUnusedAttrs
natSort = $.pivotUtilities.naturalSort
unusedAttrsContainer = @find("td.pvtUnused.pvtAxisContainer")
$(unusedAttrsContainer).children("li")
.sort((a, b) => natSort($(a).text(), $(b).text()))
.appendTo unusedAttrsContainer
pivotTable.css("opacity", 1)
opts.onRefresh(pivotUIOptions) if opts.onRefresh?
refresh = =>
pivotTable.css("opacity", 0.5)
setTimeout refreshDelayed, 10
#the very first refresh will actually display the table
refresh()
@find(".pvtAxisContainer").sortable
update: refresh
connectWith: @find(".pvtAxisContainer")
items: 'li'
placeholder: 'placeholder'
catch e
console.error(e.stack) if console?
@html opts.localeStrings.uiRenderError
return this
###
Heatmap post-processing
###
$.fn.heatmap = (scope = "heatmap") ->
[numRows, numCols] = @data "dimensions"
colorGen = (color, min, max) ->
hexGen = switch color
when "red" then (hex) -> "ff#{hex}#{hex}"
when "green" then (hex) -> "#{hex}ff#{hex}"
when "blue" then (hex) -> "#{hex}#{hex}ff"
return (x) ->
intensity = 255 - Math.round 255*(x-min)/(max-min)
hex = intensity.toString(16).split(".")[0]
hex = 0+hex if hex.length == 1
return hexGen(hex)
heatmapper = (scope, color) =>
forEachCell = (f) =>
@find(scope).each ->
x = $(this).data("value")
f(x, $(this)) if x? and isFinite(x)
values = []
forEachCell (x) -> values.push x
colorFor = colorGen color, Math.min(values...), Math.max(values...)
forEachCell (x, elem) -> elem.css "background-color", "#" + colorFor(x)
switch scope
when "heatmap"
heatmapper ".pvtVal", "red"
when "rowheatmap"
heatmapper ".pvtVal.row#{i}", "red" for i in [0...numRows]
when "colheatmap"
heatmapper ".pvtVal.col#{j}", "red" for j in [0...numCols]
heatmapper ".pvtTotal.rowTotal", "red"
heatmapper ".pvtTotal.colTotal", "red"
return this
###
Barchart post-processing
###
$.fn.barchart = ->
[numRows, numCols] = @data "dimensions"
barcharter = (scope) =>
forEachCell = (f) =>
@find(scope).each ->
x = $(this).data("value")
f(x, $(this)) if x? and isFinite(x)
values = []
forEachCell (x) -> values.push x
max = Math.max(values...)
scaler = (x) -> 100*x/(1.4*max)
forEachCell (x, elem) ->
text = elem.text()
wrapper = $("<div>").css
"position": "relative"
"height": "55px"
wrapper.append $("<div>").css
"position": "absolute"
"bottom": 0
"left": 0
"right": 0
"height": scaler(x) + "%"
"background-color": "gray"
wrapper.append $("<div>").text(text).css
"position":"relative"
"padding-left":"5px"
"padding-right":"5px"
elem.css("padding": 0,"padding-top": "5px", "text-align": "center").html wrapper
barcharter ".pvtVal.row#{i}" for i in [0...numRows]
barcharter ".pvtTotal.colTotal"
return this
| 139450 | $ = jQuery
###
Utilities
###
addSeparators = (nStr, thousandsSep, decimalSep) ->
nStr += ''
x = nStr.split('.')
x1 = x[0]
x2 = if x.length > 1 then decimalSep + x[1] else ''
rgx = /(\d+)(\d{3})/
x1 = x1.replace(rgx, '$1' + thousandsSep + '$2') while rgx.test(x1)
return x1 + x2
numberFormat = (sigfig=3, scaler=1, thousandsSep=",", decimalSep=".") ->
(x) ->
if x==0 or isNaN(x) or not isFinite(x) then ""
else addSeparators (scaler*x).toFixed(sigfig), thousandsSep, decimalSep
#technically these are aggregator constructor generator generators (!)
aggregatorTemplates =
sum: (sigfig=3, scaler=1) -> ([attr]) -> ->
sum: 0
push: (record) -> @sum += parseFloat(record[attr]) if not isNaN parseFloat(record[attr])
value: -> @sum
format: numberFormat(sigfig, scaler)
label: "Sum of #{attr}"
average: (sigfig=3, scaler=1) -> ([attr]) -> ->
sum: 0
len: 0
push: (record) ->
if not isNaN parseFloat(record[attr])
@sum += parseFloat(record[attr])
@len++
value: -> @sum/@len
format: numberFormat(sigfig, scaler)
label: "Average of #{attr}"
sumOverSum: (sigfig=3, scaler=1) -> ([num, denom]) -> ->
sumNum: 0
sumDenom: 0
push: (record) ->
@sumNum += parseFloat(record[num]) if not isNaN parseFloat(record[num])
@sumDenom += parseFloat(record[denom]) if not isNaN parseFloat(record[denom])
value: -> @sumNum/@sumDenom
format: numberFormat(sigfig, scaler)
label: "#{num}/#{denom}"
sumOverSumBound80: (sigfig=3, scaler=1, upper=true) -> ([num, denom]) -> ->
sumNum: 0
sumDenom: 0
push: (record) ->
@sumNum += parseFloat(record[num]) if not isNaN parseFloat(record[num])
@sumDenom += parseFloat(record[denom]) if not isNaN parseFloat(record[denom])
value: ->
sign = if upper then 1 else -1
(0.821187207574908/@sumDenom + @sumNum/@sumDenom + 1.2815515655446004*sign*
Math.sqrt(0.410593603787454/ (@sumDenom*@sumDenom) + (@sumNum*(1 - @sumNum/ @sumDenom))/ (@sumDenom*@sumDenom)))/
(1 + 1.642374415149816/@sumDenom)
format: numberFormat(sigfig, scaler)
label: "#{if upper then "Upper" else "Lower"} Bound of #{num}/#{denom}"
fractionOf: (wrapped, type="total") -> (x...) -> (data, rowKey, colKey) ->
selector: {total:[[],[]],row:[rowKey,[]],col:[[],colKey]}[type]
inner: wrapped(x...)(data, rowKey, colKey)
push: (record) -> @inner.push record
format: (v) -> numberFormat(2)(100*v)+"%"
label: wrapped(x...)(data, rowKey, colKey).label+" % of "+type
value: -> @inner.value() / data.getAggregator(@selector...).inner.value()
l10nWrapper: ( wrapped, formatter, labelFn) -> (x...) -> (data, rowKey, colKey) ->
inner: wrapped(x...)(data, rowKey, colKey)
push: (record) -> @inner.push record
format: formatter
label: labelFn(data)
value: -> @inner.value()
#technically these are aggregator constructor generators (!)
aggregators =
count: -> ->
count: 0
push: -> @count++
value: -> @count
format: numberFormat(0)
label: "Count"
countUnique: ([attr]) -> ->
uniq: []
push: (record) -> @uniq.push(record[attr]) if record[attr] not in @uniq
value: -> @uniq.length
format: numberFormat(0)
label: "Count Unique #{attr}"
listUnique: ([attr]) -> ->
uniq: []
push: (record) -> @uniq.push(record[attr]) if record[attr] not in @uniq
value: -> @uniq.join ", "
format: (x) -> x
label: "List Unique #{attr}"
intSum: aggregatorTemplates.sum(0)
sum: aggregatorTemplates.sum(3)
average: aggregatorTemplates.average(3)
sumOverSum: aggregatorTemplates.sumOverSum(3)
ub80: aggregatorTemplates.sumOverSumBound80(3, 1, true)
lb80: aggregatorTemplates.sumOverSumBound80(3, 1, false)
aggregators.sumAsFractionOfTotal= aggregatorTemplates.fractionOf(aggregators.sum)
aggregators.sumAsFractionOfRow= aggregatorTemplates.fractionOf(aggregators.sum, "row")
aggregators.sumAsFractionOfCol= aggregatorTemplates.fractionOf(aggregators.sum, "col")
aggregators.countAsFractionOfTotal= aggregatorTemplates.fractionOf(aggregators.count)
aggregators.countAsFractionOfRow= aggregatorTemplates.fractionOf(aggregators.count, "row")
aggregators.countAsFractionOfCol= aggregatorTemplates.fractionOf(aggregators.count, "col")
renderers =
"Table": (pvtData, opts) -> pivotTableRenderer(pvtData, opts)
"Table Barchart": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).barchart()
"Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap()
"Row Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap("rowheatmap")
"Col Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap("colheatmap")
mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
zeroPad = (number) -> ("0"+number).substr(-2,2)
derivers =
bin: (col, binWidth) -> (record) -> record[col] - record[col] % binWidth
dateFormat: (col, formatString) ->
#thanks http://stackoverflow.com/a/12213072/112871
(record) ->
date = new Date(Date.parse(record[col]))
if isNaN(date) then return ""
formatString.replace /%(.)/g, (m, p) ->
switch p
when "y" then date.getFullYear()
when "m" then zeroPad(date.getMonth()+1)
when "n" then mthNames[date.getMonth()]
when "d" then zeroPad(date.getDate())
when "w" then dayNames[date.getDay()]
when "x" then date.getDay()
when "H" then zeroPad(date.getHours())
when "M" then zeroPad(date.getMinutes())
when "S" then zeroPad(date.getSeconds())
else "%" + p
naturalSort = (as, bs) => #from http://stackoverflow.com/a/4373421/112871
rx = /(\d+)|(\D+)/g
rd = /\d/
rz = /^0/
if typeof as is "number" or typeof bs is "number"
return 1 if isNaN(as)
return -1 if isNaN(bs)
return as - bs
a = String(as).toLowerCase()
b = String(bs).toLowerCase()
return 0 if a is b
return (if a > b then 1 else -1) unless rd.test(a) and rd.test(b)
a = a.match(rx)
b = b.match(rx)
while a.length and b.length
a1 = a.shift()
b1 = b.shift()
if a1 isnt b1
if rd.test(a1) and rd.test(b1)
return a1.replace(rz, ".0") - b1.replace(rz, ".0")
else
return (if a1 > b1 then 1 else -1)
a.length - b.length
$.pivotUtilities = {aggregatorTemplates, aggregators, renderers, derivers, naturalSort, numberFormat}
###
functions for accessing input
###
deriveAttributes = (record, derivedAttributes, f) ->
record[k] = v(record) ? record[k] for k, v of derivedAttributes
record[k] ?= "null" for own k of record
f(record)
#can handle arrays or jQuery selections of tables
forEachRecord = (input, derivedAttributes, f) ->
addRecord = (record) -> deriveAttributes(record, derivedAttributes, f)
#if it's a function, have it call us back
if $.isFunction(input)
input(addRecord)
else if $.isArray(input)
if $.isArray(input[0]) #array of arrays
for own i, compactRecord of input when i > 0
record = {}
record[k] = compactRecord[j] for own j, k of input[0]
addRecord(record)
else #array of objects
addRecord(record) for record in input
else if input instanceof jQuery
tblCols = []
$("thead > tr > th", input).each (i) -> tblCols.push $(this).text()
$("tbody > tr", input).each (i) ->
record = {}
$("td", this).each (j) -> record[tblCols[j]] = $(this).text()
addRecord(record)
else
throw new Error("unknown input format")
#converts to [{attr:val, attr:val},{attr:val, attr:val}] using method above
convertToArray = (input) ->
result = []
forEachRecord input, {}, (record) -> result.push record
return result
class PivotData
constructor: (@aggregator, @colAttrs, @rowAttrs) ->
@tree = {}
@rowKeys = []
@colKeys = []
@flatRowKeys = []
@flatColKeys = []
@rowTotals = {}
@colTotals = {}
@allTotal = @aggregator(this, [], [])
@sorted = false
natSort: (as, bs) => naturalSort(as, bs)
arrSort: (a,b) => @natSort a.join(), b.join()
sortKeys: () =>
if not @sorted
@rowKeys.sort @arrSort
@colKeys.sort @arrSort
@sorted = true
getColKeys: () =>
@sortKeys()
return @colKeys
getRowKeys: () =>
@sortKeys()
return @rowKeys
flattenKey: (x) => <KEY>(String.from<KEY>(0))
processRecord: (record) ->
colKey = (record[x] for x in @colAttrs)
rowKey = (record[x] for x in @rowAttrs)
flatRowKey = @flattenKey rowKey
flatColKey = @flattenKey colKey
@allTotal.push record
if rowKey.length != 0
if flatRowKey not in @flatRowKeys
@rowKeys.push rowKey
@flatRowKeys.push flatRowKey
if not @rowTotals[flatRowKey]
@rowTotals[flatRowKey] = @aggregator(this, rowKey, [])
@rowTotals[flatRowKey].push record
if colKey.length != 0
if flatColKey not in @flatColKeys
@colKeys.push colKey
@flatColKeys.push flatColKey
if not @colTotals[flatColKey]
@colTotals[flatColKey] = @aggregator(this, [], colKey)
@colTotals[flatColKey].push record
if colKey.length != 0 and rowKey.length != 0
if flatRowKey not of @tree
@tree[flatRowKey] = {}
if flatColKey not of @tree[flatRowKey]
@tree[flatRowKey][flatColKey] = @aggregator(this, rowKey, colKey)
@tree[flatRowKey][flatColKey].push record
getAggregator: (rowKey, colKey) =>
flatRowKey = @flattenKey rowKey
flatColKey = @flattenKey colKey
if rowKey.length == 0 and colKey.length == 0
agg = @allTotal
else if rowKey.length == 0
agg = @colTotals[flatColKey]
else if colKey.length == 0
agg = @rowTotals[flatRowKey]
else
agg = @tree[flatRowKey][flatColKey]
return agg ? {value: (-> null), format: -> ""}
getPivotData = (input, cols, rows, aggregator, filter, derivedAttributes) ->
# iterate through input, accumulating data for cells
pivotData = new PivotData(aggregator, cols, rows)
forEachRecord input, derivedAttributes, (record) ->
pivotData.processRecord(record) if filter(record)
return pivotData
#helper function for setting row/col-span
spanSize = (arr, i, j) ->
if i != 0
noDraw = true
for x in [0..j]
if arr[i-1][x] != arr[i][x]
noDraw = false
if noDraw
return -1 #do not draw cell
len = 0
while i+len < arr.length
stop = false
for x in [0..j]
stop = true if arr[i][x] != arr[i+len][x]
break if stop
len++
return len
pivotTableRenderer = (pivotData, opts) ->
defaults =
localeStrings:
totals: "Totals"
opts = $.extend defaults, opts
colAttrs = pivotData.colAttrs
rowAttrs = pivotData.rowAttrs
rowKeys = pivotData.getRowKeys()
colKeys = pivotData.getColKeys()
#now actually build the output
result = $("<table class='table table-bordered pvtTable'>")
#the first few rows are for col headers
for own j, c of colAttrs
tr = $("<tr>")
if parseInt(j) == 0 and rowAttrs.length != 0
tr.append $("<th>")
.attr("colspan", rowAttrs.length)
.attr("rowspan", colAttrs.length)
tr.append $("<th class='pvtAxisLabel'>").text(c)
for own i, colKey of colKeys
x = spanSize(colKeys, parseInt(i), parseInt(j))
if x != -1
th = $("<th class='pvtColLabel'>").text(colKey[j]).attr("colspan", x)
if parseInt(j) == colAttrs.length-1 and rowAttrs.length != 0
th.attr("rowspan", 2)
tr.append th
if parseInt(j) == 0
tr.append $("<th class='pvtTotalLabel'>").text(opts.localeStrings.totals)
.attr("rowspan", colAttrs.length + (if rowAttrs.length ==0 then 0 else 1))
result.append tr
#then a row for row header headers
if rowAttrs.length !=0
tr = $("<tr>")
for own i, r of rowAttrs
tr.append $("<th class='pvtAxisLabel'>").text(r)
th = $("<th>")
if colAttrs.length ==0
th.addClass("pvtTotalLabel").text(opts.localeStrings.totals)
tr.append th
result.append tr
#now the actual data rows, with their row headers and totals
for own i, rowKey of rowKeys
tr = $("<tr>")
for own j, txt of rowKey
x = spanSize(rowKeys, parseInt(i), parseInt(j))
if x != -1
th = $("<th class='pvtRowLabel'>").text(txt).attr("rowspan", x)
if parseInt(j) == rowAttrs.length-1 and colAttrs.length !=0
th.attr("colspan",2)
tr.append th
for own j, colKey of colKeys
aggregator = pivotData.getAggregator(rowKey, colKey)
val = aggregator.value()
tr.append $("<td class='pvtVal row#{i} col#{j}'>")
.html(aggregator.format val)
.data("value", val)
totalAggregator = pivotData.getAggregator(rowKey, [])
val = totalAggregator.value()
tr.append $("<td class='pvtTotal rowTotal'>")
.html(totalAggregator.format val)
.data("value", val)
.data("for", "row"+i)
result.append tr
#finally, the row for col totals, and a grand total
tr = $("<tr>")
th = $("<th class='pvtTotalLabel'>").text(opts.localeStrings.totals)
th.attr("colspan", rowAttrs.length + (if colAttrs.length == 0 then 0 else 1))
tr.append th
for own j, colKey of colKeys
totalAggregator = pivotData.getAggregator([], colKey)
val = totalAggregator.value()
tr.append $("<td class='pvtTotal colTotal'>")
.html(totalAggregator.format val)
.data("value", val)
.data("for", "col"+j)
totalAggregator = pivotData.getAggregator([], [])
val = totalAggregator.value()
tr.append $("<td class='pvtGrandTotal'>")
.html(totalAggregator.format val)
.data("value", val)
result.append tr
#squirrel this away for later
result.data "dimensions", [rowKeys.length, colKeys.length]
return result
###
Pivot Table
###
$.fn.pivot = (input, opts) ->
defaults =
cols : []
rows: []
filter: -> true
aggregator: aggregators.count()
derivedAttributes: {},
renderer: pivotTableRenderer
rendererOptions: null
localeStrings:
renderError: "An error occurred rendering the PivotTable results."
computeError: "An error occurred computing the PivotTable results."
opts = $.extend defaults, opts
result = null
try
pivotData = getPivotData(input, opts.cols, opts.rows,
opts.aggregator, opts.filter,
opts.derivedAttributes)
try
result = opts.renderer(pivotData, opts.rendererOptions)
catch e
console.error(e.stack) if console?
result = opts.localeStrings.renderError
catch e
console.error(e.stack) if console?
result = opts.localeStrings.computeError
@html result
return this
###
UI code, calls pivot table above
###
$.fn.pivotUI = (input, inputOpts, overwrite = false) ->
defaults =
derivedAttributes: {}
aggregators: aggregators
renderers: renderers
hiddenAttributes: []
menuLimit: 200
cols: [], rows: [], vals: []
exclusions: {}
unusedAttrsVertical: false
autoSortUnusedAttrs: false
rendererOptions: null
onRefresh: null
filter: -> true
localeStrings:
renderError: "An error occurred rendering the PivotTable results."
computeError: "An error occurred computing the PivotTable results."
uiRenderError: "An error occurred rendering the PivotTable UI."
selectAll: "Select <span>All</span>"
selectNone: "Select <span>None</span>"
tooMany: "(too many to list)"
filterResults: "Filter results"
btnSubmit: "Update"
existingOpts = @data "pivotUIOptions"
if not existingOpts? or overwrite
opts = $.extend defaults, inputOpts
else
opts = existingOpts
try
#cache the input in some useful form
input = convertToArray(input)
tblCols = (k for own k of input[0])
tblCols.push c for own c of opts.derivedAttributes when (c not in tblCols)
#figure out the cardinality and some stats
axisValues = {}
axisValues[x] = {} for x in tblCols
forEachRecord input, opts.derivedAttributes, (record) ->
for own k, v of record when opts.filter(record)
v ?= "null"
axisValues[k][v] ?= 0
axisValues[k][v]++
#start building the output
uiTable = $("<table class='table table-bordered' cellpadding='5'>")
#renderer control
rendererControl = $("<td>")
renderer = $("<select class='pvtRenderer'>")
.bind "change", -> refresh() #capture reference
for own x of opts.renderers
renderer.append $("<option>").val(x).text(x)
rendererControl.append renderer
#axis list, including the double-click menu
colList = $("<td class='pvtAxisContainer pvtUnused'>")
if opts.unusedAttrsVertical
colList.addClass('pvtVertList')
else
colList.addClass('pvtHorizList')
shownAttributes = (c for c in tblCols when c not in opts.hiddenAttributes)
for i, c of shownAttributes
do (c) ->
keys = (k for k of axisValues[c])
hasExcludedItem = false
valueList = $("<div>").addClass('pvtFilterBox').hide()
clearSearch = ->
$('.pvtSearch').val('').removeClass("nobkgd")
$('label').show()
$(".clear-search").hide()
$(".checkContainer").css("border-color","hsl(0, 0%, 87%)")
$(".none").remove()
hideFilterList = ->
$(".pvtFilterBox").hide();
$("nobr").removeClass();
updateSelected = ->
checked = $(valueList).find("[type='checkbox']:checked").length
$(".selected-val em").html(checked)
return checked
valueList.append $("<h4>")
.text("#{c} (#{keys.length})")
if keys.length > opts.menuLimit
valueList.append $("<p>")
.text(opts.localeStrings.tooMany)
else
btns = $("<p>").addClass("btns-search")
btns.append $("<button>").html(opts.localeStrings.selectAll).bind "click", ->
valueList.find("input").each ->
if $(this).is(':visible')
$(this).prop "checked", true
updateSelected()
btns.append $("<button>").html(opts.localeStrings.selectNone).bind "click", ->
valueList.find("input").each ->
if $(this).is(':visible')
$(this).prop "checked", false
updateSelected()
btns.append $("<span>").addClass("clear-search").bind "click", clearSearch
btns.append $("<div>").addClass("close-btn").bind "click", hideFilterList
btns.append $("<input>").addClass("pvtSearch").attr("placeholder", opts.localeStrings.filterResults).bind "keyup", ->
filter = $(this).val().toLowerCase()
if filter
$(".clear-search").css('display', 'inline-block')
$(".pvtSearch").addClass("nobkgd")
else
$(".clear-search").hide()
$(".pvtSearch").removeClass("nobkgd")
count = 0
$(this).parents(".pvtFilterBox").find('label span').each ->
testString = this.innerText.toLowerCase().indexOf(filter)
if testString isnt -1
$(this).parent().show()
count++
else
$(this).parent().hide()
if count is 0 and $('.none').length <= 0
$(".checkContainer").css("border-color","#fffff")
$(".checkContainer").append("<p class='none'>No results. <a href='#'>Clear filter?</a></p>").bind "click", clearSearch
else if count >= 1
clearSearch()
valueList.append btns
checkContainer = $("<div>").addClass("checkContainer")
for k in keys.sort(naturalSort)
v = axisValues[c][k]
filterItem = $("<label>")
filterItemExcluded = if opts.exclusions[c] then (k in opts.exclusions[c]) else false
hasExcludedItem ||= filterItemExcluded
filterItem.append $("<input type='checkbox' class='pvtFilter'>")
.attr("checked", !filterItemExcluded).data("filter", [c,k]).bind "change", updateSelected
filterItem.append $("<span>").text "#{k} (#{v})"
checkContainer.append $("<p>").append(filterItem)
valueList.append checkContainer
updateFilter = ->
unselectedCount = $(valueList).find("[type='checkbox']").length -
$(valueList).find("[type='checkbox']:checked").length
if unselectedCount > 0
attrElem.addClass "pvtFilteredAttribute"
else
attrElem.removeClass "pvtFilteredAttribute"
if keys.length > opts.menuLimit
valueList.toggle()
else
valueList.toggle(0, refresh)
$("nobr").removeClass("active_filter")
btn_submit = $("<p>").addClass("submit-btn")
valueList.append btn_submit
.append $("<button>").text(opts.localeStrings.btnSubmit).bind "click", updateFilter
btn_submit.append $("<span>").html('<em>' + updateSelected() + '</em>' + " selected of #{keys.length} total values").addClass("selected-val")
showFilterList = (e) ->
pvtFilterBox = $(".pvtFilterBox")
hideFilterList()
nobr = $(this).parents("nobr")
nobr.toggleClass("active_filter")
position = nobr.offset()
bottom = position.top + nobr.height() + 8
valueList.css(left: position.left, top: bottom).toggle()
clearSearch()
$(document).mouseup (e) ->
if (!pvtFilterBox.is(e.target) && pvtFilterBox.has(e.target).length is 0)
hideFilterList()
triangleLink = $("<span class='pvtTriangle'>").html(" ▾")
.bind "click", showFilterList
attrElem = $("<li class='label label-info axis_#{i}'>")
.append $("<nobr>").text(c).data("attrName", c).append(triangleLink)
attrElem.addClass('pvtFilteredAttribute') if hasExcludedItem
colList.append(attrElem).append(valueList)
attrElem.bind "dblclick", showFilterList
tr1 = $("<tr>")
#aggregator menu and value area
aggregator = $("<select class='pvtAggregator'>")
.bind "change", -> refresh() #capture reference
for own x of opts.aggregators
aggregator.append $("<option>").val(x).text(x)
tr1.append $("<td class='pvtAxisContainer pvtHorizList pvtVals'>")
.append(aggregator).append($("<br>"))
#column axes
tr1.append $("<td class='pvtAxisContainer pvtHorizList pvtCols'>")
uiTable.append tr1
tr2 = $("<tr>")
#row axes
tr2.append $("<td valign='top' class='pvtAxisContainer pvtRows'>")
#the actual pivot table container
pivotTable = $("<td valign='top' class='pvtRendererArea'>")
tr2.append pivotTable
uiTable.append tr2
#finally the renderer dropdown and unused attribs are inserted at the requested location
if opts.unusedAttrsVertical
uiTable.find('tr:nth-child(1)').prepend rendererControl
uiTable.find('tr:nth-child(2)').prepend colList
else
uiTable.prepend $("<tr>").append(rendererControl).append(colList)
#render the UI in its default state
@html uiTable
#set up the UI initial state as requested by moving elements around
for x in opts.cols
@find(".pvtCols").append @find(".axis_#{shownAttributes.indexOf(x)}")
for x in opts.rows
@find(".pvtRows").append @find(".axis_#{shownAttributes.indexOf(x)}")
for x in opts.vals
@find(".pvtVals").append @find(".axis_#{shownAttributes.indexOf(x)}")
if opts.aggregatorName?
@find(".pvtAggregator").val opts.aggregatorName
if opts.rendererName?
@find(".pvtRenderer").val opts.rendererName
#set up for refreshing
refreshDelayed = =>
subopts =
derivedAttributes: opts.derivedAttributes
localeStrings: opts.localeStrings
rendererOptions: opts.rendererOptions
cols: [], rows: []
vals = []
@find(".pvtRows li nobr").each -> subopts.rows.push $(this).data("attrName")
@find(".pvtCols li nobr").each -> subopts.cols.push $(this).data("attrName")
@find(".pvtVals li nobr").each -> vals.push $(this).data("attrName")
subopts.aggregator = opts.aggregators[aggregator.val()](vals)
subopts.renderer = opts.renderers[renderer.val()]
#construct filter here
exclusions = {}
@find('input.pvtFilter').not(':checked').each ->
filter = $(this).data("filter")
if exclusions[filter[0]]?
exclusions[filter[0]].push( filter[1] )
else
exclusions[filter[0]] = [ filter[1] ]
subopts.filter = (record) ->
return false if not opts.filter(record)
for k,excludedItems of exclusions
return false if ""+record[k] in excludedItems
return true
pivotTable.pivot(input,subopts)
pivotUIOptions =
cols: subopts.cols
rows: subopts.rows
vals: vals
exclusions: exclusions
hiddenAttributes: opts.hiddenAttributes
renderers: opts.renderers
aggregators: opts.aggregators
filter: opts.filter
derivedAttributes: opts.derivedAttributes
aggregatorName: aggregator.val()
rendererName: renderer.val()
localeStrings: opts.localeStrings
rendererOptions: opts.rendererOptions
@data "pivotUIOptions", pivotUIOptions
# if requested make sure unused columns are in alphabetical order
if opts.autoSortUnusedAttrs
natSort = $.pivotUtilities.naturalSort
unusedAttrsContainer = @find("td.pvtUnused.pvtAxisContainer")
$(unusedAttrsContainer).children("li")
.sort((a, b) => natSort($(a).text(), $(b).text()))
.appendTo unusedAttrsContainer
pivotTable.css("opacity", 1)
opts.onRefresh(pivotUIOptions) if opts.onRefresh?
refresh = =>
pivotTable.css("opacity", 0.5)
setTimeout refreshDelayed, 10
#the very first refresh will actually display the table
refresh()
@find(".pvtAxisContainer").sortable
update: refresh
connectWith: @find(".pvtAxisContainer")
items: 'li'
placeholder: 'placeholder'
catch e
console.error(e.stack) if console?
@html opts.localeStrings.uiRenderError
return this
###
Heatmap post-processing
###
$.fn.heatmap = (scope = "heatmap") ->
[numRows, numCols] = @data "dimensions"
colorGen = (color, min, max) ->
hexGen = switch color
when "red" then (hex) -> "ff#{hex}#{hex}"
when "green" then (hex) -> "#{hex}ff#{hex}"
when "blue" then (hex) -> "#{hex}#{hex}ff"
return (x) ->
intensity = 255 - Math.round 255*(x-min)/(max-min)
hex = intensity.toString(16).split(".")[0]
hex = 0+hex if hex.length == 1
return hexGen(hex)
heatmapper = (scope, color) =>
forEachCell = (f) =>
@find(scope).each ->
x = $(this).data("value")
f(x, $(this)) if x? and isFinite(x)
values = []
forEachCell (x) -> values.push x
colorFor = colorGen color, Math.min(values...), Math.max(values...)
forEachCell (x, elem) -> elem.css "background-color", "#" + colorFor(x)
switch scope
when "heatmap"
heatmapper ".pvtVal", "red"
when "rowheatmap"
heatmapper ".pvtVal.row#{i}", "red" for i in [0...numRows]
when "colheatmap"
heatmapper ".pvtVal.col#{j}", "red" for j in [0...numCols]
heatmapper ".pvtTotal.rowTotal", "red"
heatmapper ".pvtTotal.colTotal", "red"
return this
###
Barchart post-processing
###
$.fn.barchart = ->
[numRows, numCols] = @data "dimensions"
barcharter = (scope) =>
forEachCell = (f) =>
@find(scope).each ->
x = $(this).data("value")
f(x, $(this)) if x? and isFinite(x)
values = []
forEachCell (x) -> values.push x
max = Math.max(values...)
scaler = (x) -> 100*x/(1.4*max)
forEachCell (x, elem) ->
text = elem.text()
wrapper = $("<div>").css
"position": "relative"
"height": "55px"
wrapper.append $("<div>").css
"position": "absolute"
"bottom": 0
"left": 0
"right": 0
"height": scaler(x) + "%"
"background-color": "gray"
wrapper.append $("<div>").text(text).css
"position":"relative"
"padding-left":"5px"
"padding-right":"5px"
elem.css("padding": 0,"padding-top": "5px", "text-align": "center").html wrapper
barcharter ".pvtVal.row#{i}" for i in [0...numRows]
barcharter ".pvtTotal.colTotal"
return this
| true | $ = jQuery
###
Utilities
###
addSeparators = (nStr, thousandsSep, decimalSep) ->
nStr += ''
x = nStr.split('.')
x1 = x[0]
x2 = if x.length > 1 then decimalSep + x[1] else ''
rgx = /(\d+)(\d{3})/
x1 = x1.replace(rgx, '$1' + thousandsSep + '$2') while rgx.test(x1)
return x1 + x2
numberFormat = (sigfig=3, scaler=1, thousandsSep=",", decimalSep=".") ->
(x) ->
if x==0 or isNaN(x) or not isFinite(x) then ""
else addSeparators (scaler*x).toFixed(sigfig), thousandsSep, decimalSep
#technically these are aggregator constructor generator generators (!)
aggregatorTemplates =
sum: (sigfig=3, scaler=1) -> ([attr]) -> ->
sum: 0
push: (record) -> @sum += parseFloat(record[attr]) if not isNaN parseFloat(record[attr])
value: -> @sum
format: numberFormat(sigfig, scaler)
label: "Sum of #{attr}"
average: (sigfig=3, scaler=1) -> ([attr]) -> ->
sum: 0
len: 0
push: (record) ->
if not isNaN parseFloat(record[attr])
@sum += parseFloat(record[attr])
@len++
value: -> @sum/@len
format: numberFormat(sigfig, scaler)
label: "Average of #{attr}"
sumOverSum: (sigfig=3, scaler=1) -> ([num, denom]) -> ->
sumNum: 0
sumDenom: 0
push: (record) ->
@sumNum += parseFloat(record[num]) if not isNaN parseFloat(record[num])
@sumDenom += parseFloat(record[denom]) if not isNaN parseFloat(record[denom])
value: -> @sumNum/@sumDenom
format: numberFormat(sigfig, scaler)
label: "#{num}/#{denom}"
sumOverSumBound80: (sigfig=3, scaler=1, upper=true) -> ([num, denom]) -> ->
sumNum: 0
sumDenom: 0
push: (record) ->
@sumNum += parseFloat(record[num]) if not isNaN parseFloat(record[num])
@sumDenom += parseFloat(record[denom]) if not isNaN parseFloat(record[denom])
value: ->
sign = if upper then 1 else -1
(0.821187207574908/@sumDenom + @sumNum/@sumDenom + 1.2815515655446004*sign*
Math.sqrt(0.410593603787454/ (@sumDenom*@sumDenom) + (@sumNum*(1 - @sumNum/ @sumDenom))/ (@sumDenom*@sumDenom)))/
(1 + 1.642374415149816/@sumDenom)
format: numberFormat(sigfig, scaler)
label: "#{if upper then "Upper" else "Lower"} Bound of #{num}/#{denom}"
fractionOf: (wrapped, type="total") -> (x...) -> (data, rowKey, colKey) ->
selector: {total:[[],[]],row:[rowKey,[]],col:[[],colKey]}[type]
inner: wrapped(x...)(data, rowKey, colKey)
push: (record) -> @inner.push record
format: (v) -> numberFormat(2)(100*v)+"%"
label: wrapped(x...)(data, rowKey, colKey).label+" % of "+type
value: -> @inner.value() / data.getAggregator(@selector...).inner.value()
l10nWrapper: ( wrapped, formatter, labelFn) -> (x...) -> (data, rowKey, colKey) ->
inner: wrapped(x...)(data, rowKey, colKey)
push: (record) -> @inner.push record
format: formatter
label: labelFn(data)
value: -> @inner.value()
#technically these are aggregator constructor generators (!)
aggregators =
count: -> ->
count: 0
push: -> @count++
value: -> @count
format: numberFormat(0)
label: "Count"
countUnique: ([attr]) -> ->
uniq: []
push: (record) -> @uniq.push(record[attr]) if record[attr] not in @uniq
value: -> @uniq.length
format: numberFormat(0)
label: "Count Unique #{attr}"
listUnique: ([attr]) -> ->
uniq: []
push: (record) -> @uniq.push(record[attr]) if record[attr] not in @uniq
value: -> @uniq.join ", "
format: (x) -> x
label: "List Unique #{attr}"
intSum: aggregatorTemplates.sum(0)
sum: aggregatorTemplates.sum(3)
average: aggregatorTemplates.average(3)
sumOverSum: aggregatorTemplates.sumOverSum(3)
ub80: aggregatorTemplates.sumOverSumBound80(3, 1, true)
lb80: aggregatorTemplates.sumOverSumBound80(3, 1, false)
aggregators.sumAsFractionOfTotal= aggregatorTemplates.fractionOf(aggregators.sum)
aggregators.sumAsFractionOfRow= aggregatorTemplates.fractionOf(aggregators.sum, "row")
aggregators.sumAsFractionOfCol= aggregatorTemplates.fractionOf(aggregators.sum, "col")
aggregators.countAsFractionOfTotal= aggregatorTemplates.fractionOf(aggregators.count)
aggregators.countAsFractionOfRow= aggregatorTemplates.fractionOf(aggregators.count, "row")
aggregators.countAsFractionOfCol= aggregatorTemplates.fractionOf(aggregators.count, "col")
renderers =
"Table": (pvtData, opts) -> pivotTableRenderer(pvtData, opts)
"Table Barchart": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).barchart()
"Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap()
"Row Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap("rowheatmap")
"Col Heatmap": (pvtData, opts) -> pivotTableRenderer(pvtData, opts).heatmap("colheatmap")
mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
zeroPad = (number) -> ("0"+number).substr(-2,2)
derivers =
bin: (col, binWidth) -> (record) -> record[col] - record[col] % binWidth
dateFormat: (col, formatString) ->
#thanks http://stackoverflow.com/a/12213072/112871
(record) ->
date = new Date(Date.parse(record[col]))
if isNaN(date) then return ""
formatString.replace /%(.)/g, (m, p) ->
switch p
when "y" then date.getFullYear()
when "m" then zeroPad(date.getMonth()+1)
when "n" then mthNames[date.getMonth()]
when "d" then zeroPad(date.getDate())
when "w" then dayNames[date.getDay()]
when "x" then date.getDay()
when "H" then zeroPad(date.getHours())
when "M" then zeroPad(date.getMinutes())
when "S" then zeroPad(date.getSeconds())
else "%" + p
naturalSort = (as, bs) => #from http://stackoverflow.com/a/4373421/112871
rx = /(\d+)|(\D+)/g
rd = /\d/
rz = /^0/
if typeof as is "number" or typeof bs is "number"
return 1 if isNaN(as)
return -1 if isNaN(bs)
return as - bs
a = String(as).toLowerCase()
b = String(bs).toLowerCase()
return 0 if a is b
return (if a > b then 1 else -1) unless rd.test(a) and rd.test(b)
a = a.match(rx)
b = b.match(rx)
while a.length and b.length
a1 = a.shift()
b1 = b.shift()
if a1 isnt b1
if rd.test(a1) and rd.test(b1)
return a1.replace(rz, ".0") - b1.replace(rz, ".0")
else
return (if a1 > b1 then 1 else -1)
a.length - b.length
$.pivotUtilities = {aggregatorTemplates, aggregators, renderers, derivers, naturalSort, numberFormat}
###
functions for accessing input
###
deriveAttributes = (record, derivedAttributes, f) ->
record[k] = v(record) ? record[k] for k, v of derivedAttributes
record[k] ?= "null" for own k of record
f(record)
#can handle arrays or jQuery selections of tables
forEachRecord = (input, derivedAttributes, f) ->
addRecord = (record) -> deriveAttributes(record, derivedAttributes, f)
#if it's a function, have it call us back
if $.isFunction(input)
input(addRecord)
else if $.isArray(input)
if $.isArray(input[0]) #array of arrays
for own i, compactRecord of input when i > 0
record = {}
record[k] = compactRecord[j] for own j, k of input[0]
addRecord(record)
else #array of objects
addRecord(record) for record in input
else if input instanceof jQuery
tblCols = []
$("thead > tr > th", input).each (i) -> tblCols.push $(this).text()
$("tbody > tr", input).each (i) ->
record = {}
$("td", this).each (j) -> record[tblCols[j]] = $(this).text()
addRecord(record)
else
throw new Error("unknown input format")
#converts to [{attr:val, attr:val},{attr:val, attr:val}] using method above
convertToArray = (input) ->
result = []
forEachRecord input, {}, (record) -> result.push record
return result
class PivotData
constructor: (@aggregator, @colAttrs, @rowAttrs) ->
@tree = {}
@rowKeys = []
@colKeys = []
@flatRowKeys = []
@flatColKeys = []
@rowTotals = {}
@colTotals = {}
@allTotal = @aggregator(this, [], [])
@sorted = false
natSort: (as, bs) => naturalSort(as, bs)
arrSort: (a,b) => @natSort a.join(), b.join()
sortKeys: () =>
if not @sorted
@rowKeys.sort @arrSort
@colKeys.sort @arrSort
@sorted = true
getColKeys: () =>
@sortKeys()
return @colKeys
getRowKeys: () =>
@sortKeys()
return @rowKeys
flattenKey: (x) => PI:KEY:<KEY>END_PI(String.fromPI:KEY:<KEY>END_PI(0))
processRecord: (record) ->
colKey = (record[x] for x in @colAttrs)
rowKey = (record[x] for x in @rowAttrs)
flatRowKey = @flattenKey rowKey
flatColKey = @flattenKey colKey
@allTotal.push record
if rowKey.length != 0
if flatRowKey not in @flatRowKeys
@rowKeys.push rowKey
@flatRowKeys.push flatRowKey
if not @rowTotals[flatRowKey]
@rowTotals[flatRowKey] = @aggregator(this, rowKey, [])
@rowTotals[flatRowKey].push record
if colKey.length != 0
if flatColKey not in @flatColKeys
@colKeys.push colKey
@flatColKeys.push flatColKey
if not @colTotals[flatColKey]
@colTotals[flatColKey] = @aggregator(this, [], colKey)
@colTotals[flatColKey].push record
if colKey.length != 0 and rowKey.length != 0
if flatRowKey not of @tree
@tree[flatRowKey] = {}
if flatColKey not of @tree[flatRowKey]
@tree[flatRowKey][flatColKey] = @aggregator(this, rowKey, colKey)
@tree[flatRowKey][flatColKey].push record
getAggregator: (rowKey, colKey) =>
flatRowKey = @flattenKey rowKey
flatColKey = @flattenKey colKey
if rowKey.length == 0 and colKey.length == 0
agg = @allTotal
else if rowKey.length == 0
agg = @colTotals[flatColKey]
else if colKey.length == 0
agg = @rowTotals[flatRowKey]
else
agg = @tree[flatRowKey][flatColKey]
return agg ? {value: (-> null), format: -> ""}
getPivotData = (input, cols, rows, aggregator, filter, derivedAttributes) ->
# iterate through input, accumulating data for cells
pivotData = new PivotData(aggregator, cols, rows)
forEachRecord input, derivedAttributes, (record) ->
pivotData.processRecord(record) if filter(record)
return pivotData
#helper function for setting row/col-span
spanSize = (arr, i, j) ->
if i != 0
noDraw = true
for x in [0..j]
if arr[i-1][x] != arr[i][x]
noDraw = false
if noDraw
return -1 #do not draw cell
len = 0
while i+len < arr.length
stop = false
for x in [0..j]
stop = true if arr[i][x] != arr[i+len][x]
break if stop
len++
return len
pivotTableRenderer = (pivotData, opts) ->
defaults =
localeStrings:
totals: "Totals"
opts = $.extend defaults, opts
colAttrs = pivotData.colAttrs
rowAttrs = pivotData.rowAttrs
rowKeys = pivotData.getRowKeys()
colKeys = pivotData.getColKeys()
#now actually build the output
result = $("<table class='table table-bordered pvtTable'>")
#the first few rows are for col headers
for own j, c of colAttrs
tr = $("<tr>")
if parseInt(j) == 0 and rowAttrs.length != 0
tr.append $("<th>")
.attr("colspan", rowAttrs.length)
.attr("rowspan", colAttrs.length)
tr.append $("<th class='pvtAxisLabel'>").text(c)
for own i, colKey of colKeys
x = spanSize(colKeys, parseInt(i), parseInt(j))
if x != -1
th = $("<th class='pvtColLabel'>").text(colKey[j]).attr("colspan", x)
if parseInt(j) == colAttrs.length-1 and rowAttrs.length != 0
th.attr("rowspan", 2)
tr.append th
if parseInt(j) == 0
tr.append $("<th class='pvtTotalLabel'>").text(opts.localeStrings.totals)
.attr("rowspan", colAttrs.length + (if rowAttrs.length ==0 then 0 else 1))
result.append tr
#then a row for row header headers
if rowAttrs.length !=0
tr = $("<tr>")
for own i, r of rowAttrs
tr.append $("<th class='pvtAxisLabel'>").text(r)
th = $("<th>")
if colAttrs.length ==0
th.addClass("pvtTotalLabel").text(opts.localeStrings.totals)
tr.append th
result.append tr
#now the actual data rows, with their row headers and totals
for own i, rowKey of rowKeys
tr = $("<tr>")
for own j, txt of rowKey
x = spanSize(rowKeys, parseInt(i), parseInt(j))
if x != -1
th = $("<th class='pvtRowLabel'>").text(txt).attr("rowspan", x)
if parseInt(j) == rowAttrs.length-1 and colAttrs.length !=0
th.attr("colspan",2)
tr.append th
for own j, colKey of colKeys
aggregator = pivotData.getAggregator(rowKey, colKey)
val = aggregator.value()
tr.append $("<td class='pvtVal row#{i} col#{j}'>")
.html(aggregator.format val)
.data("value", val)
totalAggregator = pivotData.getAggregator(rowKey, [])
val = totalAggregator.value()
tr.append $("<td class='pvtTotal rowTotal'>")
.html(totalAggregator.format val)
.data("value", val)
.data("for", "row"+i)
result.append tr
#finally, the row for col totals, and a grand total
tr = $("<tr>")
th = $("<th class='pvtTotalLabel'>").text(opts.localeStrings.totals)
th.attr("colspan", rowAttrs.length + (if colAttrs.length == 0 then 0 else 1))
tr.append th
for own j, colKey of colKeys
totalAggregator = pivotData.getAggregator([], colKey)
val = totalAggregator.value()
tr.append $("<td class='pvtTotal colTotal'>")
.html(totalAggregator.format val)
.data("value", val)
.data("for", "col"+j)
totalAggregator = pivotData.getAggregator([], [])
val = totalAggregator.value()
tr.append $("<td class='pvtGrandTotal'>")
.html(totalAggregator.format val)
.data("value", val)
result.append tr
#squirrel this away for later
result.data "dimensions", [rowKeys.length, colKeys.length]
return result
###
Pivot Table
###
$.fn.pivot = (input, opts) ->
defaults =
cols : []
rows: []
filter: -> true
aggregator: aggregators.count()
derivedAttributes: {},
renderer: pivotTableRenderer
rendererOptions: null
localeStrings:
renderError: "An error occurred rendering the PivotTable results."
computeError: "An error occurred computing the PivotTable results."
opts = $.extend defaults, opts
result = null
try
pivotData = getPivotData(input, opts.cols, opts.rows,
opts.aggregator, opts.filter,
opts.derivedAttributes)
try
result = opts.renderer(pivotData, opts.rendererOptions)
catch e
console.error(e.stack) if console?
result = opts.localeStrings.renderError
catch e
console.error(e.stack) if console?
result = opts.localeStrings.computeError
@html result
return this
###
UI code, calls pivot table above
###
$.fn.pivotUI = (input, inputOpts, overwrite = false) ->
defaults =
derivedAttributes: {}
aggregators: aggregators
renderers: renderers
hiddenAttributes: []
menuLimit: 200
cols: [], rows: [], vals: []
exclusions: {}
unusedAttrsVertical: false
autoSortUnusedAttrs: false
rendererOptions: null
onRefresh: null
filter: -> true
localeStrings:
renderError: "An error occurred rendering the PivotTable results."
computeError: "An error occurred computing the PivotTable results."
uiRenderError: "An error occurred rendering the PivotTable UI."
selectAll: "Select <span>All</span>"
selectNone: "Select <span>None</span>"
tooMany: "(too many to list)"
filterResults: "Filter results"
btnSubmit: "Update"
existingOpts = @data "pivotUIOptions"
if not existingOpts? or overwrite
opts = $.extend defaults, inputOpts
else
opts = existingOpts
try
#cache the input in some useful form
input = convertToArray(input)
tblCols = (k for own k of input[0])
tblCols.push c for own c of opts.derivedAttributes when (c not in tblCols)
#figure out the cardinality and some stats
axisValues = {}
axisValues[x] = {} for x in tblCols
forEachRecord input, opts.derivedAttributes, (record) ->
for own k, v of record when opts.filter(record)
v ?= "null"
axisValues[k][v] ?= 0
axisValues[k][v]++
#start building the output
uiTable = $("<table class='table table-bordered' cellpadding='5'>")
#renderer control
rendererControl = $("<td>")
renderer = $("<select class='pvtRenderer'>")
.bind "change", -> refresh() #capture reference
for own x of opts.renderers
renderer.append $("<option>").val(x).text(x)
rendererControl.append renderer
#axis list, including the double-click menu
colList = $("<td class='pvtAxisContainer pvtUnused'>")
if opts.unusedAttrsVertical
colList.addClass('pvtVertList')
else
colList.addClass('pvtHorizList')
shownAttributes = (c for c in tblCols when c not in opts.hiddenAttributes)
for i, c of shownAttributes
do (c) ->
keys = (k for k of axisValues[c])
hasExcludedItem = false
valueList = $("<div>").addClass('pvtFilterBox').hide()
clearSearch = ->
$('.pvtSearch').val('').removeClass("nobkgd")
$('label').show()
$(".clear-search").hide()
$(".checkContainer").css("border-color","hsl(0, 0%, 87%)")
$(".none").remove()
hideFilterList = ->
$(".pvtFilterBox").hide();
$("nobr").removeClass();
updateSelected = ->
checked = $(valueList).find("[type='checkbox']:checked").length
$(".selected-val em").html(checked)
return checked
valueList.append $("<h4>")
.text("#{c} (#{keys.length})")
if keys.length > opts.menuLimit
valueList.append $("<p>")
.text(opts.localeStrings.tooMany)
else
btns = $("<p>").addClass("btns-search")
btns.append $("<button>").html(opts.localeStrings.selectAll).bind "click", ->
valueList.find("input").each ->
if $(this).is(':visible')
$(this).prop "checked", true
updateSelected()
btns.append $("<button>").html(opts.localeStrings.selectNone).bind "click", ->
valueList.find("input").each ->
if $(this).is(':visible')
$(this).prop "checked", false
updateSelected()
btns.append $("<span>").addClass("clear-search").bind "click", clearSearch
btns.append $("<div>").addClass("close-btn").bind "click", hideFilterList
btns.append $("<input>").addClass("pvtSearch").attr("placeholder", opts.localeStrings.filterResults).bind "keyup", ->
filter = $(this).val().toLowerCase()
if filter
$(".clear-search").css('display', 'inline-block')
$(".pvtSearch").addClass("nobkgd")
else
$(".clear-search").hide()
$(".pvtSearch").removeClass("nobkgd")
count = 0
$(this).parents(".pvtFilterBox").find('label span').each ->
testString = this.innerText.toLowerCase().indexOf(filter)
if testString isnt -1
$(this).parent().show()
count++
else
$(this).parent().hide()
if count is 0 and $('.none').length <= 0
$(".checkContainer").css("border-color","#fffff")
$(".checkContainer").append("<p class='none'>No results. <a href='#'>Clear filter?</a></p>").bind "click", clearSearch
else if count >= 1
clearSearch()
valueList.append btns
checkContainer = $("<div>").addClass("checkContainer")
for k in keys.sort(naturalSort)
v = axisValues[c][k]
filterItem = $("<label>")
filterItemExcluded = if opts.exclusions[c] then (k in opts.exclusions[c]) else false
hasExcludedItem ||= filterItemExcluded
filterItem.append $("<input type='checkbox' class='pvtFilter'>")
.attr("checked", !filterItemExcluded).data("filter", [c,k]).bind "change", updateSelected
filterItem.append $("<span>").text "#{k} (#{v})"
checkContainer.append $("<p>").append(filterItem)
valueList.append checkContainer
updateFilter = ->
unselectedCount = $(valueList).find("[type='checkbox']").length -
$(valueList).find("[type='checkbox']:checked").length
if unselectedCount > 0
attrElem.addClass "pvtFilteredAttribute"
else
attrElem.removeClass "pvtFilteredAttribute"
if keys.length > opts.menuLimit
valueList.toggle()
else
valueList.toggle(0, refresh)
$("nobr").removeClass("active_filter")
btn_submit = $("<p>").addClass("submit-btn")
valueList.append btn_submit
.append $("<button>").text(opts.localeStrings.btnSubmit).bind "click", updateFilter
btn_submit.append $("<span>").html('<em>' + updateSelected() + '</em>' + " selected of #{keys.length} total values").addClass("selected-val")
showFilterList = (e) ->
pvtFilterBox = $(".pvtFilterBox")
hideFilterList()
nobr = $(this).parents("nobr")
nobr.toggleClass("active_filter")
position = nobr.offset()
bottom = position.top + nobr.height() + 8
valueList.css(left: position.left, top: bottom).toggle()
clearSearch()
$(document).mouseup (e) ->
if (!pvtFilterBox.is(e.target) && pvtFilterBox.has(e.target).length is 0)
hideFilterList()
triangleLink = $("<span class='pvtTriangle'>").html(" ▾")
.bind "click", showFilterList
attrElem = $("<li class='label label-info axis_#{i}'>")
.append $("<nobr>").text(c).data("attrName", c).append(triangleLink)
attrElem.addClass('pvtFilteredAttribute') if hasExcludedItem
colList.append(attrElem).append(valueList)
attrElem.bind "dblclick", showFilterList
tr1 = $("<tr>")
#aggregator menu and value area
aggregator = $("<select class='pvtAggregator'>")
.bind "change", -> refresh() #capture reference
for own x of opts.aggregators
aggregator.append $("<option>").val(x).text(x)
tr1.append $("<td class='pvtAxisContainer pvtHorizList pvtVals'>")
.append(aggregator).append($("<br>"))
#column axes
tr1.append $("<td class='pvtAxisContainer pvtHorizList pvtCols'>")
uiTable.append tr1
tr2 = $("<tr>")
#row axes
tr2.append $("<td valign='top' class='pvtAxisContainer pvtRows'>")
#the actual pivot table container
pivotTable = $("<td valign='top' class='pvtRendererArea'>")
tr2.append pivotTable
uiTable.append tr2
#finally the renderer dropdown and unused attribs are inserted at the requested location
if opts.unusedAttrsVertical
uiTable.find('tr:nth-child(1)').prepend rendererControl
uiTable.find('tr:nth-child(2)').prepend colList
else
uiTable.prepend $("<tr>").append(rendererControl).append(colList)
#render the UI in its default state
@html uiTable
#set up the UI initial state as requested by moving elements around
for x in opts.cols
@find(".pvtCols").append @find(".axis_#{shownAttributes.indexOf(x)}")
for x in opts.rows
@find(".pvtRows").append @find(".axis_#{shownAttributes.indexOf(x)}")
for x in opts.vals
@find(".pvtVals").append @find(".axis_#{shownAttributes.indexOf(x)}")
if opts.aggregatorName?
@find(".pvtAggregator").val opts.aggregatorName
if opts.rendererName?
@find(".pvtRenderer").val opts.rendererName
#set up for refreshing
refreshDelayed = =>
subopts =
derivedAttributes: opts.derivedAttributes
localeStrings: opts.localeStrings
rendererOptions: opts.rendererOptions
cols: [], rows: []
vals = []
@find(".pvtRows li nobr").each -> subopts.rows.push $(this).data("attrName")
@find(".pvtCols li nobr").each -> subopts.cols.push $(this).data("attrName")
@find(".pvtVals li nobr").each -> vals.push $(this).data("attrName")
subopts.aggregator = opts.aggregators[aggregator.val()](vals)
subopts.renderer = opts.renderers[renderer.val()]
#construct filter here
exclusions = {}
@find('input.pvtFilter').not(':checked').each ->
filter = $(this).data("filter")
if exclusions[filter[0]]?
exclusions[filter[0]].push( filter[1] )
else
exclusions[filter[0]] = [ filter[1] ]
subopts.filter = (record) ->
return false if not opts.filter(record)
for k,excludedItems of exclusions
return false if ""+record[k] in excludedItems
return true
pivotTable.pivot(input,subopts)
pivotUIOptions =
cols: subopts.cols
rows: subopts.rows
vals: vals
exclusions: exclusions
hiddenAttributes: opts.hiddenAttributes
renderers: opts.renderers
aggregators: opts.aggregators
filter: opts.filter
derivedAttributes: opts.derivedAttributes
aggregatorName: aggregator.val()
rendererName: renderer.val()
localeStrings: opts.localeStrings
rendererOptions: opts.rendererOptions
@data "pivotUIOptions", pivotUIOptions
# if requested make sure unused columns are in alphabetical order
if opts.autoSortUnusedAttrs
natSort = $.pivotUtilities.naturalSort
unusedAttrsContainer = @find("td.pvtUnused.pvtAxisContainer")
$(unusedAttrsContainer).children("li")
.sort((a, b) => natSort($(a).text(), $(b).text()))
.appendTo unusedAttrsContainer
pivotTable.css("opacity", 1)
opts.onRefresh(pivotUIOptions) if opts.onRefresh?
refresh = =>
pivotTable.css("opacity", 0.5)
setTimeout refreshDelayed, 10
#the very first refresh will actually display the table
refresh()
@find(".pvtAxisContainer").sortable
update: refresh
connectWith: @find(".pvtAxisContainer")
items: 'li'
placeholder: 'placeholder'
catch e
console.error(e.stack) if console?
@html opts.localeStrings.uiRenderError
return this
###
Heatmap post-processing
###
$.fn.heatmap = (scope = "heatmap") ->
[numRows, numCols] = @data "dimensions"
colorGen = (color, min, max) ->
hexGen = switch color
when "red" then (hex) -> "ff#{hex}#{hex}"
when "green" then (hex) -> "#{hex}ff#{hex}"
when "blue" then (hex) -> "#{hex}#{hex}ff"
return (x) ->
intensity = 255 - Math.round 255*(x-min)/(max-min)
hex = intensity.toString(16).split(".")[0]
hex = 0+hex if hex.length == 1
return hexGen(hex)
heatmapper = (scope, color) =>
forEachCell = (f) =>
@find(scope).each ->
x = $(this).data("value")
f(x, $(this)) if x? and isFinite(x)
values = []
forEachCell (x) -> values.push x
colorFor = colorGen color, Math.min(values...), Math.max(values...)
forEachCell (x, elem) -> elem.css "background-color", "#" + colorFor(x)
switch scope
when "heatmap"
heatmapper ".pvtVal", "red"
when "rowheatmap"
heatmapper ".pvtVal.row#{i}", "red" for i in [0...numRows]
when "colheatmap"
heatmapper ".pvtVal.col#{j}", "red" for j in [0...numCols]
heatmapper ".pvtTotal.rowTotal", "red"
heatmapper ".pvtTotal.colTotal", "red"
return this
###
Barchart post-processing
###
$.fn.barchart = ->
[numRows, numCols] = @data "dimensions"
barcharter = (scope) =>
forEachCell = (f) =>
@find(scope).each ->
x = $(this).data("value")
f(x, $(this)) if x? and isFinite(x)
values = []
forEachCell (x) -> values.push x
max = Math.max(values...)
scaler = (x) -> 100*x/(1.4*max)
forEachCell (x, elem) ->
text = elem.text()
wrapper = $("<div>").css
"position": "relative"
"height": "55px"
wrapper.append $("<div>").css
"position": "absolute"
"bottom": 0
"left": 0
"right": 0
"height": scaler(x) + "%"
"background-color": "gray"
wrapper.append $("<div>").text(text).css
"position":"relative"
"padding-left":"5px"
"padding-right":"5px"
elem.css("padding": 0,"padding-top": "5px", "text-align": "center").html wrapper
barcharter ".pvtVal.row#{i}" for i in [0...numRows]
barcharter ".pvtTotal.colTotal"
return this
|
[
{
"context": "y\n clientID: '1901234816764848'\n clientSecret: 'dbd4fab3a392b289aa77826a9e07a08e'\n callbackURL: 'http://notemanapi.seibertsoftwar",
"end": 712,
"score": 0.9903663992881775,
"start": 680,
"tag": "KEY",
"value": "dbd4fab3a392b289aa77826a9e07a08e"
}
] | server/src/routes.coffee | codyseibert/jotit | 1 | app = require './app'
LoginCtrl = require './controllers/login_controller'
UsersCtrl = require './controllers/users_controller'
FeaturesCtrl = require './controllers/features_controller'
userIsLoggedIn = require './helpers/user_is_logged_in'
userOwnsUser = require './helpers/user_owns_user'
passport = require 'passport'
FacebookStrategy = require 'passport-facebook'
models = require './models/models'
Users = models.Users
ObjectId = require('mongoose').Types.ObjectId
_ = require 'lodash'
jwt = require 'jsonwebtoken'
config = require './config/config'
TOKEN_PASSWORD = config.JWT_PASSWORD
passport.use new FacebookStrategy
clientID: '1901234816764848'
clientSecret: 'dbd4fab3a392b289aa77826a9e07a08e'
callbackURL: 'http://notemanapi.seibertsoftwaresolutions.com/login/facebook/callback'
profileFields: ['email', 'id']
, (accessToken, refreshToken, profile, cb) ->
Users.findOne(fbId: profile.id).then (u) ->
if u?
cb null, u
else
user =
fbId: profile.id
fbAccessToken: accessToken
email: profile.emails[0].value
Users.create(user).then (obj) ->
if obj?
cb null, obj
else
cb 'error creating the user'
module.exports = do ->
app.get '/login/facebook',
passport.authenticate 'facebook',
session: false
scope: ['email']
app.get '/login/facebook/callback',
passport.authenticate('facebook',
failureRedirect: 'http://noteman.seibertsoftwaresolutions.com'
session: false
)
, (req, res) ->
if req.user?
user =
_id: req.user._id
fbId: req.user.fbId
fbAccessToken: req.user.fbAccessToken
jwt.sign user, TOKEN_PASSWORD, algorithm: 'HS256', (err, token) ->
res.redirect "http://noteman.seibertsoftwaresolutions.com/topics?t=#{token}"
else
res.status 400
res.send 'user not found'
app.post '/login', LoginCtrl.post
app.get '/features', FeaturesCtrl.index
app.post '/users', UsersCtrl.post
app.get '/users/:id', userIsLoggedIn, userOwnsUser, UsersCtrl.show
app.put '/users/:id', userIsLoggedIn, userOwnsUser, UsersCtrl.put
| 161802 | app = require './app'
LoginCtrl = require './controllers/login_controller'
UsersCtrl = require './controllers/users_controller'
FeaturesCtrl = require './controllers/features_controller'
userIsLoggedIn = require './helpers/user_is_logged_in'
userOwnsUser = require './helpers/user_owns_user'
passport = require 'passport'
FacebookStrategy = require 'passport-facebook'
models = require './models/models'
Users = models.Users
ObjectId = require('mongoose').Types.ObjectId
_ = require 'lodash'
jwt = require 'jsonwebtoken'
config = require './config/config'
TOKEN_PASSWORD = config.JWT_PASSWORD
passport.use new FacebookStrategy
clientID: '1901234816764848'
clientSecret: '<KEY>'
callbackURL: 'http://notemanapi.seibertsoftwaresolutions.com/login/facebook/callback'
profileFields: ['email', 'id']
, (accessToken, refreshToken, profile, cb) ->
Users.findOne(fbId: profile.id).then (u) ->
if u?
cb null, u
else
user =
fbId: profile.id
fbAccessToken: accessToken
email: profile.emails[0].value
Users.create(user).then (obj) ->
if obj?
cb null, obj
else
cb 'error creating the user'
module.exports = do ->
app.get '/login/facebook',
passport.authenticate 'facebook',
session: false
scope: ['email']
app.get '/login/facebook/callback',
passport.authenticate('facebook',
failureRedirect: 'http://noteman.seibertsoftwaresolutions.com'
session: false
)
, (req, res) ->
if req.user?
user =
_id: req.user._id
fbId: req.user.fbId
fbAccessToken: req.user.fbAccessToken
jwt.sign user, TOKEN_PASSWORD, algorithm: 'HS256', (err, token) ->
res.redirect "http://noteman.seibertsoftwaresolutions.com/topics?t=#{token}"
else
res.status 400
res.send 'user not found'
app.post '/login', LoginCtrl.post
app.get '/features', FeaturesCtrl.index
app.post '/users', UsersCtrl.post
app.get '/users/:id', userIsLoggedIn, userOwnsUser, UsersCtrl.show
app.put '/users/:id', userIsLoggedIn, userOwnsUser, UsersCtrl.put
| true | app = require './app'
LoginCtrl = require './controllers/login_controller'
UsersCtrl = require './controllers/users_controller'
FeaturesCtrl = require './controllers/features_controller'
userIsLoggedIn = require './helpers/user_is_logged_in'
userOwnsUser = require './helpers/user_owns_user'
passport = require 'passport'
FacebookStrategy = require 'passport-facebook'
models = require './models/models'
Users = models.Users
ObjectId = require('mongoose').Types.ObjectId
_ = require 'lodash'
jwt = require 'jsonwebtoken'
config = require './config/config'
TOKEN_PASSWORD = config.JWT_PASSWORD
passport.use new FacebookStrategy
clientID: '1901234816764848'
clientSecret: 'PI:KEY:<KEY>END_PI'
callbackURL: 'http://notemanapi.seibertsoftwaresolutions.com/login/facebook/callback'
profileFields: ['email', 'id']
, (accessToken, refreshToken, profile, cb) ->
Users.findOne(fbId: profile.id).then (u) ->
if u?
cb null, u
else
user =
fbId: profile.id
fbAccessToken: accessToken
email: profile.emails[0].value
Users.create(user).then (obj) ->
if obj?
cb null, obj
else
cb 'error creating the user'
module.exports = do ->
app.get '/login/facebook',
passport.authenticate 'facebook',
session: false
scope: ['email']
app.get '/login/facebook/callback',
passport.authenticate('facebook',
failureRedirect: 'http://noteman.seibertsoftwaresolutions.com'
session: false
)
, (req, res) ->
if req.user?
user =
_id: req.user._id
fbId: req.user.fbId
fbAccessToken: req.user.fbAccessToken
jwt.sign user, TOKEN_PASSWORD, algorithm: 'HS256', (err, token) ->
res.redirect "http://noteman.seibertsoftwaresolutions.com/topics?t=#{token}"
else
res.status 400
res.send 'user not found'
app.post '/login', LoginCtrl.post
app.get '/features', FeaturesCtrl.index
app.post '/users', UsersCtrl.post
app.get '/users/:id', userIsLoggedIn, userOwnsUser, UsersCtrl.show
app.put '/users/:id', userIsLoggedIn, userOwnsUser, UsersCtrl.put
|
[
{
"context": "], ({selectedArchives}) =>\n (selectedArchives[@dataset.boardID] or= {})[@dataset.type] = +@value\n Conf['sel",
"end": 14888,
"score": 0.7731806039810181,
"start": 14872,
"tag": "EMAIL",
"value": "@dataset.boardID"
}
] | src/General/Settings.coffee | N3X15/4chan-x | 1 | Settings =
init: ->
# 4chan X settings link
link = $.el 'a',
className: 'settings-link'
textContent: '<%= meta.name %> Settings'
href: 'javascript:;'
$.on link, 'click', Settings.open
$.event 'AddMenuEntry',
type: 'header'
el: link
order: 111
# 4chan settings link
link = $.el 'a',
className: 'fourchan-settings-link'
textContent: '4chan Settings'
href: 'javascript:;'
$.on link, 'click', -> $.id('settingsWindowLink').click()
$.event 'AddMenuEntry',
type: 'header'
el: link
order: 110
open: -> Conf['Enable 4chan\'s Extension']
Settings.addSection 'Main', Settings.main
Settings.addSection 'Filter', Settings.filter
Settings.addSection 'QR', Settings.qr
Settings.addSection 'Sauce', Settings.sauce
Settings.addSection 'Subscriptions', Settings.subscriptions
Settings.addSection 'Rice', Settings.rice
Settings.addSection 'Archives', Settings.archives
Settings.addSection 'Keybinds', Settings.keybinds
$.on d, 'AddSettingsSection', Settings.addSection
$.on d, 'OpenSettings', (e) -> Settings.open e.detail
return if Conf['Enable 4chan\'s Extension']
settings = JSON.parse(localStorage.getItem '4chan-settings') or {}
return if settings.disableAll
settings.disableAll = true
localStorage.setItem '4chan-settings', JSON.stringify settings
open: (openSection) ->
return if Settings.dialog
$.event 'CloseMenu'
html = <%= importHTML('General/Settings') %>
Settings.dialog = overlay = $.el 'div',
id: 'overlay'
innerHTML: html
links = []
for section in Settings.sections
link = $.el 'a',
className: "tab-#{section.hyphenatedTitle}"
textContent: section.title
href: 'javascript:;'
$.on link, 'click', Settings.openSection.bind section
links.push link, $.tn ' | '
sectionToOpen = link if section.title is openSection
links.pop()
$.add $('.sections-list', overlay), links
(if sectionToOpen then sectionToOpen else links[0]).click()
$.on $('.close', overlay), 'click', Settings.close
$.on overlay, 'click', Settings.close
$.on overlay.firstElementChild, 'click', (e) -> e.stopPropagation()
d.body.style.width = "#{d.body.clientWidth}px"
$.addClass d.body, 'unscroll'
$.add d.body, overlay
close: ->
return unless Settings.dialog
d.body.style.removeProperty 'width'
$.rmClass d.body, 'unscroll'
$.rm Settings.dialog
delete Settings.dialog
sections: []
addSection: (title, open) ->
if typeof title isnt 'string'
{title, open} = title.detail
hyphenatedTitle = title.toLowerCase().replace /\s+/g, '-'
Settings.sections.push {title, hyphenatedTitle, open}
openSection: ->
if selected = $ '.tab-selected', Settings.dialog
$.rmClass selected, 'tab-selected'
$.addClass $(".tab-#{@hyphenatedTitle}", Settings.dialog), 'tab-selected'
section = $ 'section', Settings.dialog
$.rmAll section
section.className = "section-#{@hyphenatedTitle}"
@open section, g
section.scrollTop = 0
main: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Main') %>
$.on $('.export', section), 'click', Settings.export
$.on $('.import', section), 'click', Settings.import
$.on $('.reset', section), 'click', Settings.reset
$.on $('input', section), 'change', Settings.onImport
items = {}
inputs = {}
for key, obj of Config.main
fs = $.el 'fieldset',
innerHTML: "<legend>#{key}</legend>"
for key, arr of obj
description = arr[1]
div = $.el 'div',
innerHTML: "<label><input type=checkbox name=\"#{key}\">#{key}</label><span class=description>: #{description}</span>"
input = $ 'input', div
$.on input, 'change', $.cb.checked
items[key] = Conf[key]
inputs[key] = input
$.add fs, div
$.add section, fs
$.get items, (items) ->
for key, val of items
inputs[key].checked = val
return
div = $.el 'div',
innerHTML: "<button></button><span class=description>: Clear manually-hidden threads and posts on all boards. Reload the page to apply."
button = $ 'button', div
$.get {hiddenThreads: {}, hiddenPosts: {}}, ({hiddenThreads, hiddenPosts}) ->
hiddenNum = 0
for ID, board of hiddenThreads.boards
hiddenNum += Object.keys(board).length
for ID, board of hiddenPosts.boards
for ID, thread of board
hiddenNum += Object.keys(thread).length
button.textContent = "Hidden: #{hiddenNum}"
$.on button, 'click', ->
@textContent = 'Hidden: 0'
$.delete ['hiddenThreads', 'hiddenPosts']
$.after $('input[name="Stubs"]', section).parentNode.parentNode, div
export: ->
# Make sure to export the most recent data.
$.get Conf, (Conf) ->
# XXX don't export archives.
delete Conf['archives']
Settings.downloadExport {version: g.VERSION, date: Date.now(), Conf}
downloadExport: (data) ->
a = $.el 'a',
download: "<%= meta.name %> v#{g.VERSION}-#{data.date}.json"
href: "data:application/json;base64,#{btoa unescape encodeURIComponent JSON.stringify data, null, 2}"
<% if (type === 'userscript') { %>
p = $ '.imp-exp-result', Settings.dialog
$.rmAll p
$.add p, a
<% } %>
a.click()
import: ->
$('input', @parentNode).click()
onImport: ->
return unless file = @files[0]
output = @parentNode.nextElementSibling
unless confirm 'Your current settings will be entirely overwritten, are you sure?'
output.textContent = 'Import aborted.'
return
reader = new FileReader()
reader.onload = (e) ->
try
Settings.loadSettings JSON.parse e.target.result
if confirm 'Import successful. Reload now?'
window.location.reload()
catch err
output.textContent = 'Import failed due to an error.'
c.error err.stack
reader.readAsText file
loadSettings: (data) ->
version = data.version.split '.'
if version[0] is '2'
convertSettings = (data, map) ->
for prevKey, newKey of map
data.Conf[newKey] = data.Conf[prevKey] if newKey
delete data.Conf[prevKey]
data
data = Settings.convertSettings data,
# General confs
'Disable 4chan\'s extension': ''
'Catalog Links': ''
'Reply Navigation': ''
'Show Stubs': 'Stubs'
'Image Auto-Gif': 'Auto-GIF'
'Expand From Current': ''
'Unread Favicon': 'Unread Tab Icon'
'Post in Title': 'Thread Excerpt'
'Auto Hide QR': ''
'Open Reply in New Tab': ''
'Remember QR size': ''
'Quote Inline': 'Quote Inlining'
'Quote Preview': 'Quote Previewing'
'Indicate OP quote': ''
'Indicate Cross-thread Quotes': ''
# filter
'uniqueid': 'uniqueID'
'mod': 'capcode'
'country': 'flag'
'md5': 'MD5'
# keybinds
'openEmptyQR': 'Open empty QR'
'openQR': 'Open QR'
'openOptions': 'Open settings'
'close': 'Close'
'spoiler': 'Spoiler tags'
'code': 'Code tags'
'submit': 'Submit QR'
'watch': 'Watch'
'update': 'Update'
'unreadCountTo0': ''
'expandAllImages': 'Expand images'
'expandImage': 'Expand image'
'zero': 'Front page'
'nextPage': 'Next page'
'previousPage': 'Previous page'
'nextThread': 'Next thread'
'previousThread': 'Previous thread'
'expandThread': 'Expand thread'
'openThreadTab': 'Open thread'
'openThread': 'Open thread tab'
'nextReply': 'Next reply'
'previousReply': 'Previous reply'
'hide': 'Hide'
# updater
'Scrolling': 'Auto Scroll'
'Verbose': ''
data.Conf.sauces = data.Conf.sauces.replace /\$\d/g, (c) ->
switch c
when '$1'
'%TURL'
when '$2'
'%URL'
when '$3'
'%MD5'
when '$4'
'%board'
when '$5'
'%DMD5'
else
c
for key, val of Config.hotkeys when key of data.Conf
data.Conf[key] = data.Conf[key].replace(/ctrl|alt|meta/g, (s) -> "#{s[0].toUpperCase()}#{s[1..]}").replace /(^|.+\+)[A-Z]$/g, (s) ->
"Shift+#{s[0...-1]}#{s[-1..].toLowerCase()}"
data.Conf['WatchedThreads'] = data.WatchedThreads
if data.Conf['WatchedThreads']
data.Conf['watchedThreads'] = boards: ThreadWatcher.convert data.Conf['WatchedThreads']
delete data.Conf['WatchedThreads']
$.set data.Conf
reset: ->
if confirm 'Your current settings will be entirely wiped, are you sure?'
$.clear -> window.location.reload() if confirm 'Reset successful. Reload now?'
filter: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Filter') %>
select = $ 'select', section
$.on select, 'change', Settings.selectFilter
Settings.selectFilter.call select
selectFilter: ->
div = @nextElementSibling
if (name = @value) isnt 'guide'
$.rmAll div
ta = $.el 'textarea',
name: name
className: 'field'
spellcheck: false
$.get name, Conf[name], (item) ->
ta.value = item[name]
$.on ta, 'change', $.cb.value
$.add div, ta
return
div.innerHTML = <%= importHTML('General/Settings-section-Filter-guide') %>
qr: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-QR') %>
ta = $ 'textarea', section
$.get 'QR.personas', Conf['QR.personas'], (item) ->
ta.value = item['QR.personas']
$.on ta, 'change', $.cb.value
sauce: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Sauce') %>
ta = $ 'textarea', section
$.get 'sauces', Conf['sauces'], (item) ->
ta.value = item['sauces']
$.on ta, 'change', $.cb.value
subscriptions: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Subscriptions') %>
ta = $ 'textarea', section
$.get 'subscriptions', Conf['subscriptions'], (item) ->
ta.value = item['subscriptions']
$.on ta, 'change', $.cb.value
rice: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Rice') %>
items = {}
inputs = {}
for name in ['boardnav', 'time', 'backlink', 'fileInfo', 'favicon', 'usercss']
input = $ "[name=#{name}]", section
items[name] = Conf[name]
inputs[name] = input
$.on input, 'change', $.cb.value
$.get items, (items) ->
for key, val of items
input = inputs[key]
input.value = val
continue if key is 'usercss'
event = if key in ['favicon', 'usercss']
'change'
else
'input'
$.on input, event, Settings[key]
Settings[key].call input
return
$.on $('input[name="Custom CSS"]', section), 'change', Settings.togglecss
$.on $('#apply-css', section), 'click', Settings.usercss
boardnav: ->
Header.generateBoardList @value
time: ->
funk = Time.createFunc @value
@nextElementSibling.textContent = funk Time, new Date()
backlink: ->
@nextElementSibling.textContent = @value.replace /%id/, '123456789'
fileInfo: ->
data =
isReply: true
file:
URL: '//i.4cdn.org/g/src/1334437723720.jpg'
name: 'd9bb2efc98dd0df141a94399ff5880b7.jpg'
size: '276 KB'
sizeInBytes: 276 * 1024
dimensions: '1280x720'
isImage: true
isSpoiler: true
funk = FileInfo.createFunc @value
@nextElementSibling.innerHTML = funk FileInfo, data
favicon: ->
Favicon.switch()
Unread.update() if g.VIEW is 'thread' and Conf['Unread Tab Icon']
@nextElementSibling.innerHTML = """
<img src=#{Favicon.default}>
<img src=#{Favicon.unreadSFW}>
<img src=#{Favicon.unreadNSFW}>
<img src=#{Favicon.unreadDead}>
"""
togglecss: ->
if $('textarea[name=usercss]', $.x 'ancestor::fieldset[1]', @).disabled = !@checked
CustomCSS.rmStyle()
else
CustomCSS.addStyle()
$.cb.checked.call @
usercss: ->
CustomCSS.update()
archives: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Archives') %>
button = $ 'button', section
$.on button, 'click', ->
$.delete 'lastarchivecheck'
button.textContent = '...'
button.disabled = true
Redirect.update ->
button.textContent = 'Updated'
Settings.addArchivesTable section
Settings.addArchivesTable section
addArchivesTable: (section) ->
boards = {}
for archive in Conf['archives']
for boardID in archive.boards
data = boards[boardID] or= {
thread: []
post: []
file: []
}
data.thread.push archive
if archive.software is 'foolfuuka'
data.post.push archive
if boardID in archive.files
data.file.push archive
rows = []
for boardID in Object.keys(boards).sort() # Alphabetical order
row = $.el 'tr'
rows.push row
$.add row, $.el 'th',
textContent: "/#{boardID}/"
className: if boardID is g.BOARD.ID then 'warning' else ''
data = boards[boardID]
Settings.addArchiveCell row, boardID, data, 'thread'
Settings.addArchiveCell row, boardID, data, 'post'
Settings.addArchiveCell row, boardID, data, 'file'
tbody = $ 'tbody', section
$.rmAll tbody
$.add tbody, rows
$.get {
lastarchivecheck: 0
selectedArchives: Conf['selectedArchives']
}, ({lastarchivecheck, selectedArchives}) ->
for boardID, data of selectedArchives
for type, uid of data
if option = $ "select[data-board-i-d='#{boardID}'][data-type='#{type}'] > option[value='#{uid}']", section
option.selected = true
$('time', section).textContent = new Date(lastarchivecheck).toLocaleString()
addArchiveCell: (row, boardID, data, type) ->
options = []
for archive in data[type]
options.push $.el 'option',
textContent: archive.name
value: archive.uid
td = $.el 'td'
{length} = options
if length
td.innerHTML = '<select></select>'
select = td.firstElementChild
unless select.disabled = length is 1
$.extend select.dataset, {boardID, type}
$.on select, 'change', Settings.saveSelectedArchive
$.add select, options
else
td.textContent = 'N/A'
$.add row, td
saveSelectedArchive: ->
$.get 'selectedArchives', Conf['selectedArchives'], ({selectedArchives}) =>
(selectedArchives[@dataset.boardID] or= {})[@dataset.type] = +@value
Conf['selectedArchives'] = selectedArchives
Redirect.selectArchives()
$.set 'selectedArchives', selectedArchives
keybinds: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Keybinds') %>
tbody = $ 'tbody', section
items = {}
inputs = {}
for key, arr of Config.hotkeys
tr = $.el 'tr',
innerHTML: "<td>#{arr[1]}</td><td><input class=field></td>"
input = $ 'input', tr
input.name = key
input.spellcheck = false
items[key] = Conf[key]
inputs[key] = input
$.on input, 'keydown', Settings.keybind
$.add tbody, tr
$.get items, (items) ->
for key, val of items
inputs[key].value = val
return
keybind: (e) ->
return if e.keyCode is 9 # tab
e.preventDefault()
e.stopPropagation()
return unless (key = Keybinds.keyCode e)?
@value = key
$.cb.value.call @
| 102968 | Settings =
init: ->
# 4chan X settings link
link = $.el 'a',
className: 'settings-link'
textContent: '<%= meta.name %> Settings'
href: 'javascript:;'
$.on link, 'click', Settings.open
$.event 'AddMenuEntry',
type: 'header'
el: link
order: 111
# 4chan settings link
link = $.el 'a',
className: 'fourchan-settings-link'
textContent: '4chan Settings'
href: 'javascript:;'
$.on link, 'click', -> $.id('settingsWindowLink').click()
$.event 'AddMenuEntry',
type: 'header'
el: link
order: 110
open: -> Conf['Enable 4chan\'s Extension']
Settings.addSection 'Main', Settings.main
Settings.addSection 'Filter', Settings.filter
Settings.addSection 'QR', Settings.qr
Settings.addSection 'Sauce', Settings.sauce
Settings.addSection 'Subscriptions', Settings.subscriptions
Settings.addSection 'Rice', Settings.rice
Settings.addSection 'Archives', Settings.archives
Settings.addSection 'Keybinds', Settings.keybinds
$.on d, 'AddSettingsSection', Settings.addSection
$.on d, 'OpenSettings', (e) -> Settings.open e.detail
return if Conf['Enable 4chan\'s Extension']
settings = JSON.parse(localStorage.getItem '4chan-settings') or {}
return if settings.disableAll
settings.disableAll = true
localStorage.setItem '4chan-settings', JSON.stringify settings
open: (openSection) ->
return if Settings.dialog
$.event 'CloseMenu'
html = <%= importHTML('General/Settings') %>
Settings.dialog = overlay = $.el 'div',
id: 'overlay'
innerHTML: html
links = []
for section in Settings.sections
link = $.el 'a',
className: "tab-#{section.hyphenatedTitle}"
textContent: section.title
href: 'javascript:;'
$.on link, 'click', Settings.openSection.bind section
links.push link, $.tn ' | '
sectionToOpen = link if section.title is openSection
links.pop()
$.add $('.sections-list', overlay), links
(if sectionToOpen then sectionToOpen else links[0]).click()
$.on $('.close', overlay), 'click', Settings.close
$.on overlay, 'click', Settings.close
$.on overlay.firstElementChild, 'click', (e) -> e.stopPropagation()
d.body.style.width = "#{d.body.clientWidth}px"
$.addClass d.body, 'unscroll'
$.add d.body, overlay
close: ->
return unless Settings.dialog
d.body.style.removeProperty 'width'
$.rmClass d.body, 'unscroll'
$.rm Settings.dialog
delete Settings.dialog
sections: []
addSection: (title, open) ->
if typeof title isnt 'string'
{title, open} = title.detail
hyphenatedTitle = title.toLowerCase().replace /\s+/g, '-'
Settings.sections.push {title, hyphenatedTitle, open}
openSection: ->
if selected = $ '.tab-selected', Settings.dialog
$.rmClass selected, 'tab-selected'
$.addClass $(".tab-#{@hyphenatedTitle}", Settings.dialog), 'tab-selected'
section = $ 'section', Settings.dialog
$.rmAll section
section.className = "section-#{@hyphenatedTitle}"
@open section, g
section.scrollTop = 0
main: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Main') %>
$.on $('.export', section), 'click', Settings.export
$.on $('.import', section), 'click', Settings.import
$.on $('.reset', section), 'click', Settings.reset
$.on $('input', section), 'change', Settings.onImport
items = {}
inputs = {}
for key, obj of Config.main
fs = $.el 'fieldset',
innerHTML: "<legend>#{key}</legend>"
for key, arr of obj
description = arr[1]
div = $.el 'div',
innerHTML: "<label><input type=checkbox name=\"#{key}\">#{key}</label><span class=description>: #{description}</span>"
input = $ 'input', div
$.on input, 'change', $.cb.checked
items[key] = Conf[key]
inputs[key] = input
$.add fs, div
$.add section, fs
$.get items, (items) ->
for key, val of items
inputs[key].checked = val
return
div = $.el 'div',
innerHTML: "<button></button><span class=description>: Clear manually-hidden threads and posts on all boards. Reload the page to apply."
button = $ 'button', div
$.get {hiddenThreads: {}, hiddenPosts: {}}, ({hiddenThreads, hiddenPosts}) ->
hiddenNum = 0
for ID, board of hiddenThreads.boards
hiddenNum += Object.keys(board).length
for ID, board of hiddenPosts.boards
for ID, thread of board
hiddenNum += Object.keys(thread).length
button.textContent = "Hidden: #{hiddenNum}"
$.on button, 'click', ->
@textContent = 'Hidden: 0'
$.delete ['hiddenThreads', 'hiddenPosts']
$.after $('input[name="Stubs"]', section).parentNode.parentNode, div
export: ->
# Make sure to export the most recent data.
$.get Conf, (Conf) ->
# XXX don't export archives.
delete Conf['archives']
Settings.downloadExport {version: g.VERSION, date: Date.now(), Conf}
downloadExport: (data) ->
a = $.el 'a',
download: "<%= meta.name %> v#{g.VERSION}-#{data.date}.json"
href: "data:application/json;base64,#{btoa unescape encodeURIComponent JSON.stringify data, null, 2}"
<% if (type === 'userscript') { %>
p = $ '.imp-exp-result', Settings.dialog
$.rmAll p
$.add p, a
<% } %>
a.click()
import: ->
$('input', @parentNode).click()
onImport: ->
return unless file = @files[0]
output = @parentNode.nextElementSibling
unless confirm 'Your current settings will be entirely overwritten, are you sure?'
output.textContent = 'Import aborted.'
return
reader = new FileReader()
reader.onload = (e) ->
try
Settings.loadSettings JSON.parse e.target.result
if confirm 'Import successful. Reload now?'
window.location.reload()
catch err
output.textContent = 'Import failed due to an error.'
c.error err.stack
reader.readAsText file
loadSettings: (data) ->
version = data.version.split '.'
if version[0] is '2'
convertSettings = (data, map) ->
for prevKey, newKey of map
data.Conf[newKey] = data.Conf[prevKey] if newKey
delete data.Conf[prevKey]
data
data = Settings.convertSettings data,
# General confs
'Disable 4chan\'s extension': ''
'Catalog Links': ''
'Reply Navigation': ''
'Show Stubs': 'Stubs'
'Image Auto-Gif': 'Auto-GIF'
'Expand From Current': ''
'Unread Favicon': 'Unread Tab Icon'
'Post in Title': 'Thread Excerpt'
'Auto Hide QR': ''
'Open Reply in New Tab': ''
'Remember QR size': ''
'Quote Inline': 'Quote Inlining'
'Quote Preview': 'Quote Previewing'
'Indicate OP quote': ''
'Indicate Cross-thread Quotes': ''
# filter
'uniqueid': 'uniqueID'
'mod': 'capcode'
'country': 'flag'
'md5': 'MD5'
# keybinds
'openEmptyQR': 'Open empty QR'
'openQR': 'Open QR'
'openOptions': 'Open settings'
'close': 'Close'
'spoiler': 'Spoiler tags'
'code': 'Code tags'
'submit': 'Submit QR'
'watch': 'Watch'
'update': 'Update'
'unreadCountTo0': ''
'expandAllImages': 'Expand images'
'expandImage': 'Expand image'
'zero': 'Front page'
'nextPage': 'Next page'
'previousPage': 'Previous page'
'nextThread': 'Next thread'
'previousThread': 'Previous thread'
'expandThread': 'Expand thread'
'openThreadTab': 'Open thread'
'openThread': 'Open thread tab'
'nextReply': 'Next reply'
'previousReply': 'Previous reply'
'hide': 'Hide'
# updater
'Scrolling': 'Auto Scroll'
'Verbose': ''
data.Conf.sauces = data.Conf.sauces.replace /\$\d/g, (c) ->
switch c
when '$1'
'%TURL'
when '$2'
'%URL'
when '$3'
'%MD5'
when '$4'
'%board'
when '$5'
'%DMD5'
else
c
for key, val of Config.hotkeys when key of data.Conf
data.Conf[key] = data.Conf[key].replace(/ctrl|alt|meta/g, (s) -> "#{s[0].toUpperCase()}#{s[1..]}").replace /(^|.+\+)[A-Z]$/g, (s) ->
"Shift+#{s[0...-1]}#{s[-1..].toLowerCase()}"
data.Conf['WatchedThreads'] = data.WatchedThreads
if data.Conf['WatchedThreads']
data.Conf['watchedThreads'] = boards: ThreadWatcher.convert data.Conf['WatchedThreads']
delete data.Conf['WatchedThreads']
$.set data.Conf
reset: ->
if confirm 'Your current settings will be entirely wiped, are you sure?'
$.clear -> window.location.reload() if confirm 'Reset successful. Reload now?'
filter: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Filter') %>
select = $ 'select', section
$.on select, 'change', Settings.selectFilter
Settings.selectFilter.call select
selectFilter: ->
div = @nextElementSibling
if (name = @value) isnt 'guide'
$.rmAll div
ta = $.el 'textarea',
name: name
className: 'field'
spellcheck: false
$.get name, Conf[name], (item) ->
ta.value = item[name]
$.on ta, 'change', $.cb.value
$.add div, ta
return
div.innerHTML = <%= importHTML('General/Settings-section-Filter-guide') %>
qr: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-QR') %>
ta = $ 'textarea', section
$.get 'QR.personas', Conf['QR.personas'], (item) ->
ta.value = item['QR.personas']
$.on ta, 'change', $.cb.value
sauce: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Sauce') %>
ta = $ 'textarea', section
$.get 'sauces', Conf['sauces'], (item) ->
ta.value = item['sauces']
$.on ta, 'change', $.cb.value
subscriptions: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Subscriptions') %>
ta = $ 'textarea', section
$.get 'subscriptions', Conf['subscriptions'], (item) ->
ta.value = item['subscriptions']
$.on ta, 'change', $.cb.value
rice: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Rice') %>
items = {}
inputs = {}
for name in ['boardnav', 'time', 'backlink', 'fileInfo', 'favicon', 'usercss']
input = $ "[name=#{name}]", section
items[name] = Conf[name]
inputs[name] = input
$.on input, 'change', $.cb.value
$.get items, (items) ->
for key, val of items
input = inputs[key]
input.value = val
continue if key is 'usercss'
event = if key in ['favicon', 'usercss']
'change'
else
'input'
$.on input, event, Settings[key]
Settings[key].call input
return
$.on $('input[name="Custom CSS"]', section), 'change', Settings.togglecss
$.on $('#apply-css', section), 'click', Settings.usercss
boardnav: ->
Header.generateBoardList @value
time: ->
funk = Time.createFunc @value
@nextElementSibling.textContent = funk Time, new Date()
backlink: ->
@nextElementSibling.textContent = @value.replace /%id/, '123456789'
fileInfo: ->
data =
isReply: true
file:
URL: '//i.4cdn.org/g/src/1334437723720.jpg'
name: 'd9bb2efc98dd0df141a94399ff5880b7.jpg'
size: '276 KB'
sizeInBytes: 276 * 1024
dimensions: '1280x720'
isImage: true
isSpoiler: true
funk = FileInfo.createFunc @value
@nextElementSibling.innerHTML = funk FileInfo, data
favicon: ->
Favicon.switch()
Unread.update() if g.VIEW is 'thread' and Conf['Unread Tab Icon']
@nextElementSibling.innerHTML = """
<img src=#{Favicon.default}>
<img src=#{Favicon.unreadSFW}>
<img src=#{Favicon.unreadNSFW}>
<img src=#{Favicon.unreadDead}>
"""
togglecss: ->
if $('textarea[name=usercss]', $.x 'ancestor::fieldset[1]', @).disabled = !@checked
CustomCSS.rmStyle()
else
CustomCSS.addStyle()
$.cb.checked.call @
usercss: ->
CustomCSS.update()
archives: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Archives') %>
button = $ 'button', section
$.on button, 'click', ->
$.delete 'lastarchivecheck'
button.textContent = '...'
button.disabled = true
Redirect.update ->
button.textContent = 'Updated'
Settings.addArchivesTable section
Settings.addArchivesTable section
addArchivesTable: (section) ->
boards = {}
for archive in Conf['archives']
for boardID in archive.boards
data = boards[boardID] or= {
thread: []
post: []
file: []
}
data.thread.push archive
if archive.software is 'foolfuuka'
data.post.push archive
if boardID in archive.files
data.file.push archive
rows = []
for boardID in Object.keys(boards).sort() # Alphabetical order
row = $.el 'tr'
rows.push row
$.add row, $.el 'th',
textContent: "/#{boardID}/"
className: if boardID is g.BOARD.ID then 'warning' else ''
data = boards[boardID]
Settings.addArchiveCell row, boardID, data, 'thread'
Settings.addArchiveCell row, boardID, data, 'post'
Settings.addArchiveCell row, boardID, data, 'file'
tbody = $ 'tbody', section
$.rmAll tbody
$.add tbody, rows
$.get {
lastarchivecheck: 0
selectedArchives: Conf['selectedArchives']
}, ({lastarchivecheck, selectedArchives}) ->
for boardID, data of selectedArchives
for type, uid of data
if option = $ "select[data-board-i-d='#{boardID}'][data-type='#{type}'] > option[value='#{uid}']", section
option.selected = true
$('time', section).textContent = new Date(lastarchivecheck).toLocaleString()
addArchiveCell: (row, boardID, data, type) ->
options = []
for archive in data[type]
options.push $.el 'option',
textContent: archive.name
value: archive.uid
td = $.el 'td'
{length} = options
if length
td.innerHTML = '<select></select>'
select = td.firstElementChild
unless select.disabled = length is 1
$.extend select.dataset, {boardID, type}
$.on select, 'change', Settings.saveSelectedArchive
$.add select, options
else
td.textContent = 'N/A'
$.add row, td
saveSelectedArchive: ->
$.get 'selectedArchives', Conf['selectedArchives'], ({selectedArchives}) =>
(selectedArchives[<EMAIL>] or= {})[@dataset.type] = +@value
Conf['selectedArchives'] = selectedArchives
Redirect.selectArchives()
$.set 'selectedArchives', selectedArchives
keybinds: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Keybinds') %>
tbody = $ 'tbody', section
items = {}
inputs = {}
for key, arr of Config.hotkeys
tr = $.el 'tr',
innerHTML: "<td>#{arr[1]}</td><td><input class=field></td>"
input = $ 'input', tr
input.name = key
input.spellcheck = false
items[key] = Conf[key]
inputs[key] = input
$.on input, 'keydown', Settings.keybind
$.add tbody, tr
$.get items, (items) ->
for key, val of items
inputs[key].value = val
return
keybind: (e) ->
return if e.keyCode is 9 # tab
e.preventDefault()
e.stopPropagation()
return unless (key = Keybinds.keyCode e)?
@value = key
$.cb.value.call @
| true | Settings =
init: ->
# 4chan X settings link
link = $.el 'a',
className: 'settings-link'
textContent: '<%= meta.name %> Settings'
href: 'javascript:;'
$.on link, 'click', Settings.open
$.event 'AddMenuEntry',
type: 'header'
el: link
order: 111
# 4chan settings link
link = $.el 'a',
className: 'fourchan-settings-link'
textContent: '4chan Settings'
href: 'javascript:;'
$.on link, 'click', -> $.id('settingsWindowLink').click()
$.event 'AddMenuEntry',
type: 'header'
el: link
order: 110
open: -> Conf['Enable 4chan\'s Extension']
Settings.addSection 'Main', Settings.main
Settings.addSection 'Filter', Settings.filter
Settings.addSection 'QR', Settings.qr
Settings.addSection 'Sauce', Settings.sauce
Settings.addSection 'Subscriptions', Settings.subscriptions
Settings.addSection 'Rice', Settings.rice
Settings.addSection 'Archives', Settings.archives
Settings.addSection 'Keybinds', Settings.keybinds
$.on d, 'AddSettingsSection', Settings.addSection
$.on d, 'OpenSettings', (e) -> Settings.open e.detail
return if Conf['Enable 4chan\'s Extension']
settings = JSON.parse(localStorage.getItem '4chan-settings') or {}
return if settings.disableAll
settings.disableAll = true
localStorage.setItem '4chan-settings', JSON.stringify settings
open: (openSection) ->
return if Settings.dialog
$.event 'CloseMenu'
html = <%= importHTML('General/Settings') %>
Settings.dialog = overlay = $.el 'div',
id: 'overlay'
innerHTML: html
links = []
for section in Settings.sections
link = $.el 'a',
className: "tab-#{section.hyphenatedTitle}"
textContent: section.title
href: 'javascript:;'
$.on link, 'click', Settings.openSection.bind section
links.push link, $.tn ' | '
sectionToOpen = link if section.title is openSection
links.pop()
$.add $('.sections-list', overlay), links
(if sectionToOpen then sectionToOpen else links[0]).click()
$.on $('.close', overlay), 'click', Settings.close
$.on overlay, 'click', Settings.close
$.on overlay.firstElementChild, 'click', (e) -> e.stopPropagation()
d.body.style.width = "#{d.body.clientWidth}px"
$.addClass d.body, 'unscroll'
$.add d.body, overlay
close: ->
return unless Settings.dialog
d.body.style.removeProperty 'width'
$.rmClass d.body, 'unscroll'
$.rm Settings.dialog
delete Settings.dialog
sections: []
addSection: (title, open) ->
if typeof title isnt 'string'
{title, open} = title.detail
hyphenatedTitle = title.toLowerCase().replace /\s+/g, '-'
Settings.sections.push {title, hyphenatedTitle, open}
openSection: ->
if selected = $ '.tab-selected', Settings.dialog
$.rmClass selected, 'tab-selected'
$.addClass $(".tab-#{@hyphenatedTitle}", Settings.dialog), 'tab-selected'
section = $ 'section', Settings.dialog
$.rmAll section
section.className = "section-#{@hyphenatedTitle}"
@open section, g
section.scrollTop = 0
main: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Main') %>
$.on $('.export', section), 'click', Settings.export
$.on $('.import', section), 'click', Settings.import
$.on $('.reset', section), 'click', Settings.reset
$.on $('input', section), 'change', Settings.onImport
items = {}
inputs = {}
for key, obj of Config.main
fs = $.el 'fieldset',
innerHTML: "<legend>#{key}</legend>"
for key, arr of obj
description = arr[1]
div = $.el 'div',
innerHTML: "<label><input type=checkbox name=\"#{key}\">#{key}</label><span class=description>: #{description}</span>"
input = $ 'input', div
$.on input, 'change', $.cb.checked
items[key] = Conf[key]
inputs[key] = input
$.add fs, div
$.add section, fs
$.get items, (items) ->
for key, val of items
inputs[key].checked = val
return
div = $.el 'div',
innerHTML: "<button></button><span class=description>: Clear manually-hidden threads and posts on all boards. Reload the page to apply."
button = $ 'button', div
$.get {hiddenThreads: {}, hiddenPosts: {}}, ({hiddenThreads, hiddenPosts}) ->
hiddenNum = 0
for ID, board of hiddenThreads.boards
hiddenNum += Object.keys(board).length
for ID, board of hiddenPosts.boards
for ID, thread of board
hiddenNum += Object.keys(thread).length
button.textContent = "Hidden: #{hiddenNum}"
$.on button, 'click', ->
@textContent = 'Hidden: 0'
$.delete ['hiddenThreads', 'hiddenPosts']
$.after $('input[name="Stubs"]', section).parentNode.parentNode, div
export: ->
# Make sure to export the most recent data.
$.get Conf, (Conf) ->
# XXX don't export archives.
delete Conf['archives']
Settings.downloadExport {version: g.VERSION, date: Date.now(), Conf}
downloadExport: (data) ->
a = $.el 'a',
download: "<%= meta.name %> v#{g.VERSION}-#{data.date}.json"
href: "data:application/json;base64,#{btoa unescape encodeURIComponent JSON.stringify data, null, 2}"
<% if (type === 'userscript') { %>
p = $ '.imp-exp-result', Settings.dialog
$.rmAll p
$.add p, a
<% } %>
a.click()
import: ->
$('input', @parentNode).click()
onImport: ->
return unless file = @files[0]
output = @parentNode.nextElementSibling
unless confirm 'Your current settings will be entirely overwritten, are you sure?'
output.textContent = 'Import aborted.'
return
reader = new FileReader()
reader.onload = (e) ->
try
Settings.loadSettings JSON.parse e.target.result
if confirm 'Import successful. Reload now?'
window.location.reload()
catch err
output.textContent = 'Import failed due to an error.'
c.error err.stack
reader.readAsText file
loadSettings: (data) ->
version = data.version.split '.'
if version[0] is '2'
convertSettings = (data, map) ->
for prevKey, newKey of map
data.Conf[newKey] = data.Conf[prevKey] if newKey
delete data.Conf[prevKey]
data
data = Settings.convertSettings data,
# General confs
'Disable 4chan\'s extension': ''
'Catalog Links': ''
'Reply Navigation': ''
'Show Stubs': 'Stubs'
'Image Auto-Gif': 'Auto-GIF'
'Expand From Current': ''
'Unread Favicon': 'Unread Tab Icon'
'Post in Title': 'Thread Excerpt'
'Auto Hide QR': ''
'Open Reply in New Tab': ''
'Remember QR size': ''
'Quote Inline': 'Quote Inlining'
'Quote Preview': 'Quote Previewing'
'Indicate OP quote': ''
'Indicate Cross-thread Quotes': ''
# filter
'uniqueid': 'uniqueID'
'mod': 'capcode'
'country': 'flag'
'md5': 'MD5'
# keybinds
'openEmptyQR': 'Open empty QR'
'openQR': 'Open QR'
'openOptions': 'Open settings'
'close': 'Close'
'spoiler': 'Spoiler tags'
'code': 'Code tags'
'submit': 'Submit QR'
'watch': 'Watch'
'update': 'Update'
'unreadCountTo0': ''
'expandAllImages': 'Expand images'
'expandImage': 'Expand image'
'zero': 'Front page'
'nextPage': 'Next page'
'previousPage': 'Previous page'
'nextThread': 'Next thread'
'previousThread': 'Previous thread'
'expandThread': 'Expand thread'
'openThreadTab': 'Open thread'
'openThread': 'Open thread tab'
'nextReply': 'Next reply'
'previousReply': 'Previous reply'
'hide': 'Hide'
# updater
'Scrolling': 'Auto Scroll'
'Verbose': ''
data.Conf.sauces = data.Conf.sauces.replace /\$\d/g, (c) ->
switch c
when '$1'
'%TURL'
when '$2'
'%URL'
when '$3'
'%MD5'
when '$4'
'%board'
when '$5'
'%DMD5'
else
c
for key, val of Config.hotkeys when key of data.Conf
data.Conf[key] = data.Conf[key].replace(/ctrl|alt|meta/g, (s) -> "#{s[0].toUpperCase()}#{s[1..]}").replace /(^|.+\+)[A-Z]$/g, (s) ->
"Shift+#{s[0...-1]}#{s[-1..].toLowerCase()}"
data.Conf['WatchedThreads'] = data.WatchedThreads
if data.Conf['WatchedThreads']
data.Conf['watchedThreads'] = boards: ThreadWatcher.convert data.Conf['WatchedThreads']
delete data.Conf['WatchedThreads']
$.set data.Conf
reset: ->
if confirm 'Your current settings will be entirely wiped, are you sure?'
$.clear -> window.location.reload() if confirm 'Reset successful. Reload now?'
filter: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Filter') %>
select = $ 'select', section
$.on select, 'change', Settings.selectFilter
Settings.selectFilter.call select
selectFilter: ->
div = @nextElementSibling
if (name = @value) isnt 'guide'
$.rmAll div
ta = $.el 'textarea',
name: name
className: 'field'
spellcheck: false
$.get name, Conf[name], (item) ->
ta.value = item[name]
$.on ta, 'change', $.cb.value
$.add div, ta
return
div.innerHTML = <%= importHTML('General/Settings-section-Filter-guide') %>
qr: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-QR') %>
ta = $ 'textarea', section
$.get 'QR.personas', Conf['QR.personas'], (item) ->
ta.value = item['QR.personas']
$.on ta, 'change', $.cb.value
sauce: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Sauce') %>
ta = $ 'textarea', section
$.get 'sauces', Conf['sauces'], (item) ->
ta.value = item['sauces']
$.on ta, 'change', $.cb.value
subscriptions: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Subscriptions') %>
ta = $ 'textarea', section
$.get 'subscriptions', Conf['subscriptions'], (item) ->
ta.value = item['subscriptions']
$.on ta, 'change', $.cb.value
rice: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Rice') %>
items = {}
inputs = {}
for name in ['boardnav', 'time', 'backlink', 'fileInfo', 'favicon', 'usercss']
input = $ "[name=#{name}]", section
items[name] = Conf[name]
inputs[name] = input
$.on input, 'change', $.cb.value
$.get items, (items) ->
for key, val of items
input = inputs[key]
input.value = val
continue if key is 'usercss'
event = if key in ['favicon', 'usercss']
'change'
else
'input'
$.on input, event, Settings[key]
Settings[key].call input
return
$.on $('input[name="Custom CSS"]', section), 'change', Settings.togglecss
$.on $('#apply-css', section), 'click', Settings.usercss
boardnav: ->
Header.generateBoardList @value
time: ->
funk = Time.createFunc @value
@nextElementSibling.textContent = funk Time, new Date()
backlink: ->
@nextElementSibling.textContent = @value.replace /%id/, '123456789'
fileInfo: ->
data =
isReply: true
file:
URL: '//i.4cdn.org/g/src/1334437723720.jpg'
name: 'd9bb2efc98dd0df141a94399ff5880b7.jpg'
size: '276 KB'
sizeInBytes: 276 * 1024
dimensions: '1280x720'
isImage: true
isSpoiler: true
funk = FileInfo.createFunc @value
@nextElementSibling.innerHTML = funk FileInfo, data
favicon: ->
Favicon.switch()
Unread.update() if g.VIEW is 'thread' and Conf['Unread Tab Icon']
@nextElementSibling.innerHTML = """
<img src=#{Favicon.default}>
<img src=#{Favicon.unreadSFW}>
<img src=#{Favicon.unreadNSFW}>
<img src=#{Favicon.unreadDead}>
"""
togglecss: ->
if $('textarea[name=usercss]', $.x 'ancestor::fieldset[1]', @).disabled = !@checked
CustomCSS.rmStyle()
else
CustomCSS.addStyle()
$.cb.checked.call @
usercss: ->
CustomCSS.update()
archives: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Archives') %>
button = $ 'button', section
$.on button, 'click', ->
$.delete 'lastarchivecheck'
button.textContent = '...'
button.disabled = true
Redirect.update ->
button.textContent = 'Updated'
Settings.addArchivesTable section
Settings.addArchivesTable section
addArchivesTable: (section) ->
boards = {}
for archive in Conf['archives']
for boardID in archive.boards
data = boards[boardID] or= {
thread: []
post: []
file: []
}
data.thread.push archive
if archive.software is 'foolfuuka'
data.post.push archive
if boardID in archive.files
data.file.push archive
rows = []
for boardID in Object.keys(boards).sort() # Alphabetical order
row = $.el 'tr'
rows.push row
$.add row, $.el 'th',
textContent: "/#{boardID}/"
className: if boardID is g.BOARD.ID then 'warning' else ''
data = boards[boardID]
Settings.addArchiveCell row, boardID, data, 'thread'
Settings.addArchiveCell row, boardID, data, 'post'
Settings.addArchiveCell row, boardID, data, 'file'
tbody = $ 'tbody', section
$.rmAll tbody
$.add tbody, rows
$.get {
lastarchivecheck: 0
selectedArchives: Conf['selectedArchives']
}, ({lastarchivecheck, selectedArchives}) ->
for boardID, data of selectedArchives
for type, uid of data
if option = $ "select[data-board-i-d='#{boardID}'][data-type='#{type}'] > option[value='#{uid}']", section
option.selected = true
$('time', section).textContent = new Date(lastarchivecheck).toLocaleString()
addArchiveCell: (row, boardID, data, type) ->
options = []
for archive in data[type]
options.push $.el 'option',
textContent: archive.name
value: archive.uid
td = $.el 'td'
{length} = options
if length
td.innerHTML = '<select></select>'
select = td.firstElementChild
unless select.disabled = length is 1
$.extend select.dataset, {boardID, type}
$.on select, 'change', Settings.saveSelectedArchive
$.add select, options
else
td.textContent = 'N/A'
$.add row, td
saveSelectedArchive: ->
$.get 'selectedArchives', Conf['selectedArchives'], ({selectedArchives}) =>
(selectedArchives[PI:EMAIL:<EMAIL>END_PI] or= {})[@dataset.type] = +@value
Conf['selectedArchives'] = selectedArchives
Redirect.selectArchives()
$.set 'selectedArchives', selectedArchives
keybinds: (section) ->
section.innerHTML = <%= importHTML('General/Settings-section-Keybinds') %>
tbody = $ 'tbody', section
items = {}
inputs = {}
for key, arr of Config.hotkeys
tr = $.el 'tr',
innerHTML: "<td>#{arr[1]}</td><td><input class=field></td>"
input = $ 'input', tr
input.name = key
input.spellcheck = false
items[key] = Conf[key]
inputs[key] = input
$.on input, 'keydown', Settings.keybind
$.add tbody, tr
$.get items, (items) ->
for key, val of items
inputs[key].value = val
return
keybind: (e) ->
return if e.keyCode is 9 # tab
e.preventDefault()
e.stopPropagation()
return unless (key = Keybinds.keyCode e)?
@value = key
$.cb.value.call @
|
[
{
"context": "earch result.'\n version: '0.6'\n authors: [\n 'Tunnecino @ ignitae.com'\n ]\n",
"end": 1473,
"score": 0.9606845378875732,
"start": 1464,
"tag": "USERNAME",
"value": "Tunnecino"
},
{
"context": "t.'\n version: '0.6'\n authors: [\n 'Tunnecino @ ignitae.com'\n ... | plugins/tinysong.coffee | Arrogance/nerdobot | 1 | request = require('request')
module.exports = (apikey) ->
songURL = (query) ->
query = encodeURIComponent query
"http://tinysong.com/b/#{query}?format=json&key=#{apikey}"
banner = (message) =>
"#{@color 'blue'}#{@BOLD}TinySong#{@RESET} - #{message}"
@addCommand 'tinysong',
args: '<search terms>'
description: 'Search TinySong (GrooveShark)'
(from, query, channel) =>
if not channel?
@notice from.nick, 'That command only works in channels'
return
if not query?
@notice from.nick, 'You should specify a search query!'
return
request
url: songURL query
json: true
(err, res, data) =>
if err?
@say channel,
banner "#{@BOLD}Couldn't connect...#{@RESET}"
return
if data.error?
@say channel,
banner "#{@BOLD}Error: #{data.error}#{@RESET}"
return
if not data.SongName?
@say channel,
banner "#{@BOLD}No results...#{@RESET}"
return
[name, artist, url] = [data.SongName, data.ArtistName, data.Url]
@say channel,
banner "#{@BOLD}#{name}#{@RESET} " +
"(#{@UNDERLINE}#{artist}#{@RESET}) - " +
"#{@UNDERLINE}#{@color 'blue'}#{url}#{@RESET}"
name: 'TinySong Search'
description: 'Return the first TinySong search result.'
version: '0.6'
authors: [
'Tunnecino @ ignitae.com'
]
| 121581 | request = require('request')
module.exports = (apikey) ->
songURL = (query) ->
query = encodeURIComponent query
"http://tinysong.com/b/#{query}?format=json&key=#{apikey}"
banner = (message) =>
"#{@color 'blue'}#{@BOLD}TinySong#{@RESET} - #{message}"
@addCommand 'tinysong',
args: '<search terms>'
description: 'Search TinySong (GrooveShark)'
(from, query, channel) =>
if not channel?
@notice from.nick, 'That command only works in channels'
return
if not query?
@notice from.nick, 'You should specify a search query!'
return
request
url: songURL query
json: true
(err, res, data) =>
if err?
@say channel,
banner "#{@BOLD}Couldn't connect...#{@RESET}"
return
if data.error?
@say channel,
banner "#{@BOLD}Error: #{data.error}#{@RESET}"
return
if not data.SongName?
@say channel,
banner "#{@BOLD}No results...#{@RESET}"
return
[name, artist, url] = [data.SongName, data.ArtistName, data.Url]
@say channel,
banner "#{@BOLD}#{name}#{@RESET} " +
"(#{@UNDERLINE}#{artist}#{@RESET}) - " +
"#{@UNDERLINE}#{@color 'blue'}#{url}#{@RESET}"
name: 'TinySong Search'
description: 'Return the first TinySong search result.'
version: '0.6'
authors: [
'Tunnecino @ <EMAIL>'
]
| true | request = require('request')
module.exports = (apikey) ->
songURL = (query) ->
query = encodeURIComponent query
"http://tinysong.com/b/#{query}?format=json&key=#{apikey}"
banner = (message) =>
"#{@color 'blue'}#{@BOLD}TinySong#{@RESET} - #{message}"
@addCommand 'tinysong',
args: '<search terms>'
description: 'Search TinySong (GrooveShark)'
(from, query, channel) =>
if not channel?
@notice from.nick, 'That command only works in channels'
return
if not query?
@notice from.nick, 'You should specify a search query!'
return
request
url: songURL query
json: true
(err, res, data) =>
if err?
@say channel,
banner "#{@BOLD}Couldn't connect...#{@RESET}"
return
if data.error?
@say channel,
banner "#{@BOLD}Error: #{data.error}#{@RESET}"
return
if not data.SongName?
@say channel,
banner "#{@BOLD}No results...#{@RESET}"
return
[name, artist, url] = [data.SongName, data.ArtistName, data.Url]
@say channel,
banner "#{@BOLD}#{name}#{@RESET} " +
"(#{@UNDERLINE}#{artist}#{@RESET}) - " +
"#{@UNDERLINE}#{@color 'blue'}#{url}#{@RESET}"
name: 'TinySong Search'
description: 'Return the first TinySong search result.'
version: '0.6'
authors: [
'Tunnecino @ PI:EMAIL:<EMAIL>END_PI'
]
|
[
{
"context": "lhost:27017/rachel'\n exports.TELEGRAM_TOKEN = '119032707:AAHbZyi4mXH6GtAP1_vpNxv_KktPEDdFEgU'\n\n when 'pro",
"end": 389,
"score": 0.6832270622253418,
"start": 380,
"tag": "KEY",
"value": "119032707"
},
{
"context": "17/rachel'\n exports.TELEGRAM_TOKEN = '119032... | src/server/config/config.coffee | FindBoat/rachel-bot | 0 | # Sets application config parameters depending on `env` name
env = process.env.NODE_ENV or 'prod'
console.log "Set app environment: #{env}"
switch(env)
when 'dev'
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.MONGODB_URI = 'mongodb://localhost:27017/rachel'
exports.TELEGRAM_TOKEN = '119032707:AAHbZyi4mXH6GtAP1_vpNxv_KktPEDdFEgU'
when 'prod'
exports.DEBUG_LOG = false
exports.DEBUG_WARN = false
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = false
exports.MONGODB_URI = process.env.MONGOLAB_URI
exports.TELEGRAM_TOKEN = '112582980:AAEQILFiw749CX7mg7ULhww_rvQwuax8pXI'
else
console.log "Environment #{env} not found"
| 39874 | # Sets application config parameters depending on `env` name
env = process.env.NODE_ENV or 'prod'
console.log "Set app environment: #{env}"
switch(env)
when 'dev'
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.MONGODB_URI = 'mongodb://localhost:27017/rachel'
exports.TELEGRAM_TOKEN = '<KEY>:<KEY>'
when 'prod'
exports.DEBUG_LOG = false
exports.DEBUG_WARN = false
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = false
exports.MONGODB_URI = process.env.MONGOLAB_URI
exports.TELEGRAM_TOKEN = '<KEY>'
else
console.log "Environment #{env} not found"
| true | # Sets application config parameters depending on `env` name
env = process.env.NODE_ENV or 'prod'
console.log "Set app environment: #{env}"
switch(env)
when 'dev'
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.MONGODB_URI = 'mongodb://localhost:27017/rachel'
exports.TELEGRAM_TOKEN = 'PI:KEY:<KEY>END_PI:PI:KEY:<KEY>END_PI'
when 'prod'
exports.DEBUG_LOG = false
exports.DEBUG_WARN = false
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = false
exports.MONGODB_URI = process.env.MONGOLAB_URI
exports.TELEGRAM_TOKEN = 'PI:KEY:<KEY>END_PI'
else
console.log "Environment #{env} not found"
|
[
{
"context": "c/types/json.coffee)\n#\n# Spec: https://github.com/josephg/ShareJS/wiki/JSON-Operations\n\nnativetype = requir",
"end": 86,
"score": 0.9997211694717407,
"start": 79,
"tag": "USERNAME",
"value": "josephg"
},
{
"context": "he operand.\n parent = container\n key... | node_modules/share/test/types/json.coffee | abraarsyed/workshare | 2 | # Tests for JSON OT type. (src/types/json.coffee)
#
# Spec: https://github.com/josephg/ShareJS/wiki/JSON-Operations
nativetype = require '../../src/types/json'
randomWord = require './randomWord'
util = require 'util'
p = util.debug
i = util.inspect
# This is an awful function to clone a document snapshot for use by the random
# op generator. .. Since we don't want to corrupt the original object with
# the changes the op generator will make.
clone = (o) -> JSON.parse(JSON.stringify(o))
{randomInt, randomReal} = require('../helpers')
randomKey = (obj) ->
if Array.isArray(obj)
if obj.length == 0
undefined
else
randomInt obj.length
else
count = 0
for key of obj
result = key if randomReal() < 1/++count
result
# Generate a random new key for a value in obj.
# obj must be an Object.
randomNewKey = (obj) ->
# There's no do-while loop in coffeescript.
key = randomWord()
key = randomWord() while obj[key] != undefined
key
# Generate a random object
randomThing = ->
switch randomInt 6
when 0 then null
when 1 then ''
when 2 then randomWord()
when 3
obj = {}
obj[randomNewKey(obj)] = randomThing() for [1..randomInt(5)]
obj
when 4 then (randomThing() for [1..randomInt(5)])
when 5 then randomInt(50)
# Pick a random path to something in the object.
randomPath = (data) ->
path = []
while randomReal() > 0.85 and typeof data == 'object'
key = randomKey data
break unless key?
path.push key
data = data[key]
path
genTests = (type) ->
type.generateRandomOp = (data) ->
pct = 0.95
container = data: clone(data)
op = while randomReal() < pct
pct *= 0.6
# Pick a random object in the document operate on.
path = randomPath(container['data'])
# parent = the container for the operand. parent[key] contains the operand.
parent = container
key = 'data'
for p in path
parent = parent[key]
key = p
operand = parent[key]
if randomReal() < 0.4 and parent != container and Array.isArray(parent)
# List move
newIndex = randomInt parent.length
# Remove the element from its current position in the list
parent.splice key, 1
# Insert it in the new position.
parent.splice newIndex, 0, operand
{p:path, lm:newIndex}
else if randomReal() < 0.3 or operand == null
# Replace
newValue = randomThing()
parent[key] = newValue
if Array.isArray(parent)
{p:path, ld:operand, li:clone(newValue)}
else
{p:path, od:operand, oi:clone(newValue)}
else if typeof operand == 'string'
# String. This code is adapted from the text op generator.
if randomReal() > 0.5 or operand.length == 0
# Insert
pos = randomInt(operand.length + 1)
str = randomWord() + ' '
path.push pos
parent[key] = operand[...pos] + str + operand[pos..]
{p:path, si:str}
else
# Delete
pos = randomInt(operand.length)
length = Math.min(randomInt(4), operand.length - pos)
str = operand[pos...(pos + length)]
path.push pos
parent[key] = operand[...pos] + operand[pos + length..]
{p:path, sd:str}
else if typeof operand == 'number'
# Number
inc = randomInt(10) - 3
parent[key] += inc
{p:path, na:inc}
else if Array.isArray(operand)
# Array. Replace is covered above, so we'll just randomly insert or delete.
# This code looks remarkably similar to string insert, above.
if randomReal() > 0.5 or operand.length == 0
# Insert
pos = randomInt(operand.length + 1)
obj = randomThing()
path.push pos
operand.splice pos, 0, obj
{p:path, li:clone(obj)}
else
# Delete
pos = randomInt operand.length
obj = operand[pos]
path.push pos
operand.splice pos, 1
{p:path, ld:clone(obj)}
else
# Object
k = randomKey(operand)
if randomReal() > 0.5 or not k?
# Insert
k = randomNewKey(operand)
obj = randomThing()
path.push k
operand[k] = obj
{p:path, oi:clone(obj)}
else
obj = operand[k]
path.push k
delete operand[k]
{p:path, od:clone(obj)}
[op, container.data]
# The random op tester above will test that the OT functions are admissable, but
# debugging problems it detects is a pain.
#
# These tests should pick up *most* problems with a normal JSON OT implementation.
sanity:
'name is json': (test) ->
test.strictEqual type.name, 'json'
test.done()
'create() returns null': (test) ->
test.deepEqual type.create(), null
test.done()
'compose od,oi --> od+oi': (test) ->
test.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1}],[{p:['foo'],oi:2}]
test.deepEqual [{p:['foo'], od:1},{p:['bar'], oi:2}], type.compose [{p:['foo'],od:1}],[{p:['bar'],oi:2}]
test.done()
'transform returns sane values': (test) ->
t = (op1, op2) ->
test.deepEqual op1, type.transform op1, op2, 'left'
test.deepEqual op1, type.transform op1, op2, 'right'
t [], []
t [{p:['foo'], oi:1}], []
t [{p:['foo'], oi:1}], [{p:['bar'], oi:2}]
test.done()
number:
'Add a number': (test) ->
test.deepEqual 3, type.apply 1, [{p:[], na:2}]
test.deepEqual [3], type.apply [1], [{p:[0], na:2}]
test.done()
'Compose two adds together with the same path compresses them': (test) ->
test.deepEqual [{p:['a', 'b'], na:3}], type.compose [{p:['a', 'b'], na:1}], [{p:['a', 'b'], na:2}]
test.deepEqual [{p:['a'], na:1}, {p:['b'], na:2}], type.compose [{p:['a'], na:1}], [{p:['b'], na:2}]
test.done()
'make sure append doesn\'t overwrite values when it merges na': (test) ->
rightHas = 21
leftHas = 3
rightOp = [{"p":[],"od":0,"oi":15},{"p":[],"na":4},{"p":[],"na":1},{"p":[],"na":1}]
leftOp = [{"p":[],"na":4},{"p":[],"na":-1}]
[right_, left_] = require('../helpers').transformX type, rightOp, leftOp
s_c = type.apply rightHas, left_
c_s = type.apply leftHas, right_
test.deepEqual s_c, c_s
test.done()
# Strings should be handled internally by the text type. We'll just do some basic sanity checks here.
string:
'Apply works': (test) ->
test.deepEqual 'abc', type.apply 'a', [{p:[1], si:'bc'}]
test.deepEqual 'bc', type.apply 'abc', [{p:[0], sd:'a'}]
test.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x', 1], si:'bc'}]
test.done()
'transform splits deletes': (test) ->
test.deepEqual type.transform([{p:[0], sd:'ab'}], [{p:[1], si:'x'}], 'left'), [{p:[0], sd:'a'}, {p:[1], sd:'b'}]
test.done()
'deletes cancel each other out': (test) ->
test.deepEqual type.transform([{p:['k', 5], sd:'a'}], [{p:['k', 5], sd:'a'}], 'left'), []
test.done()
'blank inserts do not throw error': (test) ->
test.deepEqual type.transform([{p: ['k', 5], si:''}], [{p: ['k', 3], si: 'a'}], 'left'), []
test.done()
list:
'Apply inserts': (test) ->
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'c'], [{p:[0], li:'a'}]
test.deepEqual ['a', 'b', 'c'], type.apply ['a', 'c'], [{p:[1], li:'b'}]
test.deepEqual ['a', 'b', 'c'], type.apply ['a', 'b'], [{p:[2], li:'c'}]
test.done()
'Apply deletes': (test) ->
test.deepEqual ['b', 'c'], type.apply ['a', 'b', 'c'], [{p:[0], ld:'a'}]
test.deepEqual ['a', 'c'], type.apply ['a', 'b', 'c'], [{p:[1], ld:'b'}]
test.deepEqual ['a', 'b'], type.apply ['a', 'b', 'c'], [{p:[2], ld:'c'}]
test.done()
'apply replace': (test) ->
test.deepEqual ['a', 'y', 'b'], type.apply ['a', 'x', 'b'], [{p:[1], ld:'x', li:'y'}]
test.done()
'apply move': (test) ->
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[1], lm:0}]
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[0], lm:1}]
test.done()
###
'null moves compose to nops': (test) ->
test.deepEqual [], type.compose [], [{p:[3],lm:3}]
test.deepEqual [], type.compose [], [{p:[0,3],lm:3}]
test.deepEqual [], type.compose [], [{p:['x','y',0],lm:0}]
test.done()
###
'Paths are bumped when list elements are inserted or removed': (test) ->
test.deepEqual [{p:[2, 200], si:'hi'}], type.transform [{p:[1, 200], si:'hi'}], [{p:[0], li:'x'}], 'left'
test.deepEqual [{p:[1, 201], si:'hi'}], type.transform [{p:[0, 201], si:'hi'}], [{p:[0], li:'x'}], 'right'
test.deepEqual [{p:[0, 202], si:'hi'}], type.transform [{p:[0, 202], si:'hi'}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[0, 203], si:'hi'}], type.transform [{p:[1, 203], si:'hi'}], [{p:[0], ld:'x'}], 'left'
test.deepEqual [{p:[0, 204], si:'hi'}], type.transform [{p:[0, 204], si:'hi'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:['x',3], si: 'hi'}], type.transform [{p:['x',3], si:'hi'}], [{p:['x',0,'x'], li:0}], 'left'
test.deepEqual [{p:['x',3,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',5], li:0}], 'left'
test.deepEqual [{p:['x',4,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',0], li:0}], 'left'
test.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'left'
test.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'right'
test.done()
'Ops on deleted elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[0],li:'x'}], type.transform [{p:[0],li:'x'}], [{p:[0],ld:'y'}], 'left'
test.deepEqual [], type.transform [{p:[0],na:-3}], [{p:[0],ld:48}], 'left'
test.done()
'Ops on replaced elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x', li:'y'}], 'left'
test.deepEqual [{p:[0], li:'hi'}], type.transform [{p:[0], li:'hi'}], [{p:[0], ld:'x', li:'y'}], 'left'
test.done()
'Deleted data is changed to reflect edits': (test) ->
test.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1, 1], si:'bc'}], 'left'
test.done()
'Inserting then deleting an element composes into a no-op': (test) ->
test.deepEqual [], type.compose [{p:[1], li:'abc'}], [{p:[1], ld:'abc'}]
test.deepEqual [{p:[1],ld:null,li:'x'}], type.transform [{p:[0],ld:null,li:"x"}], [{p:[0],li:"The"}], 'right'
test.done()
'Composing doesn\'t change the original object': (test) ->
a = [{p:[0],ld:'abc',li:null}]
test.deepEqual [{p:[0],ld:'abc'}], type.compose a, [{p:[0],ld:null}]
test.deepEqual [{p:[0],ld:'abc',li:null}], a
test.done()
'If two inserts are simultaneous, the left op will end up first': (test) ->
test.deepEqual [{p:[1], li:'a'}], type.transform [{p:[1], li:'a'}], [{p:[1], li:'b'}], 'left'
test.deepEqual [{p:[2], li:'b'}], type.transform [{p:[1], li:'b'}], [{p:[1], li:'a'}], 'right'
test.done()
'An attempt to re-delete a list element becomes a no-op': (test) ->
test.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'right'
test.done()
'Ops on a moved element move with the element': (test) ->
test.deepEqual [{p:[10], ld:'x'}], type.transform [{p:[4], ld:'x'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], si:'a'}], type.transform [{p:[4, 1], si:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], li:'a'}], type.transform [{p:[4, 1], li:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], ld:'b', li:'a'}], type.transform [{p:[4, 1], ld:'b', li:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[0],li:null}], type.transform [{p:[0],li:null}], [{p:[0],lm:1}], 'left'
# [_,_,_,_,5,6,7,_]
# c: [_,_,_,_,5,'x',6,7,_] p:5 li:'x'
# s: [_,6,_,_,_,5,7,_] p:5 lm:1
# correct: [_,6,_,_,_,5,'x',7,_]
test.deepEqual [{p:[6],li:'x'}], type.transform [{p:[5],li:'x'}], [{p:[5],lm:1}], 'left'
# [_,_,_,_,5,6,7,_]
# c: [_,_,_,_,5,6,7,_] p:5 ld:6
# s: [_,6,_,_,_,5,7,_] p:5 lm:1
# correct: [_,_,_,_,5,7,_]
test.deepEqual [{p:[1],ld:6}], type.transform [{p:[5],ld:6}], [{p:[5],lm:1}], 'left'
#test.deepEqual [{p:[0],li:{}}], type.transform [{p:[0],li:{}}], [{p:[0],lm:0}], 'right'
test.deepEqual [{p:[0],li:[]}], type.transform [{p:[0],li:[]}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],li:'x'}], type.transform [{p:[2],li:'x'}], [{p:[0],lm:1}], 'left'
test.done()
'Target index of a moved element is changed by ld/li': (test) ->
test.deepEqual [{p:[0],lm:1}], type.transform [{p:[0], lm: 2}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[1],lm:3}], type.transform [{p:[2], lm: 4}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[0],lm:3}], type.transform [{p:[0], lm: 2}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[3],lm:5}], type.transform [{p:[2], lm: 4}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0], lm: 0}], [{p:[0], li:28}], 'left'
test.done()
'Tiebreak lm vs. ld/li': (test) ->
test.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'left'
test.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'right'
test.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'left'
test.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'right'
test.done()
'replacement vs. deletion': (test) ->
test.deepEqual [{p:[0],li:'y'}], type.transform [{p:[0],ld:'x',li:'y'}], [{p:[0],ld:'x'}], 'right'
test.done()
'replacement vs. insertion': (test) ->
test.deepEqual [{p:[1],ld:{},li:"brillig"}], type.transform [{p:[0],ld:{},li:"brillig"}], [{p:[0],li:36}], 'left'
test.done()
'replacement vs. replacement': (test) ->
test.deepEqual [], type.transform [{p:[0],ld:null,li:[]}], [{p:[0],ld:null,li:0}], 'right'
test.deepEqual [{p:[0],ld:[],li:0}], type.transform [{p:[0],ld:null,li:0}], [{p:[0],ld:null,li:[]}], 'left'
test.done()
'composing replace with delete of replaced element results in insert': (test) ->
test.deepEqual [{p:[2],ld:[]}], type.compose [{p:[2],ld:[],li:null}], [{p:[2],ld:null}]
test.done()
'lm vs lm': (test) ->
test.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:2}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[4],lm:4}], type.transform [{p:[3],lm:3}], [{p:[5],lm:0}], 'left'
test.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],lm:1}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'right'
test.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[3],lm:0}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'left'
test.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left'
test.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:5}], 'right'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:1}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[1],lm:2}], type.transform [{p:[0],lm:1}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[3],lm:2}], type.transform [{p:[2],lm:1}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[2],lm:1}], type.transform [{p:[3],lm:1}], [{p:[1],lm:3}], 'left'
test.deepEqual [{p:[2],lm:3}], type.transform [{p:[1],lm:3}], [{p:[3],lm:1}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'right'
test.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:1}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:1}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:0}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],lm:3}], 'left'
test.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:1}], [{p:[3],lm:2}], 'left'
test.deepEqual [{p:[3],lm:3}], type.transform [{p:[3],lm:2}], [{p:[2],lm:1}], 'left'
test.done()
'indices change correctly around a move': (test) ->
test.deepEqual [{p:[1,0],li:{}}], type.transform [{p:[0,0],li:{}}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],ld:{}}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],ld:{}}], 'left'
test.deepEqual [{p:[5],lm:0}], type.transform [{p:[6],lm:0}], [{p:[2],ld:{}}], 'left'
test.deepEqual [{p:[1],lm:0}], type.transform [{p:[1],lm:0}], [{p:[2],ld:{}}], 'left'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[2],lm:1}], [{p:[1],ld:3}], 'right'
test.deepEqual [{p:[1],ld:{}}], type.transform [{p:[2],ld:{}}], [{p:[1],lm:2}], 'right'
test.deepEqual [{p:[2],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[0],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[0],ld:1,li:2}], type.transform [{p:[1],ld:1,li:2}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],ld:2,li:3}], type.transform [{p:[1],ld:2,li:3}], [{p:[0],lm:1}], 'left'
test.deepEqual [{p:[1],ld:3,li:4}], type.transform [{p:[0],ld:3,li:4}], [{p:[1],lm:0}], 'left'
test.done()
'li vs lm': (test) ->
li = (p) -> [{p:[p],li:[]}]
lm = (f,t) -> [{p:[f],lm:t}]
xf = type.transform
test.deepEqual (li 0), xf (li 0), (lm 1, 3), 'left'
test.deepEqual (li 1), xf (li 1), (lm 1, 3), 'left'
test.deepEqual (li 1), xf (li 2), (lm 1, 3), 'left'
test.deepEqual (li 2), xf (li 3), (lm 1, 3), 'left'
test.deepEqual (li 4), xf (li 4), (lm 1, 3), 'left'
test.deepEqual (lm 2, 4), xf (lm 1, 3), (li 0), 'right'
test.deepEqual (lm 2, 4), xf (lm 1, 3), (li 1), 'right'
test.deepEqual (lm 1, 4), xf (lm 1, 3), (li 2), 'right'
test.deepEqual (lm 1, 4), xf (lm 1, 3), (li 3), 'right'
test.deepEqual (lm 1, 3), xf (lm 1, 3), (li 4), 'right'
test.deepEqual (li 0), xf (li 0), (lm 1, 2), 'left'
test.deepEqual (li 1), xf (li 1), (lm 1, 2), 'left'
test.deepEqual (li 1), xf (li 2), (lm 1, 2), 'left'
test.deepEqual (li 3), xf (li 3), (lm 1, 2), 'left'
test.deepEqual (li 0), xf (li 0), (lm 3, 1), 'left'
test.deepEqual (li 1), xf (li 1), (lm 3, 1), 'left'
test.deepEqual (li 3), xf (li 2), (lm 3, 1), 'left'
test.deepEqual (li 4), xf (li 3), (lm 3, 1), 'left'
test.deepEqual (li 4), xf (li 4), (lm 3, 1), 'left'
test.deepEqual (lm 4, 2), xf (lm 3, 1), (li 0), 'right'
test.deepEqual (lm 4, 2), xf (lm 3, 1), (li 1), 'right'
test.deepEqual (lm 4, 1), xf (lm 3, 1), (li 2), 'right'
test.deepEqual (lm 4, 1), xf (lm 3, 1), (li 3), 'right'
test.deepEqual (lm 3, 1), xf (lm 3, 1), (li 4), 'right'
test.deepEqual (li 0), xf (li 0), (lm 2, 1), 'left'
test.deepEqual (li 1), xf (li 1), (lm 2, 1), 'left'
test.deepEqual (li 3), xf (li 2), (lm 2, 1), 'left'
test.deepEqual (li 3), xf (li 3), (lm 2, 1), 'left'
test.done()
object:
'Apply sanity checks': (test) ->
test.deepEqual {x:'a', y:'b'}, type.apply {x:'a'}, [{p:['y'], oi:'b'}]
test.deepEqual {}, type.apply {x:'a'}, [{p:['x'], od:'a'}]
test.deepEqual {x:'b'}, type.apply {x:'a'}, [{p:['x'], od:'a', oi:'b'}]
test.done()
'Ops on deleted elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x'}], 'left'
test.deepEqual [], type.transform [{p:[9],si:"bite "}], [{p:[],od:"agimble s",oi:null}], 'right'
test.done()
'Ops on replaced elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x', oi:'y'}], 'left'
test.done()
'Deleted data is changed to reflect edits': (test) ->
test.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1, 1], si:'bc'}], 'left'
test.deepEqual [{p:[],od:25,oi:[]}], type.transform [{p:[],od:22,oi:[]}], [{p:[],na:3}], 'left'
test.deepEqual [{p:[],od:{toves:""},oi:4}], type.transform [{p:[],od:{toves:0},oi:4}], [{p:["toves"],od:0,oi:""}], 'left'
test.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[7],sd:"d "}], 'left'
test.deepEqual [], type.transform([{p:["bird"],na:2}], [{p:[],od:{bird:38},oi:20}], 'right')
test.deepEqual [{p:[],od:{bird:40},oi:20}], type.transform([{p:[],od:{bird:38},oi:20}], [{p:["bird"],na:2}], 'left')
test.deepEqual [{p:['He'],od:[]}], type.transform [{p:["He"],od:[]}], [{p:["The"],na:-3}], 'right'
test.deepEqual [], type.transform [{p:["He"],oi:{}}], [{p:[],od:{},oi:"the"}], 'left'
test.done()
'If two inserts are simultaneous, the lefts insert will win': (test) ->
test.deepEqual [{p:[1], oi:'a', od:'b'}], type.transform [{p:[1], oi:'a'}], [{p:[1], oi:'b'}], 'left'
test.deepEqual [], type.transform [{p:[1], oi:'b'}], [{p:[1], oi:'a'}], 'right'
test.done()
'parallel ops on different keys miss each other': (test) ->
test.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], oi:'z'}], 'left'
test.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], od:'z'}], 'left'
test.deepEqual [{p:["in","he"],oi:{}}], type.transform [{p:["in","he"],oi:{}}], [{p:["and"],od:{}}], 'right'
test.deepEqual [{p:['x',0],si:"his "}], type.transform [{p:['x',0],si:"his "}], [{p:['y'],od:0,oi:1}], 'right'
test.done()
'replacement vs. deletion': (test) ->
test.deepEqual [{p:[],oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:['']}], 'right'
test.done()
'replacement vs. replacement': (test) ->
test.deepEqual [], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'right'
test.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'left'
test.deepEqual [], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'right'
test.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'left'
# test diamond property
rightOps = [ {"p":[],"od":null,"oi":{}} ]
leftOps = [ {"p":[],"od":null,"oi":""} ]
rightHas = type.apply(null, rightOps)
leftHas = type.apply(null, leftOps)
[left_, right_] = require('../helpers').transformX type, leftOps, rightOps
test.deepEqual leftHas, type.apply rightHas, left_
test.deepEqual leftHas, type.apply leftHas, right_
test.done()
'An attempt to re-delete a key becomes a no-op': (test) ->
test.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'left'
test.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'right'
test.done()
randomizer: (test) ->
require('../helpers').randomizerTest type, 1000
test.done()
exports.node = genTests nativetype
exports.webclient = genTests require('../helpers/webclient').types.json
| 220596 | # Tests for JSON OT type. (src/types/json.coffee)
#
# Spec: https://github.com/josephg/ShareJS/wiki/JSON-Operations
nativetype = require '../../src/types/json'
randomWord = require './randomWord'
util = require 'util'
p = util.debug
i = util.inspect
# This is an awful function to clone a document snapshot for use by the random
# op generator. .. Since we don't want to corrupt the original object with
# the changes the op generator will make.
clone = (o) -> JSON.parse(JSON.stringify(o))
{randomInt, randomReal} = require('../helpers')
randomKey = (obj) ->
if Array.isArray(obj)
if obj.length == 0
undefined
else
randomInt obj.length
else
count = 0
for key of obj
result = key if randomReal() < 1/++count
result
# Generate a random new key for a value in obj.
# obj must be an Object.
randomNewKey = (obj) ->
# There's no do-while loop in coffeescript.
key = randomWord()
key = randomWord() while obj[key] != undefined
key
# Generate a random object
randomThing = ->
switch randomInt 6
when 0 then null
when 1 then ''
when 2 then randomWord()
when 3
obj = {}
obj[randomNewKey(obj)] = randomThing() for [1..randomInt(5)]
obj
when 4 then (randomThing() for [1..randomInt(5)])
when 5 then randomInt(50)
# Pick a random path to something in the object.
randomPath = (data) ->
path = []
while randomReal() > 0.85 and typeof data == 'object'
key = randomKey data
break unless key?
path.push key
data = data[key]
path
genTests = (type) ->
type.generateRandomOp = (data) ->
pct = 0.95
container = data: clone(data)
op = while randomReal() < pct
pct *= 0.6
# Pick a random object in the document operate on.
path = randomPath(container['data'])
# parent = the container for the operand. parent[key] contains the operand.
parent = container
key = '<KEY>'
for p in path
parent = parent[key]
key = p
operand = parent[key]
if randomReal() < 0.4 and parent != container and Array.isArray(parent)
# List move
newIndex = randomInt parent.length
# Remove the element from its current position in the list
parent.splice key, 1
# Insert it in the new position.
parent.splice newIndex, 0, operand
{p:path, lm:newIndex}
else if randomReal() < 0.3 or operand == null
# Replace
newValue = randomThing()
parent[key] = newValue
if Array.isArray(parent)
{p:path, ld:operand, li:clone(newValue)}
else
{p:path, od:operand, oi:clone(newValue)}
else if typeof operand == 'string'
# String. This code is adapted from the text op generator.
if randomReal() > 0.5 or operand.length == 0
# Insert
pos = randomInt(operand.length + 1)
str = randomWord() + ' '
path.push pos
parent[key] = operand[...pos] + str + operand[pos..]
{p:path, si:str}
else
# Delete
pos = randomInt(operand.length)
length = Math.min(randomInt(4), operand.length - pos)
str = operand[pos...(pos + length)]
path.push pos
parent[key] = operand[...pos] + operand[pos + length..]
{p:path, sd:str}
else if typeof operand == 'number'
# Number
inc = randomInt(10) - 3
parent[key] += inc
{p:path, na:inc}
else if Array.isArray(operand)
# Array. Replace is covered above, so we'll just randomly insert or delete.
# This code looks remarkably similar to string insert, above.
if randomReal() > 0.5 or operand.length == 0
# Insert
pos = randomInt(operand.length + 1)
obj = randomThing()
path.push pos
operand.splice pos, 0, obj
{p:path, li:clone(obj)}
else
# Delete
pos = randomInt operand.length
obj = operand[pos]
path.push pos
operand.splice pos, 1
{p:path, ld:clone(obj)}
else
# Object
k = randomKey(operand)
if randomReal() > 0.5 or not k?
# Insert
k = randomNewKey(operand)
obj = randomThing()
path.push k
operand[k] = obj
{p:path, oi:clone(obj)}
else
obj = operand[k]
path.push k
delete operand[k]
{p:path, od:clone(obj)}
[op, container.data]
# The random op tester above will test that the OT functions are admissable, but
# debugging problems it detects is a pain.
#
# These tests should pick up *most* problems with a normal JSON OT implementation.
sanity:
'name is json': (test) ->
test.strictEqual type.name, 'json'
test.done()
'create() returns null': (test) ->
test.deepEqual type.create(), null
test.done()
'compose od,oi --> od+oi': (test) ->
test.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1}],[{p:['foo'],oi:2}]
test.deepEqual [{p:['foo'], od:1},{p:['bar'], oi:2}], type.compose [{p:['foo'],od:1}],[{p:['bar'],oi:2}]
test.done()
'transform returns sane values': (test) ->
t = (op1, op2) ->
test.deepEqual op1, type.transform op1, op2, 'left'
test.deepEqual op1, type.transform op1, op2, 'right'
t [], []
t [{p:['foo'], oi:1}], []
t [{p:['foo'], oi:1}], [{p:['bar'], oi:2}]
test.done()
number:
'Add a number': (test) ->
test.deepEqual 3, type.apply 1, [{p:[], na:2}]
test.deepEqual [3], type.apply [1], [{p:[0], na:2}]
test.done()
'Compose two adds together with the same path compresses them': (test) ->
test.deepEqual [{p:['a', 'b'], na:3}], type.compose [{p:['a', 'b'], na:1}], [{p:['a', 'b'], na:2}]
test.deepEqual [{p:['a'], na:1}, {p:['b'], na:2}], type.compose [{p:['a'], na:1}], [{p:['b'], na:2}]
test.done()
'make sure append doesn\'t overwrite values when it merges na': (test) ->
rightHas = 21
leftHas = 3
rightOp = [{"p":[],"od":0,"oi":15},{"p":[],"na":4},{"p":[],"na":1},{"p":[],"na":1}]
leftOp = [{"p":[],"na":4},{"p":[],"na":-1}]
[right_, left_] = require('../helpers').transformX type, rightOp, leftOp
s_c = type.apply rightHas, left_
c_s = type.apply leftHas, right_
test.deepEqual s_c, c_s
test.done()
# Strings should be handled internally by the text type. We'll just do some basic sanity checks here.
string:
'Apply works': (test) ->
test.deepEqual 'abc', type.apply 'a', [{p:[1], si:'bc'}]
test.deepEqual 'bc', type.apply 'abc', [{p:[0], sd:'a'}]
test.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x', 1], si:'bc'}]
test.done()
'transform splits deletes': (test) ->
test.deepEqual type.transform([{p:[0], sd:'ab'}], [{p:[1], si:'x'}], 'left'), [{p:[0], sd:'a'}, {p:[1], sd:'b'}]
test.done()
'deletes cancel each other out': (test) ->
test.deepEqual type.transform([{p:['k', 5], sd:'a'}], [{p:['k', 5], sd:'a'}], 'left'), []
test.done()
'blank inserts do not throw error': (test) ->
test.deepEqual type.transform([{p: ['k', 5], si:''}], [{p: ['k', 3], si: 'a'}], 'left'), []
test.done()
list:
'Apply inserts': (test) ->
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'c'], [{p:[0], li:'a'}]
test.deepEqual ['a', 'b', 'c'], type.apply ['a', 'c'], [{p:[1], li:'b'}]
test.deepEqual ['a', 'b', 'c'], type.apply ['a', 'b'], [{p:[2], li:'c'}]
test.done()
'Apply deletes': (test) ->
test.deepEqual ['b', 'c'], type.apply ['a', 'b', 'c'], [{p:[0], ld:'a'}]
test.deepEqual ['a', 'c'], type.apply ['a', 'b', 'c'], [{p:[1], ld:'b'}]
test.deepEqual ['a', 'b'], type.apply ['a', 'b', 'c'], [{p:[2], ld:'c'}]
test.done()
'apply replace': (test) ->
test.deepEqual ['a', 'y', 'b'], type.apply ['a', 'x', 'b'], [{p:[1], ld:'x', li:'y'}]
test.done()
'apply move': (test) ->
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[1], lm:0}]
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[0], lm:1}]
test.done()
###
'null moves compose to nops': (test) ->
test.deepEqual [], type.compose [], [{p:[3],lm:3}]
test.deepEqual [], type.compose [], [{p:[0,3],lm:3}]
test.deepEqual [], type.compose [], [{p:['x','y',0],lm:0}]
test.done()
###
'Paths are bumped when list elements are inserted or removed': (test) ->
test.deepEqual [{p:[2, 200], si:'hi'}], type.transform [{p:[1, 200], si:'hi'}], [{p:[0], li:'x'}], 'left'
test.deepEqual [{p:[1, 201], si:'hi'}], type.transform [{p:[0, 201], si:'hi'}], [{p:[0], li:'x'}], 'right'
test.deepEqual [{p:[0, 202], si:'hi'}], type.transform [{p:[0, 202], si:'hi'}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[0, 203], si:'hi'}], type.transform [{p:[1, 203], si:'hi'}], [{p:[0], ld:'x'}], 'left'
test.deepEqual [{p:[0, 204], si:'hi'}], type.transform [{p:[0, 204], si:'hi'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:['x',3], si: 'hi'}], type.transform [{p:['x',3], si:'hi'}], [{p:['x',0,'x'], li:0}], 'left'
test.deepEqual [{p:['x',3,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',5], li:0}], 'left'
test.deepEqual [{p:['x',4,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',0], li:0}], 'left'
test.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'left'
test.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'right'
test.done()
'Ops on deleted elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[0],li:'x'}], type.transform [{p:[0],li:'x'}], [{p:[0],ld:'y'}], 'left'
test.deepEqual [], type.transform [{p:[0],na:-3}], [{p:[0],ld:48}], 'left'
test.done()
'Ops on replaced elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x', li:'y'}], 'left'
test.deepEqual [{p:[0], li:'hi'}], type.transform [{p:[0], li:'hi'}], [{p:[0], ld:'x', li:'y'}], 'left'
test.done()
'Deleted data is changed to reflect edits': (test) ->
test.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1, 1], si:'bc'}], 'left'
test.done()
'Inserting then deleting an element composes into a no-op': (test) ->
test.deepEqual [], type.compose [{p:[1], li:'abc'}], [{p:[1], ld:'abc'}]
test.deepEqual [{p:[1],ld:null,li:'x'}], type.transform [{p:[0],ld:null,li:"x"}], [{p:[0],li:"The"}], 'right'
test.done()
'Composing doesn\'t change the original object': (test) ->
a = [{p:[0],ld:'abc',li:null}]
test.deepEqual [{p:[0],ld:'abc'}], type.compose a, [{p:[0],ld:null}]
test.deepEqual [{p:[0],ld:'abc',li:null}], a
test.done()
'If two inserts are simultaneous, the left op will end up first': (test) ->
test.deepEqual [{p:[1], li:'a'}], type.transform [{p:[1], li:'a'}], [{p:[1], li:'b'}], 'left'
test.deepEqual [{p:[2], li:'b'}], type.transform [{p:[1], li:'b'}], [{p:[1], li:'a'}], 'right'
test.done()
'An attempt to re-delete a list element becomes a no-op': (test) ->
test.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'right'
test.done()
'Ops on a moved element move with the element': (test) ->
test.deepEqual [{p:[10], ld:'x'}], type.transform [{p:[4], ld:'x'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], si:'a'}], type.transform [{p:[4, 1], si:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], li:'a'}], type.transform [{p:[4, 1], li:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], ld:'b', li:'a'}], type.transform [{p:[4, 1], ld:'b', li:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[0],li:null}], type.transform [{p:[0],li:null}], [{p:[0],lm:1}], 'left'
# [_,_,_,_,5,6,7,_]
# c: [_,_,_,_,5,'x',6,7,_] p:5 li:'x'
# s: [_,6,_,_,_,5,7,_] p:5 lm:1
# correct: [_,6,_,_,_,5,'x',7,_]
test.deepEqual [{p:[6],li:'x'}], type.transform [{p:[5],li:'x'}], [{p:[5],lm:1}], 'left'
# [_,_,_,_,5,6,7,_]
# c: [_,_,_,_,5,6,7,_] p:5 ld:6
# s: [_,6,_,_,_,5,7,_] p:5 lm:1
# correct: [_,_,_,_,5,7,_]
test.deepEqual [{p:[1],ld:6}], type.transform [{p:[5],ld:6}], [{p:[5],lm:1}], 'left'
#test.deepEqual [{p:[0],li:{}}], type.transform [{p:[0],li:{}}], [{p:[0],lm:0}], 'right'
test.deepEqual [{p:[0],li:[]}], type.transform [{p:[0],li:[]}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],li:'x'}], type.transform [{p:[2],li:'x'}], [{p:[0],lm:1}], 'left'
test.done()
'Target index of a moved element is changed by ld/li': (test) ->
test.deepEqual [{p:[0],lm:1}], type.transform [{p:[0], lm: 2}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[1],lm:3}], type.transform [{p:[2], lm: 4}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[0],lm:3}], type.transform [{p:[0], lm: 2}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[3],lm:5}], type.transform [{p:[2], lm: 4}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0], lm: 0}], [{p:[0], li:28}], 'left'
test.done()
'Tiebreak lm vs. ld/li': (test) ->
test.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'left'
test.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'right'
test.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'left'
test.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'right'
test.done()
'replacement vs. deletion': (test) ->
test.deepEqual [{p:[0],li:'y'}], type.transform [{p:[0],ld:'x',li:'y'}], [{p:[0],ld:'x'}], 'right'
test.done()
'replacement vs. insertion': (test) ->
test.deepEqual [{p:[1],ld:{},li:"brillig"}], type.transform [{p:[0],ld:{},li:"brillig"}], [{p:[0],li:36}], 'left'
test.done()
'replacement vs. replacement': (test) ->
test.deepEqual [], type.transform [{p:[0],ld:null,li:[]}], [{p:[0],ld:null,li:0}], 'right'
test.deepEqual [{p:[0],ld:[],li:0}], type.transform [{p:[0],ld:null,li:0}], [{p:[0],ld:null,li:[]}], 'left'
test.done()
'composing replace with delete of replaced element results in insert': (test) ->
test.deepEqual [{p:[2],ld:[]}], type.compose [{p:[2],ld:[],li:null}], [{p:[2],ld:null}]
test.done()
'lm vs lm': (test) ->
test.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:2}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[4],lm:4}], type.transform [{p:[3],lm:3}], [{p:[5],lm:0}], 'left'
test.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],lm:1}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'right'
test.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[3],lm:0}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'left'
test.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left'
test.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:5}], 'right'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:1}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[1],lm:2}], type.transform [{p:[0],lm:1}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[3],lm:2}], type.transform [{p:[2],lm:1}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[2],lm:1}], type.transform [{p:[3],lm:1}], [{p:[1],lm:3}], 'left'
test.deepEqual [{p:[2],lm:3}], type.transform [{p:[1],lm:3}], [{p:[3],lm:1}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'right'
test.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:1}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:1}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:0}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],lm:3}], 'left'
test.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:1}], [{p:[3],lm:2}], 'left'
test.deepEqual [{p:[3],lm:3}], type.transform [{p:[3],lm:2}], [{p:[2],lm:1}], 'left'
test.done()
'indices change correctly around a move': (test) ->
test.deepEqual [{p:[1,0],li:{}}], type.transform [{p:[0,0],li:{}}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],ld:{}}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],ld:{}}], 'left'
test.deepEqual [{p:[5],lm:0}], type.transform [{p:[6],lm:0}], [{p:[2],ld:{}}], 'left'
test.deepEqual [{p:[1],lm:0}], type.transform [{p:[1],lm:0}], [{p:[2],ld:{}}], 'left'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[2],lm:1}], [{p:[1],ld:3}], 'right'
test.deepEqual [{p:[1],ld:{}}], type.transform [{p:[2],ld:{}}], [{p:[1],lm:2}], 'right'
test.deepEqual [{p:[2],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[0],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[0],ld:1,li:2}], type.transform [{p:[1],ld:1,li:2}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],ld:2,li:3}], type.transform [{p:[1],ld:2,li:3}], [{p:[0],lm:1}], 'left'
test.deepEqual [{p:[1],ld:3,li:4}], type.transform [{p:[0],ld:3,li:4}], [{p:[1],lm:0}], 'left'
test.done()
'li vs lm': (test) ->
li = (p) -> [{p:[p],li:[]}]
lm = (f,t) -> [{p:[f],lm:t}]
xf = type.transform
test.deepEqual (li 0), xf (li 0), (lm 1, 3), 'left'
test.deepEqual (li 1), xf (li 1), (lm 1, 3), 'left'
test.deepEqual (li 1), xf (li 2), (lm 1, 3), 'left'
test.deepEqual (li 2), xf (li 3), (lm 1, 3), 'left'
test.deepEqual (li 4), xf (li 4), (lm 1, 3), 'left'
test.deepEqual (lm 2, 4), xf (lm 1, 3), (li 0), 'right'
test.deepEqual (lm 2, 4), xf (lm 1, 3), (li 1), 'right'
test.deepEqual (lm 1, 4), xf (lm 1, 3), (li 2), 'right'
test.deepEqual (lm 1, 4), xf (lm 1, 3), (li 3), 'right'
test.deepEqual (lm 1, 3), xf (lm 1, 3), (li 4), 'right'
test.deepEqual (li 0), xf (li 0), (lm 1, 2), 'left'
test.deepEqual (li 1), xf (li 1), (lm 1, 2), 'left'
test.deepEqual (li 1), xf (li 2), (lm 1, 2), 'left'
test.deepEqual (li 3), xf (li 3), (lm 1, 2), 'left'
test.deepEqual (li 0), xf (li 0), (lm 3, 1), 'left'
test.deepEqual (li 1), xf (li 1), (lm 3, 1), 'left'
test.deepEqual (li 3), xf (li 2), (lm 3, 1), 'left'
test.deepEqual (li 4), xf (li 3), (lm 3, 1), 'left'
test.deepEqual (li 4), xf (li 4), (lm 3, 1), 'left'
test.deepEqual (lm 4, 2), xf (lm 3, 1), (li 0), 'right'
test.deepEqual (lm 4, 2), xf (lm 3, 1), (li 1), 'right'
test.deepEqual (lm 4, 1), xf (lm 3, 1), (li 2), 'right'
test.deepEqual (lm 4, 1), xf (lm 3, 1), (li 3), 'right'
test.deepEqual (lm 3, 1), xf (lm 3, 1), (li 4), 'right'
test.deepEqual (li 0), xf (li 0), (lm 2, 1), 'left'
test.deepEqual (li 1), xf (li 1), (lm 2, 1), 'left'
test.deepEqual (li 3), xf (li 2), (lm 2, 1), 'left'
test.deepEqual (li 3), xf (li 3), (lm 2, 1), 'left'
test.done()
object:
'Apply sanity checks': (test) ->
test.deepEqual {x:'a', y:'b'}, type.apply {x:'a'}, [{p:['y'], oi:'b'}]
test.deepEqual {}, type.apply {x:'a'}, [{p:['x'], od:'a'}]
test.deepEqual {x:'b'}, type.apply {x:'a'}, [{p:['x'], od:'a', oi:'b'}]
test.done()
'Ops on deleted elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x'}], 'left'
test.deepEqual [], type.transform [{p:[9],si:"bite "}], [{p:[],od:"agimble s",oi:null}], 'right'
test.done()
'Ops on replaced elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x', oi:'y'}], 'left'
test.done()
'Deleted data is changed to reflect edits': (test) ->
test.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1, 1], si:'bc'}], 'left'
test.deepEqual [{p:[],od:25,oi:[]}], type.transform [{p:[],od:22,oi:[]}], [{p:[],na:3}], 'left'
test.deepEqual [{p:[],od:{toves:""},oi:4}], type.transform [{p:[],od:{toves:0},oi:4}], [{p:["toves"],od:0,oi:""}], 'left'
test.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[7],sd:"d "}], 'left'
test.deepEqual [], type.transform([{p:["bird"],na:2}], [{p:[],od:{bird:38},oi:20}], 'right')
test.deepEqual [{p:[],od:{bird:40},oi:20}], type.transform([{p:[],od:{bird:38},oi:20}], [{p:["bird"],na:2}], 'left')
test.deepEqual [{p:['He'],od:[]}], type.transform [{p:["He"],od:[]}], [{p:["The"],na:-3}], 'right'
test.deepEqual [], type.transform [{p:["He"],oi:{}}], [{p:[],od:{},oi:"the"}], 'left'
test.done()
'If two inserts are simultaneous, the lefts insert will win': (test) ->
test.deepEqual [{p:[1], oi:'a', od:'b'}], type.transform [{p:[1], oi:'a'}], [{p:[1], oi:'b'}], 'left'
test.deepEqual [], type.transform [{p:[1], oi:'b'}], [{p:[1], oi:'a'}], 'right'
test.done()
'parallel ops on different keys miss each other': (test) ->
test.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], oi:'z'}], 'left'
test.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], od:'z'}], 'left'
test.deepEqual [{p:["in","he"],oi:{}}], type.transform [{p:["in","he"],oi:{}}], [{p:["and"],od:{}}], 'right'
test.deepEqual [{p:['x',0],si:"his "}], type.transform [{p:['x',0],si:"his "}], [{p:['y'],od:0,oi:1}], 'right'
test.done()
'replacement vs. deletion': (test) ->
test.deepEqual [{p:[],oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:['']}], 'right'
test.done()
'replacement vs. replacement': (test) ->
test.deepEqual [], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'right'
test.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'left'
test.deepEqual [], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'right'
test.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'left'
# test diamond property
rightOps = [ {"p":[],"od":null,"oi":{}} ]
leftOps = [ {"p":[],"od":null,"oi":""} ]
rightHas = type.apply(null, rightOps)
leftHas = type.apply(null, leftOps)
[left_, right_] = require('../helpers').transformX type, leftOps, rightOps
test.deepEqual leftHas, type.apply rightHas, left_
test.deepEqual leftHas, type.apply leftHas, right_
test.done()
'An attempt to re-delete a key becomes a no-op': (test) ->
test.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'left'
test.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'right'
test.done()
randomizer: (test) ->
require('../helpers').randomizerTest type, 1000
test.done()
exports.node = genTests nativetype
exports.webclient = genTests require('../helpers/webclient').types.json
| true | # Tests for JSON OT type. (src/types/json.coffee)
#
# Spec: https://github.com/josephg/ShareJS/wiki/JSON-Operations
nativetype = require '../../src/types/json'
randomWord = require './randomWord'
util = require 'util'
p = util.debug
i = util.inspect
# This is an awful function to clone a document snapshot for use by the random
# op generator. .. Since we don't want to corrupt the original object with
# the changes the op generator will make.
clone = (o) -> JSON.parse(JSON.stringify(o))
{randomInt, randomReal} = require('../helpers')
randomKey = (obj) ->
if Array.isArray(obj)
if obj.length == 0
undefined
else
randomInt obj.length
else
count = 0
for key of obj
result = key if randomReal() < 1/++count
result
# Generate a random new key for a value in obj.
# obj must be an Object.
randomNewKey = (obj) ->
# There's no do-while loop in coffeescript.
key = randomWord()
key = randomWord() while obj[key] != undefined
key
# Generate a random object
randomThing = ->
switch randomInt 6
when 0 then null
when 1 then ''
when 2 then randomWord()
when 3
obj = {}
obj[randomNewKey(obj)] = randomThing() for [1..randomInt(5)]
obj
when 4 then (randomThing() for [1..randomInt(5)])
when 5 then randomInt(50)
# Pick a random path to something in the object.
randomPath = (data) ->
path = []
while randomReal() > 0.85 and typeof data == 'object'
key = randomKey data
break unless key?
path.push key
data = data[key]
path
genTests = (type) ->
type.generateRandomOp = (data) ->
pct = 0.95
container = data: clone(data)
op = while randomReal() < pct
pct *= 0.6
# Pick a random object in the document operate on.
path = randomPath(container['data'])
# parent = the container for the operand. parent[key] contains the operand.
parent = container
key = 'PI:KEY:<KEY>END_PI'
for p in path
parent = parent[key]
key = p
operand = parent[key]
if randomReal() < 0.4 and parent != container and Array.isArray(parent)
# List move
newIndex = randomInt parent.length
# Remove the element from its current position in the list
parent.splice key, 1
# Insert it in the new position.
parent.splice newIndex, 0, operand
{p:path, lm:newIndex}
else if randomReal() < 0.3 or operand == null
# Replace
newValue = randomThing()
parent[key] = newValue
if Array.isArray(parent)
{p:path, ld:operand, li:clone(newValue)}
else
{p:path, od:operand, oi:clone(newValue)}
else if typeof operand == 'string'
# String. This code is adapted from the text op generator.
if randomReal() > 0.5 or operand.length == 0
# Insert
pos = randomInt(operand.length + 1)
str = randomWord() + ' '
path.push pos
parent[key] = operand[...pos] + str + operand[pos..]
{p:path, si:str}
else
# Delete
pos = randomInt(operand.length)
length = Math.min(randomInt(4), operand.length - pos)
str = operand[pos...(pos + length)]
path.push pos
parent[key] = operand[...pos] + operand[pos + length..]
{p:path, sd:str}
else if typeof operand == 'number'
# Number
inc = randomInt(10) - 3
parent[key] += inc
{p:path, na:inc}
else if Array.isArray(operand)
# Array. Replace is covered above, so we'll just randomly insert or delete.
# This code looks remarkably similar to string insert, above.
if randomReal() > 0.5 or operand.length == 0
# Insert
pos = randomInt(operand.length + 1)
obj = randomThing()
path.push pos
operand.splice pos, 0, obj
{p:path, li:clone(obj)}
else
# Delete
pos = randomInt operand.length
obj = operand[pos]
path.push pos
operand.splice pos, 1
{p:path, ld:clone(obj)}
else
# Object
k = randomKey(operand)
if randomReal() > 0.5 or not k?
# Insert
k = randomNewKey(operand)
obj = randomThing()
path.push k
operand[k] = obj
{p:path, oi:clone(obj)}
else
obj = operand[k]
path.push k
delete operand[k]
{p:path, od:clone(obj)}
[op, container.data]
# The random op tester above will test that the OT functions are admissable, but
# debugging problems it detects is a pain.
#
# These tests should pick up *most* problems with a normal JSON OT implementation.
sanity:
'name is json': (test) ->
test.strictEqual type.name, 'json'
test.done()
'create() returns null': (test) ->
test.deepEqual type.create(), null
test.done()
'compose od,oi --> od+oi': (test) ->
test.deepEqual [{p:['foo'], od:1, oi:2}], type.compose [{p:['foo'],od:1}],[{p:['foo'],oi:2}]
test.deepEqual [{p:['foo'], od:1},{p:['bar'], oi:2}], type.compose [{p:['foo'],od:1}],[{p:['bar'],oi:2}]
test.done()
'transform returns sane values': (test) ->
t = (op1, op2) ->
test.deepEqual op1, type.transform op1, op2, 'left'
test.deepEqual op1, type.transform op1, op2, 'right'
t [], []
t [{p:['foo'], oi:1}], []
t [{p:['foo'], oi:1}], [{p:['bar'], oi:2}]
test.done()
number:
'Add a number': (test) ->
test.deepEqual 3, type.apply 1, [{p:[], na:2}]
test.deepEqual [3], type.apply [1], [{p:[0], na:2}]
test.done()
'Compose two adds together with the same path compresses them': (test) ->
test.deepEqual [{p:['a', 'b'], na:3}], type.compose [{p:['a', 'b'], na:1}], [{p:['a', 'b'], na:2}]
test.deepEqual [{p:['a'], na:1}, {p:['b'], na:2}], type.compose [{p:['a'], na:1}], [{p:['b'], na:2}]
test.done()
'make sure append doesn\'t overwrite values when it merges na': (test) ->
rightHas = 21
leftHas = 3
rightOp = [{"p":[],"od":0,"oi":15},{"p":[],"na":4},{"p":[],"na":1},{"p":[],"na":1}]
leftOp = [{"p":[],"na":4},{"p":[],"na":-1}]
[right_, left_] = require('../helpers').transformX type, rightOp, leftOp
s_c = type.apply rightHas, left_
c_s = type.apply leftHas, right_
test.deepEqual s_c, c_s
test.done()
# Strings should be handled internally by the text type. We'll just do some basic sanity checks here.
string:
'Apply works': (test) ->
test.deepEqual 'abc', type.apply 'a', [{p:[1], si:'bc'}]
test.deepEqual 'bc', type.apply 'abc', [{p:[0], sd:'a'}]
test.deepEqual {x:'abc'}, type.apply {x:'a'}, [{p:['x', 1], si:'bc'}]
test.done()
'transform splits deletes': (test) ->
test.deepEqual type.transform([{p:[0], sd:'ab'}], [{p:[1], si:'x'}], 'left'), [{p:[0], sd:'a'}, {p:[1], sd:'b'}]
test.done()
'deletes cancel each other out': (test) ->
test.deepEqual type.transform([{p:['k', 5], sd:'a'}], [{p:['k', 5], sd:'a'}], 'left'), []
test.done()
'blank inserts do not throw error': (test) ->
test.deepEqual type.transform([{p: ['k', 5], si:''}], [{p: ['k', 3], si: 'a'}], 'left'), []
test.done()
list:
'Apply inserts': (test) ->
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'c'], [{p:[0], li:'a'}]
test.deepEqual ['a', 'b', 'c'], type.apply ['a', 'c'], [{p:[1], li:'b'}]
test.deepEqual ['a', 'b', 'c'], type.apply ['a', 'b'], [{p:[2], li:'c'}]
test.done()
'Apply deletes': (test) ->
test.deepEqual ['b', 'c'], type.apply ['a', 'b', 'c'], [{p:[0], ld:'a'}]
test.deepEqual ['a', 'c'], type.apply ['a', 'b', 'c'], [{p:[1], ld:'b'}]
test.deepEqual ['a', 'b'], type.apply ['a', 'b', 'c'], [{p:[2], ld:'c'}]
test.done()
'apply replace': (test) ->
test.deepEqual ['a', 'y', 'b'], type.apply ['a', 'x', 'b'], [{p:[1], ld:'x', li:'y'}]
test.done()
'apply move': (test) ->
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[1], lm:0}]
test.deepEqual ['a', 'b', 'c'], type.apply ['b', 'a', 'c'], [{p:[0], lm:1}]
test.done()
###
'null moves compose to nops': (test) ->
test.deepEqual [], type.compose [], [{p:[3],lm:3}]
test.deepEqual [], type.compose [], [{p:[0,3],lm:3}]
test.deepEqual [], type.compose [], [{p:['x','y',0],lm:0}]
test.done()
###
'Paths are bumped when list elements are inserted or removed': (test) ->
test.deepEqual [{p:[2, 200], si:'hi'}], type.transform [{p:[1, 200], si:'hi'}], [{p:[0], li:'x'}], 'left'
test.deepEqual [{p:[1, 201], si:'hi'}], type.transform [{p:[0, 201], si:'hi'}], [{p:[0], li:'x'}], 'right'
test.deepEqual [{p:[0, 202], si:'hi'}], type.transform [{p:[0, 202], si:'hi'}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[0, 203], si:'hi'}], type.transform [{p:[1, 203], si:'hi'}], [{p:[0], ld:'x'}], 'left'
test.deepEqual [{p:[0, 204], si:'hi'}], type.transform [{p:[0, 204], si:'hi'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:['x',3], si: 'hi'}], type.transform [{p:['x',3], si:'hi'}], [{p:['x',0,'x'], li:0}], 'left'
test.deepEqual [{p:['x',3,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',5], li:0}], 'left'
test.deepEqual [{p:['x',4,'x'], si: 'hi'}], type.transform [{p:['x',3,'x'], si:'hi'}], [{p:['x',0], li:0}], 'left'
test.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'left'
test.deepEqual [{p:[1],ld:2}], type.transform [{p:[0],ld:2}], [{p:[0],li:1}], 'right'
test.done()
'Ops on deleted elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[0],li:'x'}], type.transform [{p:[0],li:'x'}], [{p:[0],ld:'y'}], 'left'
test.deepEqual [], type.transform [{p:[0],na:-3}], [{p:[0],ld:48}], 'left'
test.done()
'Ops on replaced elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], ld:'x', li:'y'}], 'left'
test.deepEqual [{p:[0], li:'hi'}], type.transform [{p:[0], li:'hi'}], [{p:[0], ld:'x', li:'y'}], 'left'
test.done()
'Deleted data is changed to reflect edits': (test) ->
test.deepEqual [{p:[1], ld:'abc'}], type.transform [{p:[1], ld:'a'}], [{p:[1, 1], si:'bc'}], 'left'
test.done()
'Inserting then deleting an element composes into a no-op': (test) ->
test.deepEqual [], type.compose [{p:[1], li:'abc'}], [{p:[1], ld:'abc'}]
test.deepEqual [{p:[1],ld:null,li:'x'}], type.transform [{p:[0],ld:null,li:"x"}], [{p:[0],li:"The"}], 'right'
test.done()
'Composing doesn\'t change the original object': (test) ->
a = [{p:[0],ld:'abc',li:null}]
test.deepEqual [{p:[0],ld:'abc'}], type.compose a, [{p:[0],ld:null}]
test.deepEqual [{p:[0],ld:'abc',li:null}], a
test.done()
'If two inserts are simultaneous, the left op will end up first': (test) ->
test.deepEqual [{p:[1], li:'a'}], type.transform [{p:[1], li:'a'}], [{p:[1], li:'b'}], 'left'
test.deepEqual [{p:[2], li:'b'}], type.transform [{p:[1], li:'b'}], [{p:[1], li:'a'}], 'right'
test.done()
'An attempt to re-delete a list element becomes a no-op': (test) ->
test.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [], type.transform [{p:[1], ld:'x'}], [{p:[1], ld:'x'}], 'right'
test.done()
'Ops on a moved element move with the element': (test) ->
test.deepEqual [{p:[10], ld:'x'}], type.transform [{p:[4], ld:'x'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], si:'a'}], type.transform [{p:[4, 1], si:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], li:'a'}], type.transform [{p:[4, 1], li:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[10, 1], ld:'b', li:'a'}], type.transform [{p:[4, 1], ld:'b', li:'a'}], [{p:[4], lm:10}], 'left'
test.deepEqual [{p:[0],li:null}], type.transform [{p:[0],li:null}], [{p:[0],lm:1}], 'left'
# [_,_,_,_,5,6,7,_]
# c: [_,_,_,_,5,'x',6,7,_] p:5 li:'x'
# s: [_,6,_,_,_,5,7,_] p:5 lm:1
# correct: [_,6,_,_,_,5,'x',7,_]
test.deepEqual [{p:[6],li:'x'}], type.transform [{p:[5],li:'x'}], [{p:[5],lm:1}], 'left'
# [_,_,_,_,5,6,7,_]
# c: [_,_,_,_,5,6,7,_] p:5 ld:6
# s: [_,6,_,_,_,5,7,_] p:5 lm:1
# correct: [_,_,_,_,5,7,_]
test.deepEqual [{p:[1],ld:6}], type.transform [{p:[5],ld:6}], [{p:[5],lm:1}], 'left'
#test.deepEqual [{p:[0],li:{}}], type.transform [{p:[0],li:{}}], [{p:[0],lm:0}], 'right'
test.deepEqual [{p:[0],li:[]}], type.transform [{p:[0],li:[]}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],li:'x'}], type.transform [{p:[2],li:'x'}], [{p:[0],lm:1}], 'left'
test.done()
'Target index of a moved element is changed by ld/li': (test) ->
test.deepEqual [{p:[0],lm:1}], type.transform [{p:[0], lm: 2}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[1],lm:3}], type.transform [{p:[2], lm: 4}], [{p:[1], ld:'x'}], 'left'
test.deepEqual [{p:[0],lm:3}], type.transform [{p:[0], lm: 2}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[3],lm:5}], type.transform [{p:[2], lm: 4}], [{p:[1], li:'x'}], 'left'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0], lm: 0}], [{p:[0], li:28}], 'left'
test.done()
'Tiebreak lm vs. ld/li': (test) ->
test.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'left'
test.deepEqual [], type.transform [{p:[0], lm: 2}], [{p:[0], ld:'x'}], 'right'
test.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'left'
test.deepEqual [{p:[1], lm:3}], type.transform [{p:[0], lm: 2}], [{p:[0], li:'x'}], 'right'
test.done()
'replacement vs. deletion': (test) ->
test.deepEqual [{p:[0],li:'y'}], type.transform [{p:[0],ld:'x',li:'y'}], [{p:[0],ld:'x'}], 'right'
test.done()
'replacement vs. insertion': (test) ->
test.deepEqual [{p:[1],ld:{},li:"brillig"}], type.transform [{p:[0],ld:{},li:"brillig"}], [{p:[0],li:36}], 'left'
test.done()
'replacement vs. replacement': (test) ->
test.deepEqual [], type.transform [{p:[0],ld:null,li:[]}], [{p:[0],ld:null,li:0}], 'right'
test.deepEqual [{p:[0],ld:[],li:0}], type.transform [{p:[0],ld:null,li:0}], [{p:[0],ld:null,li:[]}], 'left'
test.done()
'composing replace with delete of replaced element results in insert': (test) ->
test.deepEqual [{p:[2],ld:[]}], type.compose [{p:[2],ld:[],li:null}], [{p:[2],ld:null}]
test.done()
'lm vs lm': (test) ->
test.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:2}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[4],lm:4}], type.transform [{p:[3],lm:3}], [{p:[5],lm:0}], 'left'
test.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],lm:1}], type.transform [{p:[2],lm:0}], [{p:[1],lm:0}], 'right'
test.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[3],lm:0}], type.transform [{p:[2],lm:0}], [{p:[5],lm:0}], 'left'
test.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left'
test.deepEqual [{p:[0],lm:5}], type.transform [{p:[2],lm:5}], [{p:[2],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:5}], 'right'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:1}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[1],lm:2}], type.transform [{p:[0],lm:1}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[3],lm:2}], type.transform [{p:[2],lm:1}], [{p:[5],lm:0}], 'right'
test.deepEqual [{p:[2],lm:1}], type.transform [{p:[3],lm:1}], [{p:[1],lm:3}], 'left'
test.deepEqual [{p:[2],lm:3}], type.transform [{p:[1],lm:3}], [{p:[3],lm:1}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[2],lm:6}], type.transform [{p:[2],lm:6}], [{p:[1],lm:0}], 'right'
test.deepEqual [{p:[0],lm:2}], type.transform [{p:[0],lm:1}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[2],lm:0}], type.transform [{p:[2],lm:1}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[0],lm:0}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],lm:3}], 'left'
test.deepEqual [{p:[3],lm:1}], type.transform [{p:[2],lm:1}], [{p:[3],lm:2}], 'left'
test.deepEqual [{p:[3],lm:3}], type.transform [{p:[3],lm:2}], [{p:[2],lm:1}], 'left'
test.done()
'indices change correctly around a move': (test) ->
test.deepEqual [{p:[1,0],li:{}}], type.transform [{p:[0,0],li:{}}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[1],lm:0}], [{p:[0],ld:{}}], 'left'
test.deepEqual [{p:[0],lm:0}], type.transform [{p:[0],lm:1}], [{p:[1],ld:{}}], 'left'
test.deepEqual [{p:[5],lm:0}], type.transform [{p:[6],lm:0}], [{p:[2],ld:{}}], 'left'
test.deepEqual [{p:[1],lm:0}], type.transform [{p:[1],lm:0}], [{p:[2],ld:{}}], 'left'
test.deepEqual [{p:[1],lm:1}], type.transform [{p:[2],lm:1}], [{p:[1],ld:3}], 'right'
test.deepEqual [{p:[1],ld:{}}], type.transform [{p:[2],ld:{}}], [{p:[1],lm:2}], 'right'
test.deepEqual [{p:[2],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[2],lm:1}], 'left'
test.deepEqual [{p:[0],ld:{}}], type.transform [{p:[1],ld:{}}], [{p:[0],lm:1}], 'right'
test.deepEqual [{p:[0],ld:1,li:2}], type.transform [{p:[1],ld:1,li:2}], [{p:[1],lm:0}], 'left'
test.deepEqual [{p:[0],ld:2,li:3}], type.transform [{p:[1],ld:2,li:3}], [{p:[0],lm:1}], 'left'
test.deepEqual [{p:[1],ld:3,li:4}], type.transform [{p:[0],ld:3,li:4}], [{p:[1],lm:0}], 'left'
test.done()
'li vs lm': (test) ->
li = (p) -> [{p:[p],li:[]}]
lm = (f,t) -> [{p:[f],lm:t}]
xf = type.transform
test.deepEqual (li 0), xf (li 0), (lm 1, 3), 'left'
test.deepEqual (li 1), xf (li 1), (lm 1, 3), 'left'
test.deepEqual (li 1), xf (li 2), (lm 1, 3), 'left'
test.deepEqual (li 2), xf (li 3), (lm 1, 3), 'left'
test.deepEqual (li 4), xf (li 4), (lm 1, 3), 'left'
test.deepEqual (lm 2, 4), xf (lm 1, 3), (li 0), 'right'
test.deepEqual (lm 2, 4), xf (lm 1, 3), (li 1), 'right'
test.deepEqual (lm 1, 4), xf (lm 1, 3), (li 2), 'right'
test.deepEqual (lm 1, 4), xf (lm 1, 3), (li 3), 'right'
test.deepEqual (lm 1, 3), xf (lm 1, 3), (li 4), 'right'
test.deepEqual (li 0), xf (li 0), (lm 1, 2), 'left'
test.deepEqual (li 1), xf (li 1), (lm 1, 2), 'left'
test.deepEqual (li 1), xf (li 2), (lm 1, 2), 'left'
test.deepEqual (li 3), xf (li 3), (lm 1, 2), 'left'
test.deepEqual (li 0), xf (li 0), (lm 3, 1), 'left'
test.deepEqual (li 1), xf (li 1), (lm 3, 1), 'left'
test.deepEqual (li 3), xf (li 2), (lm 3, 1), 'left'
test.deepEqual (li 4), xf (li 3), (lm 3, 1), 'left'
test.deepEqual (li 4), xf (li 4), (lm 3, 1), 'left'
test.deepEqual (lm 4, 2), xf (lm 3, 1), (li 0), 'right'
test.deepEqual (lm 4, 2), xf (lm 3, 1), (li 1), 'right'
test.deepEqual (lm 4, 1), xf (lm 3, 1), (li 2), 'right'
test.deepEqual (lm 4, 1), xf (lm 3, 1), (li 3), 'right'
test.deepEqual (lm 3, 1), xf (lm 3, 1), (li 4), 'right'
test.deepEqual (li 0), xf (li 0), (lm 2, 1), 'left'
test.deepEqual (li 1), xf (li 1), (lm 2, 1), 'left'
test.deepEqual (li 3), xf (li 2), (lm 2, 1), 'left'
test.deepEqual (li 3), xf (li 3), (lm 2, 1), 'left'
test.done()
object:
'Apply sanity checks': (test) ->
test.deepEqual {x:'a', y:'b'}, type.apply {x:'a'}, [{p:['y'], oi:'b'}]
test.deepEqual {}, type.apply {x:'a'}, [{p:['x'], od:'a'}]
test.deepEqual {x:'b'}, type.apply {x:'a'}, [{p:['x'], od:'a', oi:'b'}]
test.done()
'Ops on deleted elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x'}], 'left'
test.deepEqual [], type.transform [{p:[9],si:"bite "}], [{p:[],od:"agimble s",oi:null}], 'right'
test.done()
'Ops on replaced elements become noops': (test) ->
test.deepEqual [], type.transform [{p:[1, 0], si:'hi'}], [{p:[1], od:'x', oi:'y'}], 'left'
test.done()
'Deleted data is changed to reflect edits': (test) ->
test.deepEqual [{p:[1], od:'abc'}], type.transform [{p:[1], od:'a'}], [{p:[1, 1], si:'bc'}], 'left'
test.deepEqual [{p:[],od:25,oi:[]}], type.transform [{p:[],od:22,oi:[]}], [{p:[],na:3}], 'left'
test.deepEqual [{p:[],od:{toves:""},oi:4}], type.transform [{p:[],od:{toves:0},oi:4}], [{p:["toves"],od:0,oi:""}], 'left'
test.deepEqual [{p:[],od:"thou an",oi:[]}], type.transform [{p:[],od:"thou and ",oi:[]}], [{p:[7],sd:"d "}], 'left'
test.deepEqual [], type.transform([{p:["bird"],na:2}], [{p:[],od:{bird:38},oi:20}], 'right')
test.deepEqual [{p:[],od:{bird:40},oi:20}], type.transform([{p:[],od:{bird:38},oi:20}], [{p:["bird"],na:2}], 'left')
test.deepEqual [{p:['He'],od:[]}], type.transform [{p:["He"],od:[]}], [{p:["The"],na:-3}], 'right'
test.deepEqual [], type.transform [{p:["He"],oi:{}}], [{p:[],od:{},oi:"the"}], 'left'
test.done()
'If two inserts are simultaneous, the lefts insert will win': (test) ->
test.deepEqual [{p:[1], oi:'a', od:'b'}], type.transform [{p:[1], oi:'a'}], [{p:[1], oi:'b'}], 'left'
test.deepEqual [], type.transform [{p:[1], oi:'b'}], [{p:[1], oi:'a'}], 'right'
test.done()
'parallel ops on different keys miss each other': (test) ->
test.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], oi:'z'}], 'left'
test.deepEqual [{p:['a'], oi: 'x'}], type.transform [{p:['a'], oi:'x'}], [{p:['b'], od:'z'}], 'left'
test.deepEqual [{p:["in","he"],oi:{}}], type.transform [{p:["in","he"],oi:{}}], [{p:["and"],od:{}}], 'right'
test.deepEqual [{p:['x',0],si:"his "}], type.transform [{p:['x',0],si:"his "}], [{p:['y'],od:0,oi:1}], 'right'
test.done()
'replacement vs. deletion': (test) ->
test.deepEqual [{p:[],oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:['']}], 'right'
test.done()
'replacement vs. replacement': (test) ->
test.deepEqual [], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'right'
test.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:['']},{p:[],oi:{}}], [{p:[],od:['']},{p:[],oi:null}], 'left'
test.deepEqual [], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'right'
test.deepEqual [{p:[],od:null,oi:{}}], type.transform [{p:[],od:[''],oi:{}}], [{p:[],od:[''],oi:null}], 'left'
# test diamond property
rightOps = [ {"p":[],"od":null,"oi":{}} ]
leftOps = [ {"p":[],"od":null,"oi":""} ]
rightHas = type.apply(null, rightOps)
leftHas = type.apply(null, leftOps)
[left_, right_] = require('../helpers').transformX type, leftOps, rightOps
test.deepEqual leftHas, type.apply rightHas, left_
test.deepEqual leftHas, type.apply leftHas, right_
test.done()
'An attempt to re-delete a key becomes a no-op': (test) ->
test.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'left'
test.deepEqual [], type.transform [{p:['k'], od:'x'}], [{p:['k'], od:'x'}], 'right'
test.done()
randomizer: (test) ->
require('../helpers').randomizerTest type, 1000
test.done()
exports.node = genTests nativetype
exports.webclient = genTests require('../helpers/webclient').types.json
|
[
{
"context": "}\n s3upload =\n Bucket: upload.bucket,\n Key: upload.sha1\n UploadId: s3UploadId\n {partParams} = up",
"end": 4161,
"score": 0.8062745928764343,
"start": 4155,
"tag": "KEY",
"value": "upload"
},
{
"context": "ultipartUpload\n Bucket: bucket\n K... | packages/nog-blob/nog-blob-server.coffee | nogproject/nog | 0 | { NogBlob, NogBlobTest } = share
# Access action constants.
AA_UPLOAD = 'nog-blob/upload'
AA_DOWNLOAD = 'nog-blob/download'
{
ERR_BLOB_ABORT_PENDING
ERR_BLOB_CONFLICT
ERR_BLOB_NOT_FOUND
ERR_BLOB_UPLOAD_EXISTS
ERR_DB
ERR_LIMIT_S3_OBJECT_SIZE
ERR_PARAM_INVALID
ERR_UPLOADID_UNKNOWN
ERR_UPLOAD_COMPLETE
nogthrow
} = NogError
config = NogBlob.config
isSha1 = Match.Where (x) ->
check x, String
if not (x.match /^[0-9a-f]{40}$/)?
throw new Match.Error 'not a sha1'
true
matchNonNegativeNumber = Match.Where (x) ->
check x, Number
unless x >= 0
throw new Match.Error "Expected non-negative number; got #{x}."
true
# Compute parts that respect the AWS specs:
# <http://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html>
partParamsForSize = (size) ->
MB = 1024 * 1024
minPartSize = 5 * MB
maxNParts = 10000
usualMaxPartSize = 100 * MB
usualNParts = 10
maxSize = maxNParts * 5 * 1000 * MB
if size > maxSize
nogthrow ERR_LIMIT_S3_OBJECT_SIZE, {size, maxSize}
partSize = Math.ceil(size / usualNParts)
if partSize < minPartSize
partSize = minPartSize
else if partSize > usualMaxPartSize
partSize = usualMaxPartSize
if partSize > size
partSize = size
# S3 requires at least one part, even if it has size 0.
if partSize > 0
nParts = Math.ceil(size / partSize)
else
nParts = 1
if nParts > maxNParts
partSize = Math.ceil(size / maxNParts)
nParts = Math.ceil(size / partSize)
return {
totalSize: size
nParts: nParts
partSize: partSize
}
createParts = (upload, partParams, ids) ->
upload = _.pick(upload, 'Bucket', 'Key', 'UploadId')
for i in ids
if 0 < i <= partParams.nParts
partNumber: i
start: (i - 1) * partParams.partSize
end: Math.min i * partParams.partSize, partParams.totalSize
url: NogBlob.bucketRouter.getSignedUploadPartUrl(
_.extend(upload, { PartNumber: i })
)
else
nogthrow ERR_PARAM_INVALID,
reason: "
The part number #{i} is out of range [1, #{partParams.nParts}].
"
collectionContains = (coll, sel) ->
coll.findOne(sel, {fields: {_id: 1}})?
share.startMultipartUpload_server = (user, opts) ->
check opts,
name: String
size: matchNonNegativeNumber
sha1: isSha1
limit: Match.Optional Number
{sha1, name, size} = opts
NogBlob.checkAccess user, AA_UPLOAD, {size}
sel = {_id: sha1, sha1, size, status: 'available'}
if collectionContains NogBlob.blobs, sel
return 'known'
NogBlob.blobs.upsert {
_id: sha1
}, {
$setOnInsert: { sha1, size, status: 'init', mtime: new Date() }
}
# If the size does not match, the blob must have been inserted previously
# with a different size.
if not collectionContains NogBlob.blobs, {_id: sha1, sha1, size}
nogthrow ERR_BLOB_CONFLICT, {sha1}
partParams = partParamsForSize size
upload = NogBlob.bucketRouter.createMultipartUpload { key: sha1 }
s3UploadId = upload.UploadId
bucket = upload.Bucket
NogBlob.uploads.insert {
_id: s3UploadId, bucket, partParams, name, heartbeat: new Date(), sha1
}
NogBlob.blobs.update {
_id: sha1, status: 'init'
}, {
$set: {status: 'uploading'}
$currentDate: {mtime: true}
}
if opts.limit?
unless opts.limit > 0
nogthrow ERR_PARAM_INVALID, {
reason: "Invalid limit #{opts.limit} (limit must be greater than 0)."
}
nStartParts = Math.min opts.limit, partParams.nParts
else
nStartParts = Math.min config.maxNStartParts, partParams.nParts
parts = createParts upload, partParams, [1..nStartParts]
return {
s3UploadId: s3UploadId
nParts: partParams.nParts
startParts: parts
}
share.getUploadParts_server = (user, opts) ->
check opts,
s3UploadId: String
partNumbers: Match.Optional [Number]
offset: Match.Optional Number
limit: Match.Optional Number
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
s3upload =
Bucket: upload.bucket,
Key: upload.sha1
UploadId: s3UploadId
{partParams} = upload
partNumbers = opts.partNumbers
if not partNumbers?
offset = opts.offset ? 0
limit = opts.limit ? config.maxNStartParts
if not (0 <= offset < partParams.nParts)
nogthrow ERR_PARAM_INVALID,
reason: "
The offset #{offset} is out of range [0, #{partParams.nParts}[.
"
partNumbers = [(offset + 1)..Math.min(offset + limit, partParams.nParts)]
NogBlob.uploads.update s3UploadId, {$set: {heartbeat: new Date()}}
res =
s3UploadId: s3UploadId
parts: createParts s3upload, partParams, partNumbers
nParts: partParams.nParts
return res
share.pushUploadedPart_server = (user, opts) ->
check opts,
s3UploadId: String
partNumber: Number
etag: String
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
nModified = NogBlob.uploads.update {
_id: s3UploadId
}, {
$set: {heartbeat: new Date()}
$push: {parts: {PartNumber: opts.partNumber, ETag: opts.etag}}
}
if nModified is 0
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
return
# `checkPartsComplete()` assumes that `parts` is sorted.
checkPartsComplete = (parts, partParams) ->
if parts.length isnt partParams.nParts
nogthrow ERR_PARAM_INVALID,
reason: "
Wrong number of parts (expected #{partParams.nParts}, got
#{parts.length}).
"
for i in [0...partParams.nParts]
pn = parts[i].PartNumber
if pn isnt (i + 1)
nogthrow ERR_PARAM_INVALID, {reason: "Unexpected PartNumber #{pn}."}
share.completeMultipartUpload_server = (user, opts) ->
check opts,
s3UploadId: String
s3Parts: Match.Optional [{PartNumber: Number, ETag: String}]
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
{sha1, partParams, bucket} = upload
parts = opts.s3Parts ? upload.parts
# S3 requires the parts to be sorted.
parts = _.sortBy parts, 'PartNumber'
checkPartsComplete parts, upload.partParams
# If the status isn't uploading, a concurrent upload must have succeeded; so
# abort this one.
if not collectionContains(NogBlob.blobs, {_id: sha1, status: 'uploading'})
try
NogBlob.bucketRouter.abortMultipartUpload
Bucket: bucket
Key: sha1
UploadId: s3UploadId
catch cause
# It might be a temporary network error. Keep the upload in the
# collection, so that a clean up job can abort it later.
nogthrow ERR_UPLOAD_COMPLETE, {cause}
NogBlob.uploads.remove {_id: s3UploadId}
return sha1
try
NogBlob.bucketRouter.completeMultipartUpload
Bucket: bucket
Key: sha1
UploadId: s3UploadId
MultipartUpload: {Parts: parts}
catch cause
# This might be a temporary network error. Keep the upload in the uploads
# collection, so that a clean up job can cancel it later.
nogthrow ERR_UPLOAD_COMPLETE, {cause}
NogBlob.uploads.remove {_id: s3UploadId}
# Push log separately to add entry even if status != 'uploading'.
username = user?.username ? 'unknown'
NogBlob.blobs.update {
_id: sha1
}, {
$push: {
log: {
ts: new Date()
msg: "Uploaded by '#{username}' from local file '#{upload.name}'."
}
}
}
NogBlob.blobs.update {
_id: sha1, status: 'uploading'
}, {
$set: {
status: 'available',
locs: [
{
bucket: bucket,
status: 'online',
mpp: { n: partParams.nParts, psize: partParams.partSize }
}
]
}
$currentDate: {mtime: true}
}
return sha1
share.abortMultipartUpload_server = (user, opts) ->
check opts,
s3UploadId: String
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, opts
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
NogBlob.bucketRouter.abortMultipartUpload
Bucket: upload.bucket
Key: upload.sha1
UploadId: s3UploadId
NogBlob.uploads.remove {_id: s3UploadId}
return
share.getBlobDownloadURL_server = (user, opts) ->
check opts,
sha1: isSha1
filename: String
NogBlob.checkAccess user, AA_DOWNLOAD, {}
if not (blob = NogBlob.blobs.findOne {_id: opts.sha1})?
nogthrow ERR_BLOB_NOT_FOUND, {blob: opts.sha1}
return NogBlob.bucketRouter.getDownloadUrl {
blob,
filename: opts.filename
}
Meteor.publish 'nog-blob/blobs', (sha1s) ->
NogBlob.checkAccess @userId, AA_UPLOAD, {sha1s}
return NogBlob.blobs.find {_id: {$in: sha1s}},
fields:
sha1: true
size: true
status: true
class BlobsApi
constructor: (deps) ->
{
@blobs, @checkAccess, @repoSets
} = deps
actions: () ->
[
{ method: 'GET', path: '/:blob', action: @get_blob }
{ method: 'GET', path: '/:blob/content', action: @get_blob_content }
]
# Use `=>` to bind the actions to access this instance's state.
get_blob: (req) =>
@checkAccess req.auth?.user, AA_DOWNLOAD, req.params
{params, baseUrl} = req
if @repoSets?
params = _.pick params, 'blob', 'ownerName', 'repoName'
check params, {blob: isSha1, ownerName: String, repoName: String}
else
params = _.pick params, 'blob'
check params, { blob: isSha1 }
blob = @blobs.findOne params.blob
if not blob?
nogthrow ERR_BLOB_NOT_FOUND, {blob: params.blob}
if @repoSets?
@repoSets.checkMembership {
ownerName: params.ownerName
repoName: params.repoName
sha1: params.blob
}, 'blob'
res = _.pick blob, 'size', 'status', 'sha1'
res._id =
id: blob._id,
href: Meteor.absoluteUrl(baseUrl[1..] + '/' + blob._id)
res.content =
href: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
res
get_blob_content: (req) =>
@checkAccess req.auth?.user, AA_DOWNLOAD, req.params
{params} = req
if @repoSets?
params = _.pick params, 'blob', 'ownerName', 'repoName'
check params, {blob: isSha1, ownerName: String, repoName: String}
else
params = _.pick params, 'blob'
check params, { blob: isSha1 }
blob = @blobs.findOne params.blob
if not blob?
nogthrow ERR_BLOB_NOT_FOUND, {blob: params.blob}
if @repoSets?
@repoSets.checkMembership {
ownerName: params.ownerName
repoName: params.repoName
sha1: params.blob
}, 'blob'
return {
statusCode: 307
location: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
}
{format: urlformat} = Npm.require 'url'
asPartsPage = (opts) ->
count = opts.nParts
offset = opts.parts[0].partNumber - 1
limit = opts.parts.length
nextOffset = offset + limit
if nextOffset < count
next = urlformat
pathname: [
opts.baseUrl, opts.sha1, 'uploads', opts.s3UploadId, 'parts'
].join('/')
query:
offset: nextOffset
limit: limit
next = Meteor.absoluteUrl(next[1..])
else
next = null
return {
count: count
offset: offset
limit: limit
next: next
items: for p in opts.parts
p.href = p.url
_.omit p, 'url'
}
# `UploadsApi` must be mounted at the same path as `BlobApi` to share the base
# url. This is similar to the AWS multipart API
# <http://docs.aws.amazon.com/AmazonS3/latest/dev/sdksupportformpu.html>. A
# notable difference is that `UploadsApi` uses a path suffix `/uploads` instead
# of a query `?upload`.
class UploadsApi
constructor: (deps) ->
{@repoSets} = deps
actions: () ->
[
{
method: 'POST'
path: '/:sha1/uploads'
action: @post_start
}
{
method: 'GET'
path: '/:sha1/uploads/:s3UploadId/parts'
action: @get_parts
}
{
method: 'POST'
path: '/:sha1/uploads/:s3UploadId'
action: @post_complete
}
]
# Use `=>` to bind the actions to this instance.
post_start: (req) =>
opts = _.pick req.params, 'sha1'
if req.query?.limit?
opts.limit = Number(req.query.limit)
_.extend opts, req.body
res = share.startMultipartUpload_server req.auth?.user, opts
# Return 409 'conflict' if the blob already exists. An alternative would
# be 303 'see other'. See discussion on SO
# <http://stackoverflow.com/questions/3825990/http-response-code-for-post-when-resource-already-exists>.
#
# Since the upload is not started, the blob will be added to the repo sets
# now, so that it can be used for an object. This is not perfect, since it
# allows a malicious user to guess sha1s and get access to the
# corresponding content by contructing an object knowing only the sha1 of
# the blob. It seems acceptable, since we trust clients to send valid
# sha1s anyway. An alternative would be to allow another upload and put it
# into some kind of quarantine until a server side job has confirmed the
# sha1 and then delete the upload and use the first upload instead. The
# additional upload would be prove that the user actually had access to the
# data that correspond to the sha1.
if res is 'known'
if @repoSets?
params = _.pick req.params, 'ownerName', 'repoName'
check params, {ownerName: String, repoName: String}
@repoSets.updateMembership params, {type: 'blob', sha1: opts.sha1}
nogthrow ERR_BLOB_UPLOAD_EXISTS, {sha1: opts.sha1}
# Return 201 'created', since the upload has an id and behaves like a new
# resource.
return {
statusCode: 201
upload:
id: res.s3UploadId
href: do ->
path = [
req.baseUrl, opts.sha1, 'uploads', res.s3UploadId
].join('/')
Meteor.absoluteUrl(path[1..])
parts: asPartsPage
baseUrl: req.baseUrl
sha1: opts.sha1
s3UploadId: res.s3UploadId
nParts: res.nParts
parts: res.startParts
}
get_parts: (req) =>
sha1 = req.params.sha1
check sha1, isSha1
opts = {
s3UploadId: req.params.s3UploadId
}
if req.query?.offset?
opts.offset = Number(req.query.offset)
if req.query?.limit?
opts.limit = Number(req.query.limit)
res = share.getUploadParts_server req.auth?.user, opts
return asPartsPage
baseUrl: req.baseUrl
sha1: sha1
s3UploadId: res.s3UploadId
nParts: res.nParts
parts: res.parts
post_complete: (req) =>
opts = {
s3UploadId: req.params.s3UploadId
s3Parts: req.body?.s3Parts
}
blobid = share.completeMultipartUpload_server req.auth?.user, opts
if @repoSets?
params = _.pick req.params, 'ownerName', 'repoName'
check params, {ownerName: String, repoName: String}
@repoSets.updateMembership params, {type: 'blob', sha1: blobid}
# Assume that BlobsApi is mounted at the same path as UploadApi.
baseUrl = req.baseUrl
# The implementation is similar to the code in BlobsApi. Consider
# factoring out common parts.
#
# The download URL returned here could be tied to the upload bucket. But
# it is not necessary, since the bucket router will automatically select
# the upload bucket if it is the only one that contains the blob.
blob = NogBlob.blobs.findOne blobid
res = _.pick blob, 'size', 'status', 'sha1'
res._id =
id: blob._id,
href: Meteor.absoluteUrl(baseUrl[1..] + '/' + blob._id)
res.content =
href: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
res.statusCode = 201
res
share.init_server = ->
deps = _.pick NogBlob, 'blobs', 'checkAccess'
if NogBlob.repoSets
deps.repoSets = NogBlob.repoSets
NogBlob.api.blobs = new BlobsApi deps
NogBlob.api.uploads = new UploadsApi deps
share.init_server()
NogBlobTest.BlobsApi = BlobsApi
NogBlobTest.UploadsApi = UploadsApi
| 169290 | { NogBlob, NogBlobTest } = share
# Access action constants.
AA_UPLOAD = 'nog-blob/upload'
AA_DOWNLOAD = 'nog-blob/download'
{
ERR_BLOB_ABORT_PENDING
ERR_BLOB_CONFLICT
ERR_BLOB_NOT_FOUND
ERR_BLOB_UPLOAD_EXISTS
ERR_DB
ERR_LIMIT_S3_OBJECT_SIZE
ERR_PARAM_INVALID
ERR_UPLOADID_UNKNOWN
ERR_UPLOAD_COMPLETE
nogthrow
} = NogError
config = NogBlob.config
isSha1 = Match.Where (x) ->
check x, String
if not (x.match /^[0-9a-f]{40}$/)?
throw new Match.Error 'not a sha1'
true
matchNonNegativeNumber = Match.Where (x) ->
check x, Number
unless x >= 0
throw new Match.Error "Expected non-negative number; got #{x}."
true
# Compute parts that respect the AWS specs:
# <http://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html>
partParamsForSize = (size) ->
MB = 1024 * 1024
minPartSize = 5 * MB
maxNParts = 10000
usualMaxPartSize = 100 * MB
usualNParts = 10
maxSize = maxNParts * 5 * 1000 * MB
if size > maxSize
nogthrow ERR_LIMIT_S3_OBJECT_SIZE, {size, maxSize}
partSize = Math.ceil(size / usualNParts)
if partSize < minPartSize
partSize = minPartSize
else if partSize > usualMaxPartSize
partSize = usualMaxPartSize
if partSize > size
partSize = size
# S3 requires at least one part, even if it has size 0.
if partSize > 0
nParts = Math.ceil(size / partSize)
else
nParts = 1
if nParts > maxNParts
partSize = Math.ceil(size / maxNParts)
nParts = Math.ceil(size / partSize)
return {
totalSize: size
nParts: nParts
partSize: partSize
}
createParts = (upload, partParams, ids) ->
upload = _.pick(upload, 'Bucket', 'Key', 'UploadId')
for i in ids
if 0 < i <= partParams.nParts
partNumber: i
start: (i - 1) * partParams.partSize
end: Math.min i * partParams.partSize, partParams.totalSize
url: NogBlob.bucketRouter.getSignedUploadPartUrl(
_.extend(upload, { PartNumber: i })
)
else
nogthrow ERR_PARAM_INVALID,
reason: "
The part number #{i} is out of range [1, #{partParams.nParts}].
"
collectionContains = (coll, sel) ->
coll.findOne(sel, {fields: {_id: 1}})?
share.startMultipartUpload_server = (user, opts) ->
check opts,
name: String
size: matchNonNegativeNumber
sha1: isSha1
limit: Match.Optional Number
{sha1, name, size} = opts
NogBlob.checkAccess user, AA_UPLOAD, {size}
sel = {_id: sha1, sha1, size, status: 'available'}
if collectionContains NogBlob.blobs, sel
return 'known'
NogBlob.blobs.upsert {
_id: sha1
}, {
$setOnInsert: { sha1, size, status: 'init', mtime: new Date() }
}
# If the size does not match, the blob must have been inserted previously
# with a different size.
if not collectionContains NogBlob.blobs, {_id: sha1, sha1, size}
nogthrow ERR_BLOB_CONFLICT, {sha1}
partParams = partParamsForSize size
upload = NogBlob.bucketRouter.createMultipartUpload { key: sha1 }
s3UploadId = upload.UploadId
bucket = upload.Bucket
NogBlob.uploads.insert {
_id: s3UploadId, bucket, partParams, name, heartbeat: new Date(), sha1
}
NogBlob.blobs.update {
_id: sha1, status: 'init'
}, {
$set: {status: 'uploading'}
$currentDate: {mtime: true}
}
if opts.limit?
unless opts.limit > 0
nogthrow ERR_PARAM_INVALID, {
reason: "Invalid limit #{opts.limit} (limit must be greater than 0)."
}
nStartParts = Math.min opts.limit, partParams.nParts
else
nStartParts = Math.min config.maxNStartParts, partParams.nParts
parts = createParts upload, partParams, [1..nStartParts]
return {
s3UploadId: s3UploadId
nParts: partParams.nParts
startParts: parts
}
share.getUploadParts_server = (user, opts) ->
check opts,
s3UploadId: String
partNumbers: Match.Optional [Number]
offset: Match.Optional Number
limit: Match.Optional Number
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
s3upload =
Bucket: upload.bucket,
Key: <KEY>.sha1
UploadId: s3UploadId
{partParams} = upload
partNumbers = opts.partNumbers
if not partNumbers?
offset = opts.offset ? 0
limit = opts.limit ? config.maxNStartParts
if not (0 <= offset < partParams.nParts)
nogthrow ERR_PARAM_INVALID,
reason: "
The offset #{offset} is out of range [0, #{partParams.nParts}[.
"
partNumbers = [(offset + 1)..Math.min(offset + limit, partParams.nParts)]
NogBlob.uploads.update s3UploadId, {$set: {heartbeat: new Date()}}
res =
s3UploadId: s3UploadId
parts: createParts s3upload, partParams, partNumbers
nParts: partParams.nParts
return res
share.pushUploadedPart_server = (user, opts) ->
check opts,
s3UploadId: String
partNumber: Number
etag: String
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
nModified = NogBlob.uploads.update {
_id: s3UploadId
}, {
$set: {heartbeat: new Date()}
$push: {parts: {PartNumber: opts.partNumber, ETag: opts.etag}}
}
if nModified is 0
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
return
# `checkPartsComplete()` assumes that `parts` is sorted.
checkPartsComplete = (parts, partParams) ->
if parts.length isnt partParams.nParts
nogthrow ERR_PARAM_INVALID,
reason: "
Wrong number of parts (expected #{partParams.nParts}, got
#{parts.length}).
"
for i in [0...partParams.nParts]
pn = parts[i].PartNumber
if pn isnt (i + 1)
nogthrow ERR_PARAM_INVALID, {reason: "Unexpected PartNumber #{pn}."}
share.completeMultipartUpload_server = (user, opts) ->
check opts,
s3UploadId: String
s3Parts: Match.Optional [{PartNumber: Number, ETag: String}]
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
{sha1, partParams, bucket} = upload
parts = opts.s3Parts ? upload.parts
# S3 requires the parts to be sorted.
parts = _.sortBy parts, 'PartNumber'
checkPartsComplete parts, upload.partParams
# If the status isn't uploading, a concurrent upload must have succeeded; so
# abort this one.
if not collectionContains(NogBlob.blobs, {_id: sha1, status: 'uploading'})
try
NogBlob.bucketRouter.abortMultipartUpload
Bucket: bucket
Key: <NAME>1
UploadId: s3UploadId
catch cause
# It might be a temporary network error. Keep the upload in the
# collection, so that a clean up job can abort it later.
nogthrow ERR_UPLOAD_COMPLETE, {cause}
NogBlob.uploads.remove {_id: s3UploadId}
return sha1
try
NogBlob.bucketRouter.completeMultipartUpload
Bucket: bucket
Key: <NAME>1
UploadId: s3UploadId
MultipartUpload: {Parts: parts}
catch cause
# This might be a temporary network error. Keep the upload in the uploads
# collection, so that a clean up job can cancel it later.
nogthrow ERR_UPLOAD_COMPLETE, {cause}
NogBlob.uploads.remove {_id: s3UploadId}
# Push log separately to add entry even if status != 'uploading'.
username = user?.username ? 'unknown'
NogBlob.blobs.update {
_id: sha1
}, {
$push: {
log: {
ts: new Date()
msg: "Uploaded by '#{username}' from local file '#{upload.name}'."
}
}
}
NogBlob.blobs.update {
_id: sha1, status: 'uploading'
}, {
$set: {
status: 'available',
locs: [
{
bucket: bucket,
status: 'online',
mpp: { n: partParams.nParts, psize: partParams.partSize }
}
]
}
$currentDate: {mtime: true}
}
return sha1
share.abortMultipartUpload_server = (user, opts) ->
check opts,
s3UploadId: String
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, opts
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
NogBlob.bucketRouter.abortMultipartUpload
Bucket: upload.bucket
Key: upload.sha1
UploadId: s3UploadId
NogBlob.uploads.remove {_id: s3UploadId}
return
share.getBlobDownloadURL_server = (user, opts) ->
check opts,
sha1: isSha1
filename: String
NogBlob.checkAccess user, AA_DOWNLOAD, {}
if not (blob = NogBlob.blobs.findOne {_id: opts.sha1})?
nogthrow ERR_BLOB_NOT_FOUND, {blob: opts.sha1}
return NogBlob.bucketRouter.getDownloadUrl {
blob,
filename: opts.filename
}
Meteor.publish 'nog-blob/blobs', (sha1s) ->
NogBlob.checkAccess @userId, AA_UPLOAD, {sha1s}
return NogBlob.blobs.find {_id: {$in: sha1s}},
fields:
sha1: true
size: true
status: true
class BlobsApi
constructor: (deps) ->
{
@blobs, @checkAccess, @repoSets
} = deps
actions: () ->
[
{ method: 'GET', path: '/:blob', action: @get_blob }
{ method: 'GET', path: '/:blob/content', action: @get_blob_content }
]
# Use `=>` to bind the actions to access this instance's state.
get_blob: (req) =>
@checkAccess req.auth?.user, AA_DOWNLOAD, req.params
{params, baseUrl} = req
if @repoSets?
params = _.pick params, 'blob', 'ownerName', 'repoName'
check params, {blob: isSha1, ownerName: String, repoName: String}
else
params = _.pick params, 'blob'
check params, { blob: isSha1 }
blob = @blobs.findOne params.blob
if not blob?
nogthrow ERR_BLOB_NOT_FOUND, {blob: params.blob}
if @repoSets?
@repoSets.checkMembership {
ownerName: params.ownerName
repoName: params.repoName
sha1: params.blob
}, 'blob'
res = _.pick blob, 'size', 'status', 'sha1'
res._id =
id: blob._id,
href: Meteor.absoluteUrl(baseUrl[1..] + '/' + blob._id)
res.content =
href: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
res
get_blob_content: (req) =>
@checkAccess req.auth?.user, AA_DOWNLOAD, req.params
{params} = req
if @repoSets?
params = _.pick params, 'blob', 'ownerName', 'repoName'
check params, {blob: isSha1, ownerName: String, repoName: String}
else
params = _.pick params, 'blob'
check params, { blob: isSha1 }
blob = @blobs.findOne params.blob
if not blob?
nogthrow ERR_BLOB_NOT_FOUND, {blob: params.blob}
if @repoSets?
@repoSets.checkMembership {
ownerName: params.ownerName
repoName: params.repoName
sha1: params.blob
}, 'blob'
return {
statusCode: 307
location: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
}
{format: urlformat} = Npm.require 'url'
asPartsPage = (opts) ->
count = opts.nParts
offset = opts.parts[0].partNumber - 1
limit = opts.parts.length
nextOffset = offset + limit
if nextOffset < count
next = urlformat
pathname: [
opts.baseUrl, opts.sha1, 'uploads', opts.s3UploadId, 'parts'
].join('/')
query:
offset: nextOffset
limit: limit
next = Meteor.absoluteUrl(next[1..])
else
next = null
return {
count: count
offset: offset
limit: limit
next: next
items: for p in opts.parts
p.href = p.url
_.omit p, 'url'
}
# `UploadsApi` must be mounted at the same path as `BlobApi` to share the base
# url. This is similar to the AWS multipart API
# <http://docs.aws.amazon.com/AmazonS3/latest/dev/sdksupportformpu.html>. A
# notable difference is that `UploadsApi` uses a path suffix `/uploads` instead
# of a query `?upload`.
class UploadsApi
constructor: (deps) ->
{@repoSets} = deps
actions: () ->
[
{
method: 'POST'
path: '/:sha1/uploads'
action: @post_start
}
{
method: 'GET'
path: '/:sha1/uploads/:s3UploadId/parts'
action: @get_parts
}
{
method: 'POST'
path: '/:sha1/uploads/:s3UploadId'
action: @post_complete
}
]
# Use `=>` to bind the actions to this instance.
post_start: (req) =>
opts = _.pick req.params, 'sha1'
if req.query?.limit?
opts.limit = Number(req.query.limit)
_.extend opts, req.body
res = share.startMultipartUpload_server req.auth?.user, opts
# Return 409 'conflict' if the blob already exists. An alternative would
# be 303 'see other'. See discussion on SO
# <http://stackoverflow.com/questions/3825990/http-response-code-for-post-when-resource-already-exists>.
#
# Since the upload is not started, the blob will be added to the repo sets
# now, so that it can be used for an object. This is not perfect, since it
# allows a malicious user to guess sha1s and get access to the
# corresponding content by contructing an object knowing only the sha1 of
# the blob. It seems acceptable, since we trust clients to send valid
# sha1s anyway. An alternative would be to allow another upload and put it
# into some kind of quarantine until a server side job has confirmed the
# sha1 and then delete the upload and use the first upload instead. The
# additional upload would be prove that the user actually had access to the
# data that correspond to the sha1.
if res is 'known'
if @repoSets?
params = _.pick req.params, 'ownerName', 'repoName'
check params, {ownerName: String, repoName: String}
@repoSets.updateMembership params, {type: 'blob', sha1: opts.sha1}
nogthrow ERR_BLOB_UPLOAD_EXISTS, {sha1: opts.sha1}
# Return 201 'created', since the upload has an id and behaves like a new
# resource.
return {
statusCode: 201
upload:
id: res.s3UploadId
href: do ->
path = [
req.baseUrl, opts.sha1, 'uploads', res.s3UploadId
].join('/')
Meteor.absoluteUrl(path[1..])
parts: asPartsPage
baseUrl: req.baseUrl
sha1: opts.sha1
s3UploadId: res.s3UploadId
nParts: res.nParts
parts: res.startParts
}
get_parts: (req) =>
sha1 = req.params.sha1
check sha1, isSha1
opts = {
s3UploadId: req.params.s3UploadId
}
if req.query?.offset?
opts.offset = Number(req.query.offset)
if req.query?.limit?
opts.limit = Number(req.query.limit)
res = share.getUploadParts_server req.auth?.user, opts
return asPartsPage
baseUrl: req.baseUrl
sha1: sha1
s3UploadId: res.s3UploadId
nParts: res.nParts
parts: res.parts
post_complete: (req) =>
opts = {
s3UploadId: req.params.s3UploadId
s3Parts: req.body?.s3Parts
}
blobid = share.completeMultipartUpload_server req.auth?.user, opts
if @repoSets?
params = _.pick req.params, 'ownerName', 'repoName'
check params, {ownerName: String, repoName: String}
@repoSets.updateMembership params, {type: 'blob', sha1: blobid}
# Assume that BlobsApi is mounted at the same path as UploadApi.
baseUrl = req.baseUrl
# The implementation is similar to the code in BlobsApi. Consider
# factoring out common parts.
#
# The download URL returned here could be tied to the upload bucket. But
# it is not necessary, since the bucket router will automatically select
# the upload bucket if it is the only one that contains the blob.
blob = NogBlob.blobs.findOne blobid
res = _.pick blob, 'size', 'status', 'sha1'
res._id =
id: blob._id,
href: Meteor.absoluteUrl(baseUrl[1..] + '/' + blob._id)
res.content =
href: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
res.statusCode = 201
res
share.init_server = ->
deps = _.pick NogBlob, 'blobs', 'checkAccess'
if NogBlob.repoSets
deps.repoSets = NogBlob.repoSets
NogBlob.api.blobs = new BlobsApi deps
NogBlob.api.uploads = new UploadsApi deps
share.init_server()
NogBlobTest.BlobsApi = BlobsApi
NogBlobTest.UploadsApi = UploadsApi
| true | { NogBlob, NogBlobTest } = share
# Access action constants.
AA_UPLOAD = 'nog-blob/upload'
AA_DOWNLOAD = 'nog-blob/download'
{
ERR_BLOB_ABORT_PENDING
ERR_BLOB_CONFLICT
ERR_BLOB_NOT_FOUND
ERR_BLOB_UPLOAD_EXISTS
ERR_DB
ERR_LIMIT_S3_OBJECT_SIZE
ERR_PARAM_INVALID
ERR_UPLOADID_UNKNOWN
ERR_UPLOAD_COMPLETE
nogthrow
} = NogError
config = NogBlob.config
isSha1 = Match.Where (x) ->
check x, String
if not (x.match /^[0-9a-f]{40}$/)?
throw new Match.Error 'not a sha1'
true
matchNonNegativeNumber = Match.Where (x) ->
check x, Number
unless x >= 0
throw new Match.Error "Expected non-negative number; got #{x}."
true
# Compute parts that respect the AWS specs:
# <http://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html>
partParamsForSize = (size) ->
MB = 1024 * 1024
minPartSize = 5 * MB
maxNParts = 10000
usualMaxPartSize = 100 * MB
usualNParts = 10
maxSize = maxNParts * 5 * 1000 * MB
if size > maxSize
nogthrow ERR_LIMIT_S3_OBJECT_SIZE, {size, maxSize}
partSize = Math.ceil(size / usualNParts)
if partSize < minPartSize
partSize = minPartSize
else if partSize > usualMaxPartSize
partSize = usualMaxPartSize
if partSize > size
partSize = size
# S3 requires at least one part, even if it has size 0.
if partSize > 0
nParts = Math.ceil(size / partSize)
else
nParts = 1
if nParts > maxNParts
partSize = Math.ceil(size / maxNParts)
nParts = Math.ceil(size / partSize)
return {
totalSize: size
nParts: nParts
partSize: partSize
}
createParts = (upload, partParams, ids) ->
upload = _.pick(upload, 'Bucket', 'Key', 'UploadId')
for i in ids
if 0 < i <= partParams.nParts
partNumber: i
start: (i - 1) * partParams.partSize
end: Math.min i * partParams.partSize, partParams.totalSize
url: NogBlob.bucketRouter.getSignedUploadPartUrl(
_.extend(upload, { PartNumber: i })
)
else
nogthrow ERR_PARAM_INVALID,
reason: "
The part number #{i} is out of range [1, #{partParams.nParts}].
"
collectionContains = (coll, sel) ->
coll.findOne(sel, {fields: {_id: 1}})?
share.startMultipartUpload_server = (user, opts) ->
check opts,
name: String
size: matchNonNegativeNumber
sha1: isSha1
limit: Match.Optional Number
{sha1, name, size} = opts
NogBlob.checkAccess user, AA_UPLOAD, {size}
sel = {_id: sha1, sha1, size, status: 'available'}
if collectionContains NogBlob.blobs, sel
return 'known'
NogBlob.blobs.upsert {
_id: sha1
}, {
$setOnInsert: { sha1, size, status: 'init', mtime: new Date() }
}
# If the size does not match, the blob must have been inserted previously
# with a different size.
if not collectionContains NogBlob.blobs, {_id: sha1, sha1, size}
nogthrow ERR_BLOB_CONFLICT, {sha1}
partParams = partParamsForSize size
upload = NogBlob.bucketRouter.createMultipartUpload { key: sha1 }
s3UploadId = upload.UploadId
bucket = upload.Bucket
NogBlob.uploads.insert {
_id: s3UploadId, bucket, partParams, name, heartbeat: new Date(), sha1
}
NogBlob.blobs.update {
_id: sha1, status: 'init'
}, {
$set: {status: 'uploading'}
$currentDate: {mtime: true}
}
if opts.limit?
unless opts.limit > 0
nogthrow ERR_PARAM_INVALID, {
reason: "Invalid limit #{opts.limit} (limit must be greater than 0)."
}
nStartParts = Math.min opts.limit, partParams.nParts
else
nStartParts = Math.min config.maxNStartParts, partParams.nParts
parts = createParts upload, partParams, [1..nStartParts]
return {
s3UploadId: s3UploadId
nParts: partParams.nParts
startParts: parts
}
share.getUploadParts_server = (user, opts) ->
check opts,
s3UploadId: String
partNumbers: Match.Optional [Number]
offset: Match.Optional Number
limit: Match.Optional Number
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
s3upload =
Bucket: upload.bucket,
Key: PI:KEY:<KEY>END_PI.sha1
UploadId: s3UploadId
{partParams} = upload
partNumbers = opts.partNumbers
if not partNumbers?
offset = opts.offset ? 0
limit = opts.limit ? config.maxNStartParts
if not (0 <= offset < partParams.nParts)
nogthrow ERR_PARAM_INVALID,
reason: "
The offset #{offset} is out of range [0, #{partParams.nParts}[.
"
partNumbers = [(offset + 1)..Math.min(offset + limit, partParams.nParts)]
NogBlob.uploads.update s3UploadId, {$set: {heartbeat: new Date()}}
res =
s3UploadId: s3UploadId
parts: createParts s3upload, partParams, partNumbers
nParts: partParams.nParts
return res
share.pushUploadedPart_server = (user, opts) ->
check opts,
s3UploadId: String
partNumber: Number
etag: String
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
nModified = NogBlob.uploads.update {
_id: s3UploadId
}, {
$set: {heartbeat: new Date()}
$push: {parts: {PartNumber: opts.partNumber, ETag: opts.etag}}
}
if nModified is 0
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
return
# `checkPartsComplete()` assumes that `parts` is sorted.
checkPartsComplete = (parts, partParams) ->
if parts.length isnt partParams.nParts
nogthrow ERR_PARAM_INVALID,
reason: "
Wrong number of parts (expected #{partParams.nParts}, got
#{parts.length}).
"
for i in [0...partParams.nParts]
pn = parts[i].PartNumber
if pn isnt (i + 1)
nogthrow ERR_PARAM_INVALID, {reason: "Unexpected PartNumber #{pn}."}
share.completeMultipartUpload_server = (user, opts) ->
check opts,
s3UploadId: String
s3Parts: Match.Optional [{PartNumber: Number, ETag: String}]
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, {s3UploadId}
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
{sha1, partParams, bucket} = upload
parts = opts.s3Parts ? upload.parts
# S3 requires the parts to be sorted.
parts = _.sortBy parts, 'PartNumber'
checkPartsComplete parts, upload.partParams
# If the status isn't uploading, a concurrent upload must have succeeded; so
# abort this one.
if not collectionContains(NogBlob.blobs, {_id: sha1, status: 'uploading'})
try
NogBlob.bucketRouter.abortMultipartUpload
Bucket: bucket
Key: PI:NAME:<NAME>END_PI1
UploadId: s3UploadId
catch cause
# It might be a temporary network error. Keep the upload in the
# collection, so that a clean up job can abort it later.
nogthrow ERR_UPLOAD_COMPLETE, {cause}
NogBlob.uploads.remove {_id: s3UploadId}
return sha1
try
NogBlob.bucketRouter.completeMultipartUpload
Bucket: bucket
Key: PI:NAME:<NAME>END_PI1
UploadId: s3UploadId
MultipartUpload: {Parts: parts}
catch cause
# This might be a temporary network error. Keep the upload in the uploads
# collection, so that a clean up job can cancel it later.
nogthrow ERR_UPLOAD_COMPLETE, {cause}
NogBlob.uploads.remove {_id: s3UploadId}
# Push log separately to add entry even if status != 'uploading'.
username = user?.username ? 'unknown'
NogBlob.blobs.update {
_id: sha1
}, {
$push: {
log: {
ts: new Date()
msg: "Uploaded by '#{username}' from local file '#{upload.name}'."
}
}
}
NogBlob.blobs.update {
_id: sha1, status: 'uploading'
}, {
$set: {
status: 'available',
locs: [
{
bucket: bucket,
status: 'online',
mpp: { n: partParams.nParts, psize: partParams.partSize }
}
]
}
$currentDate: {mtime: true}
}
return sha1
share.abortMultipartUpload_server = (user, opts) ->
check opts,
s3UploadId: String
{s3UploadId} = opts
NogBlob.checkAccess user, AA_UPLOAD, opts
if not (upload = NogBlob.uploads.findOne s3UploadId)?
nogthrow ERR_UPLOADID_UNKNOWN, {s3UploadId}
NogBlob.bucketRouter.abortMultipartUpload
Bucket: upload.bucket
Key: upload.sha1
UploadId: s3UploadId
NogBlob.uploads.remove {_id: s3UploadId}
return
share.getBlobDownloadURL_server = (user, opts) ->
check opts,
sha1: isSha1
filename: String
NogBlob.checkAccess user, AA_DOWNLOAD, {}
if not (blob = NogBlob.blobs.findOne {_id: opts.sha1})?
nogthrow ERR_BLOB_NOT_FOUND, {blob: opts.sha1}
return NogBlob.bucketRouter.getDownloadUrl {
blob,
filename: opts.filename
}
Meteor.publish 'nog-blob/blobs', (sha1s) ->
NogBlob.checkAccess @userId, AA_UPLOAD, {sha1s}
return NogBlob.blobs.find {_id: {$in: sha1s}},
fields:
sha1: true
size: true
status: true
class BlobsApi
constructor: (deps) ->
{
@blobs, @checkAccess, @repoSets
} = deps
actions: () ->
[
{ method: 'GET', path: '/:blob', action: @get_blob }
{ method: 'GET', path: '/:blob/content', action: @get_blob_content }
]
# Use `=>` to bind the actions to access this instance's state.
get_blob: (req) =>
@checkAccess req.auth?.user, AA_DOWNLOAD, req.params
{params, baseUrl} = req
if @repoSets?
params = _.pick params, 'blob', 'ownerName', 'repoName'
check params, {blob: isSha1, ownerName: String, repoName: String}
else
params = _.pick params, 'blob'
check params, { blob: isSha1 }
blob = @blobs.findOne params.blob
if not blob?
nogthrow ERR_BLOB_NOT_FOUND, {blob: params.blob}
if @repoSets?
@repoSets.checkMembership {
ownerName: params.ownerName
repoName: params.repoName
sha1: params.blob
}, 'blob'
res = _.pick blob, 'size', 'status', 'sha1'
res._id =
id: blob._id,
href: Meteor.absoluteUrl(baseUrl[1..] + '/' + blob._id)
res.content =
href: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
res
get_blob_content: (req) =>
@checkAccess req.auth?.user, AA_DOWNLOAD, req.params
{params} = req
if @repoSets?
params = _.pick params, 'blob', 'ownerName', 'repoName'
check params, {blob: isSha1, ownerName: String, repoName: String}
else
params = _.pick params, 'blob'
check params, { blob: isSha1 }
blob = @blobs.findOne params.blob
if not blob?
nogthrow ERR_BLOB_NOT_FOUND, {blob: params.blob}
if @repoSets?
@repoSets.checkMembership {
ownerName: params.ownerName
repoName: params.repoName
sha1: params.blob
}, 'blob'
return {
statusCode: 307
location: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
}
{format: urlformat} = Npm.require 'url'
asPartsPage = (opts) ->
count = opts.nParts
offset = opts.parts[0].partNumber - 1
limit = opts.parts.length
nextOffset = offset + limit
if nextOffset < count
next = urlformat
pathname: [
opts.baseUrl, opts.sha1, 'uploads', opts.s3UploadId, 'parts'
].join('/')
query:
offset: nextOffset
limit: limit
next = Meteor.absoluteUrl(next[1..])
else
next = null
return {
count: count
offset: offset
limit: limit
next: next
items: for p in opts.parts
p.href = p.url
_.omit p, 'url'
}
# `UploadsApi` must be mounted at the same path as `BlobApi` to share the base
# url. This is similar to the AWS multipart API
# <http://docs.aws.amazon.com/AmazonS3/latest/dev/sdksupportformpu.html>. A
# notable difference is that `UploadsApi` uses a path suffix `/uploads` instead
# of a query `?upload`.
class UploadsApi
constructor: (deps) ->
{@repoSets} = deps
actions: () ->
[
{
method: 'POST'
path: '/:sha1/uploads'
action: @post_start
}
{
method: 'GET'
path: '/:sha1/uploads/:s3UploadId/parts'
action: @get_parts
}
{
method: 'POST'
path: '/:sha1/uploads/:s3UploadId'
action: @post_complete
}
]
# Use `=>` to bind the actions to this instance.
post_start: (req) =>
opts = _.pick req.params, 'sha1'
if req.query?.limit?
opts.limit = Number(req.query.limit)
_.extend opts, req.body
res = share.startMultipartUpload_server req.auth?.user, opts
# Return 409 'conflict' if the blob already exists. An alternative would
# be 303 'see other'. See discussion on SO
# <http://stackoverflow.com/questions/3825990/http-response-code-for-post-when-resource-already-exists>.
#
# Since the upload is not started, the blob will be added to the repo sets
# now, so that it can be used for an object. This is not perfect, since it
# allows a malicious user to guess sha1s and get access to the
# corresponding content by contructing an object knowing only the sha1 of
# the blob. It seems acceptable, since we trust clients to send valid
# sha1s anyway. An alternative would be to allow another upload and put it
# into some kind of quarantine until a server side job has confirmed the
# sha1 and then delete the upload and use the first upload instead. The
# additional upload would be prove that the user actually had access to the
# data that correspond to the sha1.
if res is 'known'
if @repoSets?
params = _.pick req.params, 'ownerName', 'repoName'
check params, {ownerName: String, repoName: String}
@repoSets.updateMembership params, {type: 'blob', sha1: opts.sha1}
nogthrow ERR_BLOB_UPLOAD_EXISTS, {sha1: opts.sha1}
# Return 201 'created', since the upload has an id and behaves like a new
# resource.
return {
statusCode: 201
upload:
id: res.s3UploadId
href: do ->
path = [
req.baseUrl, opts.sha1, 'uploads', res.s3UploadId
].join('/')
Meteor.absoluteUrl(path[1..])
parts: asPartsPage
baseUrl: req.baseUrl
sha1: opts.sha1
s3UploadId: res.s3UploadId
nParts: res.nParts
parts: res.startParts
}
get_parts: (req) =>
sha1 = req.params.sha1
check sha1, isSha1
opts = {
s3UploadId: req.params.s3UploadId
}
if req.query?.offset?
opts.offset = Number(req.query.offset)
if req.query?.limit?
opts.limit = Number(req.query.limit)
res = share.getUploadParts_server req.auth?.user, opts
return asPartsPage
baseUrl: req.baseUrl
sha1: sha1
s3UploadId: res.s3UploadId
nParts: res.nParts
parts: res.parts
post_complete: (req) =>
opts = {
s3UploadId: req.params.s3UploadId
s3Parts: req.body?.s3Parts
}
blobid = share.completeMultipartUpload_server req.auth?.user, opts
if @repoSets?
params = _.pick req.params, 'ownerName', 'repoName'
check params, {ownerName: String, repoName: String}
@repoSets.updateMembership params, {type: 'blob', sha1: blobid}
# Assume that BlobsApi is mounted at the same path as UploadApi.
baseUrl = req.baseUrl
# The implementation is similar to the code in BlobsApi. Consider
# factoring out common parts.
#
# The download URL returned here could be tied to the upload bucket. But
# it is not necessary, since the bucket router will automatically select
# the upload bucket if it is the only one that contains the blob.
blob = NogBlob.blobs.findOne blobid
res = _.pick blob, 'size', 'status', 'sha1'
res._id =
id: blob._id,
href: Meteor.absoluteUrl(baseUrl[1..] + '/' + blob._id)
res.content =
href: NogBlob.bucketRouter.getDownloadUrl {
blob, filename: "#{blob._id}.dat"
}
res.statusCode = 201
res
share.init_server = ->
deps = _.pick NogBlob, 'blobs', 'checkAccess'
if NogBlob.repoSets
deps.repoSets = NogBlob.repoSets
NogBlob.api.blobs = new BlobsApi deps
NogBlob.api.uploads = new UploadsApi deps
share.init_server()
NogBlobTest.BlobsApi = BlobsApi
NogBlobTest.UploadsApi = UploadsApi
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999086260795593,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/changelog-chart.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @ChangelogChart
constructor: (area) ->
@options =
scales:
x: d3.scaleTime()
y: d3.scaleLinear()
class: d3.scaleOrdinal()
@area = d3.select area
@area.classed 'changelog-chart', true
@svg = @area
.append 'svg'
@svgWrapper = @svg
.append 'g'
@areaFunction = d3.area()
.curve d3.curveMonotoneX
.x (d) => @options.scales.x d.data.date
.y1 (d) => @options.scales.y d[1]
.y0 (d, i) => @options.scales.y d[0]
@hoverArea = @svg.append 'rect'
.classed 'changelog-chart__hover-area', true
.on 'mouseout', @hideTooltip
.on 'mousemove', @moveTooltip
@tooltipArea = @area.append 'div'
.classed 'changelog-chart__tooltip-area', true
@tooltipContainer = @tooltipArea.append 'div'
.classed 'changelog-chart__tooltip-container', true
.attr 'data-visibility', 'hidden'
@tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip-line', true
@tooltip = @tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip', true
@tooltipName = @tooltip.append 'div'
@tooltipUserCount = @tooltip.append 'div'
.classed 'changelog-chart__text changelog-chart__text--user-count', true
@tooltipDate = @tooltip.append 'div'
.classed 'changelog-chart__text changelog-chart__text--date', true
@tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip-line', true
@tooltipLine = @tooltipContainer.selectAll '.changelog-chart__tooltip-line'
loadData: ->
@config = osu.parseJson 'json-chart-config'
{data, hasData} = @normalizeData @config.build_history
stack = d3.stack()
.keys @config.order
.value (d, val) ->
if d[val]? then d[val].normalized else 0
@data = stack data
@hasData = @config.build_history? &&
@config.build_history.length > 0 &&
hasData
@resize()
setDimensions: ->
areaDims = @area.node().getBoundingClientRect()
@width = areaDims.width
@height = areaDims.height
setSvgSize: ->
@svg
.attr 'width', @width
.attr 'height', @height
setHoverAreaSize: ->
@hoverArea
.attr 'width', @width
.attr 'height', @height
setScalesRange: ->
@options.scales.x
.range [0, @width]
.domain [_.first(@data[0])?.data.date, _.last(@data[0])?.data.date]
@options.scales.y
.range [0, @height]
.domain [0, 1]
@options.scales.class
.range _.map @config.order, (d, i) =>
# rotate over available build ids (0-6) when the amount of builds
# exceeds the available amount of colors
if @config.stream_name? then "#{@config.stream_name}-build-#{i % 7}" else _.kebabCase d
.domain @config.order
drawLines: ->
@svgWrapper
.selectAll 'g'
.data @data
.enter()
.append 'path'
.attr 'class', (d) => "changelog-chart__area changelog-chart__area--#{@options.scales.class d.key}"
.attr 'd', @areaFunction
showTooltip: =>
Fade.in @tooltipContainer.node()
hideTooltip: =>
Fade.out @tooltipContainer.node()
moveTooltip: =>
mousePos = d3.mouse @hoverArea.node()
@x = @options.scales.x.invert mousePos[0]
@y = mousePos[1] / @height
@showTooltip()
Timeout.clear @_autoHideTooltip
@_autoHideTooltip = Timeout.set 3000, @hideTooltip
@positionTooltip()
positionTooltip: =>
x = @x
y = @y
pos = d3.bisector((d) -> d.data.date).left @data[0], x
return unless pos
for el, i in @data
if y <= el[pos][1] && el[pos].data[el.key]?
dataRow = i
currentLabel = el.key
labelModifier = @options.scales.class currentLabel
break
coord = @options.scales.x x
@tooltipName
.attr 'class', "changelog-chart__text changelog-chart__text--name changelog-chart__text--#{labelModifier}"
.text currentLabel
@tooltipUserCount.text osu.formatNumber(@data[dataRow][pos].data[currentLabel].user_count)
@tooltipDate.text @data[dataRow][pos].data.date_formatted
tooltipWidth = @tooltip.node().getBoundingClientRect().width
tooltipXBase = coord - (tooltipWidth / 2)
# shift the toltip container when near to the left/right edge
# of the chart, so that the tooltip doesn't extend outside of ito
tooltipX =
if tooltipXBase < 0
0
else if tooltipXBase + tooltipWidth > @width
@width - tooltipWidth
else
tooltipXBase
@tooltip
.style 'transform', "translateX(#{tooltipX}px)"
@tooltipLine
.style 'transform', "translateX(#{coord}px)"
resize: =>
@area.classed 'hidden', !@hasData
return if !@hasData
@setDimensions()
@setScalesRange()
@setSvgSize()
@setHoverAreaSize()
@drawLines()
@positionTooltip()
normalizeData: (rawData) ->
# normalize the user count values
# and parse data into a form digestible by d3.stack()
resetLabel = null
hasData = null
data =
for own timestamp, values of _.groupBy rawData, 'created_at'
sum = _.sumBy values, 'user_count'
if sum == 0
fakedVal = _.find(values, label: resetLabel) if resetLabel?
unless fakedVal?
fakedVal = _.last(values)
resetLabel = fakedVal.label
fakedVal.user_count = 1
sum = 1
else
hasData ?= true
# parse date stored in strings to JS Date object for use by
# d3 domains, and format it into a string shown on the tooltip
m = moment values[0].created_at
obj =
created_at: timestamp
date: m.toDate()
date_formatted: m.format 'YYYY/MM/DD'
for val in values
val.normalized = val.user_count / sum
obj[val.label] = val
obj
{data, hasData}
| 152495 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @ChangelogChart
constructor: (area) ->
@options =
scales:
x: d3.scaleTime()
y: d3.scaleLinear()
class: d3.scaleOrdinal()
@area = d3.select area
@area.classed 'changelog-chart', true
@svg = @area
.append 'svg'
@svgWrapper = @svg
.append 'g'
@areaFunction = d3.area()
.curve d3.curveMonotoneX
.x (d) => @options.scales.x d.data.date
.y1 (d) => @options.scales.y d[1]
.y0 (d, i) => @options.scales.y d[0]
@hoverArea = @svg.append 'rect'
.classed 'changelog-chart__hover-area', true
.on 'mouseout', @hideTooltip
.on 'mousemove', @moveTooltip
@tooltipArea = @area.append 'div'
.classed 'changelog-chart__tooltip-area', true
@tooltipContainer = @tooltipArea.append 'div'
.classed 'changelog-chart__tooltip-container', true
.attr 'data-visibility', 'hidden'
@tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip-line', true
@tooltip = @tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip', true
@tooltipName = @tooltip.append 'div'
@tooltipUserCount = @tooltip.append 'div'
.classed 'changelog-chart__text changelog-chart__text--user-count', true
@tooltipDate = @tooltip.append 'div'
.classed 'changelog-chart__text changelog-chart__text--date', true
@tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip-line', true
@tooltipLine = @tooltipContainer.selectAll '.changelog-chart__tooltip-line'
loadData: ->
@config = osu.parseJson 'json-chart-config'
{data, hasData} = @normalizeData @config.build_history
stack = d3.stack()
.keys @config.order
.value (d, val) ->
if d[val]? then d[val].normalized else 0
@data = stack data
@hasData = @config.build_history? &&
@config.build_history.length > 0 &&
hasData
@resize()
setDimensions: ->
areaDims = @area.node().getBoundingClientRect()
@width = areaDims.width
@height = areaDims.height
setSvgSize: ->
@svg
.attr 'width', @width
.attr 'height', @height
setHoverAreaSize: ->
@hoverArea
.attr 'width', @width
.attr 'height', @height
setScalesRange: ->
@options.scales.x
.range [0, @width]
.domain [_.first(@data[0])?.data.date, _.last(@data[0])?.data.date]
@options.scales.y
.range [0, @height]
.domain [0, 1]
@options.scales.class
.range _.map @config.order, (d, i) =>
# rotate over available build ids (0-6) when the amount of builds
# exceeds the available amount of colors
if @config.stream_name? then "#{@config.stream_name}-build-#{i % 7}" else _.kebabCase d
.domain @config.order
drawLines: ->
@svgWrapper
.selectAll 'g'
.data @data
.enter()
.append 'path'
.attr 'class', (d) => "changelog-chart__area changelog-chart__area--#{@options.scales.class d.key}"
.attr 'd', @areaFunction
showTooltip: =>
Fade.in @tooltipContainer.node()
hideTooltip: =>
Fade.out @tooltipContainer.node()
moveTooltip: =>
mousePos = d3.mouse @hoverArea.node()
@x = @options.scales.x.invert mousePos[0]
@y = mousePos[1] / @height
@showTooltip()
Timeout.clear @_autoHideTooltip
@_autoHideTooltip = Timeout.set 3000, @hideTooltip
@positionTooltip()
positionTooltip: =>
x = @x
y = @y
pos = d3.bisector((d) -> d.data.date).left @data[0], x
return unless pos
for el, i in @data
if y <= el[pos][1] && el[pos].data[el.key]?
dataRow = i
currentLabel = el.key
labelModifier = @options.scales.class currentLabel
break
coord = @options.scales.x x
@tooltipName
.attr 'class', "changelog-chart__text changelog-chart__text--name changelog-chart__text--#{labelModifier}"
.text currentLabel
@tooltipUserCount.text osu.formatNumber(@data[dataRow][pos].data[currentLabel].user_count)
@tooltipDate.text @data[dataRow][pos].data.date_formatted
tooltipWidth = @tooltip.node().getBoundingClientRect().width
tooltipXBase = coord - (tooltipWidth / 2)
# shift the toltip container when near to the left/right edge
# of the chart, so that the tooltip doesn't extend outside of ito
tooltipX =
if tooltipXBase < 0
0
else if tooltipXBase + tooltipWidth > @width
@width - tooltipWidth
else
tooltipXBase
@tooltip
.style 'transform', "translateX(#{tooltipX}px)"
@tooltipLine
.style 'transform', "translateX(#{coord}px)"
resize: =>
@area.classed 'hidden', !@hasData
return if !@hasData
@setDimensions()
@setScalesRange()
@setSvgSize()
@setHoverAreaSize()
@drawLines()
@positionTooltip()
normalizeData: (rawData) ->
# normalize the user count values
# and parse data into a form digestible by d3.stack()
resetLabel = null
hasData = null
data =
for own timestamp, values of _.groupBy rawData, 'created_at'
sum = _.sumBy values, 'user_count'
if sum == 0
fakedVal = _.find(values, label: resetLabel) if resetLabel?
unless fakedVal?
fakedVal = _.last(values)
resetLabel = fakedVal.label
fakedVal.user_count = 1
sum = 1
else
hasData ?= true
# parse date stored in strings to JS Date object for use by
# d3 domains, and format it into a string shown on the tooltip
m = moment values[0].created_at
obj =
created_at: timestamp
date: m.toDate()
date_formatted: m.format 'YYYY/MM/DD'
for val in values
val.normalized = val.user_count / sum
obj[val.label] = val
obj
{data, hasData}
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @ChangelogChart
constructor: (area) ->
@options =
scales:
x: d3.scaleTime()
y: d3.scaleLinear()
class: d3.scaleOrdinal()
@area = d3.select area
@area.classed 'changelog-chart', true
@svg = @area
.append 'svg'
@svgWrapper = @svg
.append 'g'
@areaFunction = d3.area()
.curve d3.curveMonotoneX
.x (d) => @options.scales.x d.data.date
.y1 (d) => @options.scales.y d[1]
.y0 (d, i) => @options.scales.y d[0]
@hoverArea = @svg.append 'rect'
.classed 'changelog-chart__hover-area', true
.on 'mouseout', @hideTooltip
.on 'mousemove', @moveTooltip
@tooltipArea = @area.append 'div'
.classed 'changelog-chart__tooltip-area', true
@tooltipContainer = @tooltipArea.append 'div'
.classed 'changelog-chart__tooltip-container', true
.attr 'data-visibility', 'hidden'
@tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip-line', true
@tooltip = @tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip', true
@tooltipName = @tooltip.append 'div'
@tooltipUserCount = @tooltip.append 'div'
.classed 'changelog-chart__text changelog-chart__text--user-count', true
@tooltipDate = @tooltip.append 'div'
.classed 'changelog-chart__text changelog-chart__text--date', true
@tooltipContainer.append 'div'
.classed 'changelog-chart__tooltip-line', true
@tooltipLine = @tooltipContainer.selectAll '.changelog-chart__tooltip-line'
loadData: ->
@config = osu.parseJson 'json-chart-config'
{data, hasData} = @normalizeData @config.build_history
stack = d3.stack()
.keys @config.order
.value (d, val) ->
if d[val]? then d[val].normalized else 0
@data = stack data
@hasData = @config.build_history? &&
@config.build_history.length > 0 &&
hasData
@resize()
setDimensions: ->
areaDims = @area.node().getBoundingClientRect()
@width = areaDims.width
@height = areaDims.height
setSvgSize: ->
@svg
.attr 'width', @width
.attr 'height', @height
setHoverAreaSize: ->
@hoverArea
.attr 'width', @width
.attr 'height', @height
setScalesRange: ->
@options.scales.x
.range [0, @width]
.domain [_.first(@data[0])?.data.date, _.last(@data[0])?.data.date]
@options.scales.y
.range [0, @height]
.domain [0, 1]
@options.scales.class
.range _.map @config.order, (d, i) =>
# rotate over available build ids (0-6) when the amount of builds
# exceeds the available amount of colors
if @config.stream_name? then "#{@config.stream_name}-build-#{i % 7}" else _.kebabCase d
.domain @config.order
drawLines: ->
@svgWrapper
.selectAll 'g'
.data @data
.enter()
.append 'path'
.attr 'class', (d) => "changelog-chart__area changelog-chart__area--#{@options.scales.class d.key}"
.attr 'd', @areaFunction
showTooltip: =>
Fade.in @tooltipContainer.node()
hideTooltip: =>
Fade.out @tooltipContainer.node()
moveTooltip: =>
mousePos = d3.mouse @hoverArea.node()
@x = @options.scales.x.invert mousePos[0]
@y = mousePos[1] / @height
@showTooltip()
Timeout.clear @_autoHideTooltip
@_autoHideTooltip = Timeout.set 3000, @hideTooltip
@positionTooltip()
positionTooltip: =>
x = @x
y = @y
pos = d3.bisector((d) -> d.data.date).left @data[0], x
return unless pos
for el, i in @data
if y <= el[pos][1] && el[pos].data[el.key]?
dataRow = i
currentLabel = el.key
labelModifier = @options.scales.class currentLabel
break
coord = @options.scales.x x
@tooltipName
.attr 'class', "changelog-chart__text changelog-chart__text--name changelog-chart__text--#{labelModifier}"
.text currentLabel
@tooltipUserCount.text osu.formatNumber(@data[dataRow][pos].data[currentLabel].user_count)
@tooltipDate.text @data[dataRow][pos].data.date_formatted
tooltipWidth = @tooltip.node().getBoundingClientRect().width
tooltipXBase = coord - (tooltipWidth / 2)
# shift the toltip container when near to the left/right edge
# of the chart, so that the tooltip doesn't extend outside of ito
tooltipX =
if tooltipXBase < 0
0
else if tooltipXBase + tooltipWidth > @width
@width - tooltipWidth
else
tooltipXBase
@tooltip
.style 'transform', "translateX(#{tooltipX}px)"
@tooltipLine
.style 'transform', "translateX(#{coord}px)"
resize: =>
@area.classed 'hidden', !@hasData
return if !@hasData
@setDimensions()
@setScalesRange()
@setSvgSize()
@setHoverAreaSize()
@drawLines()
@positionTooltip()
normalizeData: (rawData) ->
# normalize the user count values
# and parse data into a form digestible by d3.stack()
resetLabel = null
hasData = null
data =
for own timestamp, values of _.groupBy rawData, 'created_at'
sum = _.sumBy values, 'user_count'
if sum == 0
fakedVal = _.find(values, label: resetLabel) if resetLabel?
unless fakedVal?
fakedVal = _.last(values)
resetLabel = fakedVal.label
fakedVal.user_count = 1
sum = 1
else
hasData ?= true
# parse date stored in strings to JS Date object for use by
# d3 domains, and format it into a string shown on the tooltip
m = moment values[0].created_at
obj =
created_at: timestamp
date: m.toDate()
date_formatted: m.format 'YYYY/MM/DD'
for val in values
val.normalized = val.user_count / sum
obj[val.label] = val
obj
{data, hasData}
|
[
{
"context": "version 1.0.0\n@file Tab.js\n@author Elison de Campos\n@contact http://jokerjs.zaez.net/contato\n\n@co",
"end": 135,
"score": 0.9998723268508911,
"start": 119,
"tag": "NAME",
"value": "Elison de Campos"
}
] | vendor/assets/javascripts/joker/Tab.coffee | zaeznet/joker-rails | 0 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Tab.js
@author Elison de Campos
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
class Joker.Tab extends Joker.Core
constructor: ->
super
@setEvents()
changeTab: (e) ->
ref = e.currentTarget.dataset.tabReference
tabmenu = @libSupport ".tabs-menu[rel=#{ref}]"
container = @libSupport ".tabs-container[data-tab=#{ref}]"
tabmenu.find("a.active").removeClass "active"
container.find(".tab.active").removeClass "active"
@libSupport(e.currentTarget).addClass "active"
@libSupport("##{e.currentTarget.dataset.tabTarget}").addClass "active"
jwindow = @libSupport(e.currentTarget).closest '.jwindow'
JokerUtils.getObject(jwindow.attr 'id').setScroll()
createTab: (el) ->
el.dataset.tab = JokerUtils.uniqid()
el = @libSupport el
tabs = el.find '.tab'
tabmenu = @libSupport @createTabMenu(tabs, el.data("tab"))
tabmenu.insertBefore "##{el.data 'parent'}"
tabmenu.find("a").on 'click.tab', @libSupport.proxy(@changeTab, @)
tabmenu.find("a").first().trigger 'click'
createTabMenu: (elements, id) ->
string_content = ""
elements.each (index, el) =>
width = Math.round(100/elements.length)
width = width+100-width*elements.length if (index+1) == elements.length
el.id = JokerUtils.uniqid()
string_content += Object.clone(@accessor("patterns").link).assign
target: el.id
ref: id
icon: el.dataset.tabIcon
text: el.dataset.tabText
width: width
Object.clone(@accessor("patterns").container).assign
ref: id
content: string_content
setEvents: ->
@libSupport(document).on "ajaxComplete", @libSupport.proxy(@verifyNewTab, @)
verifyNewTab: (e) ->
@libSupport(".tabs-container:not([data-tab])").each (index, el) => @createTab el
@debugPrefix: "Joker_Tab"
@className : "Joker_Tab"
###
@type [Joker.Tab]
###
@instance : undefined
@patterns:
container: """
<div class="row-fluid">
<ul class="tabs-menu" rel="{ref}">
{content}
</ul>
</div>
"""
link: """
<li style="width:{width}%;"><a href="#" data-tab-target="{target}" data-tab-reference="{ref}"><i class="{icon}"></i>{text}</a></li>
"""
###
Retorna a variavel unica para a instacia do objeto
@return [Joker.Tab]
###
@getInstance: ->
Joker.Tab.instance = new Joker.Tab() unless Joker.Tab.instance?
Joker.Tab.instance | 209744 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Tab.js
@author <NAME>
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
class Joker.Tab extends Joker.Core
constructor: ->
super
@setEvents()
changeTab: (e) ->
ref = e.currentTarget.dataset.tabReference
tabmenu = @libSupport ".tabs-menu[rel=#{ref}]"
container = @libSupport ".tabs-container[data-tab=#{ref}]"
tabmenu.find("a.active").removeClass "active"
container.find(".tab.active").removeClass "active"
@libSupport(e.currentTarget).addClass "active"
@libSupport("##{e.currentTarget.dataset.tabTarget}").addClass "active"
jwindow = @libSupport(e.currentTarget).closest '.jwindow'
JokerUtils.getObject(jwindow.attr 'id').setScroll()
createTab: (el) ->
el.dataset.tab = JokerUtils.uniqid()
el = @libSupport el
tabs = el.find '.tab'
tabmenu = @libSupport @createTabMenu(tabs, el.data("tab"))
tabmenu.insertBefore "##{el.data 'parent'}"
tabmenu.find("a").on 'click.tab', @libSupport.proxy(@changeTab, @)
tabmenu.find("a").first().trigger 'click'
createTabMenu: (elements, id) ->
string_content = ""
elements.each (index, el) =>
width = Math.round(100/elements.length)
width = width+100-width*elements.length if (index+1) == elements.length
el.id = JokerUtils.uniqid()
string_content += Object.clone(@accessor("patterns").link).assign
target: el.id
ref: id
icon: el.dataset.tabIcon
text: el.dataset.tabText
width: width
Object.clone(@accessor("patterns").container).assign
ref: id
content: string_content
setEvents: ->
@libSupport(document).on "ajaxComplete", @libSupport.proxy(@verifyNewTab, @)
verifyNewTab: (e) ->
@libSupport(".tabs-container:not([data-tab])").each (index, el) => @createTab el
@debugPrefix: "Joker_Tab"
@className : "Joker_Tab"
###
@type [Joker.Tab]
###
@instance : undefined
@patterns:
container: """
<div class="row-fluid">
<ul class="tabs-menu" rel="{ref}">
{content}
</ul>
</div>
"""
link: """
<li style="width:{width}%;"><a href="#" data-tab-target="{target}" data-tab-reference="{ref}"><i class="{icon}"></i>{text}</a></li>
"""
###
Retorna a variavel unica para a instacia do objeto
@return [Joker.Tab]
###
@getInstance: ->
Joker.Tab.instance = new Joker.Tab() unless Joker.Tab.instance?
Joker.Tab.instance | true | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Tab.js
@author PI:NAME:<NAME>END_PI
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2013 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
class Joker.Tab extends Joker.Core
constructor: ->
super
@setEvents()
changeTab: (e) ->
ref = e.currentTarget.dataset.tabReference
tabmenu = @libSupport ".tabs-menu[rel=#{ref}]"
container = @libSupport ".tabs-container[data-tab=#{ref}]"
tabmenu.find("a.active").removeClass "active"
container.find(".tab.active").removeClass "active"
@libSupport(e.currentTarget).addClass "active"
@libSupport("##{e.currentTarget.dataset.tabTarget}").addClass "active"
jwindow = @libSupport(e.currentTarget).closest '.jwindow'
JokerUtils.getObject(jwindow.attr 'id').setScroll()
createTab: (el) ->
el.dataset.tab = JokerUtils.uniqid()
el = @libSupport el
tabs = el.find '.tab'
tabmenu = @libSupport @createTabMenu(tabs, el.data("tab"))
tabmenu.insertBefore "##{el.data 'parent'}"
tabmenu.find("a").on 'click.tab', @libSupport.proxy(@changeTab, @)
tabmenu.find("a").first().trigger 'click'
createTabMenu: (elements, id) ->
string_content = ""
elements.each (index, el) =>
width = Math.round(100/elements.length)
width = width+100-width*elements.length if (index+1) == elements.length
el.id = JokerUtils.uniqid()
string_content += Object.clone(@accessor("patterns").link).assign
target: el.id
ref: id
icon: el.dataset.tabIcon
text: el.dataset.tabText
width: width
Object.clone(@accessor("patterns").container).assign
ref: id
content: string_content
setEvents: ->
@libSupport(document).on "ajaxComplete", @libSupport.proxy(@verifyNewTab, @)
verifyNewTab: (e) ->
@libSupport(".tabs-container:not([data-tab])").each (index, el) => @createTab el
@debugPrefix: "Joker_Tab"
@className : "Joker_Tab"
###
@type [Joker.Tab]
###
@instance : undefined
@patterns:
container: """
<div class="row-fluid">
<ul class="tabs-menu" rel="{ref}">
{content}
</ul>
</div>
"""
link: """
<li style="width:{width}%;"><a href="#" data-tab-target="{target}" data-tab-reference="{ref}"><i class="{icon}"></i>{text}</a></li>
"""
###
Retorna a variavel unica para a instacia do objeto
@return [Joker.Tab]
###
@getInstance: ->
Joker.Tab.instance = new Joker.Tab() unless Joker.Tab.instance?
Joker.Tab.instance |
[
{
"context": "ifornia, based in New York, New York',\n name: 'Dustin Yellin',\n href: '/artist/dustin-yellin',\n biograph",
"end": 170,
"score": 0.9998834729194641,
"start": 157,
"tag": "NAME",
"value": "Dustin Yellin"
},
{
"context": " href: '/artist/dustin-yellin',\n ... | desktop/apps/artwork/components/related_artists/test/artists_fixture.coffee | dblock/force | 1 | { fabricate } = require 'antigravity'
module.exports =
[
bio: 'American, born 1975, Los Angeles, California, based in New York, New York',
name: 'Dustin Yellin',
href: '/artist/dustin-yellin',
biography: 'Dustin Yellin is as known for his image-rich sculptures as he is for his entrepreneurship'
exhibition_highlights: null
articles: [
{
thumbnail_image: {
href: '/image1.jpg'
cropped:
url: '/images/image_1.jpg'
},
href: '/article/the-art-genome-project-10-artists-who-defied-classification-in-2015',
title: '10 Artists Who Defied Classification in 2015',
author: { name: 'Artsy Editoral' }
},
{
thumbnail_image: {
href: '/image2.jpg'
cropped:
url: '/images/image_2.jpg'
},
href: '/article/editorial-dustin-yellin-and-eric-fischls-two-person-show',
title: 'Dustin Yellin and Eric Fischl’s Two-Person Show Reconsiders the Human Figure',
author: { name: 'Artsy Editoral' }
},
{
thumbnail_image: {
href: '/image3.jpg'
cropped:
url: '/images/image_1.jpg'
},
href: '/article/theavgd-eddie-brannan-and-dustin-yellin-from',
title: 'Eddie Brannan & Dustin Yellin - From Manhattan to Red Hook',
author: { name: 'Artsy Editoral' }
}
]
artists: [
{
"id": "james-rosenquist",
"name": "James Rosenquist",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2F3VUm07DpKQNQdA_QfCrPcA%2Flarge.jpg"
}
},
"birthday": "1933",
"nationality": "American",
"years": "born 1933",
"counts": {
"artworks": 106,
"for_sale_artworks": 92
},
"href": "/artist/james-rosenquist"
},
{
"id": "tom-wesselmann",
"name": "Tom Wesselmann",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2F8smV519M1L352CTihrfW7A%2Flarge.jpg"
}
},
"birthday": "1931",
"nationality": "American",
"years": "1931-2004",
"counts": {
"artworks": 188,
"for_sale_artworks": 148
},
"href": "/artist/tom-wesselmann"
},
{
"id": "roy-lichtenstein",
"name": "Roy Lichtenstein",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2For9oKva9F7V4VjrUKKx2iA%2Flarge.jpg"
}
},
"birthday": "1923",
"nationality": "American",
"years": "1923-1997",
"counts": {
"artworks": 327,
"for_sale_artworks": 202
},
"href": "/artist/roy-lichtenstein"
},
{
"id": "robert-indiana",
"name": "Robert Indiana",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FxPV7zLtiKJPPxRVJTEtHIA%2Flarge.jpg"
}
},
"birthday": "1928",
"nationality": "American",
"years": "born 1928",
"counts": {
"artworks": 196,
"for_sale_artworks": 163
},
"href": "/artist/robert-indiana"
},
{
"id": "jim-dine",
"name": "Jim Dine",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FLl4gMf_OsLMehbgv05H6mw%2Flarge.jpg"
}
},
"birthday": "1935",
"nationality": "American",
"years": "born 1935",
"counts": {
"artworks": 353,
"for_sale_artworks": 313
},
"href": "/artist/jim-dine"
},
{
"id": "claes-oldenburg-and-coosje-van-bruggen",
"name": "Claes Oldenburg & Coosje van Bruggen",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FlnJopeqKO7np6fvqpegQpQ%2Flarge.jpg"
}
},
"birthday": "1929 and 1942",
"nationality": "American",
"years": "1929 and 1942",
"counts": {
"artworks": 10,
"for_sale_artworks": 9
},
"href": "/artist/claes-oldenburg-and-coosje-van-bruggen"
},
{
"id": "richard-hamilton",
"name": "Richard Hamilton",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FCqLm5-pqOP2wlCcXoxTkhw%2Flarge.jpg"
}
},
"birthday": "1922",
"nationality": "British",
"years": "1922-2011",
"counts": {
"artworks": 62,
"for_sale_artworks": 43
},
"href": "/artist/richard-hamilton"
}
]
]
| 32241 | { fabricate } = require 'antigravity'
module.exports =
[
bio: 'American, born 1975, Los Angeles, California, based in New York, New York',
name: '<NAME>',
href: '/artist/dustin-yellin',
biography: '<NAME> is as known for his image-rich sculptures as he is for his entrepreneurship'
exhibition_highlights: null
articles: [
{
thumbnail_image: {
href: '/image1.jpg'
cropped:
url: '/images/image_1.jpg'
},
href: '/article/the-art-genome-project-10-artists-who-defied-classification-in-2015',
title: '10 Artists Who Defied Classification in 2015',
author: { name: 'Artsy Editoral' }
},
{
thumbnail_image: {
href: '/image2.jpg'
cropped:
url: '/images/image_2.jpg'
},
href: '/article/editorial-dustin-yellin-and-eric-fischls-two-person-show',
title: '<NAME> and <NAME>’s Two-Person Show Reconsiders the Human Figure',
author: { name: 'Artsy Editoral' }
},
{
thumbnail_image: {
href: '/image3.jpg'
cropped:
url: '/images/image_1.jpg'
},
href: '/article/theavgd-eddie-brannan-and-dustin-yellin-from',
title: '<NAME> & <NAME> - From Manhattan to Red Hook',
author: { name: 'Artsy Editoral' }
}
]
artists: [
{
"id": "james-rosenquist",
"name": "<NAME>",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2F3VUm07DpKQNQdA_QfCrPcA%2Flarge.jpg"
}
},
"birthday": "1933",
"nationality": "American",
"years": "born 1933",
"counts": {
"artworks": 106,
"for_sale_artworks": 92
},
"href": "/artist/james-rosenquist"
},
{
"id": "tom-wesselmann",
"name": "<NAME>",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2F8smV519M1L352CTihrfW7A%2Flarge.jpg"
}
},
"birthday": "1931",
"nationality": "American",
"years": "1931-2004",
"counts": {
"artworks": 188,
"for_sale_artworks": 148
},
"href": "/artist/tom-wesselmann"
},
{
"id": "roy-lichtenstein",
"name": "<NAME>",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2For9oKva9F7V4VjrUKKx2iA%2Flarge.jpg"
}
},
"birthday": "1923",
"nationality": "American",
"years": "1923-1997",
"counts": {
"artworks": 327,
"for_sale_artworks": 202
},
"href": "/artist/roy-lichtenstein"
},
{
"id": "robert-indiana",
"name": "<NAME>",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FxPV7zLtiKJPPxRVJTEtHIA%2Flarge.jpg"
}
},
"birthday": "1928",
"nationality": "American",
"years": "born 1928",
"counts": {
"artworks": 196,
"for_sale_artworks": 163
},
"href": "/artist/robert-indiana"
},
{
"id": "jim-dine",
"name": "<NAME>",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FLl4gMf_OsLMehbgv05H6mw%2Flarge.jpg"
}
},
"birthday": "1935",
"nationality": "American",
"years": "born 1935",
"counts": {
"artworks": 353,
"for_sale_artworks": 313
},
"href": "/artist/jim-dine"
},
{
"id": "<NAME>es-oldenburg-and-coosje-van-bruggen",
"name": "<NAME> & <NAME>",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FlnJopeqKO7np6fvqpegQpQ%2Flarge.jpg"
}
},
"birthday": "1929 and 1942",
"nationality": "American",
"years": "1929 and 1942",
"counts": {
"artworks": 10,
"for_sale_artworks": 9
},
"href": "/artist/claes-oldenburg-and-coosje-van-bruggen"
},
{
"id": "richard-hamilton",
"name": "<NAME>",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FCqLm5-pqOP2wlCcXoxTkhw%2Flarge.jpg"
}
},
"birthday": "1922",
"nationality": "British",
"years": "1922-2011",
"counts": {
"artworks": 62,
"for_sale_artworks": 43
},
"href": "/artist/richard-hamilton"
}
]
]
| true | { fabricate } = require 'antigravity'
module.exports =
[
bio: 'American, born 1975, Los Angeles, California, based in New York, New York',
name: 'PI:NAME:<NAME>END_PI',
href: '/artist/dustin-yellin',
biography: 'PI:NAME:<NAME>END_PI is as known for his image-rich sculptures as he is for his entrepreneurship'
exhibition_highlights: null
articles: [
{
thumbnail_image: {
href: '/image1.jpg'
cropped:
url: '/images/image_1.jpg'
},
href: '/article/the-art-genome-project-10-artists-who-defied-classification-in-2015',
title: '10 Artists Who Defied Classification in 2015',
author: { name: 'Artsy Editoral' }
},
{
thumbnail_image: {
href: '/image2.jpg'
cropped:
url: '/images/image_2.jpg'
},
href: '/article/editorial-dustin-yellin-and-eric-fischls-two-person-show',
title: 'PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI’s Two-Person Show Reconsiders the Human Figure',
author: { name: 'Artsy Editoral' }
},
{
thumbnail_image: {
href: '/image3.jpg'
cropped:
url: '/images/image_1.jpg'
},
href: '/article/theavgd-eddie-brannan-and-dustin-yellin-from',
title: 'PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI - From Manhattan to Red Hook',
author: { name: 'Artsy Editoral' }
}
]
artists: [
{
"id": "james-rosenquist",
"name": "PI:NAME:<NAME>END_PI",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2F3VUm07DpKQNQdA_QfCrPcA%2Flarge.jpg"
}
},
"birthday": "1933",
"nationality": "American",
"years": "born 1933",
"counts": {
"artworks": 106,
"for_sale_artworks": 92
},
"href": "/artist/james-rosenquist"
},
{
"id": "tom-wesselmann",
"name": "PI:NAME:<NAME>END_PI",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2F8smV519M1L352CTihrfW7A%2Flarge.jpg"
}
},
"birthday": "1931",
"nationality": "American",
"years": "1931-2004",
"counts": {
"artworks": 188,
"for_sale_artworks": 148
},
"href": "/artist/tom-wesselmann"
},
{
"id": "roy-lichtenstein",
"name": "PI:NAME:<NAME>END_PI",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2For9oKva9F7V4VjrUKKx2iA%2Flarge.jpg"
}
},
"birthday": "1923",
"nationality": "American",
"years": "1923-1997",
"counts": {
"artworks": 327,
"for_sale_artworks": 202
},
"href": "/artist/roy-lichtenstein"
},
{
"id": "robert-indiana",
"name": "PI:NAME:<NAME>END_PI",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FxPV7zLtiKJPPxRVJTEtHIA%2Flarge.jpg"
}
},
"birthday": "1928",
"nationality": "American",
"years": "born 1928",
"counts": {
"artworks": 196,
"for_sale_artworks": 163
},
"href": "/artist/robert-indiana"
},
{
"id": "jim-dine",
"name": "PI:NAME:<NAME>END_PI",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FLl4gMf_OsLMehbgv05H6mw%2Flarge.jpg"
}
},
"birthday": "1935",
"nationality": "American",
"years": "born 1935",
"counts": {
"artworks": 353,
"for_sale_artworks": 313
},
"href": "/artist/jim-dine"
},
{
"id": "PI:NAME:<NAME>END_PIes-oldenburg-and-coosje-van-bruggen",
"name": "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FlnJopeqKO7np6fvqpegQpQ%2Flarge.jpg"
}
},
"birthday": "1929 and 1942",
"nationality": "American",
"years": "1929 and 1942",
"counts": {
"artworks": 10,
"for_sale_artworks": 9
},
"href": "/artist/claes-oldenburg-and-coosje-van-bruggen"
},
{
"id": "richard-hamilton",
"name": "PI:NAME:<NAME>END_PI",
"image": {
"cropped": {
"url": "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&width=400&height=300&quality=95&src=https%3A%2F%2Fd32dm0rphc51dk.cloudfront.net%2FCqLm5-pqOP2wlCcXoxTkhw%2Flarge.jpg"
}
},
"birthday": "1922",
"nationality": "British",
"years": "1922-2011",
"counts": {
"artworks": 62,
"for_sale_artworks": 43
},
"href": "/artist/richard-hamilton"
}
]
]
|
[
{
"context": "# Author: Connor Beardsmore <connor.beardsmore@gmail.com>\n# Last Modified: 22",
"end": 27,
"score": 0.9998863339424133,
"start": 10,
"tag": "NAME",
"value": "Connor Beardsmore"
},
{
"context": "# Author: Connor Beardsmore <connor.beardsmore@gmail.com>\n# Last Modified:... | Upcoming-iCal-Events.widget/main.coffee | cbeardsmore/UpcomingEvents | 8 | # Author: Connor Beardsmore <connor.beardsmore@gmail.com>
# Last Modified: 22/03/18
# Customisations
# Refresh Frequency
REFRESH_FREQUENCY = "1h"
# Number of days shown from today.
NO_DAYS_TO_SHOW = 2
# Show which calendar you pulled from before event name.
SHOW_CALENDER = false
# Ignore specific calendars.
IGNORE_CALENDERS = [
'name/UUID of thecalendar to ignore',
'other calendar etc'
]
# Show full date including time.
SHOW_DATE_TIME = true
# Characters after this value will be replaced with ...
MAX_CHARACTERS = 50
# Use date for day after tomorrow.
USE_DATE_AS_SUBHEADING = false
# Label for all day events
ALL_DAY_EVENT_LABEL = 'All Day'
# Construct bash command using options.
# icalBuddy has more functionality that can be used here.
# Refer to https://hasseg.org/icalBuddy/man.html
executablePath = "/usr/local/bin/icalBuddy "
baseCommand = ' eventsToday' + '+' + NO_DAYS_TO_SHOW
options = "-n -eed -tf '%I:%M %p' "
if IGNORE_CALENDERS
options = options + '-ec ' + IGNORE_CALENDERS.join(',')
# Bash command to pull events from icalBuddy
command: executablePath + options + baseCommand
# Update is called once per hour
refreshFrequency: REFRESH_FREQUENCY
# CSS styling
style: """
top: 10px
top: 1.3%
right: 1%
color: black
font-family: Helvetica
background-color rgba(black, 0.5)
padding 15px
border-radius 5px
div
display: block
color white
font-size: 14px
font-weight: 450
text-align left
#head
font-weight: bold
font-size 20px
#subhead
font-weight: bold
font-size 16px
border-bottom solid 1px clear
padding-top 6px
padding-bottom 3px
"""
# Initial render for heading
render: (output) -> """
"""
# Update when refresh occurs
update: (output, domEl) ->
dateRegex = '\\d{2}-[a-zA-Z]{3}-\\d{4}'
lines = output.split('\n')
bullet = lines[0][0]
dom = $(domEl)
dom.empty()
dom.append("""<div id="head"> Upcoming Events </div>""")
# Filter out all lines that aren't event headers or dates
lines = lines.filter (x) -> (
( x.startsWith(bullet) ) ||
( x.search('(today|tomorrow)') != -1 ) ||
( x.search(dateRegex) != -1 )
)
#Add No Events tag if nothing upcoming
if ( lines.length == 0 )
# Don't add tag twice
if (! dom.text().includes("No Events"))
dom.append(""" <div id="subhead"> No Events </div> """)
return
# Go over all events and append data into the DOM
for i in [0...lines.length-1]
# Print today subheading
header = ""
day = ''
if (lines[i+1].startsWith(" today"))
if (! dom.text().includes('Today'))
header = 'Today'
# Print tomorrow subheading
else if ( lines[i+1].startsWith(" tomorrow") )
if (! dom.text().includes('Tomorrow'))
header = 'Tomorrow'
# Print day after tomorrow subheading
else if ( lines[i+1].startsWith(" day after"))
if (!dom.text().includes('Day After Tomorrow'))
header = 'Day After Tomorrow'
# Print later subheading
else if ( lines[i+1].search(dateRegex) != -1 )
day = lines[i+1].trim().substr(0,11)
dayHeader = if USE_DATE_AS_SUBHEADING then day else 'Later'
if (!dom.text().includes(dayHeader))
header = dayHeader
# If required add in the header
if (header != "")
dom.append("""<div id="subhead">#{header}</div> """)
# Events start with bullet point
if (lines[i][0] == bullet)
nameAndCalendar = lines[i].split('(')
if nameAndCalendar.length < 2
continue
name = nameAndCalendar[0].replace(bullet, '')
calendar = 'No Calendar'
if nameAndCalendar[1] != undefined
calendar = nameAndCalendar[1].replace(')','')
if ( name.length > MAX_CHARACTERS )
name = name.substr(0, MAX_CHARACTERS) + "..."
datePrefix = if (day && not USE_DATE_AS_SUBHEADING) then day + ' ' else ''
date = ((lines[i+1].split("at"))[1])
if !date?
date = ALL_DAY_EVENT_LABEL
# Combine all fields
final = name
if SHOW_DATE_TIME
final = datePrefix + date + " - " + final
if SHOW_CALENDER
final = calendar + " - " + final
# Add this HTML to previous
dom.append("""<div>#{final}</div>""")
| 53653 | # Author: <NAME> <<EMAIL>>
# Last Modified: 22/03/18
# Customisations
# Refresh Frequency
REFRESH_FREQUENCY = "1h"
# Number of days shown from today.
NO_DAYS_TO_SHOW = 2
# Show which calendar you pulled from before event name.
SHOW_CALENDER = false
# Ignore specific calendars.
IGNORE_CALENDERS = [
'name/UUID of thecalendar to ignore',
'other calendar etc'
]
# Show full date including time.
SHOW_DATE_TIME = true
# Characters after this value will be replaced with ...
MAX_CHARACTERS = 50
# Use date for day after tomorrow.
USE_DATE_AS_SUBHEADING = false
# Label for all day events
ALL_DAY_EVENT_LABEL = 'All Day'
# Construct bash command using options.
# icalBuddy has more functionality that can be used here.
# Refer to https://hasseg.org/icalBuddy/man.html
executablePath = "/usr/local/bin/icalBuddy "
baseCommand = ' eventsToday' + '+' + NO_DAYS_TO_SHOW
options = "-n -eed -tf '%I:%M %p' "
if IGNORE_CALENDERS
options = options + '-ec ' + IGNORE_CALENDERS.join(',')
# Bash command to pull events from icalBuddy
command: executablePath + options + baseCommand
# Update is called once per hour
refreshFrequency: REFRESH_FREQUENCY
# CSS styling
style: """
top: 10px
top: 1.3%
right: 1%
color: black
font-family: Helvetica
background-color rgba(black, 0.5)
padding 15px
border-radius 5px
div
display: block
color white
font-size: 14px
font-weight: 450
text-align left
#head
font-weight: bold
font-size 20px
#subhead
font-weight: bold
font-size 16px
border-bottom solid 1px clear
padding-top 6px
padding-bottom 3px
"""
# Initial render for heading
render: (output) -> """
"""
# Update when refresh occurs
update: (output, domEl) ->
dateRegex = '\\d{2}-[a-zA-Z]{3}-\\d{4}'
lines = output.split('\n')
bullet = lines[0][0]
dom = $(domEl)
dom.empty()
dom.append("""<div id="head"> Upcoming Events </div>""")
# Filter out all lines that aren't event headers or dates
lines = lines.filter (x) -> (
( x.startsWith(bullet) ) ||
( x.search('(today|tomorrow)') != -1 ) ||
( x.search(dateRegex) != -1 )
)
#Add No Events tag if nothing upcoming
if ( lines.length == 0 )
# Don't add tag twice
if (! dom.text().includes("No Events"))
dom.append(""" <div id="subhead"> No Events </div> """)
return
# Go over all events and append data into the DOM
for i in [0...lines.length-1]
# Print today subheading
header = ""
day = ''
if (lines[i+1].startsWith(" today"))
if (! dom.text().includes('Today'))
header = 'Today'
# Print tomorrow subheading
else if ( lines[i+1].startsWith(" tomorrow") )
if (! dom.text().includes('Tomorrow'))
header = 'Tomorrow'
# Print day after tomorrow subheading
else if ( lines[i+1].startsWith(" day after"))
if (!dom.text().includes('Day After Tomorrow'))
header = 'Day After Tomorrow'
# Print later subheading
else if ( lines[i+1].search(dateRegex) != -1 )
day = lines[i+1].trim().substr(0,11)
dayHeader = if USE_DATE_AS_SUBHEADING then day else 'Later'
if (!dom.text().includes(dayHeader))
header = dayHeader
# If required add in the header
if (header != "")
dom.append("""<div id="subhead">#{header}</div> """)
# Events start with bullet point
if (lines[i][0] == bullet)
nameAndCalendar = lines[i].split('(')
if nameAndCalendar.length < 2
continue
name = nameAndCalendar[0].replace(bullet, '')
calendar = 'No Calendar'
if nameAndCalendar[1] != undefined
calendar = nameAndCalendar[1].replace(')','')
if ( name.length > MAX_CHARACTERS )
name = name.substr(0, MAX_CHARACTERS) + "..."
datePrefix = if (day && not USE_DATE_AS_SUBHEADING) then day + ' ' else ''
date = ((lines[i+1].split("at"))[1])
if !date?
date = ALL_DAY_EVENT_LABEL
# Combine all fields
final = name
if SHOW_DATE_TIME
final = datePrefix + date + " - " + final
if SHOW_CALENDER
final = calendar + " - " + final
# Add this HTML to previous
dom.append("""<div>#{final}</div>""")
| true | # Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Last Modified: 22/03/18
# Customisations
# Refresh Frequency
REFRESH_FREQUENCY = "1h"
# Number of days shown from today.
NO_DAYS_TO_SHOW = 2
# Show which calendar you pulled from before event name.
SHOW_CALENDER = false
# Ignore specific calendars.
IGNORE_CALENDERS = [
'name/UUID of thecalendar to ignore',
'other calendar etc'
]
# Show full date including time.
SHOW_DATE_TIME = true
# Characters after this value will be replaced with ...
MAX_CHARACTERS = 50
# Use date for day after tomorrow.
USE_DATE_AS_SUBHEADING = false
# Label for all day events
ALL_DAY_EVENT_LABEL = 'All Day'
# Construct bash command using options.
# icalBuddy has more functionality that can be used here.
# Refer to https://hasseg.org/icalBuddy/man.html
executablePath = "/usr/local/bin/icalBuddy "
baseCommand = ' eventsToday' + '+' + NO_DAYS_TO_SHOW
options = "-n -eed -tf '%I:%M %p' "
if IGNORE_CALENDERS
options = options + '-ec ' + IGNORE_CALENDERS.join(',')
# Bash command to pull events from icalBuddy
command: executablePath + options + baseCommand
# Update is called once per hour
refreshFrequency: REFRESH_FREQUENCY
# CSS styling
style: """
top: 10px
top: 1.3%
right: 1%
color: black
font-family: Helvetica
background-color rgba(black, 0.5)
padding 15px
border-radius 5px
div
display: block
color white
font-size: 14px
font-weight: 450
text-align left
#head
font-weight: bold
font-size 20px
#subhead
font-weight: bold
font-size 16px
border-bottom solid 1px clear
padding-top 6px
padding-bottom 3px
"""
# Initial render for heading
render: (output) -> """
"""
# Update when refresh occurs
update: (output, domEl) ->
dateRegex = '\\d{2}-[a-zA-Z]{3}-\\d{4}'
lines = output.split('\n')
bullet = lines[0][0]
dom = $(domEl)
dom.empty()
dom.append("""<div id="head"> Upcoming Events </div>""")
# Filter out all lines that aren't event headers or dates
lines = lines.filter (x) -> (
( x.startsWith(bullet) ) ||
( x.search('(today|tomorrow)') != -1 ) ||
( x.search(dateRegex) != -1 )
)
#Add No Events tag if nothing upcoming
if ( lines.length == 0 )
# Don't add tag twice
if (! dom.text().includes("No Events"))
dom.append(""" <div id="subhead"> No Events </div> """)
return
# Go over all events and append data into the DOM
for i in [0...lines.length-1]
# Print today subheading
header = ""
day = ''
if (lines[i+1].startsWith(" today"))
if (! dom.text().includes('Today'))
header = 'Today'
# Print tomorrow subheading
else if ( lines[i+1].startsWith(" tomorrow") )
if (! dom.text().includes('Tomorrow'))
header = 'Tomorrow'
# Print day after tomorrow subheading
else if ( lines[i+1].startsWith(" day after"))
if (!dom.text().includes('Day After Tomorrow'))
header = 'Day After Tomorrow'
# Print later subheading
else if ( lines[i+1].search(dateRegex) != -1 )
day = lines[i+1].trim().substr(0,11)
dayHeader = if USE_DATE_AS_SUBHEADING then day else 'Later'
if (!dom.text().includes(dayHeader))
header = dayHeader
# If required add in the header
if (header != "")
dom.append("""<div id="subhead">#{header}</div> """)
# Events start with bullet point
if (lines[i][0] == bullet)
nameAndCalendar = lines[i].split('(')
if nameAndCalendar.length < 2
continue
name = nameAndCalendar[0].replace(bullet, '')
calendar = 'No Calendar'
if nameAndCalendar[1] != undefined
calendar = nameAndCalendar[1].replace(')','')
if ( name.length > MAX_CHARACTERS )
name = name.substr(0, MAX_CHARACTERS) + "..."
datePrefix = if (day && not USE_DATE_AS_SUBHEADING) then day + ' ' else ''
date = ((lines[i+1].split("at"))[1])
if !date?
date = ALL_DAY_EVENT_LABEL
# Combine all fields
final = name
if SHOW_DATE_TIME
final = datePrefix + date + " - " + final
if SHOW_CALENDER
final = calendar + " - " + final
# Add this HTML to previous
dom.append("""<div>#{final}</div>""")
|
[
{
"context": " heardAbout: 'magical interwebs'\n firstName: 'First'\n lastName: 'Last'\n}\n\nsetupTeacher = co.wrap (",
"end": 854,
"score": 0.9996407628059387,
"start": 849,
"tag": "NAME",
"value": "First"
},
{
"context": " interwebs'\n firstName: 'First'\n lastName: 'L... | spec/server/functional/delighted.spec.coffee | johanvl/codecombat | 1 | require '../common'
utils = require '../utils'
_ = require 'lodash'
Promise = require 'bluebird'
User = require '../../../server/models/User'
TrialRequest = require '../../../server/models/TrialRequest'
Prepaid = require '../../../server/models/Prepaid'
Classroom = require '../../../server/models/Classroom'
Course = require '../../../server/models/Course'
CourseInstance = require '../../../server/models/CourseInstance'
Campaign = require '../../../server/models/Campaign'
LevelSession = require '../../../server/models/LevelSession'
Level = require '../../../server/models/Level'
request = require '../request'
delighted = require '../../../server/delighted'
co = require 'co'
trialRequestFixture = {
type: 'course'
properties:
location: 'SF, CA'
age: '14-17'
numStudents: 14
heardAbout: 'magical interwebs'
firstName: 'First'
lastName: 'Last'
}
setupTeacher = co.wrap (trialRequestData) ->
fixture = _.cloneDeep(trialRequestData)
user = yield utils.initUser({gender: 'male', lastLevel: 'abcd', preferredLanguage: 'en', testGroupNumber: 1, role: 'teacher'})
yield utils.loginUser(user)
fixture.properties.email ?= user.get('email')
fixture.properties.country ?= 'USA'
fixture.type ?= 'course'
[res, body] = yield request.postAsync(getURL('/db/trial.request'), { json: fixture })
expect(delighted.postPeople).not.toHaveBeenCalled()
user
makeClassroom = co.wrap (user, name) ->
data = { name: name }
[res, body] = yield request.postAsync {uri: getURL('/db/classroom'), json: data }
expect(res.statusCode).toBe(201)
expect(res.body.name).toBe(name)
expect(res.body.members.length).toBe(0)
expect(res.body.ownerID).toBe(user.id)
describe 'delighted', ->
beforeEach utils.wrap ->
yield utils.clearModels([User, TrialRequest, User, Classroom, Course, Level, Campaign])
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
campaignJSON = { name: 'Campaign', levels: {} }
[res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSON})
@campaign = yield Campaign.findById(res.body._id)
@course = Course({name: 'Course', campaignID: @campaign._id, releasePhase: 'released'})
yield @course.save()
spyOn(delighted, 'postPeople')
it 'no longer creates a profile trial creation', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
it 'creates a profile when the first class is created', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
# Add class one
yield makeClassroom @user, "Classroom 1"
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('engaged')
# Add reset
delighted.postPeople.calls.reset()
#Add class two
yield makeClassroom @user, "Classroom 2"
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'does not create a profile in Germany', utils.wrap ->
fixture = _.cloneDeep(trialRequestFixture)
fixture.properties.country = 'Germany'
@user = yield setupTeacher fixture
yield makeClassroom @user, "Classroom 1"
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'creates a profile when the first course prepaid is added', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'course'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('paid full')
delighted.postPeople.calls.reset()
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'course'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'creates a profile when the first starter prepaid is added', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'starter_license'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('paid starter')
delighted.postPeople.calls.reset()
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'starter_license'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).not.toHaveBeenCalled()
| 204815 | require '../common'
utils = require '../utils'
_ = require 'lodash'
Promise = require 'bluebird'
User = require '../../../server/models/User'
TrialRequest = require '../../../server/models/TrialRequest'
Prepaid = require '../../../server/models/Prepaid'
Classroom = require '../../../server/models/Classroom'
Course = require '../../../server/models/Course'
CourseInstance = require '../../../server/models/CourseInstance'
Campaign = require '../../../server/models/Campaign'
LevelSession = require '../../../server/models/LevelSession'
Level = require '../../../server/models/Level'
request = require '../request'
delighted = require '../../../server/delighted'
co = require 'co'
trialRequestFixture = {
type: 'course'
properties:
location: 'SF, CA'
age: '14-17'
numStudents: 14
heardAbout: 'magical interwebs'
firstName: '<NAME>'
lastName: '<NAME>'
}
setupTeacher = co.wrap (trialRequestData) ->
fixture = _.cloneDeep(trialRequestData)
user = yield utils.initUser({gender: 'male', lastLevel: 'abcd', preferredLanguage: 'en', testGroupNumber: 1, role: 'teacher'})
yield utils.loginUser(user)
fixture.properties.email ?= user.get('email')
fixture.properties.country ?= 'USA'
fixture.type ?= 'course'
[res, body] = yield request.postAsync(getURL('/db/trial.request'), { json: fixture })
expect(delighted.postPeople).not.toHaveBeenCalled()
user
makeClassroom = co.wrap (user, name) ->
data = { name: name }
[res, body] = yield request.postAsync {uri: getURL('/db/classroom'), json: data }
expect(res.statusCode).toBe(201)
expect(res.body.name).toBe(name)
expect(res.body.members.length).toBe(0)
expect(res.body.ownerID).toBe(user.id)
describe 'delighted', ->
beforeEach utils.wrap ->
yield utils.clearModels([User, TrialRequest, User, Classroom, Course, Level, Campaign])
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
campaignJSON = { name: 'Campaign', levels: {} }
[res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSON})
@campaign = yield Campaign.findById(res.body._id)
@course = Course({name: 'Course', campaignID: @campaign._id, releasePhase: 'released'})
yield @course.save()
spyOn(delighted, 'postPeople')
it 'no longer creates a profile trial creation', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
it 'creates a profile when the first class is created', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
# Add class one
yield makeClassroom @user, "Classroom 1"
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('engaged')
# Add reset
delighted.postPeople.calls.reset()
#Add class two
yield makeClassroom @user, "Classroom 2"
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'does not create a profile in Germany', utils.wrap ->
fixture = _.cloneDeep(trialRequestFixture)
fixture.properties.country = 'Germany'
@user = yield setupTeacher fixture
yield makeClassroom @user, "Classroom 1"
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'creates a profile when the first course prepaid is added', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'course'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('paid full')
delighted.postPeople.calls.reset()
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'course'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'creates a profile when the first starter prepaid is added', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'starter_license'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('paid starter')
delighted.postPeople.calls.reset()
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'starter_license'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).not.toHaveBeenCalled()
| true | require '../common'
utils = require '../utils'
_ = require 'lodash'
Promise = require 'bluebird'
User = require '../../../server/models/User'
TrialRequest = require '../../../server/models/TrialRequest'
Prepaid = require '../../../server/models/Prepaid'
Classroom = require '../../../server/models/Classroom'
Course = require '../../../server/models/Course'
CourseInstance = require '../../../server/models/CourseInstance'
Campaign = require '../../../server/models/Campaign'
LevelSession = require '../../../server/models/LevelSession'
Level = require '../../../server/models/Level'
request = require '../request'
delighted = require '../../../server/delighted'
co = require 'co'
trialRequestFixture = {
type: 'course'
properties:
location: 'SF, CA'
age: '14-17'
numStudents: 14
heardAbout: 'magical interwebs'
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
}
setupTeacher = co.wrap (trialRequestData) ->
fixture = _.cloneDeep(trialRequestData)
user = yield utils.initUser({gender: 'male', lastLevel: 'abcd', preferredLanguage: 'en', testGroupNumber: 1, role: 'teacher'})
yield utils.loginUser(user)
fixture.properties.email ?= user.get('email')
fixture.properties.country ?= 'USA'
fixture.type ?= 'course'
[res, body] = yield request.postAsync(getURL('/db/trial.request'), { json: fixture })
expect(delighted.postPeople).not.toHaveBeenCalled()
user
makeClassroom = co.wrap (user, name) ->
data = { name: name }
[res, body] = yield request.postAsync {uri: getURL('/db/classroom'), json: data }
expect(res.statusCode).toBe(201)
expect(res.body.name).toBe(name)
expect(res.body.members.length).toBe(0)
expect(res.body.ownerID).toBe(user.id)
describe 'delighted', ->
beforeEach utils.wrap ->
yield utils.clearModels([User, TrialRequest, User, Classroom, Course, Level, Campaign])
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
campaignJSON = { name: 'Campaign', levels: {} }
[res, body] = yield request.postAsync({uri: getURL('/db/campaign'), json: campaignJSON})
@campaign = yield Campaign.findById(res.body._id)
@course = Course({name: 'Course', campaignID: @campaign._id, releasePhase: 'released'})
yield @course.save()
spyOn(delighted, 'postPeople')
it 'no longer creates a profile trial creation', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
it 'creates a profile when the first class is created', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
# Add class one
yield makeClassroom @user, "Classroom 1"
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('engaged')
# Add reset
delighted.postPeople.calls.reset()
#Add class two
yield makeClassroom @user, "Classroom 2"
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'does not create a profile in Germany', utils.wrap ->
fixture = _.cloneDeep(trialRequestFixture)
fixture.properties.country = 'Germany'
@user = yield setupTeacher fixture
yield makeClassroom @user, "Classroom 1"
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'creates a profile when the first course prepaid is added', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'course'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('paid full')
delighted.postPeople.calls.reset()
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'course'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).not.toHaveBeenCalled()
it 'creates a profile when the first starter prepaid is added', utils.wrap ->
@user = yield setupTeacher trialRequestFixture
admin = yield utils.initAdmin()
yield utils.loginUser(admin)
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'starter_license'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).toHaveBeenCalled()
delightedProps = delighted.postPeople.calls.first().args[0]
expect(delightedProps.delay).toBe(3600 * 24 * 7)
expect(delightedProps.properties.status).toBe('paid starter')
delighted.postPeople.calls.reset()
[res, body] = yield request.postAsync({url: getURL('/db/prepaid'), json: {
type: 'starter_license'
creator: @user.id
}})
expect(res.statusCode).toBe(201)
prepaid = yield Prepaid.findById(res.body._id)
expect(prepaid).toBeDefined()
expect(prepaid.get('creator').equals(@user._id)).toBe(true)
expect(prepaid.get('code')).toBeDefined()
expect(delighted.postPeople).not.toHaveBeenCalled()
|
[
{
"context": "id: 0, active: true, facebookId: 0, notes: \"Met at Alice'ss\"}\n {id: 1, active: true, linkedinId: 1, not",
"end": 86,
"score": 0.9993594288825989,
"start": 81,
"tag": "NAME",
"value": "Alice"
},
{
"context": "id: 1, active: true, linkedinId: 1, notes: \"Met at Bob'... | test/helpers/fixtures.coffee | jamesknelson/angular-deputy | 1 | fixtures =
contacts: [
{id: 0, active: true, facebookId: 0, notes: "Met at Alice'ss"}
{id: 1, active: true, linkedinId: 1, notes: "Met at Bob's"}
{id: 2, active: false, linkedinId: 5, facebookId: 6, notes: "Met at Charlie's"}
]
questions: [
{id: 0, type: "import", question: "What is this person's name?"}
{id: 1, type: "custom", question: "What is this person's birthday?"}
]
cards: [
{id: 0, active: true, questionId: 0, contactId: 0, answer: 'Dave'}
{id: 1, active: true, questionId: 1, contactId: 0, answer: 'February 30th 2088'}
{id: 2, active: false, questionId: 0, contactId: 1, answer: 'Esther'}
{id: 3, active: true, questionId: 1, contactId: 1, answer: 'Hundreds of years BC'}
{id: 4, active: true, questionId: 0, contactId: 2, answer: 'Fred'}
{id: 5, active: true, questionId: 1, contactId: 2, answer: 'Yesterday'}
]
do (fixtures) ->
buildFixtureIndexes = (name) ->
fixtures[name+'ById'] = {}
fixtures[name].forEach (r) -> fixtures[name+'ById'][r.id] = r
buildFixtureIndexes('contacts')
buildFixtureIndexes('questions')
buildFixtureIndexes('cards')
null | 88367 | fixtures =
contacts: [
{id: 0, active: true, facebookId: 0, notes: "Met at <NAME>'ss"}
{id: 1, active: true, linkedinId: 1, notes: "Met at <NAME>'s"}
{id: 2, active: false, linkedinId: 5, facebookId: 6, notes: "Met at <NAME>'s"}
]
questions: [
{id: 0, type: "import", question: "What is this person's name?"}
{id: 1, type: "custom", question: "What is this person's birthday?"}
]
cards: [
{id: 0, active: true, questionId: 0, contactId: 0, answer: '<NAME>'}
{id: 1, active: true, questionId: 1, contactId: 0, answer: 'February 30th 2088'}
{id: 2, active: false, questionId: 0, contactId: 1, answer: '<NAME>'}
{id: 3, active: true, questionId: 1, contactId: 1, answer: 'Hundreds of years BC'}
{id: 4, active: true, questionId: 0, contactId: 2, answer: '<NAME>'}
{id: 5, active: true, questionId: 1, contactId: 2, answer: 'Yesterday'}
]
do (fixtures) ->
buildFixtureIndexes = (name) ->
fixtures[name+'ById'] = {}
fixtures[name].forEach (r) -> fixtures[name+'ById'][r.id] = r
buildFixtureIndexes('contacts')
buildFixtureIndexes('questions')
buildFixtureIndexes('cards')
null | true | fixtures =
contacts: [
{id: 0, active: true, facebookId: 0, notes: "Met at PI:NAME:<NAME>END_PI'ss"}
{id: 1, active: true, linkedinId: 1, notes: "Met at PI:NAME:<NAME>END_PI's"}
{id: 2, active: false, linkedinId: 5, facebookId: 6, notes: "Met at PI:NAME:<NAME>END_PI's"}
]
questions: [
{id: 0, type: "import", question: "What is this person's name?"}
{id: 1, type: "custom", question: "What is this person's birthday?"}
]
cards: [
{id: 0, active: true, questionId: 0, contactId: 0, answer: 'PI:NAME:<NAME>END_PI'}
{id: 1, active: true, questionId: 1, contactId: 0, answer: 'February 30th 2088'}
{id: 2, active: false, questionId: 0, contactId: 1, answer: 'PI:NAME:<NAME>END_PI'}
{id: 3, active: true, questionId: 1, contactId: 1, answer: 'Hundreds of years BC'}
{id: 4, active: true, questionId: 0, contactId: 2, answer: 'PI:NAME:<NAME>END_PI'}
{id: 5, active: true, questionId: 1, contactId: 2, answer: 'Yesterday'}
]
do (fixtures) ->
buildFixtureIndexes = (name) ->
fixtures[name+'ById'] = {}
fixtures[name].forEach (r) -> fixtures[name+'ById'][r.id] = r
buildFixtureIndexes('contacts')
buildFixtureIndexes('questions')
buildFixtureIndexes('cards')
null |
[
{
"context": "the terms of the MIT license.\n# Copyright 2012 (c) Markus Kohlhase <mail@markus-kohlhase.de>\n\nJOAP_NS = \"jabber:iq:j",
"end": 102,
"score": 0.9999006390571594,
"start": 87,
"tag": "NAME",
"value": "Markus Kohlhase"
},
{
"context": "IT license.\n# Copyright 2012 (c) ... | joap/strophe.joap.coffee | calendar42/strophejs-plugins | 0 | # This program is distributed under the terms of the MIT license.
# Copyright 2012 (c) Markus Kohlhase <mail@markus-kohlhase.de>
JOAP_NS = "jabber:iq:joap"
# Private static members
conn = null
onError = (cb=->) -> (iq) ->
err = iq.getElementsByTagName("error")[0]
if err?
code = err.getAttribute("code") * 1
msg = err.textContent
msg = "JOAP server is unavailable" if code is 503
cb iq, new JOAPError msg, code
else
cb iq, new JOAPError "Unknown error"
addXMLAttributes = (iq, attrs) ->
if typeof attrs is "object"
for k,v of attrs
iq.c("attribute")
.c("name").t(k).up()
.cnode(conn.rpc._convertToXML v).up().up()
parseAttributes = (iq) ->
attrs = iq.getElementsByTagName("attribute")
data = {}
for a in attrs
key = a.getElementsByTagName("name")[0].textContent
data[key] = conn.rpc._convertFromXML a.getElementsByTagName("value")[0]
data
parseNewAddress = (iq) ->
address = iq.getElementsByTagName("newAddress")[0].textContent
parseSearch = (iq) ->
items = iq.getElementsByTagName("item")
(i.textContent for i in items)
parseAttributeDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
type: d.getElementsByTagName("type")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseMethodDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
returnType: d.getElementsByTagName("returnType")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseDesc = (desc) ->
res = {}
if desc instanceof NodeList
for c in desc
res[c.getAttribute "xml:lang"] = c.textContent
else
res.desc[desc.getAttribute "xml:lang"] = desc.textContent
res
parseDescription = (iq) ->
result = desc: {}, attributes: {}, methods: {}, classes: []
describe = iq.getElementsByTagName("describe")[0]
for c in describe.childNodes
switch c.tagName.toLowerCase()
when "desc"
result.desc[c.getAttribute "xml:lang"] = c.textContent
when "attributedescription"
ad = parseAttributeDescription c
result.attributes[ad.name] = ad
when "methoddescription"
md = parseMethodDescription c
result.methods[md.name] = md
when "superclass"
result.superclass = c.textContent
when "timestamp"
result.timestamp = c.textContent
when "class"
classes.push = c.textContent
result
class JOAPError extends Error
constructor: (@message, @code)->
@name = "JOAPError"
class Server
constructor: (@service) ->
sendRequest: (type, clazz, cb, opt={}) ->
iq = @createIq type, clazz, opt.instance
opt.beforeSend? iq
success = (res) -> cb? res, null, opt.onResult?(res)
conn.sendIQ iq, success, onError(cb)
createIq: (type, clazz, instance) ->
iqType = "set"
iqType = "get" if (type in ["read", "search", "describe"])
$iq(to: @getAddress(clazz, instance), type: iqType)
.c(type, xmlns: JOAP_NS)
getAddress: (clazz, instance) ->
addr = ""
addr += "#{clazz}@" if clazz if typeof clazz is "string"
addr += @service
addr += "/#{instance}" if (typeof(instance) in ["string", "number"])
addr
describe: (clazz, instance, cb) ->
if typeof clazz is "function"
cb = clazz
clazz = instance = null
else if typeof instance is "function"
cb = instance
instance = null
@sendRequest "describe", clazz, cb,
instance: instance
onResult: parseDescription
add: (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
@sendRequest "add", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
read: (clazz, instance, limits, cb) ->
cb = limits if typeof limits is "function"
@sendRequest "read", clazz, cb,
instance: instance
beforeSend: (iq) -> if limits instanceof Array
iq.c("name").t(l).up() for l in limits
onResult: parseAttributes
edit: (clazz, instance, attrs, cb) -> @sendRequest "edit", clazz, cb,
instance: instance
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseAttributes
delete: (clazz, instance, cb) -> @sendRequest "delete", clazz, cb,
instance: instance
search: (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
@sendRequest "search", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseSearch
Strophe.addConnectionPlugin 'joap', do ->
getObjectServer = (service) -> new Server service
init = (c) ->
conn = c
Strophe.addNamespace "JOAP", JOAP_NS
if not conn.hasOwnProperty "disco"
Strophe.warn "You need the discovery plugin to have JOAP fully implemented."
else
conn.disco.addIdentity "automation", "joap"
conn.disco.addFeature Strophe.NS.JOAP
# public API
init: init
getObjectServer: getObjectServer
JOAPError: JOAPError
| 36725 | # This program is distributed under the terms of the MIT license.
# Copyright 2012 (c) <NAME> <<EMAIL>>
JOAP_NS = "jabber:iq:joap"
# Private static members
conn = null
onError = (cb=->) -> (iq) ->
err = iq.getElementsByTagName("error")[0]
if err?
code = err.getAttribute("code") * 1
msg = err.textContent
msg = "JOAP server is unavailable" if code is 503
cb iq, new JOAPError msg, code
else
cb iq, new JOAPError "Unknown error"
addXMLAttributes = (iq, attrs) ->
if typeof attrs is "object"
for k,v of attrs
iq.c("attribute")
.c("name").t(k).up()
.cnode(conn.rpc._convertToXML v).up().up()
parseAttributes = (iq) ->
attrs = iq.getElementsByTagName("attribute")
data = {}
for a in attrs
key = a.getElementsByTagName("name")[0].textContent
data[key] = conn.rpc._convertFromXML a.getElementsByTagName("value")[0]
data
parseNewAddress = (iq) ->
address = iq.getElementsByTagName("newAddress")[0].textContent
parseSearch = (iq) ->
items = iq.getElementsByTagName("item")
(i.textContent for i in items)
parseAttributeDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
type: d.getElementsByTagName("type")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseMethodDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
returnType: d.getElementsByTagName("returnType")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseDesc = (desc) ->
res = {}
if desc instanceof NodeList
for c in desc
res[c.getAttribute "xml:lang"] = c.textContent
else
res.desc[desc.getAttribute "xml:lang"] = desc.textContent
res
parseDescription = (iq) ->
result = desc: {}, attributes: {}, methods: {}, classes: []
describe = iq.getElementsByTagName("describe")[0]
for c in describe.childNodes
switch c.tagName.toLowerCase()
when "desc"
result.desc[c.getAttribute "xml:lang"] = c.textContent
when "attributedescription"
ad = parseAttributeDescription c
result.attributes[ad.name] = ad
when "methoddescription"
md = parseMethodDescription c
result.methods[md.name] = md
when "superclass"
result.superclass = c.textContent
when "timestamp"
result.timestamp = c.textContent
when "class"
classes.push = c.textContent
result
class JOAPError extends Error
constructor: (@message, @code)->
@name = "JOAPError"
class Server
constructor: (@service) ->
sendRequest: (type, clazz, cb, opt={}) ->
iq = @createIq type, clazz, opt.instance
opt.beforeSend? iq
success = (res) -> cb? res, null, opt.onResult?(res)
conn.sendIQ iq, success, onError(cb)
createIq: (type, clazz, instance) ->
iqType = "set"
iqType = "get" if (type in ["read", "search", "describe"])
$iq(to: @getAddress(clazz, instance), type: iqType)
.c(type, xmlns: JOAP_NS)
getAddress: (clazz, instance) ->
addr = ""
addr += "#{clazz}@" if clazz if typeof clazz is "string"
addr += @service
addr += "/#{instance}" if (typeof(instance) in ["string", "number"])
addr
describe: (clazz, instance, cb) ->
if typeof clazz is "function"
cb = clazz
clazz = instance = null
else if typeof instance is "function"
cb = instance
instance = null
@sendRequest "describe", clazz, cb,
instance: instance
onResult: parseDescription
add: (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
@sendRequest "add", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
read: (clazz, instance, limits, cb) ->
cb = limits if typeof limits is "function"
@sendRequest "read", clazz, cb,
instance: instance
beforeSend: (iq) -> if limits instanceof Array
iq.c("name").t(l).up() for l in limits
onResult: parseAttributes
edit: (clazz, instance, attrs, cb) -> @sendRequest "edit", clazz, cb,
instance: instance
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseAttributes
delete: (clazz, instance, cb) -> @sendRequest "delete", clazz, cb,
instance: instance
search: (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
@sendRequest "search", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseSearch
Strophe.addConnectionPlugin 'joap', do ->
getObjectServer = (service) -> new Server service
init = (c) ->
conn = c
Strophe.addNamespace "JOAP", JOAP_NS
if not conn.hasOwnProperty "disco"
Strophe.warn "You need the discovery plugin to have JOAP fully implemented."
else
conn.disco.addIdentity "automation", "joap"
conn.disco.addFeature Strophe.NS.JOAP
# public API
init: init
getObjectServer: getObjectServer
JOAPError: JOAPError
| true | # This program is distributed under the terms of the MIT license.
# Copyright 2012 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
JOAP_NS = "jabber:iq:joap"
# Private static members
conn = null
onError = (cb=->) -> (iq) ->
err = iq.getElementsByTagName("error")[0]
if err?
code = err.getAttribute("code") * 1
msg = err.textContent
msg = "JOAP server is unavailable" if code is 503
cb iq, new JOAPError msg, code
else
cb iq, new JOAPError "Unknown error"
addXMLAttributes = (iq, attrs) ->
if typeof attrs is "object"
for k,v of attrs
iq.c("attribute")
.c("name").t(k).up()
.cnode(conn.rpc._convertToXML v).up().up()
parseAttributes = (iq) ->
attrs = iq.getElementsByTagName("attribute")
data = {}
for a in attrs
key = a.getElementsByTagName("name")[0].textContent
data[key] = conn.rpc._convertFromXML a.getElementsByTagName("value")[0]
data
parseNewAddress = (iq) ->
address = iq.getElementsByTagName("newAddress")[0].textContent
parseSearch = (iq) ->
items = iq.getElementsByTagName("item")
(i.textContent for i in items)
parseAttributeDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
type: d.getElementsByTagName("type")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseMethodDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
returnType: d.getElementsByTagName("returnType")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseDesc = (desc) ->
res = {}
if desc instanceof NodeList
for c in desc
res[c.getAttribute "xml:lang"] = c.textContent
else
res.desc[desc.getAttribute "xml:lang"] = desc.textContent
res
parseDescription = (iq) ->
result = desc: {}, attributes: {}, methods: {}, classes: []
describe = iq.getElementsByTagName("describe")[0]
for c in describe.childNodes
switch c.tagName.toLowerCase()
when "desc"
result.desc[c.getAttribute "xml:lang"] = c.textContent
when "attributedescription"
ad = parseAttributeDescription c
result.attributes[ad.name] = ad
when "methoddescription"
md = parseMethodDescription c
result.methods[md.name] = md
when "superclass"
result.superclass = c.textContent
when "timestamp"
result.timestamp = c.textContent
when "class"
classes.push = c.textContent
result
class JOAPError extends Error
constructor: (@message, @code)->
@name = "JOAPError"
class Server
constructor: (@service) ->
sendRequest: (type, clazz, cb, opt={}) ->
iq = @createIq type, clazz, opt.instance
opt.beforeSend? iq
success = (res) -> cb? res, null, opt.onResult?(res)
conn.sendIQ iq, success, onError(cb)
createIq: (type, clazz, instance) ->
iqType = "set"
iqType = "get" if (type in ["read", "search", "describe"])
$iq(to: @getAddress(clazz, instance), type: iqType)
.c(type, xmlns: JOAP_NS)
getAddress: (clazz, instance) ->
addr = ""
addr += "#{clazz}@" if clazz if typeof clazz is "string"
addr += @service
addr += "/#{instance}" if (typeof(instance) in ["string", "number"])
addr
describe: (clazz, instance, cb) ->
if typeof clazz is "function"
cb = clazz
clazz = instance = null
else if typeof instance is "function"
cb = instance
instance = null
@sendRequest "describe", clazz, cb,
instance: instance
onResult: parseDescription
add: (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
@sendRequest "add", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
read: (clazz, instance, limits, cb) ->
cb = limits if typeof limits is "function"
@sendRequest "read", clazz, cb,
instance: instance
beforeSend: (iq) -> if limits instanceof Array
iq.c("name").t(l).up() for l in limits
onResult: parseAttributes
edit: (clazz, instance, attrs, cb) -> @sendRequest "edit", clazz, cb,
instance: instance
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseAttributes
delete: (clazz, instance, cb) -> @sendRequest "delete", clazz, cb,
instance: instance
search: (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
@sendRequest "search", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseSearch
Strophe.addConnectionPlugin 'joap', do ->
getObjectServer = (service) -> new Server service
init = (c) ->
conn = c
Strophe.addNamespace "JOAP", JOAP_NS
if not conn.hasOwnProperty "disco"
Strophe.warn "You need the discovery plugin to have JOAP fully implemented."
else
conn.disco.addIdentity "automation", "joap"
conn.disco.addFeature Strophe.NS.JOAP
# public API
init: init
getObjectServer: getObjectServer
JOAPError: JOAPError
|
[
{
"context": "list.add_item {id:13, name: 'Element 3', author: 'John'} \n",
"end": 3628,
"score": 0.9984531402587891,
"start": 3624,
"tag": "NAME",
"value": "John"
}
] | test/components/list/selectable_list_test.coffee | pieces-js/pieces-list | 0 | 'use strict'
h = require 'pieces-list/test/helpers'
utils = pi.utils
Nod = pi.Nod
describe "List.Selectable", ->
root = h.test_cont(pi.Nod.body)
after ->
root.remove()
test_div = list = null
beforeEach ->
test_div = Nod.create('div')
test_div.style position:'relative'
root.append test_div
test_div.append """
<div class="pi" data-component="list" data-plugins="selectable" data-pid="test" style="position:relative">
<ul class="list">
<li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li>
<li class="item" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li>
<li class="item" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li>
</ul>
</div>
"""
pi.app.view.piecify()
list = test_div.find('.pi')
afterEach ->
test_div.remove()
it "select one item when radio", (done)->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'item_click', (event) =>
expect(list.selected()[0].record.key).to.equal "anyone"
done()
h.clickElement test_div.find('.pi').find('[data-id="3"]').node
it "select several items when check", (done)->
list.selectable.type 'check'
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selected', (event) =>
expect(list.selected().length).to.equal 2
expect(event.data.length).to.equal 2
done()
h.clickElement test_div.find('.pi').find('[data-id="3"]').node
it "select new item", (done)->
item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>')
list.add_item item
list.on 'selected', (event) =>
expect(list.selected()[0].record.key).to.equal 'new'
expect(event.data[0].record.key).to.equal 'new'
done()
h.clickElement test_div.find('.pi').find('[data-id="4"]').node
it "send cleared event when all items are deselected", (done)->
list.selectable.type 'check'
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
it "send cleared when selected item is removed", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.remove_item_at 0
it "send cleared when selected item is removed after _selected was cached", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.selected()
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.remove_item_at 0
it "send cleared when list completely cleared", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.clear()
it "not send cleared on item added", (done) ->
list.item_renderer =
render: (data) ->
nod = Nod.create ("<div>#{ data.name }</div>")
nod.addClass 'item'
nod.append "<span class='author'>#{ data.author }</span>"
pi.utils.extend nod,data
nod
list.on 'selection_cleared', (event) =>
expect(false).to.equal true
done()
utils.after 1000, ->
done()
list.add_item {id:13, name: 'Element 3', author: 'John'}
| 206898 | 'use strict'
h = require 'pieces-list/test/helpers'
utils = pi.utils
Nod = pi.Nod
describe "List.Selectable", ->
root = h.test_cont(pi.Nod.body)
after ->
root.remove()
test_div = list = null
beforeEach ->
test_div = Nod.create('div')
test_div.style position:'relative'
root.append test_div
test_div.append """
<div class="pi" data-component="list" data-plugins="selectable" data-pid="test" style="position:relative">
<ul class="list">
<li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li>
<li class="item" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li>
<li class="item" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li>
</ul>
</div>
"""
pi.app.view.piecify()
list = test_div.find('.pi')
afterEach ->
test_div.remove()
it "select one item when radio", (done)->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'item_click', (event) =>
expect(list.selected()[0].record.key).to.equal "anyone"
done()
h.clickElement test_div.find('.pi').find('[data-id="3"]').node
it "select several items when check", (done)->
list.selectable.type 'check'
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selected', (event) =>
expect(list.selected().length).to.equal 2
expect(event.data.length).to.equal 2
done()
h.clickElement test_div.find('.pi').find('[data-id="3"]').node
it "select new item", (done)->
item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>')
list.add_item item
list.on 'selected', (event) =>
expect(list.selected()[0].record.key).to.equal 'new'
expect(event.data[0].record.key).to.equal 'new'
done()
h.clickElement test_div.find('.pi').find('[data-id="4"]').node
it "send cleared event when all items are deselected", (done)->
list.selectable.type 'check'
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
it "send cleared when selected item is removed", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.remove_item_at 0
it "send cleared when selected item is removed after _selected was cached", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.selected()
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.remove_item_at 0
it "send cleared when list completely cleared", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.clear()
it "not send cleared on item added", (done) ->
list.item_renderer =
render: (data) ->
nod = Nod.create ("<div>#{ data.name }</div>")
nod.addClass 'item'
nod.append "<span class='author'>#{ data.author }</span>"
pi.utils.extend nod,data
nod
list.on 'selection_cleared', (event) =>
expect(false).to.equal true
done()
utils.after 1000, ->
done()
list.add_item {id:13, name: 'Element 3', author: '<NAME>'}
| true | 'use strict'
h = require 'pieces-list/test/helpers'
utils = pi.utils
Nod = pi.Nod
describe "List.Selectable", ->
root = h.test_cont(pi.Nod.body)
after ->
root.remove()
test_div = list = null
beforeEach ->
test_div = Nod.create('div')
test_div.style position:'relative'
root.append test_div
test_div.append """
<div class="pi" data-component="list" data-plugins="selectable" data-pid="test" style="position:relative">
<ul class="list">
<li class="item" data-id="1" data-key="one">One<span class="tags">killer,puppy</span></li>
<li class="item" data-id="2" data-key="someone">Two<span class="tags">puppy, coward</span></li>
<li class="item" data-id="3" data-key="anyone">Tre<span class="tags">bully,zombopuppy</span></li>
</ul>
</div>
"""
pi.app.view.piecify()
list = test_div.find('.pi')
afterEach ->
test_div.remove()
it "select one item when radio", (done)->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'item_click', (event) =>
expect(list.selected()[0].record.key).to.equal "anyone"
done()
h.clickElement test_div.find('.pi').find('[data-id="3"]').node
it "select several items when check", (done)->
list.selectable.type 'check'
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selected', (event) =>
expect(list.selected().length).to.equal 2
expect(event.data.length).to.equal 2
done()
h.clickElement test_div.find('.pi').find('[data-id="3"]').node
it "select new item", (done)->
item = Nod.create('<li class="item" data-id="4" data-key="new">New</li>')
list.add_item item
list.on 'selected', (event) =>
expect(list.selected()[0].record.key).to.equal 'new'
expect(event.data[0].record.key).to.equal 'new'
done()
h.clickElement test_div.find('.pi').find('[data-id="4"]').node
it "send cleared event when all items are deselected", (done)->
list.selectable.type 'check'
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
it "send cleared when selected item is removed", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.remove_item_at 0
it "send cleared when selected item is removed after _selected was cached", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.selected()
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.remove_item_at 0
it "send cleared when list completely cleared", (done) ->
h.clickElement test_div.find('.pi').find('[data-id="1"]').node
list.on 'selection_cleared', (event) =>
expect(list.selected().length).to.equal 0
done()
list.clear()
it "not send cleared on item added", (done) ->
list.item_renderer =
render: (data) ->
nod = Nod.create ("<div>#{ data.name }</div>")
nod.addClass 'item'
nod.append "<span class='author'>#{ data.author }</span>"
pi.utils.extend nod,data
nod
list.on 'selection_cleared', (event) =>
expect(false).to.equal true
done()
utils.after 1000, ->
done()
list.add_item {id:13, name: 'Element 3', author: 'PI:NAME:<NAME>END_PI'}
|
[
{
"context": "inding community structure in very large networks, A Clauset, MEJ Newman, C Moore - Physical review E, 2004\n#-",
"end": 270,
"score": 0.9998272061347961,
"start": 261,
"tag": "NAME",
"value": "A Clauset"
},
{
"context": "unity structure in very large networks, A Clause... | src/network/cluster.coffee | romind/d3plus_sandbox | 1 | normalize = require "./normalize.coffee"
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Community detection algorithm (graph clustering/partitioning)
# Based on the paper:
# Finding community structure in very large networks, A Clauset, MEJ Newman, C Moore - Physical review E, 2004
#------------------------------------------------------------------------------
# edges; a list of edge objects
# options; a dictionary of options with attributes
# distance; it can be:
# undefined; every edge has default distance of 1
# constant; every edge has the same distance
# string; the name of the attribute in edge that describes the distance of that edge
# array; each value corresponds to the distance of the respective edge in the edges array
# function; given edge, returns the distance
# nodeid; it can be:
# undefined; then we assume that each node obtained by getting the endpoints of an edge is a string/number describing the id of the node
# string; the name of the attribute in node that describes the id of the node.
# function; given the node, returns the id.
# startpoint; it can be:
# undefined; it is assumed that edge.source points to the source node of the edge
# string; the name of the attribute in edge pointing to the source node of the edge
# function; given an edge returns the source node of that edge
# endpoint; it can be:
# undefined; it is assumed that edge.target points to the target of the edge
# string; the name of the attribute in edge pointing to the target of the edge
# function; given an edge returns the target node of that edge
# nodes; if defined, the input is assumed to be normalized and nodes is assumed to be a dictionary
# that maps node id to the outedges of the node
# returns an array of communities, where each community is an array of node ids belonging to that community.
module.exports = (edges, options) ->
## For visualization debugging purposes ##
events = []
######### User's options normalization ############
if not options? then options = {}
if not options.nodes? or typeof options.nodes isnt 'object'
[edges, options] = normalize edges, options
if options is null then return null
# unpack options object
{distance, nodeid, startpoint, endpoint, nodes} = options
####### END user's input normalization #########
# build the nodes map, which stores the degree of every node
nodesMap = {}
for id of nodes
nodesMap[id] = { node: nodes[id].node, degree:0 }
# build the links map, which stores the expected number of links between every pair of nodes
m = 0
linksMap = {}
for edge in edges
a = nodeid startpoint edge
b = nodeid endpoint edge
linksMap[a] = {} if a not of linksMap
linksMap[b] = {} if b not of linksMap
if b not of linksMap[a]
linksMap[a][b] = 0
linksMap[b][a] = 0
m++
nodesMap[a].degree+=1
nodesMap[b].degree+=1
communities = {}
Q = 0
for id, node of nodesMap
communities[id] = {score: node.degree / (2.0*m), nodes:[id]}
for a of linksMap
for b of linksMap[a]
linksMap[a][b] = 1.0 / (2*m) - (nodesMap[a].degree * nodesMap[b].degree)/(4.0*m*m)
iter = 0
while iter < 1000
## find largest element of links
deltaQ = -1
maxa = undefined
maxb = undefined
for a of linksMap
for b of linksMap[a]
if linksMap[a][b] > deltaQ
deltaQ = linksMap[a][b]
maxa = a
maxb = b
break if deltaQ < 0
## merge maxa into maxb
for k of linksMap[maxa]
if k isnt maxb
if k of linksMap[maxb]
## k is connected to both a and b
linksMap[maxb][k] += linksMap[maxa][k]
else
## k is connected to a but not b
linksMap[maxb][k] = linksMap[maxa][k] - 2*communities[maxb].score*communities[k].score
linksMap[k][maxb] = linksMap[maxb][k]
delete linksMap[k][maxa]
for k of linksMap[maxb]
if k not of linksMap[maxa] and k isnt maxb
## k is connected to b but not a
linksMap[maxb][k] -= 2*communities[maxa].score*communities[k].score
linksMap[k][maxb] = linksMap[maxb][k]
for node in communities[maxa].nodes
communities[maxb].nodes.push node
communities[maxb].score += communities[maxa].score
if options.vdebug then events.push type: 'merge', father: maxb, child: maxa, nodes: communities[maxb].nodes
delete communities[maxa]
delete linksMap[maxa]
Q += deltaQ
iter++
## sort communities by size
commSizes = ([cid, community.nodes.length] for cid, community of communities)
commSizes.sort (a,b) -> b[1] - a[1]
result = (communities[commSize[0]].nodes for commSize in commSizes)
return [result, events]
| 195483 | normalize = require "./normalize.coffee"
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Community detection algorithm (graph clustering/partitioning)
# Based on the paper:
# Finding community structure in very large networks, <NAME>, <NAME>, <NAME> - Physical review E, 2004
#------------------------------------------------------------------------------
# edges; a list of edge objects
# options; a dictionary of options with attributes
# distance; it can be:
# undefined; every edge has default distance of 1
# constant; every edge has the same distance
# string; the name of the attribute in edge that describes the distance of that edge
# array; each value corresponds to the distance of the respective edge in the edges array
# function; given edge, returns the distance
# nodeid; it can be:
# undefined; then we assume that each node obtained by getting the endpoints of an edge is a string/number describing the id of the node
# string; the name of the attribute in node that describes the id of the node.
# function; given the node, returns the id.
# startpoint; it can be:
# undefined; it is assumed that edge.source points to the source node of the edge
# string; the name of the attribute in edge pointing to the source node of the edge
# function; given an edge returns the source node of that edge
# endpoint; it can be:
# undefined; it is assumed that edge.target points to the target of the edge
# string; the name of the attribute in edge pointing to the target of the edge
# function; given an edge returns the target node of that edge
# nodes; if defined, the input is assumed to be normalized and nodes is assumed to be a dictionary
# that maps node id to the outedges of the node
# returns an array of communities, where each community is an array of node ids belonging to that community.
module.exports = (edges, options) ->
## For visualization debugging purposes ##
events = []
######### User's options normalization ############
if not options? then options = {}
if not options.nodes? or typeof options.nodes isnt 'object'
[edges, options] = normalize edges, options
if options is null then return null
# unpack options object
{distance, nodeid, startpoint, endpoint, nodes} = options
####### END user's input normalization #########
# build the nodes map, which stores the degree of every node
nodesMap = {}
for id of nodes
nodesMap[id] = { node: nodes[id].node, degree:0 }
# build the links map, which stores the expected number of links between every pair of nodes
m = 0
linksMap = {}
for edge in edges
a = nodeid startpoint edge
b = nodeid endpoint edge
linksMap[a] = {} if a not of linksMap
linksMap[b] = {} if b not of linksMap
if b not of linksMap[a]
linksMap[a][b] = 0
linksMap[b][a] = 0
m++
nodesMap[a].degree+=1
nodesMap[b].degree+=1
communities = {}
Q = 0
for id, node of nodesMap
communities[id] = {score: node.degree / (2.0*m), nodes:[id]}
for a of linksMap
for b of linksMap[a]
linksMap[a][b] = 1.0 / (2*m) - (nodesMap[a].degree * nodesMap[b].degree)/(4.0*m*m)
iter = 0
while iter < 1000
## find largest element of links
deltaQ = -1
maxa = undefined
maxb = undefined
for a of linksMap
for b of linksMap[a]
if linksMap[a][b] > deltaQ
deltaQ = linksMap[a][b]
maxa = a
maxb = b
break if deltaQ < 0
## merge maxa into maxb
for k of linksMap[maxa]
if k isnt maxb
if k of linksMap[maxb]
## k is connected to both a and b
linksMap[maxb][k] += linksMap[maxa][k]
else
## k is connected to a but not b
linksMap[maxb][k] = linksMap[maxa][k] - 2*communities[maxb].score*communities[k].score
linksMap[k][maxb] = linksMap[maxb][k]
delete linksMap[k][maxa]
for k of linksMap[maxb]
if k not of linksMap[maxa] and k isnt maxb
## k is connected to b but not a
linksMap[maxb][k] -= 2*communities[maxa].score*communities[k].score
linksMap[k][maxb] = linksMap[maxb][k]
for node in communities[maxa].nodes
communities[maxb].nodes.push node
communities[maxb].score += communities[maxa].score
if options.vdebug then events.push type: 'merge', father: maxb, child: maxa, nodes: communities[maxb].nodes
delete communities[maxa]
delete linksMap[maxa]
Q += deltaQ
iter++
## sort communities by size
commSizes = ([cid, community.nodes.length] for cid, community of communities)
commSizes.sort (a,b) -> b[1] - a[1]
result = (communities[commSize[0]].nodes for commSize in commSizes)
return [result, events]
| true | normalize = require "./normalize.coffee"
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Community detection algorithm (graph clustering/partitioning)
# Based on the paper:
# Finding community structure in very large networks, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI - Physical review E, 2004
#------------------------------------------------------------------------------
# edges; a list of edge objects
# options; a dictionary of options with attributes
# distance; it can be:
# undefined; every edge has default distance of 1
# constant; every edge has the same distance
# string; the name of the attribute in edge that describes the distance of that edge
# array; each value corresponds to the distance of the respective edge in the edges array
# function; given edge, returns the distance
# nodeid; it can be:
# undefined; then we assume that each node obtained by getting the endpoints of an edge is a string/number describing the id of the node
# string; the name of the attribute in node that describes the id of the node.
# function; given the node, returns the id.
# startpoint; it can be:
# undefined; it is assumed that edge.source points to the source node of the edge
# string; the name of the attribute in edge pointing to the source node of the edge
# function; given an edge returns the source node of that edge
# endpoint; it can be:
# undefined; it is assumed that edge.target points to the target of the edge
# string; the name of the attribute in edge pointing to the target of the edge
# function; given an edge returns the target node of that edge
# nodes; if defined, the input is assumed to be normalized and nodes is assumed to be a dictionary
# that maps node id to the outedges of the node
# returns an array of communities, where each community is an array of node ids belonging to that community.
module.exports = (edges, options) ->
## For visualization debugging purposes ##
events = []
######### User's options normalization ############
if not options? then options = {}
if not options.nodes? or typeof options.nodes isnt 'object'
[edges, options] = normalize edges, options
if options is null then return null
# unpack options object
{distance, nodeid, startpoint, endpoint, nodes} = options
####### END user's input normalization #########
# build the nodes map, which stores the degree of every node
nodesMap = {}
for id of nodes
nodesMap[id] = { node: nodes[id].node, degree:0 }
# build the links map, which stores the expected number of links between every pair of nodes
m = 0
linksMap = {}
for edge in edges
a = nodeid startpoint edge
b = nodeid endpoint edge
linksMap[a] = {} if a not of linksMap
linksMap[b] = {} if b not of linksMap
if b not of linksMap[a]
linksMap[a][b] = 0
linksMap[b][a] = 0
m++
nodesMap[a].degree+=1
nodesMap[b].degree+=1
communities = {}
Q = 0
for id, node of nodesMap
communities[id] = {score: node.degree / (2.0*m), nodes:[id]}
for a of linksMap
for b of linksMap[a]
linksMap[a][b] = 1.0 / (2*m) - (nodesMap[a].degree * nodesMap[b].degree)/(4.0*m*m)
iter = 0
while iter < 1000
## find largest element of links
deltaQ = -1
maxa = undefined
maxb = undefined
for a of linksMap
for b of linksMap[a]
if linksMap[a][b] > deltaQ
deltaQ = linksMap[a][b]
maxa = a
maxb = b
break if deltaQ < 0
## merge maxa into maxb
for k of linksMap[maxa]
if k isnt maxb
if k of linksMap[maxb]
## k is connected to both a and b
linksMap[maxb][k] += linksMap[maxa][k]
else
## k is connected to a but not b
linksMap[maxb][k] = linksMap[maxa][k] - 2*communities[maxb].score*communities[k].score
linksMap[k][maxb] = linksMap[maxb][k]
delete linksMap[k][maxa]
for k of linksMap[maxb]
if k not of linksMap[maxa] and k isnt maxb
## k is connected to b but not a
linksMap[maxb][k] -= 2*communities[maxa].score*communities[k].score
linksMap[k][maxb] = linksMap[maxb][k]
for node in communities[maxa].nodes
communities[maxb].nodes.push node
communities[maxb].score += communities[maxa].score
if options.vdebug then events.push type: 'merge', father: maxb, child: maxa, nodes: communities[maxb].nodes
delete communities[maxa]
delete linksMap[maxa]
Q += deltaQ
iter++
## sort communities by size
commSizes = ([cid, community.nodes.length] for cid, community of communities)
commSizes.sort (a,b) -> b[1] - a[1]
result = (communities[commSize[0]].nodes for commSize in commSizes)
return [result, events]
|
[
{
"context": "dimo: 'Ver podcast en Podimo'\n subscribe: 'Suscríbete'\n\n 'nl-NL':\n chaptermarks:\n show: ",
"end": 5769,
"score": 0.8138477206230164,
"start": 5759,
"tag": "NAME",
"value": "Suscríbete"
}
] | src/javascripts/i18n.coffee | clawfire/podigee-podcast-player | 204 | class I18n
# List of locales that follow BCP-47
SUPPORTED_LOCALES = ['en-US', 'de-DE', 'es-ES', 'nl-NL', 'pl-PL']
# E.g a user with en-GB will get the language 'en'
# The languages are in ISO 639-1
SUPPORTED_LANGUAGES = ['en', 'de', 'es', 'nl', 'pl']
# locale<string> BCP-47, e.g. "en-US", can be nil
# defaultLocale<string> BCP-47, e.g. "de-DE", should not be nil
# if locale is nil, the locale will be computed, falling back to defaultLocale
constructor: (@locale, @defaultLocale) ->
@locale ||= @locale || @getLocale()
true
getLocale: ->
preferredLocale = @getUserPreferredLocale()
preferredLanguage = @getLanguageFromLocale(preferredLocale)
bestLocale = @getLocaleForLanguage(preferredLanguage)
bestLocale || @defaultLocale
# private
getUserPreferredLocale: ->
navigator.language || navigator.userLanguage
# locale<string>, e.g. "en-US", format: BCP-47
getLanguageFromLocale: (locale) ->
locale.substring(0, 2)
# language<string>, e.g. "en", format: ISO 639-1
# for now, it's pretty simple
getLocaleForLanguage: (language) ->
switch language
when "en" then "en-US"
when "de" then "de-DE"
when "es" then "es-ES"
when "nl" then "nl-NL"
when "pl" then "pl-PL"
t: (key) ->
keys = key.split('.')
value = @translationMap[@locale]
for k in keys
value = value[k]
if value
value
else
key
translationMap:
'en-US':
chaptermarks:
show: 'Show chaptermarks'
title: 'Chaptermarks'
chromecast:
play: 'Play on chromecast'
download:
episode: 'Download episode'
episode_info:
more_info: 'Show more info'
title: 'Episode info'
playlist:
show: 'Show playlist'
title: 'Playlist'
load_more: 'Load more episodes'
progress_bar:
switch_time_mode: 'Switch time display mode'
share:
copy_episode_link: 'Copy episode link'
email: 'Email'
embed_player: 'Embed player'
episode: 'Episode'
episode_url: 'Share link to episode'
start_at: 'Start at'
theme:
playPause: 'Play'
play: 'Play'
pause: 'Pause'
backward: 'Backward 10s'
forward: 'Forward 30s'
changePlaybackSpeed: 'Change Playback Speed'
transcript:
search: 'Search in transcript'
show: 'Show transcription'
title: 'Transcription'
subscribeBar:
allEpisodes: 'All Episodes'
podcastOnItunes: 'View Podcast on Apple Podcasts'
podcastOnSpotify: 'View Podcast on Spotify'
podcastOnDeezer: 'View Podcast on Deezer'
podcastOnAlexa: 'View Podcast on Alexa'
podcastOnPodimo: 'View Podcast on Podimo'
subscribe: 'Subscribe'
'de-DE':
chaptermarks:
show: 'Kapitelmarken anzeigen'
title: 'Kapitelmarken'
chromecast:
play: 'Auf Chromecast abspielen'
download:
episode: 'Episode herunterladen'
episode_info:
more_info: 'Mehr Infos anzeigen'
title: 'Episoden-Infos'
playlist:
show: 'Wiedergabeliste anzeigen'
title: 'Wiedergabeliste'
load_more: 'Mehr Episoden laden'
progress_bar:
switch_time_mode: 'Anzeigemodus ändern'
share:
copy_episode_link: 'Link zur Episode kopieren'
email: 'E-Mail'
embed_player: 'Player einbetten'
episode: 'Episode'
episode_url: 'Link zur Episode teilen'
start_at: 'Wiedergabe ab'
theme:
playPause: 'Play'
play: 'Play'
pause: 'Pause'
backward: '10s zurück'
forward: '30s vorwärts'
changePlaybackSpeed: 'Abspielgeschwindigkeit ändern'
transcript:
search: 'Transkript durchsuchen'
show: 'Transkript anzeigen'
title: 'Transkript'
subscribeBar:
allEpisodes: 'Alle Episoden'
podcastOnItunes: 'Podcast auf Apple Podcasts ansehen'
podcastOnSpotify: 'Podcast auf Spotify ansehen'
podcastOnDeezer: 'Podcast auf Deezer ansehen'
podcastOnAlexa: 'Podcast auf Alexa ansehen'
podcastOnPodimo: 'Podcast auf Podimo ansehen'
subscribe: 'Abonnieren'
'es-ES':
chaptermarks:
show: 'Marca temporal'
title: 'Marcas temporales'
chromecast:
play: 'Reproducir en chromecast'
download:
episode: 'Descargar capítulo'
episode_info:
more_info: 'Mostrar más informaciones'
title: 'Informaciones del capítulo'
playlist:
show: 'Mostrar lista de reproducción'
title: 'Lista de reproducción'
load_more: 'Más capítulos'
progress_bar:
switch_time_mode: 'Cambiar el modo de visualización'
share:
copy_episode_link: 'Copiar enlace del capítulo'
email: 'Correo electrónico'
embed_player: 'Embed del reproductor'
episode: 'Capítulo'
episode_url: 'Compartir enlace del capítulo'
start_at: 'Empezar en'
theme:
playPause: 'Reproducir'
play: 'Reproducir'
pause: 'Pausar'
backward: 'Rebobinar 10s'
forward: 'Avanzar 30s'
changePlaybackSpeed: 'Cambiar velocidad de reproducción'
transcript:
search: 'Buscar en transcripción'
show: 'Mostrar transcripción'
title: 'Transcripción'
subscribeBar:
allEpisodes: 'Todos los capítulos'
podcastOnItunes: 'Ver podcast en Apple Podcasts'
podcastOnSpotify: 'Ver podcast en Spotify'
podcastOnDeezer: 'Ver podcast en Deezer'
podcastOnAlexa: 'Ver podcast en Alexa'
podcastOnPodimo: 'Ver podcast en Podimo'
subscribe: 'Suscríbete'
'nl-NL':
chaptermarks:
show: 'Toon hoofdstukmarkeringen'
title: 'Hoofdstukmarkeringen'
chromecast:
play: 'Speel af op chromecast'
download:
episode: 'Download aflevering'
episode_info:
more_info: 'Toon meer info'
title: 'Aflevering info'
playlist:
show: 'Toon afspeellijst'
title: 'Afspeellijst'
load_more: 'Laad meer afleveringen'
progress_bar:
switch_time_mode: 'Verander tijdweergave'
share:
copy_episode_link: 'Kopieër link naar aflevering'
email: 'E-mail'
embed_player: 'Embed speler'
episode: 'Aflevering'
episode_url: 'Deel link naar aflevering'
start_at: 'Begin op'
theme:
playPause: 'Afspelen'
play: 'Afspelen'
pause: 'Pauzeren'
backward: 'Terug 10s'
forward: 'Vooruit 30s'
changePlaybackSpeed: 'Verander afspeelsnelheid'
transcript:
search: 'Zoek in transcript'
show: 'Toon transcriptie'
title: 'Transcriptie'
subscribeBar:
allEpisodes: 'Alle Afleveringen'
podcastOnItunes: 'Toon Podcast op Apple Podcasts'
podcastOnSpotify: 'Toon Podcast op Spotify'
podcastOnDeezer: 'Toon Podcast op Deezer'
podcastOnAlexa: 'Toon Podcast op Alexa'
podcastOnPodimo: 'Toon Podcast op Podimo'
subscribe: 'Abonneer'
'pl-PL':
chaptermarks:
show: 'Pokaż znaczniki rozdziałów'
title: 'Rozdziały'
chromecast:
play: 'Odtwórz w chromecast'
download:
episode: 'Pobierz odcinek'
episode_info:
more_info: 'Pokaż więcej informacji'
title: 'Informacje o odcinku'
playlist:
show: 'Pokaż listę odtwarzania'
title: 'Lista odtwarzania'
load_more: 'Załaduj więcej odcinków'
progress_bar:
switch_time_mode: 'Przełącz tryb wyświetlania czasu'
share:
copy_episode_link: 'Kopiuj link do odcinka'
email: 'E-mail'
embed_player: 'Osadź odtwarzacz'
episode: 'Odcinek'
episode_url: 'Udostępnij link do odcinka'
start_at: 'Rozpocznij od'
theme:
playPause: 'Odtwórz'
play: 'Odtwórz'
pause: 'Pauza'
backward: '10s wstecz'
forward: '30s do przodu'
changePlaybackSpeed: 'Zmień prędkość odtwarzania'
transcript:
search: 'Szukaj w transkrypcji'
show: 'Pokaż transkrypcję'
title: 'Transkrypcja'
subscribeBar:
allEpisodes: 'Wszystkie odcinki'
podcastOnItunes: 'Zobacz podcast na Apple Podcasts'
podcastOnSpotify: 'Zobacz podcast na Spotify'
podcastOnDeezer: 'Zobacz podcast na Deezer'
podcastOnAlexa: 'Zobacz podcast na Alexa'
podcastOnPodimo: 'Zobacz podcast na Podimo'
subscribe: 'Subskrybuj'
module.exports = I18n
| 156035 | class I18n
# List of locales that follow BCP-47
SUPPORTED_LOCALES = ['en-US', 'de-DE', 'es-ES', 'nl-NL', 'pl-PL']
# E.g a user with en-GB will get the language 'en'
# The languages are in ISO 639-1
SUPPORTED_LANGUAGES = ['en', 'de', 'es', 'nl', 'pl']
# locale<string> BCP-47, e.g. "en-US", can be nil
# defaultLocale<string> BCP-47, e.g. "de-DE", should not be nil
# if locale is nil, the locale will be computed, falling back to defaultLocale
constructor: (@locale, @defaultLocale) ->
@locale ||= @locale || @getLocale()
true
getLocale: ->
preferredLocale = @getUserPreferredLocale()
preferredLanguage = @getLanguageFromLocale(preferredLocale)
bestLocale = @getLocaleForLanguage(preferredLanguage)
bestLocale || @defaultLocale
# private
getUserPreferredLocale: ->
navigator.language || navigator.userLanguage
# locale<string>, e.g. "en-US", format: BCP-47
getLanguageFromLocale: (locale) ->
locale.substring(0, 2)
# language<string>, e.g. "en", format: ISO 639-1
# for now, it's pretty simple
getLocaleForLanguage: (language) ->
switch language
when "en" then "en-US"
when "de" then "de-DE"
when "es" then "es-ES"
when "nl" then "nl-NL"
when "pl" then "pl-PL"
t: (key) ->
keys = key.split('.')
value = @translationMap[@locale]
for k in keys
value = value[k]
if value
value
else
key
translationMap:
'en-US':
chaptermarks:
show: 'Show chaptermarks'
title: 'Chaptermarks'
chromecast:
play: 'Play on chromecast'
download:
episode: 'Download episode'
episode_info:
more_info: 'Show more info'
title: 'Episode info'
playlist:
show: 'Show playlist'
title: 'Playlist'
load_more: 'Load more episodes'
progress_bar:
switch_time_mode: 'Switch time display mode'
share:
copy_episode_link: 'Copy episode link'
email: 'Email'
embed_player: 'Embed player'
episode: 'Episode'
episode_url: 'Share link to episode'
start_at: 'Start at'
theme:
playPause: 'Play'
play: 'Play'
pause: 'Pause'
backward: 'Backward 10s'
forward: 'Forward 30s'
changePlaybackSpeed: 'Change Playback Speed'
transcript:
search: 'Search in transcript'
show: 'Show transcription'
title: 'Transcription'
subscribeBar:
allEpisodes: 'All Episodes'
podcastOnItunes: 'View Podcast on Apple Podcasts'
podcastOnSpotify: 'View Podcast on Spotify'
podcastOnDeezer: 'View Podcast on Deezer'
podcastOnAlexa: 'View Podcast on Alexa'
podcastOnPodimo: 'View Podcast on Podimo'
subscribe: 'Subscribe'
'de-DE':
chaptermarks:
show: 'Kapitelmarken anzeigen'
title: 'Kapitelmarken'
chromecast:
play: 'Auf Chromecast abspielen'
download:
episode: 'Episode herunterladen'
episode_info:
more_info: 'Mehr Infos anzeigen'
title: 'Episoden-Infos'
playlist:
show: 'Wiedergabeliste anzeigen'
title: 'Wiedergabeliste'
load_more: 'Mehr Episoden laden'
progress_bar:
switch_time_mode: 'Anzeigemodus ändern'
share:
copy_episode_link: 'Link zur Episode kopieren'
email: 'E-Mail'
embed_player: 'Player einbetten'
episode: 'Episode'
episode_url: 'Link zur Episode teilen'
start_at: 'Wiedergabe ab'
theme:
playPause: 'Play'
play: 'Play'
pause: 'Pause'
backward: '10s zurück'
forward: '30s vorwärts'
changePlaybackSpeed: 'Abspielgeschwindigkeit ändern'
transcript:
search: 'Transkript durchsuchen'
show: 'Transkript anzeigen'
title: 'Transkript'
subscribeBar:
allEpisodes: 'Alle Episoden'
podcastOnItunes: 'Podcast auf Apple Podcasts ansehen'
podcastOnSpotify: 'Podcast auf Spotify ansehen'
podcastOnDeezer: 'Podcast auf Deezer ansehen'
podcastOnAlexa: 'Podcast auf Alexa ansehen'
podcastOnPodimo: 'Podcast auf Podimo ansehen'
subscribe: 'Abonnieren'
'es-ES':
chaptermarks:
show: 'Marca temporal'
title: 'Marcas temporales'
chromecast:
play: 'Reproducir en chromecast'
download:
episode: 'Descargar capítulo'
episode_info:
more_info: 'Mostrar más informaciones'
title: 'Informaciones del capítulo'
playlist:
show: 'Mostrar lista de reproducción'
title: 'Lista de reproducción'
load_more: 'Más capítulos'
progress_bar:
switch_time_mode: 'Cambiar el modo de visualización'
share:
copy_episode_link: 'Copiar enlace del capítulo'
email: 'Correo electrónico'
embed_player: 'Embed del reproductor'
episode: 'Capítulo'
episode_url: 'Compartir enlace del capítulo'
start_at: 'Empezar en'
theme:
playPause: 'Reproducir'
play: 'Reproducir'
pause: 'Pausar'
backward: 'Rebobinar 10s'
forward: 'Avanzar 30s'
changePlaybackSpeed: 'Cambiar velocidad de reproducción'
transcript:
search: 'Buscar en transcripción'
show: 'Mostrar transcripción'
title: 'Transcripción'
subscribeBar:
allEpisodes: 'Todos los capítulos'
podcastOnItunes: 'Ver podcast en Apple Podcasts'
podcastOnSpotify: 'Ver podcast en Spotify'
podcastOnDeezer: 'Ver podcast en Deezer'
podcastOnAlexa: 'Ver podcast en Alexa'
podcastOnPodimo: 'Ver podcast en Podimo'
subscribe: '<NAME>'
'nl-NL':
chaptermarks:
show: 'Toon hoofdstukmarkeringen'
title: 'Hoofdstukmarkeringen'
chromecast:
play: 'Speel af op chromecast'
download:
episode: 'Download aflevering'
episode_info:
more_info: 'Toon meer info'
title: 'Aflevering info'
playlist:
show: 'Toon afspeellijst'
title: 'Afspeellijst'
load_more: 'Laad meer afleveringen'
progress_bar:
switch_time_mode: 'Verander tijdweergave'
share:
copy_episode_link: 'Kopieër link naar aflevering'
email: 'E-mail'
embed_player: 'Embed speler'
episode: 'Aflevering'
episode_url: 'Deel link naar aflevering'
start_at: 'Begin op'
theme:
playPause: 'Afspelen'
play: 'Afspelen'
pause: 'Pauzeren'
backward: 'Terug 10s'
forward: 'Vooruit 30s'
changePlaybackSpeed: 'Verander afspeelsnelheid'
transcript:
search: 'Zoek in transcript'
show: 'Toon transcriptie'
title: 'Transcriptie'
subscribeBar:
allEpisodes: 'Alle Afleveringen'
podcastOnItunes: 'Toon Podcast op Apple Podcasts'
podcastOnSpotify: 'Toon Podcast op Spotify'
podcastOnDeezer: 'Toon Podcast op Deezer'
podcastOnAlexa: 'Toon Podcast op Alexa'
podcastOnPodimo: 'Toon Podcast op Podimo'
subscribe: 'Abonneer'
'pl-PL':
chaptermarks:
show: 'Pokaż znaczniki rozdziałów'
title: 'Rozdziały'
chromecast:
play: 'Odtwórz w chromecast'
download:
episode: 'Pobierz odcinek'
episode_info:
more_info: 'Pokaż więcej informacji'
title: 'Informacje o odcinku'
playlist:
show: 'Pokaż listę odtwarzania'
title: 'Lista odtwarzania'
load_more: 'Załaduj więcej odcinków'
progress_bar:
switch_time_mode: 'Przełącz tryb wyświetlania czasu'
share:
copy_episode_link: 'Kopiuj link do odcinka'
email: 'E-mail'
embed_player: 'Osadź odtwarzacz'
episode: 'Odcinek'
episode_url: 'Udostępnij link do odcinka'
start_at: 'Rozpocznij od'
theme:
playPause: 'Odtwórz'
play: 'Odtwórz'
pause: 'Pauza'
backward: '10s wstecz'
forward: '30s do przodu'
changePlaybackSpeed: 'Zmień prędkość odtwarzania'
transcript:
search: 'Szukaj w transkrypcji'
show: 'Pokaż transkrypcję'
title: 'Transkrypcja'
subscribeBar:
allEpisodes: 'Wszystkie odcinki'
podcastOnItunes: 'Zobacz podcast na Apple Podcasts'
podcastOnSpotify: 'Zobacz podcast na Spotify'
podcastOnDeezer: 'Zobacz podcast na Deezer'
podcastOnAlexa: 'Zobacz podcast na Alexa'
podcastOnPodimo: 'Zobacz podcast na Podimo'
subscribe: 'Subskrybuj'
module.exports = I18n
| true | class I18n
# List of locales that follow BCP-47
SUPPORTED_LOCALES = ['en-US', 'de-DE', 'es-ES', 'nl-NL', 'pl-PL']
# E.g a user with en-GB will get the language 'en'
# The languages are in ISO 639-1
SUPPORTED_LANGUAGES = ['en', 'de', 'es', 'nl', 'pl']
# locale<string> BCP-47, e.g. "en-US", can be nil
# defaultLocale<string> BCP-47, e.g. "de-DE", should not be nil
# if locale is nil, the locale will be computed, falling back to defaultLocale
constructor: (@locale, @defaultLocale) ->
@locale ||= @locale || @getLocale()
true
getLocale: ->
preferredLocale = @getUserPreferredLocale()
preferredLanguage = @getLanguageFromLocale(preferredLocale)
bestLocale = @getLocaleForLanguage(preferredLanguage)
bestLocale || @defaultLocale
# private
getUserPreferredLocale: ->
navigator.language || navigator.userLanguage
# locale<string>, e.g. "en-US", format: BCP-47
getLanguageFromLocale: (locale) ->
locale.substring(0, 2)
# language<string>, e.g. "en", format: ISO 639-1
# for now, it's pretty simple
getLocaleForLanguage: (language) ->
switch language
when "en" then "en-US"
when "de" then "de-DE"
when "es" then "es-ES"
when "nl" then "nl-NL"
when "pl" then "pl-PL"
t: (key) ->
keys = key.split('.')
value = @translationMap[@locale]
for k in keys
value = value[k]
if value
value
else
key
translationMap:
'en-US':
chaptermarks:
show: 'Show chaptermarks'
title: 'Chaptermarks'
chromecast:
play: 'Play on chromecast'
download:
episode: 'Download episode'
episode_info:
more_info: 'Show more info'
title: 'Episode info'
playlist:
show: 'Show playlist'
title: 'Playlist'
load_more: 'Load more episodes'
progress_bar:
switch_time_mode: 'Switch time display mode'
share:
copy_episode_link: 'Copy episode link'
email: 'Email'
embed_player: 'Embed player'
episode: 'Episode'
episode_url: 'Share link to episode'
start_at: 'Start at'
theme:
playPause: 'Play'
play: 'Play'
pause: 'Pause'
backward: 'Backward 10s'
forward: 'Forward 30s'
changePlaybackSpeed: 'Change Playback Speed'
transcript:
search: 'Search in transcript'
show: 'Show transcription'
title: 'Transcription'
subscribeBar:
allEpisodes: 'All Episodes'
podcastOnItunes: 'View Podcast on Apple Podcasts'
podcastOnSpotify: 'View Podcast on Spotify'
podcastOnDeezer: 'View Podcast on Deezer'
podcastOnAlexa: 'View Podcast on Alexa'
podcastOnPodimo: 'View Podcast on Podimo'
subscribe: 'Subscribe'
'de-DE':
chaptermarks:
show: 'Kapitelmarken anzeigen'
title: 'Kapitelmarken'
chromecast:
play: 'Auf Chromecast abspielen'
download:
episode: 'Episode herunterladen'
episode_info:
more_info: 'Mehr Infos anzeigen'
title: 'Episoden-Infos'
playlist:
show: 'Wiedergabeliste anzeigen'
title: 'Wiedergabeliste'
load_more: 'Mehr Episoden laden'
progress_bar:
switch_time_mode: 'Anzeigemodus ändern'
share:
copy_episode_link: 'Link zur Episode kopieren'
email: 'E-Mail'
embed_player: 'Player einbetten'
episode: 'Episode'
episode_url: 'Link zur Episode teilen'
start_at: 'Wiedergabe ab'
theme:
playPause: 'Play'
play: 'Play'
pause: 'Pause'
backward: '10s zurück'
forward: '30s vorwärts'
changePlaybackSpeed: 'Abspielgeschwindigkeit ändern'
transcript:
search: 'Transkript durchsuchen'
show: 'Transkript anzeigen'
title: 'Transkript'
subscribeBar:
allEpisodes: 'Alle Episoden'
podcastOnItunes: 'Podcast auf Apple Podcasts ansehen'
podcastOnSpotify: 'Podcast auf Spotify ansehen'
podcastOnDeezer: 'Podcast auf Deezer ansehen'
podcastOnAlexa: 'Podcast auf Alexa ansehen'
podcastOnPodimo: 'Podcast auf Podimo ansehen'
subscribe: 'Abonnieren'
'es-ES':
chaptermarks:
show: 'Marca temporal'
title: 'Marcas temporales'
chromecast:
play: 'Reproducir en chromecast'
download:
episode: 'Descargar capítulo'
episode_info:
more_info: 'Mostrar más informaciones'
title: 'Informaciones del capítulo'
playlist:
show: 'Mostrar lista de reproducción'
title: 'Lista de reproducción'
load_more: 'Más capítulos'
progress_bar:
switch_time_mode: 'Cambiar el modo de visualización'
share:
copy_episode_link: 'Copiar enlace del capítulo'
email: 'Correo electrónico'
embed_player: 'Embed del reproductor'
episode: 'Capítulo'
episode_url: 'Compartir enlace del capítulo'
start_at: 'Empezar en'
theme:
playPause: 'Reproducir'
play: 'Reproducir'
pause: 'Pausar'
backward: 'Rebobinar 10s'
forward: 'Avanzar 30s'
changePlaybackSpeed: 'Cambiar velocidad de reproducción'
transcript:
search: 'Buscar en transcripción'
show: 'Mostrar transcripción'
title: 'Transcripción'
subscribeBar:
allEpisodes: 'Todos los capítulos'
podcastOnItunes: 'Ver podcast en Apple Podcasts'
podcastOnSpotify: 'Ver podcast en Spotify'
podcastOnDeezer: 'Ver podcast en Deezer'
podcastOnAlexa: 'Ver podcast en Alexa'
podcastOnPodimo: 'Ver podcast en Podimo'
subscribe: 'PI:NAME:<NAME>END_PI'
'nl-NL':
chaptermarks:
show: 'Toon hoofdstukmarkeringen'
title: 'Hoofdstukmarkeringen'
chromecast:
play: 'Speel af op chromecast'
download:
episode: 'Download aflevering'
episode_info:
more_info: 'Toon meer info'
title: 'Aflevering info'
playlist:
show: 'Toon afspeellijst'
title: 'Afspeellijst'
load_more: 'Laad meer afleveringen'
progress_bar:
switch_time_mode: 'Verander tijdweergave'
share:
copy_episode_link: 'Kopieër link naar aflevering'
email: 'E-mail'
embed_player: 'Embed speler'
episode: 'Aflevering'
episode_url: 'Deel link naar aflevering'
start_at: 'Begin op'
theme:
playPause: 'Afspelen'
play: 'Afspelen'
pause: 'Pauzeren'
backward: 'Terug 10s'
forward: 'Vooruit 30s'
changePlaybackSpeed: 'Verander afspeelsnelheid'
transcript:
search: 'Zoek in transcript'
show: 'Toon transcriptie'
title: 'Transcriptie'
subscribeBar:
allEpisodes: 'Alle Afleveringen'
podcastOnItunes: 'Toon Podcast op Apple Podcasts'
podcastOnSpotify: 'Toon Podcast op Spotify'
podcastOnDeezer: 'Toon Podcast op Deezer'
podcastOnAlexa: 'Toon Podcast op Alexa'
podcastOnPodimo: 'Toon Podcast op Podimo'
subscribe: 'Abonneer'
'pl-PL':
chaptermarks:
show: 'Pokaż znaczniki rozdziałów'
title: 'Rozdziały'
chromecast:
play: 'Odtwórz w chromecast'
download:
episode: 'Pobierz odcinek'
episode_info:
more_info: 'Pokaż więcej informacji'
title: 'Informacje o odcinku'
playlist:
show: 'Pokaż listę odtwarzania'
title: 'Lista odtwarzania'
load_more: 'Załaduj więcej odcinków'
progress_bar:
switch_time_mode: 'Przełącz tryb wyświetlania czasu'
share:
copy_episode_link: 'Kopiuj link do odcinka'
email: 'E-mail'
embed_player: 'Osadź odtwarzacz'
episode: 'Odcinek'
episode_url: 'Udostępnij link do odcinka'
start_at: 'Rozpocznij od'
theme:
playPause: 'Odtwórz'
play: 'Odtwórz'
pause: 'Pauza'
backward: '10s wstecz'
forward: '30s do przodu'
changePlaybackSpeed: 'Zmień prędkość odtwarzania'
transcript:
search: 'Szukaj w transkrypcji'
show: 'Pokaż transkrypcję'
title: 'Transkrypcja'
subscribeBar:
allEpisodes: 'Wszystkie odcinki'
podcastOnItunes: 'Zobacz podcast na Apple Podcasts'
podcastOnSpotify: 'Zobacz podcast na Spotify'
podcastOnDeezer: 'Zobacz podcast na Deezer'
podcastOnAlexa: 'Zobacz podcast na Alexa'
podcastOnPodimo: 'Zobacz podcast na Podimo'
subscribe: 'Subskrybuj'
module.exports = I18n
|
[
{
"context": " ,\n token: \"alsoirrelevant\"\n starts: 90\n ",
"end": 2444,
"score": 0.6185713410377502,
"start": 2430,
"tag": "KEY",
"value": "alsoirrelevant"
},
{
"context": "245\n ,\n ... | src/coffee/expression/parse/parentheses.spec.coffee | jameswilddev/influx7 | 1 | describe "expression", -> describe "parse", -> describe "parentheses", ->
rewire = require "rewire"
describe "imports", ->
expressionParseParentheses = rewire "./parentheses"
it "expressionParse", -> (expect expressionParseParentheses.__get__ "expressionParse").toBe require "./../parse"
describe "on calling", ->
expressionParseParentheses = rewire "./parentheses"
run = (config) ->
describe config.description, ->
inputCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.input
expressionParseParentheses.__set__ "expressionParse", (given) ->
if config.expectRecursion
(expect given).toEqual config.expectRecursion
if config.invalid then null else "test recursed"
else
fail "unexpected recursion"
if config.throws
it "throws the expected exception", -> (expect -> expressionParseParentheses inputCopy).toThrow config.throws
else
it "returns the expected output", -> (expect expressionParseParentheses inputCopy).toEqual config.output
beforeEach ->
try
expressionParseParentheses inputCopy
catch
it "does not modify the input", -> (expect inputCopy).toEqual config.input
run
description: "empty parentheses"
input: [
token: "("
children: []
starts: 23
ends: 245
]
throws:
reason: "emptyExpression"
starts: 23
ends: 245
run
description: "empty parentheses of wrong type"
input: [
token: "["
children: []
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses of wrong type"
input: [
token: "["
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
]
starts: 23
ends: 245
]
output: null
run
description: "empty parentheses followed by other tokens"
input: [
token: "("
children: []
starts: 23
ends: 245
,
token: "alsoirrelevant"
starts: 260
ends: 280
]
output: null
run
description: "empty parentheses preceded by other tokens"
input: [
token: "alsoirrelevant"
starts: 2
ends: 15
,
token: "("
children: []
starts: 23
ends: 245
]
output: null
run
description: "empty parentheses followed by other parentheses"
input: [
token: "("
children: []
starts: 23
ends: 245
,
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 263
ends: 289
]
output: null
run
description: "empty parentheses preceded by other parentheses"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
token: "("
children: []
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses followed by other tokens"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
"youguessedit"
]
output: null
run
description: "non-empty parentheses preceded by other tokens"
input: [
"youguessedit"
,
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses followed by other parentheses"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
token: "("
children: [
"youguessedit"
]
starts: 23
ends: 245
]
output: null
run
description: "parentheses containing a single token forming a valid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
]
output:
parentheses: "test recursed"
starts: 23
ends: 245
run
description: "parentheses containing multiple tokens forming a valid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
output:
parentheses: "test recursed"
starts: 23
ends: 245
run
description: "parentheses containing a single token forming an invalid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
]
throws:
reason: "invalidExpression"
starts: 23
ends: 245
invalid: true
run
description: "parentheses containing multiple tokens forming an invalid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
throws:
reason: "invalidExpression"
starts: 23
ends: 245
invalid: true | 19310 | describe "expression", -> describe "parse", -> describe "parentheses", ->
rewire = require "rewire"
describe "imports", ->
expressionParseParentheses = rewire "./parentheses"
it "expressionParse", -> (expect expressionParseParentheses.__get__ "expressionParse").toBe require "./../parse"
describe "on calling", ->
expressionParseParentheses = rewire "./parentheses"
run = (config) ->
describe config.description, ->
inputCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.input
expressionParseParentheses.__set__ "expressionParse", (given) ->
if config.expectRecursion
(expect given).toEqual config.expectRecursion
if config.invalid then null else "test recursed"
else
fail "unexpected recursion"
if config.throws
it "throws the expected exception", -> (expect -> expressionParseParentheses inputCopy).toThrow config.throws
else
it "returns the expected output", -> (expect expressionParseParentheses inputCopy).toEqual config.output
beforeEach ->
try
expressionParseParentheses inputCopy
catch
it "does not modify the input", -> (expect inputCopy).toEqual config.input
run
description: "empty parentheses"
input: [
token: "("
children: []
starts: 23
ends: 245
]
throws:
reason: "emptyExpression"
starts: 23
ends: 245
run
description: "empty parentheses of wrong type"
input: [
token: "["
children: []
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses of wrong type"
input: [
token: "["
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "<KEY>"
starts: 90
ends: 140
]
starts: 23
ends: 245
]
output: null
run
description: "empty parentheses followed by other tokens"
input: [
token: "("
children: []
starts: 23
ends: 245
,
token: "<KEY>"
starts: 260
ends: 280
]
output: null
run
description: "empty parentheses preceded by other tokens"
input: [
token: "alsoirrelevant"
starts: 2
ends: 15
,
token: "("
children: []
starts: 23
ends: 245
]
output: null
run
description: "empty parentheses followed by other parentheses"
input: [
token: "("
children: []
starts: 23
ends: 245
,
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 263
ends: 289
]
output: null
run
description: "empty parentheses preceded by other parentheses"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
token: "("
children: []
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses followed by other tokens"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
"youguessedit"
]
output: null
run
description: "non-empty parentheses preceded by other tokens"
input: [
"youguessedit"
,
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses followed by other parentheses"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
token: "("
children: [
"youguessedit"
]
starts: 23
ends: 245
]
output: null
run
description: "parentheses containing a single token forming a valid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
]
output:
parentheses: "test recursed"
starts: 23
ends: 245
run
description: "parentheses containing multiple tokens forming a valid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
output:
parentheses: "test recursed"
starts: 23
ends: 245
run
description: "parentheses containing a single token forming an invalid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
]
throws:
reason: "invalidExpression"
starts: 23
ends: 245
invalid: true
run
description: "parentheses containing multiple tokens forming an invalid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
throws:
reason: "invalidExpression"
starts: 23
ends: 245
invalid: true | true | describe "expression", -> describe "parse", -> describe "parentheses", ->
rewire = require "rewire"
describe "imports", ->
expressionParseParentheses = rewire "./parentheses"
it "expressionParse", -> (expect expressionParseParentheses.__get__ "expressionParse").toBe require "./../parse"
describe "on calling", ->
expressionParseParentheses = rewire "./parentheses"
run = (config) ->
describe config.description, ->
inputCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.input
expressionParseParentheses.__set__ "expressionParse", (given) ->
if config.expectRecursion
(expect given).toEqual config.expectRecursion
if config.invalid then null else "test recursed"
else
fail "unexpected recursion"
if config.throws
it "throws the expected exception", -> (expect -> expressionParseParentheses inputCopy).toThrow config.throws
else
it "returns the expected output", -> (expect expressionParseParentheses inputCopy).toEqual config.output
beforeEach ->
try
expressionParseParentheses inputCopy
catch
it "does not modify the input", -> (expect inputCopy).toEqual config.input
run
description: "empty parentheses"
input: [
token: "("
children: []
starts: 23
ends: 245
]
throws:
reason: "emptyExpression"
starts: 23
ends: 245
run
description: "empty parentheses of wrong type"
input: [
token: "["
children: []
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses of wrong type"
input: [
token: "["
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "PI:KEY:<KEY>END_PI"
starts: 90
ends: 140
]
starts: 23
ends: 245
]
output: null
run
description: "empty parentheses followed by other tokens"
input: [
token: "("
children: []
starts: 23
ends: 245
,
token: "PI:KEY:<KEY>END_PI"
starts: 260
ends: 280
]
output: null
run
description: "empty parentheses preceded by other tokens"
input: [
token: "alsoirrelevant"
starts: 2
ends: 15
,
token: "("
children: []
starts: 23
ends: 245
]
output: null
run
description: "empty parentheses followed by other parentheses"
input: [
token: "("
children: []
starts: 23
ends: 245
,
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 263
ends: 289
]
output: null
run
description: "empty parentheses preceded by other parentheses"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
token: "("
children: []
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses followed by other tokens"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
"youguessedit"
]
output: null
run
description: "non-empty parentheses preceded by other tokens"
input: [
"youguessedit"
,
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
]
output: null
run
description: "non-empty parentheses followed by other parentheses"
input: [
token: "("
children: [
"irrelevant"
"alsoirrelevant"
]
starts: 23
ends: 245
,
token: "("
children: [
"youguessedit"
]
starts: 23
ends: 245
]
output: null
run
description: "parentheses containing a single token forming a valid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
]
output:
parentheses: "test recursed"
starts: 23
ends: 245
run
description: "parentheses containing multiple tokens forming a valid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
output:
parentheses: "test recursed"
starts: 23
ends: 245
run
description: "parentheses containing a single token forming an invalid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
]
throws:
reason: "invalidExpression"
starts: 23
ends: 245
invalid: true
run
description: "parentheses containing multiple tokens forming an invalid expression"
input: [
token: "("
children: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
starts: 23
ends: 245
]
expectRecursion: [
token: "irrelevant"
starts: 30
ends: 70
,
token: "alsoirrelevant"
starts: 90
ends: 140
,
token: "youguessedit"
starts: 160
ends: 190
]
throws:
reason: "invalidExpression"
starts: 23
ends: 245
invalid: true |
[
{
"context": "rn recipients\n# return [\n# {to:'yuryilinikh@gmail.com', name: 'Yury', post: 'My awesome post header abo",
"end": 2265,
"score": 0.9999275207519531,
"start": 2244,
"tag": "EMAIL",
"value": "yuryilinikh@gmail.com"
},
{
"context": "\n# {to:'y... | src/server/utils/marketing_mails.coffee | LaPingvino/rizzoma | 88 | async = require('async')
Conf = require('../conf').Conf
logger = Conf.getLogger('marketing_mails')
SmtpTransport = require('../notification/transport/smtp').SmtpTransport
class MarketingMailer
constructor: () ->
conf = Conf.getNotificationConf()
@_smtp = new SmtpTransport(conf.transport.smtp)
@_smtp.init()
@_timeout = 1 # seconds between mails
run: (recipientsFile, callback) ->
recipients = @_parseRecipients(recipientsFile)
# следующую строку необходимо раскомментировать, чтобы пошла реальная отправка писем
#@_sendMails(recipients, callback)
_parseRecipients: (recipientsFile) ->
###
Загружает и разбирает текстовый файл с email получателей и данными для писем.
Строки в файле разделяются \n (перенос строки), каждая строка - это одно отправляемое письмо.
Поля в файле разделяются символом табуляции. В одном из полей должен быть указан email получателя,
в остальных полях указываются дополнительные данные, которые будут переданы в шаблон письма.
###
fs = require('fs')
t = fs.readFileSync(recipientsFile).toString()
lines = t.trim().split(/\s*\n\s*/)
recipients = []
for line, i in lines
parts = line.split(/\t/)
# parts - это поля одной строки.
partsCount = 7 # количество полей в каждой строке. Если полей будет не столько, то строка будет пропущена.
emailPartNumber = 3 # номер поля с email получателя. Нумерация с нуля (т.е. 3 - это четвертое поле).
if parts.length == partsCount and parts[emailPartNumber].indexOf('@') != -1
# Разбирает поля и раскладывает их по переменным.
# "to" - это email получателя, остальные поля можно называть как угодно,
# по этим названиям к ним можно будет доступиться в шаблоне.
recipients.push {to: parts[emailPartNumber], name: parts[2], post: parts[5], postUrl: parts[6]}
else
logger.warn ("Bad line #{i+1}: '#{line}', skiping")
logger.debug(recipients)
logger.info("Got #{recipients.length} recipients")
return recipients
# return [
# {to:'yuryilinikh@gmail.com', name: 'Yury', post: 'My awesome post header about Education', postUrl: 'http://mypost.com'}
# ]
_sendMails: (recipients, callback) ->
tasks = []
for recipient in recipients
tasks.push do(recipient) =>
return (callback) =>
context = recipient
# Если в письме должны быть аттачменты, то раскомментировать следующие строки.
# Для каждого аттачмента указывается имя файла и путь, откуда его брать,
# а также "cid" - имя, по которому его можно будет адресовывать в html-коде письма:
# картинку с cid:'GW_users.png' в html можно будет подключить конструкцией
# <img src="cid:GW_users.png" alt="описание картинки" />.
# context.attachments = [
# {fileName: 'GW_users.png', cid: 'GW_users.png', filePath: 'src/static/img/marketing_mails/gw_users.png'}
# ]
@_smtp.notificateUser({email: recipient.to}, 'marketing_blogger_mail_3', context, (err, res) =>
setTimeout(() =>
callback(null, err)
, @_timeout * 1000 )
)
async.series(tasks, (err, res) ->
logger.info(res)
callback?(null)
)
module.exports.MarketingMailer = new MarketingMailer
| 100554 | async = require('async')
Conf = require('../conf').Conf
logger = Conf.getLogger('marketing_mails')
SmtpTransport = require('../notification/transport/smtp').SmtpTransport
class MarketingMailer
constructor: () ->
conf = Conf.getNotificationConf()
@_smtp = new SmtpTransport(conf.transport.smtp)
@_smtp.init()
@_timeout = 1 # seconds between mails
run: (recipientsFile, callback) ->
recipients = @_parseRecipients(recipientsFile)
# следующую строку необходимо раскомментировать, чтобы пошла реальная отправка писем
#@_sendMails(recipients, callback)
_parseRecipients: (recipientsFile) ->
###
Загружает и разбирает текстовый файл с email получателей и данными для писем.
Строки в файле разделяются \n (перенос строки), каждая строка - это одно отправляемое письмо.
Поля в файле разделяются символом табуляции. В одном из полей должен быть указан email получателя,
в остальных полях указываются дополнительные данные, которые будут переданы в шаблон письма.
###
fs = require('fs')
t = fs.readFileSync(recipientsFile).toString()
lines = t.trim().split(/\s*\n\s*/)
recipients = []
for line, i in lines
parts = line.split(/\t/)
# parts - это поля одной строки.
partsCount = 7 # количество полей в каждой строке. Если полей будет не столько, то строка будет пропущена.
emailPartNumber = 3 # номер поля с email получателя. Нумерация с нуля (т.е. 3 - это четвертое поле).
if parts.length == partsCount and parts[emailPartNumber].indexOf('@') != -1
# Разбирает поля и раскладывает их по переменным.
# "to" - это email получателя, остальные поля можно называть как угодно,
# по этим названиям к ним можно будет доступиться в шаблоне.
recipients.push {to: parts[emailPartNumber], name: parts[2], post: parts[5], postUrl: parts[6]}
else
logger.warn ("Bad line #{i+1}: '#{line}', skiping")
logger.debug(recipients)
logger.info("Got #{recipients.length} recipients")
return recipients
# return [
# {to:'<EMAIL>', name: '<NAME>', post: 'My awesome post header about Education', postUrl: 'http://mypost.com'}
# ]
_sendMails: (recipients, callback) ->
tasks = []
for recipient in recipients
tasks.push do(recipient) =>
return (callback) =>
context = recipient
# Если в письме должны быть аттачменты, то раскомментировать следующие строки.
# Для каждого аттачмента указывается имя файла и путь, откуда его брать,
# а также "cid" - имя, по которому его можно будет адресовывать в html-коде письма:
# картинку с cid:'GW_users.png' в html можно будет подключить конструкцией
# <img src="cid:GW_users.png" alt="описание картинки" />.
# context.attachments = [
# {fileName: 'GW_users.png', cid: 'GW_users.png', filePath: 'src/static/img/marketing_mails/gw_users.png'}
# ]
@_smtp.notificateUser({email: recipient.to}, 'marketing_blogger_mail_3', context, (err, res) =>
setTimeout(() =>
callback(null, err)
, @_timeout * 1000 )
)
async.series(tasks, (err, res) ->
logger.info(res)
callback?(null)
)
module.exports.MarketingMailer = new MarketingMailer
| true | async = require('async')
Conf = require('../conf').Conf
logger = Conf.getLogger('marketing_mails')
SmtpTransport = require('../notification/transport/smtp').SmtpTransport
class MarketingMailer
constructor: () ->
conf = Conf.getNotificationConf()
@_smtp = new SmtpTransport(conf.transport.smtp)
@_smtp.init()
@_timeout = 1 # seconds between mails
run: (recipientsFile, callback) ->
recipients = @_parseRecipients(recipientsFile)
# следующую строку необходимо раскомментировать, чтобы пошла реальная отправка писем
#@_sendMails(recipients, callback)
_parseRecipients: (recipientsFile) ->
###
Загружает и разбирает текстовый файл с email получателей и данными для писем.
Строки в файле разделяются \n (перенос строки), каждая строка - это одно отправляемое письмо.
Поля в файле разделяются символом табуляции. В одном из полей должен быть указан email получателя,
в остальных полях указываются дополнительные данные, которые будут переданы в шаблон письма.
###
fs = require('fs')
t = fs.readFileSync(recipientsFile).toString()
lines = t.trim().split(/\s*\n\s*/)
recipients = []
for line, i in lines
parts = line.split(/\t/)
# parts - это поля одной строки.
partsCount = 7 # количество полей в каждой строке. Если полей будет не столько, то строка будет пропущена.
emailPartNumber = 3 # номер поля с email получателя. Нумерация с нуля (т.е. 3 - это четвертое поле).
if parts.length == partsCount and parts[emailPartNumber].indexOf('@') != -1
# Разбирает поля и раскладывает их по переменным.
# "to" - это email получателя, остальные поля можно называть как угодно,
# по этим названиям к ним можно будет доступиться в шаблоне.
recipients.push {to: parts[emailPartNumber], name: parts[2], post: parts[5], postUrl: parts[6]}
else
logger.warn ("Bad line #{i+1}: '#{line}', skiping")
logger.debug(recipients)
logger.info("Got #{recipients.length} recipients")
return recipients
# return [
# {to:'PI:EMAIL:<EMAIL>END_PI', name: 'PI:NAME:<NAME>END_PI', post: 'My awesome post header about Education', postUrl: 'http://mypost.com'}
# ]
_sendMails: (recipients, callback) ->
tasks = []
for recipient in recipients
tasks.push do(recipient) =>
return (callback) =>
context = recipient
# Если в письме должны быть аттачменты, то раскомментировать следующие строки.
# Для каждого аттачмента указывается имя файла и путь, откуда его брать,
# а также "cid" - имя, по которому его можно будет адресовывать в html-коде письма:
# картинку с cid:'GW_users.png' в html можно будет подключить конструкцией
# <img src="cid:GW_users.png" alt="описание картинки" />.
# context.attachments = [
# {fileName: 'GW_users.png', cid: 'GW_users.png', filePath: 'src/static/img/marketing_mails/gw_users.png'}
# ]
@_smtp.notificateUser({email: recipient.to}, 'marketing_blogger_mail_3', context, (err, res) =>
setTimeout(() =>
callback(null, err)
, @_timeout * 1000 )
)
async.series(tasks, (err, res) ->
logger.info(res)
callback?(null)
)
module.exports.MarketingMailer = new MarketingMailer
|
[
{
"context": "= l10nProvider\n\t\t\tl10nProvider.add 'en-US', key: 'message-en'\n\t\t\tl10nProvider.add 'uk-UA', key: 'message-ua'\n\n",
"end": 216,
"score": 0.9960692524909973,
"start": 206,
"tag": "KEY",
"value": "message-en"
},
{
"context": ": 'message-en'\n\t\t\tl10nProvider.add ... | test/unit/service.spec.coffee | 4vanger/angular-l10n | 18 | describe "L10n service", ->
provider = null
service = null
beforeEach ->
angular.module('test-service', ['l10n']).config (l10nProvider) ->
provider = l10nProvider
l10nProvider.add 'en-US', key: 'message-en'
l10nProvider.add 'uk-UA', key: 'message-ua'
module 'test-service'
inject (l10n) -> service = l10n
afterEach ->
# cleanup
provider.locale = null
provider.localeMessages = {}
provider.db = {}
it 'should have en-us as default locale (angular defined)', ->
expect(service.getLocale()).toEqual('en-us')
it 'should return all locales with getAllLocales()', ->
expect(service.getAllLocales()).toEqual(
'en-US': key: 'message-en'
'uk-UA': key: 'message-ua'
)
it 'should change locales using setLocale', ->
service.setLocale 'en-US'
expect(service.getLocale()).toBe('en-US')
service.setLocale 'ua-UK'
expect(service.getLocale()).toBe('ua-UK')
service.setLocale 'en-US'
describe 'l10n.get method', ->
provider = null
service = null
beforeEach ->
angular.module('test-get', ['l10n']).config (l10nProvider) ->
provider = l10nProvider
l10nProvider.add 'en-US',
message: 'one'
nested:
message: 'nested message'
nested:
message: 'nested nested message'
'key.with.dots': 'value'
references:
originalMessage: 'This is message from "originalMessage" resource'
referencedMessage: '@references.originalMessage'
referencedReferencedMessage: '@references.referencedMessage'
escapedMessage: '\\@angularjs is nice twitter to follow'
subs:
hello: 'Hello, %1'
hello2: 'Hello, %1 and %2'
objects:
monthsArr: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
pluralizeParams:
'0': 'Nobody is viewing.'
'one': '1 person is viewing.'
'other': '{} people are viewing.'
l10nProvider.add 'en-CA',
'not-existing-message': 'This exists only in en-CA'
module 'test-get'
inject (l10n) ->
service = l10n
l10n.setLocale 'en-US'
afterEach ->
# cleanup
provider.locale = null
provider.localeMessages = {}
provider.db = {}
it 'should get messages from current locale', ->
expect(service.get('message')).toBe 'one'
it 'should get messages from current locale as service keys', ->
expect(service.message).toBe 'one'
it 'should get nested messages', ->
expect(service.get('key.with.dots')).toBe 'key.with.dots'
expect(service.get('nested.message')).toBe 'nested message'
expect(service.get('nested.nested.message')).toBe 'nested nested message'
it 'should get nested messages as service keys', ->
expect(service.nested.message).toBe 'nested message'
expect(service.nested.nested.message).toBe 'nested nested message'
it 'should be able to reference messages using @ sign', ->
expect(service.get('references.referencedMessage')).toBe 'This is message from "originalMessage" resource'
expect(service.get('references.referencedReferencedMessage')).toBe 'This is message from "originalMessage" resource'
it 'should be able to substitute params', ->
expect(service.get('subs.hello')).toBe 'Hello, %1'
expect(service.get('subs.hello', null)).toBe 'Hello, null'
expect(service.get('subs.hello', 123)).toBe 'Hello, 123'
expect(service.get('subs.hello', 'name')).toBe 'Hello, name'
expect(service.get('subs.hello', 'name', 'name2')).toBe 'Hello, name'
expect(service.get('subs.hello2')).toBe 'Hello, %1 and %2'
expect(service.get('subs.hello2', 'name')).toBe 'Hello, name and %2'
expect(service.get('subs.hello2', 'name', 'name2')).toBe 'Hello, name and name2'
expect(service.get('subs.hello2', 'name', 'name2', 'name3' )).toBe 'Hello, name and name2'
expect(service.get('%1 %2 %3 %4 %5 %6 %7 %8 %9 %10', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).toBe '1 2 3 4 5 6 7 8 9 10'
it 'should fallback to fallback language if no locale for current language is present', ->
expect(service.get('not-existing-message')).toBe 'not-existing-message'
service.setFallbackLocale 'en-CA'
expect(service.get('not-existing-message')).toBe 'This exists only in en-CA'
describe 'l10n directives', ->
compile = null
scope = null
service = null
beforeEach ->
angular.module('test-directive', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
directive:
dirText: 'This line is inserted using l10n-text directive'
dirHtml: 'This line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
dirTitle: 'This title is inserted using l10n-title directive'
dirPlaceholder: 'This placeholder is inserted using l10n-placeholder directive'
dirHref: 'http://en.example.com/Localized link'
dirValue: 'This line is inserted using l10n-value directive'
l10nProvider.add 'uk-UA',
directive:
dirText: 'UAThis line is inserted using l10n-text directive'
dirHtml: 'UAThis line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
dirTitle: 'UAThis title is inserted using l10n-title directive'
dirPlaceholder: 'UAThis placeholder is inserted using l10n-placeholder directive'
dirHref: 'http://ua.example.com/Localized link'
dirValue: 'UAThis line is inserted using l10n-value directive'
module 'test-directive'
inject ($compile, $rootScope, l10n) ->
l10n.setLocale 'en-US'
service = l10n
scope = $rootScope
compile = $compile
setHTML = (html) ->
el = angular.element(html)
compile(el)(scope)
scope.$digest()
return el
it 'should support l10n-text attribute', ->
expect(setHTML('<div l10n-text="directive.dirText"></div>').html()).toBe 'This line is inserted using l10n-text directive'
it 'should support l10n-html attribute', ->
expect(setHTML('<div l10n-html="directive.dirHtml"></div>').html()).toBe 'This line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
it 'should support l10n-title attribute', ->
expect(setHTML('<div l10n-title="directive.dirTitle"></div>').attr('title')).toBe 'This title is inserted using l10n-title directive'
it 'should support l10n-placeholder attribute', ->
expect(setHTML('<div l10n-placeholder="directive.dirPlaceholder"></div>').attr('placeholder')).toBe 'This placeholder is inserted using l10n-placeholder directive'
it 'should support l10n-href attribute', ->
expect(setHTML('<a l10n-href="directive.dirHref"></a>').attr('href')).toBe 'http://en.example.com/Localized link'
it 'should support l10n-value attribute', ->
expect(setHTML('<input l10n-value="directive.dirValue"/>').attr('value')).toBe 'This line is inserted using l10n-value directive'
it 'should update directive values when locale is changed', ->
service.setLocale 'uk-UA'
expect(setHTML('<div l10n-text="directive.dirText"></div>').html()).toBe 'UAThis line is inserted using l10n-text directive'
expect(setHTML('<div l10n-html="directive.dirHtml"></div>').html()).toBe 'UAThis line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
expect(setHTML('<div l10n-title="directive.dirTitle"></div>').attr('title')).toBe 'UAThis title is inserted using l10n-title directive'
expect(setHTML('<div l10n-placeholder="directive.dirPlaceholder"></div>').attr('placeholder')).toBe 'UAThis placeholder is inserted using l10n-placeholder directive'
expect(setHTML('<a l10n-href="directive.dirHref"></a>').attr('href')).toBe 'http://ua.example.com/Localized link'
expect(setHTML('<input l10n-value="directive.dirValue"/>').attr('value')).toBe 'UAThis line is inserted using l10n-value directive'
describe 'l10n using interpolation', ->
compile = null
scope = null
beforeEach ->
angular.module('test-directive', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
interpolation:
message: 'This message is inserted through interpolation using object property.'
nested:
message: 'this is nested message'
l10nProvider.add 'uk-UA',
interpolation:
message: 'UAThis message is inserted through interpolation using object property.'
nested:
message: 'UAthis is nested message'
module 'test-directive'
inject ($compile, $rootScope, l10n) ->
l10n.setLocale 'en-US'
scope = $rootScope
scope.l10n = l10n
compile = $compile
setText = (text) ->
el = angular.element('<div>' + text + '</div>')
compile(el)(scope)
scope.$digest()
return el.html()
it 'should work as service keys', ->
expect(setText('{{ l10n.interpolation.message }}')).toBe 'This message is inserted through interpolation using object property.'
it 'should work when .get method is used', ->
expect(setText('{{ l10n.get("interpolation.message")}}')).toBe 'This message is inserted through interpolation using object property.'
describe 'l10n filter', ->
filter = null
service = null
beforeEach ->
angular.module('test-filter', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
filter:
hello: 'Hello, filter'
hello2: 'Hello %1 and %2'
l10nProvider.add 'uk-UA',
filter:
hello: 'UAHello, filter'
hello2: 'UAHello %1 and %2'
module 'test-filter'
inject ($filter, l10n) ->
l10n.setLocale 'en-US'
service = l10n
filter = $filter
it 'should work', ->
expect(filter('l10n')('filter.hello')).toBe 'Hello, filter'
it 'should accept params', ->
expect(filter('l10n')('filter.hello2')).toBe 'Hello %1 and %2'
expect(filter('l10n')('filter.hello2', 'one')).toBe 'Hello one and %2'
expect(filter('l10n')('filter.hello2', 'one', 'two')).toBe 'Hello one and two'
expect(filter('l10n')('filter.hello2', 'one', 'two', 'three')).toBe 'Hello one and two'
it 'should respect active locale', ->
expect(filter('l10n')('filter.hello')).toBe 'Hello, filter'
service.setLocale 'uk-UA'
expect(filter('l10n')('filter.hello')).toBe 'UAHello, filter'
describe 'provider to service', ->
it 'default locale can be changed using l10nProvider.setLocale', ->
angular.module('provider2service', ['l10n']).config (l10nProvider) ->
l10nProvider.setLocale 'uk-UA'
module 'provider2service'
inject (l10n) ->
expect(l10n.getLocale()).toEqual('uk-UA')
| 85221 | describe "L10n service", ->
provider = null
service = null
beforeEach ->
angular.module('test-service', ['l10n']).config (l10nProvider) ->
provider = l10nProvider
l10nProvider.add 'en-US', key: '<KEY>'
l10nProvider.add 'uk-UA', key: '<KEY>'
module 'test-service'
inject (l10n) -> service = l10n
afterEach ->
# cleanup
provider.locale = null
provider.localeMessages = {}
provider.db = {}
it 'should have en-us as default locale (angular defined)', ->
expect(service.getLocale()).toEqual('en-us')
it 'should return all locales with getAllLocales()', ->
expect(service.getAllLocales()).toEqual(
'en-US': key: '<KEY>'
'uk-UA': key: '<KEY>'
)
it 'should change locales using setLocale', ->
service.setLocale 'en-US'
expect(service.getLocale()).toBe('en-US')
service.setLocale 'ua-UK'
expect(service.getLocale()).toBe('ua-UK')
service.setLocale 'en-US'
describe 'l10n.get method', ->
provider = null
service = null
beforeEach ->
angular.module('test-get', ['l10n']).config (l10nProvider) ->
provider = l10nProvider
l10nProvider.add 'en-US',
message: 'one'
nested:
message: 'nested message'
nested:
message: 'nested nested message'
'key.with.dots': 'value'
references:
originalMessage: 'This is message from "originalMessage" resource'
referencedMessage: '@references.originalMessage'
referencedReferencedMessage: '@references.referencedMessage'
escapedMessage: '\\@angularjs is nice twitter to follow'
subs:
hello: 'Hello, %1'
hello2: 'Hello, %1 and %2'
objects:
monthsArr: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
pluralizeParams:
'0': 'Nobody is viewing.'
'one': '1 person is viewing.'
'other': '{} people are viewing.'
l10nProvider.add 'en-CA',
'not-existing-message': 'This exists only in en-CA'
module 'test-get'
inject (l10n) ->
service = l10n
l10n.setLocale 'en-US'
afterEach ->
# cleanup
provider.locale = null
provider.localeMessages = {}
provider.db = {}
it 'should get messages from current locale', ->
expect(service.get('message')).toBe 'one'
it 'should get messages from current locale as service keys', ->
expect(service.message).toBe 'one'
it 'should get nested messages', ->
expect(service.get('key.with.dots')).toBe 'key.with.dots'
expect(service.get('nested.message')).toBe 'nested message'
expect(service.get('nested.nested.message')).toBe 'nested nested message'
it 'should get nested messages as service keys', ->
expect(service.nested.message).toBe 'nested message'
expect(service.nested.nested.message).toBe 'nested nested message'
it 'should be able to reference messages using @ sign', ->
expect(service.get('references.referencedMessage')).toBe 'This is message from "originalMessage" resource'
expect(service.get('references.referencedReferencedMessage')).toBe 'This is message from "originalMessage" resource'
it 'should be able to substitute params', ->
expect(service.get('subs.hello')).toBe 'Hello, %1'
expect(service.get('subs.hello', null)).toBe 'Hello, null'
expect(service.get('subs.hello', 123)).toBe 'Hello, 123'
expect(service.get('subs.hello', 'name')).toBe 'Hello, name'
expect(service.get('subs.hello', 'name', 'name2')).toBe 'Hello, name'
expect(service.get('subs.hello2')).toBe 'Hello, %1 and %2'
expect(service.get('subs.hello2', 'name')).toBe 'Hello, name and %2'
expect(service.get('subs.hello2', 'name', 'name2')).toBe 'Hello, name and name2'
expect(service.get('subs.hello2', 'name', 'name2', 'name3' )).toBe 'Hello, name and name2'
expect(service.get('%1 %2 %3 %4 %5 %6 %7 %8 %9 %10', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).toBe '1 2 3 4 5 6 7 8 9 10'
it 'should fallback to fallback language if no locale for current language is present', ->
expect(service.get('not-existing-message')).toBe 'not-existing-message'
service.setFallbackLocale 'en-CA'
expect(service.get('not-existing-message')).toBe 'This exists only in en-CA'
describe 'l10n directives', ->
compile = null
scope = null
service = null
beforeEach ->
angular.module('test-directive', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
directive:
dirText: 'This line is inserted using l10n-text directive'
dirHtml: 'This line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
dirTitle: 'This title is inserted using l10n-title directive'
dirPlaceholder: 'This placeholder is inserted using l10n-placeholder directive'
dirHref: 'http://en.example.com/Localized link'
dirValue: 'This line is inserted using l10n-value directive'
l10nProvider.add 'uk-UA',
directive:
dirText: 'UAThis line is inserted using l10n-text directive'
dirHtml: 'UAThis line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
dirTitle: 'UAThis title is inserted using l10n-title directive'
dirPlaceholder: 'UAThis placeholder is inserted using l10n-placeholder directive'
dirHref: 'http://ua.example.com/Localized link'
dirValue: 'UAThis line is inserted using l10n-value directive'
module 'test-directive'
inject ($compile, $rootScope, l10n) ->
l10n.setLocale 'en-US'
service = l10n
scope = $rootScope
compile = $compile
setHTML = (html) ->
el = angular.element(html)
compile(el)(scope)
scope.$digest()
return el
it 'should support l10n-text attribute', ->
expect(setHTML('<div l10n-text="directive.dirText"></div>').html()).toBe 'This line is inserted using l10n-text directive'
it 'should support l10n-html attribute', ->
expect(setHTML('<div l10n-html="directive.dirHtml"></div>').html()).toBe 'This line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
it 'should support l10n-title attribute', ->
expect(setHTML('<div l10n-title="directive.dirTitle"></div>').attr('title')).toBe 'This title is inserted using l10n-title directive'
it 'should support l10n-placeholder attribute', ->
expect(setHTML('<div l10n-placeholder="directive.dirPlaceholder"></div>').attr('placeholder')).toBe 'This placeholder is inserted using l10n-placeholder directive'
it 'should support l10n-href attribute', ->
expect(setHTML('<a l10n-href="directive.dirHref"></a>').attr('href')).toBe 'http://en.example.com/Localized link'
it 'should support l10n-value attribute', ->
expect(setHTML('<input l10n-value="directive.dirValue"/>').attr('value')).toBe 'This line is inserted using l10n-value directive'
it 'should update directive values when locale is changed', ->
service.setLocale 'uk-UA'
expect(setHTML('<div l10n-text="directive.dirText"></div>').html()).toBe 'UAThis line is inserted using l10n-text directive'
expect(setHTML('<div l10n-html="directive.dirHtml"></div>').html()).toBe 'UAThis line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
expect(setHTML('<div l10n-title="directive.dirTitle"></div>').attr('title')).toBe 'UAThis title is inserted using l10n-title directive'
expect(setHTML('<div l10n-placeholder="directive.dirPlaceholder"></div>').attr('placeholder')).toBe 'UAThis placeholder is inserted using l10n-placeholder directive'
expect(setHTML('<a l10n-href="directive.dirHref"></a>').attr('href')).toBe 'http://ua.example.com/Localized link'
expect(setHTML('<input l10n-value="directive.dirValue"/>').attr('value')).toBe 'UAThis line is inserted using l10n-value directive'
describe 'l10n using interpolation', ->
compile = null
scope = null
beforeEach ->
angular.module('test-directive', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
interpolation:
message: 'This message is inserted through interpolation using object property.'
nested:
message: 'this is nested message'
l10nProvider.add 'uk-UA',
interpolation:
message: 'UAThis message is inserted through interpolation using object property.'
nested:
message: 'UAthis is nested message'
module 'test-directive'
inject ($compile, $rootScope, l10n) ->
l10n.setLocale 'en-US'
scope = $rootScope
scope.l10n = l10n
compile = $compile
setText = (text) ->
el = angular.element('<div>' + text + '</div>')
compile(el)(scope)
scope.$digest()
return el.html()
it 'should work as service keys', ->
expect(setText('{{ l10n.interpolation.message }}')).toBe 'This message is inserted through interpolation using object property.'
it 'should work when .get method is used', ->
expect(setText('{{ l10n.get("interpolation.message")}}')).toBe 'This message is inserted through interpolation using object property.'
describe 'l10n filter', ->
filter = null
service = null
beforeEach ->
angular.module('test-filter', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
filter:
hello: 'Hello, filter'
hello2: 'Hello %1 and %2'
l10nProvider.add 'uk-UA',
filter:
hello: 'UAHello, filter'
hello2: 'UAHello %1 and %2'
module 'test-filter'
inject ($filter, l10n) ->
l10n.setLocale 'en-US'
service = l10n
filter = $filter
it 'should work', ->
expect(filter('l10n')('filter.hello')).toBe 'Hello, filter'
it 'should accept params', ->
expect(filter('l10n')('filter.hello2')).toBe 'Hello %1 and %2'
expect(filter('l10n')('filter.hello2', 'one')).toBe 'Hello one and %2'
expect(filter('l10n')('filter.hello2', 'one', 'two')).toBe 'Hello one and two'
expect(filter('l10n')('filter.hello2', 'one', 'two', 'three')).toBe 'Hello one and two'
it 'should respect active locale', ->
expect(filter('l10n')('filter.hello')).toBe 'Hello, filter'
service.setLocale 'uk-UA'
expect(filter('l10n')('filter.hello')).toBe 'UAHello, filter'
describe 'provider to service', ->
it 'default locale can be changed using l10nProvider.setLocale', ->
angular.module('provider2service', ['l10n']).config (l10nProvider) ->
l10nProvider.setLocale 'uk-UA'
module 'provider2service'
inject (l10n) ->
expect(l10n.getLocale()).toEqual('uk-UA')
| true | describe "L10n service", ->
provider = null
service = null
beforeEach ->
angular.module('test-service', ['l10n']).config (l10nProvider) ->
provider = l10nProvider
l10nProvider.add 'en-US', key: 'PI:KEY:<KEY>END_PI'
l10nProvider.add 'uk-UA', key: 'PI:KEY:<KEY>END_PI'
module 'test-service'
inject (l10n) -> service = l10n
afterEach ->
# cleanup
provider.locale = null
provider.localeMessages = {}
provider.db = {}
it 'should have en-us as default locale (angular defined)', ->
expect(service.getLocale()).toEqual('en-us')
it 'should return all locales with getAllLocales()', ->
expect(service.getAllLocales()).toEqual(
'en-US': key: 'PI:KEY:<KEY>END_PI'
'uk-UA': key: 'PI:KEY:<KEY>END_PI'
)
it 'should change locales using setLocale', ->
service.setLocale 'en-US'
expect(service.getLocale()).toBe('en-US')
service.setLocale 'ua-UK'
expect(service.getLocale()).toBe('ua-UK')
service.setLocale 'en-US'
describe 'l10n.get method', ->
provider = null
service = null
beforeEach ->
angular.module('test-get', ['l10n']).config (l10nProvider) ->
provider = l10nProvider
l10nProvider.add 'en-US',
message: 'one'
nested:
message: 'nested message'
nested:
message: 'nested nested message'
'key.with.dots': 'value'
references:
originalMessage: 'This is message from "originalMessage" resource'
referencedMessage: '@references.originalMessage'
referencedReferencedMessage: '@references.referencedMessage'
escapedMessage: '\\@angularjs is nice twitter to follow'
subs:
hello: 'Hello, %1'
hello2: 'Hello, %1 and %2'
objects:
monthsArr: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
pluralizeParams:
'0': 'Nobody is viewing.'
'one': '1 person is viewing.'
'other': '{} people are viewing.'
l10nProvider.add 'en-CA',
'not-existing-message': 'This exists only in en-CA'
module 'test-get'
inject (l10n) ->
service = l10n
l10n.setLocale 'en-US'
afterEach ->
# cleanup
provider.locale = null
provider.localeMessages = {}
provider.db = {}
it 'should get messages from current locale', ->
expect(service.get('message')).toBe 'one'
it 'should get messages from current locale as service keys', ->
expect(service.message).toBe 'one'
it 'should get nested messages', ->
expect(service.get('key.with.dots')).toBe 'key.with.dots'
expect(service.get('nested.message')).toBe 'nested message'
expect(service.get('nested.nested.message')).toBe 'nested nested message'
it 'should get nested messages as service keys', ->
expect(service.nested.message).toBe 'nested message'
expect(service.nested.nested.message).toBe 'nested nested message'
it 'should be able to reference messages using @ sign', ->
expect(service.get('references.referencedMessage')).toBe 'This is message from "originalMessage" resource'
expect(service.get('references.referencedReferencedMessage')).toBe 'This is message from "originalMessage" resource'
it 'should be able to substitute params', ->
expect(service.get('subs.hello')).toBe 'Hello, %1'
expect(service.get('subs.hello', null)).toBe 'Hello, null'
expect(service.get('subs.hello', 123)).toBe 'Hello, 123'
expect(service.get('subs.hello', 'name')).toBe 'Hello, name'
expect(service.get('subs.hello', 'name', 'name2')).toBe 'Hello, name'
expect(service.get('subs.hello2')).toBe 'Hello, %1 and %2'
expect(service.get('subs.hello2', 'name')).toBe 'Hello, name and %2'
expect(service.get('subs.hello2', 'name', 'name2')).toBe 'Hello, name and name2'
expect(service.get('subs.hello2', 'name', 'name2', 'name3' )).toBe 'Hello, name and name2'
expect(service.get('%1 %2 %3 %4 %5 %6 %7 %8 %9 %10', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).toBe '1 2 3 4 5 6 7 8 9 10'
it 'should fallback to fallback language if no locale for current language is present', ->
expect(service.get('not-existing-message')).toBe 'not-existing-message'
service.setFallbackLocale 'en-CA'
expect(service.get('not-existing-message')).toBe 'This exists only in en-CA'
describe 'l10n directives', ->
compile = null
scope = null
service = null
beforeEach ->
angular.module('test-directive', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
directive:
dirText: 'This line is inserted using l10n-text directive'
dirHtml: 'This line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
dirTitle: 'This title is inserted using l10n-title directive'
dirPlaceholder: 'This placeholder is inserted using l10n-placeholder directive'
dirHref: 'http://en.example.com/Localized link'
dirValue: 'This line is inserted using l10n-value directive'
l10nProvider.add 'uk-UA',
directive:
dirText: 'UAThis line is inserted using l10n-text directive'
dirHtml: 'UAThis line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
dirTitle: 'UAThis title is inserted using l10n-title directive'
dirPlaceholder: 'UAThis placeholder is inserted using l10n-placeholder directive'
dirHref: 'http://ua.example.com/Localized link'
dirValue: 'UAThis line is inserted using l10n-value directive'
module 'test-directive'
inject ($compile, $rootScope, l10n) ->
l10n.setLocale 'en-US'
service = l10n
scope = $rootScope
compile = $compile
setHTML = (html) ->
el = angular.element(html)
compile(el)(scope)
scope.$digest()
return el
it 'should support l10n-text attribute', ->
expect(setHTML('<div l10n-text="directive.dirText"></div>').html()).toBe 'This line is inserted using l10n-text directive'
it 'should support l10n-html attribute', ->
expect(setHTML('<div l10n-html="directive.dirHtml"></div>').html()).toBe 'This line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
it 'should support l10n-title attribute', ->
expect(setHTML('<div l10n-title="directive.dirTitle"></div>').attr('title')).toBe 'This title is inserted using l10n-title directive'
it 'should support l10n-placeholder attribute', ->
expect(setHTML('<div l10n-placeholder="directive.dirPlaceholder"></div>').attr('placeholder')).toBe 'This placeholder is inserted using l10n-placeholder directive'
it 'should support l10n-href attribute', ->
expect(setHTML('<a l10n-href="directive.dirHref"></a>').attr('href')).toBe 'http://en.example.com/Localized link'
it 'should support l10n-value attribute', ->
expect(setHTML('<input l10n-value="directive.dirValue"/>').attr('value')).toBe 'This line is inserted using l10n-value directive'
it 'should update directive values when locale is changed', ->
service.setLocale 'uk-UA'
expect(setHTML('<div l10n-text="directive.dirText"></div>').html()).toBe 'UAThis line is inserted using l10n-text directive'
expect(setHTML('<div l10n-html="directive.dirHtml"></div>').html()).toBe 'UAThis line is inserted using l10n-html directive. And it has <b><i>HTML markup</i></b>'
expect(setHTML('<div l10n-title="directive.dirTitle"></div>').attr('title')).toBe 'UAThis title is inserted using l10n-title directive'
expect(setHTML('<div l10n-placeholder="directive.dirPlaceholder"></div>').attr('placeholder')).toBe 'UAThis placeholder is inserted using l10n-placeholder directive'
expect(setHTML('<a l10n-href="directive.dirHref"></a>').attr('href')).toBe 'http://ua.example.com/Localized link'
expect(setHTML('<input l10n-value="directive.dirValue"/>').attr('value')).toBe 'UAThis line is inserted using l10n-value directive'
describe 'l10n using interpolation', ->
compile = null
scope = null
beforeEach ->
angular.module('test-directive', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
interpolation:
message: 'This message is inserted through interpolation using object property.'
nested:
message: 'this is nested message'
l10nProvider.add 'uk-UA',
interpolation:
message: 'UAThis message is inserted through interpolation using object property.'
nested:
message: 'UAthis is nested message'
module 'test-directive'
inject ($compile, $rootScope, l10n) ->
l10n.setLocale 'en-US'
scope = $rootScope
scope.l10n = l10n
compile = $compile
setText = (text) ->
el = angular.element('<div>' + text + '</div>')
compile(el)(scope)
scope.$digest()
return el.html()
it 'should work as service keys', ->
expect(setText('{{ l10n.interpolation.message }}')).toBe 'This message is inserted through interpolation using object property.'
it 'should work when .get method is used', ->
expect(setText('{{ l10n.get("interpolation.message")}}')).toBe 'This message is inserted through interpolation using object property.'
describe 'l10n filter', ->
filter = null
service = null
beforeEach ->
angular.module('test-filter', ['l10n', 'l10n-tools']).config (l10nProvider) ->
l10nProvider.add 'en-US',
filter:
hello: 'Hello, filter'
hello2: 'Hello %1 and %2'
l10nProvider.add 'uk-UA',
filter:
hello: 'UAHello, filter'
hello2: 'UAHello %1 and %2'
module 'test-filter'
inject ($filter, l10n) ->
l10n.setLocale 'en-US'
service = l10n
filter = $filter
it 'should work', ->
expect(filter('l10n')('filter.hello')).toBe 'Hello, filter'
it 'should accept params', ->
expect(filter('l10n')('filter.hello2')).toBe 'Hello %1 and %2'
expect(filter('l10n')('filter.hello2', 'one')).toBe 'Hello one and %2'
expect(filter('l10n')('filter.hello2', 'one', 'two')).toBe 'Hello one and two'
expect(filter('l10n')('filter.hello2', 'one', 'two', 'three')).toBe 'Hello one and two'
it 'should respect active locale', ->
expect(filter('l10n')('filter.hello')).toBe 'Hello, filter'
service.setLocale 'uk-UA'
expect(filter('l10n')('filter.hello')).toBe 'UAHello, filter'
describe 'provider to service', ->
it 'default locale can be changed using l10nProvider.setLocale', ->
angular.module('provider2service', ['l10n']).config (l10nProvider) ->
l10nProvider.setLocale 'uk-UA'
module 'provider2service'
inject (l10n) ->
expect(l10n.getLocale()).toEqual('uk-UA')
|
[
{
"context": " RouteClientValidator.configure({headerClientKey:'client_id', routes})\n .then (msg)->\n ",
"end": 728,
"score": 0.9865312576293945,
"start": 719,
"tag": "KEY",
"value": "client_id"
},
{
"context": "Validator\n clientKey = if clientId th... | test/indexSpec.coffee | akuma1/express-client-validator | 4 | RouteClientValidator = require "../src/index"
_ = require('underscore')
describe "route client validator",->
{sandbox, req, res, next} = {}
beforeEach ->
sandbox = sinon.sandbox.create()
res =
status : sandbox.stub()
send : sandbox.stub()
next = sandbox.stub()
afterEach ->
sandbox.restore()
describe "route setup",->
{route} = {}
beforeEach ->
route =
url : "/route-3/?"
methods : ["PUT","POST","DELETE"]
clientIds : ["CLIENT-1"]
setupAndRunTest = (routes, errorMessage)->
RouteClientValidator.configure({headerClientKey:'client_id', routes})
.then (msg)->
should.fail(errorMessage)
.catch (error)->
error.message.should.eql(errorMessage)
describe "throws error", ->
it "when no routes are configured", ->
setupAndRunTest(undefined,"restricted routes list need to be provided")
it "when empty routes are configured", ->
setupAndRunTest([],"should NOT have less than 1 items")
it "when route has a missing url property", ->
delete route.url
setupAndRunTest([route],"/0 should have required property 'url'")
it "when route has a missing methods property", ->
delete route.methods
setupAndRunTest([route],"/0 should have required property 'methods'")
it "when route has a missing clientIds property", ->
delete route.clientIds
setupAndRunTest([route],"/0 should have required property 'clientIds'")
it "when route url property is empty", ->
route.url = ''
setupAndRunTest([route],"/0/url should NOT be shorter than 1 characters")
it "when route methods property is emtpy", ->
route.methods = []
setupAndRunTest([route],"/0/methods should NOT have less than 1 items")
it "when route method property is not strings", ->
route.methods = [0]
setupAndRunTest([route],"/0/methods/0 should be string")
it "when route clientIds property is not strings", ->
route.clientIds = [0]
setupAndRunTest([route],"/0/clientIds/0 should be string")
describe 'success', ->
setupAndRunSuccessTest = (routes)->
RouteClientValidator.configure({headerClientKey:'client_id', routes})
.then (msg)->
msg.should.eql('routes configured')
.catch (error)->
should.fail(error.message)
it 'to have empty client ids', ->
route.clientIds = []
setupAndRunSuccessTest([route],"/0/clientIds/0 should be string")
describe "route validation",->
{validator,req,routes} = {}
beforeEach ->
routes = require "./sampleData"
configure = (clientId, appRoutes = routes)->
RouteClientValidator.configure({headerClientKey:clientId, routes: appRoutes})
{validator} = RouteClientValidator
clientKey = if clientId then clientId else 'client-id'
req =
originalUrl : "/route-3/AVENGERS"
method : "PUT"
headers : {}
req.headers[clientKey] = "CLIENT-1"
success = (res,next)->
res.status.should.not.have.been.called
res.send.should.not.have.been.called
next.should.have.been.called
failure = (res,next)->
res.status.should.have.been.calledWithExactly 403
res.send.should.have.been.calledWithExactly "Invalid Client"
next.should.not.have.been.called
setupAndAssert=(req,assert)->
validator(req,res,next)
assert(res,next)
describe "using default client header" , ->
beforeEach ->
configure()
describe "success when client is valid and route", ->
it 'matches exactly', ->
req.originalUrl = "/route-3/AVENGERS/child-route/123"
setupAndAssert(req,success)
it 'matches exactly with special characters', ->
req.originalUrl = "/route-3/AVENGERS$1/child-route/123"
setupAndAssert(req,success)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/user"
setupAndAssert(req,success)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/user"
req.headers['client-id'] = "CLIENT-2"
setupAndAssert(req,success)
it 'no route matched till the root',->
newRoutes = _(routes).clone()
newRoutes.shift()
configure(null, newRoutes)
req.originalUrl = "/app/AVENGERS/user"
req.headers['client-id'] = "CLIENT-2"
setupAndAssert(req,success)
describe "success when client is not provided and", ->
it 'the route is open to all',->
req.originalUrl = "/route-4"
req.method = 'GET'
req.headers['client-id'] = undefined
setupAndAssert(req,success)
describe "success different client and route", ->
beforeEach ->
req.method = 'GET'
req.headers['client-id'] = 'CLIENT-3'
it 'matches exactly', ->
req.originalUrl = "/route-2"
setupAndAssert(req,success)
it 'matches exactly with route ending with /', ->
req.originalUrl = "/route-2/"
setupAndAssert(req,success)
it 'matches exactly with route ending with query params', ->
req.originalUrl = "/route-2?a=123&b=456"
setupAndAssert(req,success)
it 'matches exactly with route ending / and query params', ->
req.originalUrl = "/route-2/?a=123&b=456"
setupAndAssert(req,success)
describe 'forbidden when client is invalid and route',->
beforeEach ->
req.headers["client-id"] = "BAD-CLIENT"
it "matches exactly",->
setupAndAssert(req,failure)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/user"
setupAndAssert(req,failure)
it 'matches till root', ->
req.originalUrl = "/random-route/AVENGERS/random-child-route"
setupAndAssert(req,failure)
describe "using custom client header" , ->
beforeEach ->
configure("my_client_header")
describe "success when client is valid and route", ->
it 'matches exactly', ->
setupAndAssert(req,success)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/random-child-route"
setupAndAssert(req,success)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/random-child-route"
req.headers['my_client_header'] = "CLIENT-2"
setupAndAssert(req,success)
it 'no route matched till the root',->
newRoutes = _(routes).clone()
newRoutes.shift()
configure("my_client_header", newRoutes)
req.originalUrl = "/app/AVENGERS/random-child-route"
setupAndAssert(req,success)
describe 'forbidden when client is invalid and route',->
beforeEach ->
req.headers["my_client_header"] = "BAD-CLIENT"
it "matches exactly",->
setupAndAssert(req,failure)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/random-child-route"
setupAndAssert(req,failure)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/random-child-route"
setupAndAssert(req,failure)
| 129616 | RouteClientValidator = require "../src/index"
_ = require('underscore')
describe "route client validator",->
{sandbox, req, res, next} = {}
beforeEach ->
sandbox = sinon.sandbox.create()
res =
status : sandbox.stub()
send : sandbox.stub()
next = sandbox.stub()
afterEach ->
sandbox.restore()
describe "route setup",->
{route} = {}
beforeEach ->
route =
url : "/route-3/?"
methods : ["PUT","POST","DELETE"]
clientIds : ["CLIENT-1"]
setupAndRunTest = (routes, errorMessage)->
RouteClientValidator.configure({headerClientKey:'<KEY>', routes})
.then (msg)->
should.fail(errorMessage)
.catch (error)->
error.message.should.eql(errorMessage)
describe "throws error", ->
it "when no routes are configured", ->
setupAndRunTest(undefined,"restricted routes list need to be provided")
it "when empty routes are configured", ->
setupAndRunTest([],"should NOT have less than 1 items")
it "when route has a missing url property", ->
delete route.url
setupAndRunTest([route],"/0 should have required property 'url'")
it "when route has a missing methods property", ->
delete route.methods
setupAndRunTest([route],"/0 should have required property 'methods'")
it "when route has a missing clientIds property", ->
delete route.clientIds
setupAndRunTest([route],"/0 should have required property 'clientIds'")
it "when route url property is empty", ->
route.url = ''
setupAndRunTest([route],"/0/url should NOT be shorter than 1 characters")
it "when route methods property is emtpy", ->
route.methods = []
setupAndRunTest([route],"/0/methods should NOT have less than 1 items")
it "when route method property is not strings", ->
route.methods = [0]
setupAndRunTest([route],"/0/methods/0 should be string")
it "when route clientIds property is not strings", ->
route.clientIds = [0]
setupAndRunTest([route],"/0/clientIds/0 should be string")
describe 'success', ->
setupAndRunSuccessTest = (routes)->
RouteClientValidator.configure({headerClientKey:'client_id', routes})
.then (msg)->
msg.should.eql('routes configured')
.catch (error)->
should.fail(error.message)
it 'to have empty client ids', ->
route.clientIds = []
setupAndRunSuccessTest([route],"/0/clientIds/0 should be string")
describe "route validation",->
{validator,req,routes} = {}
beforeEach ->
routes = require "./sampleData"
configure = (clientId, appRoutes = routes)->
RouteClientValidator.configure({headerClientKey:clientId, routes: appRoutes})
{validator} = RouteClientValidator
clientKey = if clientId then <KEY> else '<KEY>'
req =
originalUrl : "/route-3/AVENGERS"
method : "PUT"
headers : {}
req.headers[clientKey] = "CLIENT-1"
success = (res,next)->
res.status.should.not.have.been.called
res.send.should.not.have.been.called
next.should.have.been.called
failure = (res,next)->
res.status.should.have.been.calledWithExactly 403
res.send.should.have.been.calledWithExactly "Invalid Client"
next.should.not.have.been.called
setupAndAssert=(req,assert)->
validator(req,res,next)
assert(res,next)
describe "using default client header" , ->
beforeEach ->
configure()
describe "success when client is valid and route", ->
it 'matches exactly', ->
req.originalUrl = "/route-3/AVENGERS/child-route/123"
setupAndAssert(req,success)
it 'matches exactly with special characters', ->
req.originalUrl = "/route-3/AVENGERS$1/child-route/123"
setupAndAssert(req,success)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/user"
setupAndAssert(req,success)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/user"
req.headers['client-id'] = "CLIENT-2"
setupAndAssert(req,success)
it 'no route matched till the root',->
newRoutes = _(routes).clone()
newRoutes.shift()
configure(null, newRoutes)
req.originalUrl = "/app/AVENGERS/user"
req.headers['client-id'] = "CLIENT-2"
setupAndAssert(req,success)
describe "success when client is not provided and", ->
it 'the route is open to all',->
req.originalUrl = "/route-4"
req.method = 'GET'
req.headers['client-id'] = undefined
setupAndAssert(req,success)
describe "success different client and route", ->
beforeEach ->
req.method = 'GET'
req.headers['client-id'] = 'CLIENT-3'
it 'matches exactly', ->
req.originalUrl = "/route-2"
setupAndAssert(req,success)
it 'matches exactly with route ending with /', ->
req.originalUrl = "/route-2/"
setupAndAssert(req,success)
it 'matches exactly with route ending with query params', ->
req.originalUrl = "/route-2?a=123&b=456"
setupAndAssert(req,success)
it 'matches exactly with route ending / and query params', ->
req.originalUrl = "/route-2/?a=123&b=456"
setupAndAssert(req,success)
describe 'forbidden when client is invalid and route',->
beforeEach ->
req.headers["client-id"] = "BAD-CLIENT"
it "matches exactly",->
setupAndAssert(req,failure)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/user"
setupAndAssert(req,failure)
it 'matches till root', ->
req.originalUrl = "/random-route/AVENGERS/random-child-route"
setupAndAssert(req,failure)
describe "using custom client header" , ->
beforeEach ->
configure("my_client_header")
describe "success when client is valid and route", ->
it 'matches exactly', ->
setupAndAssert(req,success)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/random-child-route"
setupAndAssert(req,success)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/random-child-route"
req.headers['my_client_header'] = "CLIENT-2"
setupAndAssert(req,success)
it 'no route matched till the root',->
newRoutes = _(routes).clone()
newRoutes.shift()
configure("my_client_header", newRoutes)
req.originalUrl = "/app/AVENGERS/random-child-route"
setupAndAssert(req,success)
describe 'forbidden when client is invalid and route',->
beforeEach ->
req.headers["my_client_header"] = "BAD-CLIENT"
it "matches exactly",->
setupAndAssert(req,failure)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/random-child-route"
setupAndAssert(req,failure)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/random-child-route"
setupAndAssert(req,failure)
| true | RouteClientValidator = require "../src/index"
_ = require('underscore')
describe "route client validator",->
{sandbox, req, res, next} = {}
beforeEach ->
sandbox = sinon.sandbox.create()
res =
status : sandbox.stub()
send : sandbox.stub()
next = sandbox.stub()
afterEach ->
sandbox.restore()
describe "route setup",->
{route} = {}
beforeEach ->
route =
url : "/route-3/?"
methods : ["PUT","POST","DELETE"]
clientIds : ["CLIENT-1"]
setupAndRunTest = (routes, errorMessage)->
RouteClientValidator.configure({headerClientKey:'PI:KEY:<KEY>END_PI', routes})
.then (msg)->
should.fail(errorMessage)
.catch (error)->
error.message.should.eql(errorMessage)
describe "throws error", ->
it "when no routes are configured", ->
setupAndRunTest(undefined,"restricted routes list need to be provided")
it "when empty routes are configured", ->
setupAndRunTest([],"should NOT have less than 1 items")
it "when route has a missing url property", ->
delete route.url
setupAndRunTest([route],"/0 should have required property 'url'")
it "when route has a missing methods property", ->
delete route.methods
setupAndRunTest([route],"/0 should have required property 'methods'")
it "when route has a missing clientIds property", ->
delete route.clientIds
setupAndRunTest([route],"/0 should have required property 'clientIds'")
it "when route url property is empty", ->
route.url = ''
setupAndRunTest([route],"/0/url should NOT be shorter than 1 characters")
it "when route methods property is emtpy", ->
route.methods = []
setupAndRunTest([route],"/0/methods should NOT have less than 1 items")
it "when route method property is not strings", ->
route.methods = [0]
setupAndRunTest([route],"/0/methods/0 should be string")
it "when route clientIds property is not strings", ->
route.clientIds = [0]
setupAndRunTest([route],"/0/clientIds/0 should be string")
describe 'success', ->
setupAndRunSuccessTest = (routes)->
RouteClientValidator.configure({headerClientKey:'client_id', routes})
.then (msg)->
msg.should.eql('routes configured')
.catch (error)->
should.fail(error.message)
it 'to have empty client ids', ->
route.clientIds = []
setupAndRunSuccessTest([route],"/0/clientIds/0 should be string")
describe "route validation",->
{validator,req,routes} = {}
beforeEach ->
routes = require "./sampleData"
configure = (clientId, appRoutes = routes)->
RouteClientValidator.configure({headerClientKey:clientId, routes: appRoutes})
{validator} = RouteClientValidator
clientKey = if clientId then PI:KEY:<KEY>END_PI else 'PI:KEY:<KEY>END_PI'
req =
originalUrl : "/route-3/AVENGERS"
method : "PUT"
headers : {}
req.headers[clientKey] = "CLIENT-1"
success = (res,next)->
res.status.should.not.have.been.called
res.send.should.not.have.been.called
next.should.have.been.called
failure = (res,next)->
res.status.should.have.been.calledWithExactly 403
res.send.should.have.been.calledWithExactly "Invalid Client"
next.should.not.have.been.called
setupAndAssert=(req,assert)->
validator(req,res,next)
assert(res,next)
describe "using default client header" , ->
beforeEach ->
configure()
describe "success when client is valid and route", ->
it 'matches exactly', ->
req.originalUrl = "/route-3/AVENGERS/child-route/123"
setupAndAssert(req,success)
it 'matches exactly with special characters', ->
req.originalUrl = "/route-3/AVENGERS$1/child-route/123"
setupAndAssert(req,success)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/user"
setupAndAssert(req,success)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/user"
req.headers['client-id'] = "CLIENT-2"
setupAndAssert(req,success)
it 'no route matched till the root',->
newRoutes = _(routes).clone()
newRoutes.shift()
configure(null, newRoutes)
req.originalUrl = "/app/AVENGERS/user"
req.headers['client-id'] = "CLIENT-2"
setupAndAssert(req,success)
describe "success when client is not provided and", ->
it 'the route is open to all',->
req.originalUrl = "/route-4"
req.method = 'GET'
req.headers['client-id'] = undefined
setupAndAssert(req,success)
describe "success different client and route", ->
beforeEach ->
req.method = 'GET'
req.headers['client-id'] = 'CLIENT-3'
it 'matches exactly', ->
req.originalUrl = "/route-2"
setupAndAssert(req,success)
it 'matches exactly with route ending with /', ->
req.originalUrl = "/route-2/"
setupAndAssert(req,success)
it 'matches exactly with route ending with query params', ->
req.originalUrl = "/route-2?a=123&b=456"
setupAndAssert(req,success)
it 'matches exactly with route ending / and query params', ->
req.originalUrl = "/route-2/?a=123&b=456"
setupAndAssert(req,success)
describe 'forbidden when client is invalid and route',->
beforeEach ->
req.headers["client-id"] = "BAD-CLIENT"
it "matches exactly",->
setupAndAssert(req,failure)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/user"
setupAndAssert(req,failure)
it 'matches till root', ->
req.originalUrl = "/random-route/AVENGERS/random-child-route"
setupAndAssert(req,failure)
describe "using custom client header" , ->
beforeEach ->
configure("my_client_header")
describe "success when client is valid and route", ->
it 'matches exactly', ->
setupAndAssert(req,success)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/random-child-route"
setupAndAssert(req,success)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/random-child-route"
req.headers['my_client_header'] = "CLIENT-2"
setupAndAssert(req,success)
it 'no route matched till the root',->
newRoutes = _(routes).clone()
newRoutes.shift()
configure("my_client_header", newRoutes)
req.originalUrl = "/app/AVENGERS/random-child-route"
setupAndAssert(req,success)
describe 'forbidden when client is invalid and route',->
beforeEach ->
req.headers["my_client_header"] = "BAD-CLIENT"
it "matches exactly",->
setupAndAssert(req,failure)
it 'matches partially', ->
req.originalUrl = "/route-3/AVENGERS/random-child-route"
setupAndAssert(req,failure)
it 'matches till root', ->
req.originalUrl = "/app/AVENGERS/random-child-route"
setupAndAssert(req,failure)
|
[
{
"context": "er\n\n baseParams: ->\n result = '?token=' + Langtrainer.LangtrainerApp.currentUser.readAttribute('token')\n result += ",
"end": 436,
"score": 0.5598938465118408,
"start": 414,
"tag": "KEY",
"value": "trainer.LangtrainerApp"
},
{
"context": " result = '?token=' ... | app/assets/javascripts/langtrainer_frontend_backbone/models/step.js.coffee | beorc/langtrainer_frontend_backbone | 0 | class Langtrainer.LangtrainerApp.Models.Step extends Backbone.Model
initialize: ->
@resetState()
resetState: ->
@wordsHelped = 0
@stepsHelped = 0
@wrongAnsers = 0
difficultyIndex: (answer) ->
wordsNumber = answer.split(' ').length
if wordsNumber == 0
return 1
return @stepsHelped + @wrongAnsers/2 + @wordsHelped/wordsNumber
baseParams: ->
result = '?token=' + Langtrainer.LangtrainerApp.currentUser.readAttribute('token')
result += '&unit=' + Langtrainer.LangtrainerApp.currentUser.getCurrentCourse().getCurrentUnit().get('id')
result += '&step=' + @id
result += '&native_language=' + Langtrainer.LangtrainerApp.currentUser.getCurrentNativeLanguage().get('slug')
result += '&language=' + Langtrainer.LangtrainerApp.currentUser.getCurrentForeignLanguage().get('slug')
nextWordUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/help_next_word'
result += @baseParams()
verifyAnswerUrl: (answer) ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/verify_answer'
result += @baseParams()
result += '&answer=' + answer
result += '&difficulty_index=' + @difficultyIndex(answer)
nextStepUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/next_step'
result += @baseParams()
showRightAnswerUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/show_right_answer'
result += @baseParams()
question: (language) ->
result = ''
question = @get("#{language.get('slug')}_question")
if question? && question.length > 0
result = question
if result.length == 0
answer = @answers(language)[0]
result = _.string.trim(answer)
_.string.capitalize result.trim()
answers: (language) ->
@get("#{language.get('slug')}_answers").split('|')
sanitizeText: (text) ->
result = text
result = result.replace(/(\n\r|\n|\r)/g, ' ')
result = result.replace(/\s{2,}/g, ' ')
result = result.trim()
sanitizeForRegex: (text) ->
result = text
result = result.replace(/\?/g, '\\?')
questionHelp: (language) ->
@get("#{language.get('slug')}_help")
matches: (answer, rightAnswer) ->
answerRegexp = XRegExp("^#{@sanitizeText(@sanitizeForRegex(answer))}", 'i')
answerRegexp.exec @sanitizeText(rightAnswer)
nextWordMatches: (answer, rightAnswer) ->
answerRegexp = XRegExp("^#{@sanitizeText(@sanitizeForRegex(answer))}([\\p{L}\\p{P}]*)\\s*([\\p{L}\\p{P}]*)")
answerRegexp.exec @sanitizeText(rightAnswer)
verifyAnswer: (answer, language, context) ->
that = @
rightAnswer = null
if answer.length is 0
Langtrainer.LangtrainerApp.trainingBus.trigger('step:emptyInput', @)
else
rightAnswer = _.find @answers(language), (rightAnswer) ->
!!that.matches(answer, rightAnswer)
if rightAnswer?
Langtrainer.LangtrainerApp.trainingBus.trigger('step:rightInput', @)
else
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongInput', @)
rightAnswer
triggerEvent: (context, eventName) ->
@trigger(context + ':' + eventName)
nextWord: (answer, language) ->
$.ajax
url: @nextWordUrl()
dataType: 'json'
that = @
result = null
_.find @answers(language), (rightAnswer) ->
result = that.nextWordMatches(answer, rightAnswer)
!!result
if result? && result[2].length > 0
@wordsHelped += 1
result
verifyAnswerOnServer: (answer, language) ->
if answer.length is 0
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongAnswer', that)
return
that = @
$.ajax
url: @verifyAnswerUrl(@sanitizeText(answer))
dataType: 'json'
success: (response) ->
if response
that.set response
Langtrainer.LangtrainerApp.trainingBus.trigger('step:changed', that)
Langtrainer.LangtrainerApp.trainingBus.trigger('step:rightAnswer', that)
that.resetState()
else
that.wrongAnsers += 1
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongAnswer', that)
error: ->
Langtrainer.LangtrainerApp.trainingBus.trigger 'step:verificationError', that
nextStep: ->
that = @
$.ajax
url: @nextStepUrl()
dataType: 'json'
success: (response) ->
that.resetState()
that.set response
Langtrainer.LangtrainerApp.trainingBus.trigger('step:changed', that)
error: ->
Langtrainer.LangtrainerApp.trainingBus.trigger 'step:verificationError', that
showRightAnswer: ->
$.ajax
url: @showRightAnswerUrl()
dataType: 'json'
@stepsHelped += 1
| 138383 | class Langtrainer.LangtrainerApp.Models.Step extends Backbone.Model
initialize: ->
@resetState()
resetState: ->
@wordsHelped = 0
@stepsHelped = 0
@wrongAnsers = 0
difficultyIndex: (answer) ->
wordsNumber = answer.split(' ').length
if wordsNumber == 0
return 1
return @stepsHelped + @wrongAnsers/2 + @wordsHelped/wordsNumber
baseParams: ->
result = '?token=' + Lang<KEY>.<KEY>.readAttribute('token')
result += '&unit=' + Langtrainer.LangtrainerApp.currentUser.getCurrentCourse().getCurrentUnit().get('id')
result += '&step=' + @id
result += '&native_language=' + Langtrainer.LangtrainerApp.currentUser.getCurrentNativeLanguage().get('slug')
result += '&language=' + Langtrainer.LangtrainerApp.currentUser.getCurrentForeignLanguage().get('slug')
nextWordUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/help_next_word'
result += @baseParams()
verifyAnswerUrl: (answer) ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/verify_answer'
result += @baseParams()
result += '&answer=' + answer
result += '&difficulty_index=' + @difficultyIndex(answer)
nextStepUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/next_step'
result += @baseParams()
showRightAnswerUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/show_right_answer'
result += @baseParams()
question: (language) ->
result = ''
question = @get("#{language.get('slug')}_question")
if question? && question.length > 0
result = question
if result.length == 0
answer = @answers(language)[0]
result = _.string.trim(answer)
_.string.capitalize result.trim()
answers: (language) ->
@get("#{language.get('slug')}_answers").split('|')
sanitizeText: (text) ->
result = text
result = result.replace(/(\n\r|\n|\r)/g, ' ')
result = result.replace(/\s{2,}/g, ' ')
result = result.trim()
sanitizeForRegex: (text) ->
result = text
result = result.replace(/\?/g, '\\?')
questionHelp: (language) ->
@get("#{language.get('slug')}_help")
matches: (answer, rightAnswer) ->
answerRegexp = XRegExp("^#{@sanitizeText(@sanitizeForRegex(answer))}", 'i')
answerRegexp.exec @sanitizeText(rightAnswer)
nextWordMatches: (answer, rightAnswer) ->
answerRegexp = XRegExp("^#{@sanitizeText(@sanitizeForRegex(answer))}([\\p{L}\\p{P}]*)\\s*([\\p{L}\\p{P}]*)")
answerRegexp.exec @sanitizeText(rightAnswer)
verifyAnswer: (answer, language, context) ->
that = @
rightAnswer = null
if answer.length is 0
Langtrainer.LangtrainerApp.trainingBus.trigger('step:emptyInput', @)
else
rightAnswer = _.find @answers(language), (rightAnswer) ->
!!that.matches(answer, rightAnswer)
if rightAnswer?
Langtrainer.LangtrainerApp.trainingBus.trigger('step:rightInput', @)
else
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongInput', @)
rightAnswer
triggerEvent: (context, eventName) ->
@trigger(context + ':' + eventName)
nextWord: (answer, language) ->
$.ajax
url: @nextWordUrl()
dataType: 'json'
that = @
result = null
_.find @answers(language), (rightAnswer) ->
result = that.nextWordMatches(answer, rightAnswer)
!!result
if result? && result[2].length > 0
@wordsHelped += 1
result
verifyAnswerOnServer: (answer, language) ->
if answer.length is 0
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongAnswer', that)
return
that = @
$.ajax
url: @verifyAnswerUrl(@sanitizeText(answer))
dataType: 'json'
success: (response) ->
if response
that.set response
Langtrainer.LangtrainerApp.trainingBus.trigger('step:changed', that)
Langtrainer.LangtrainerApp.trainingBus.trigger('step:rightAnswer', that)
that.resetState()
else
that.wrongAnsers += 1
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongAnswer', that)
error: ->
Langtrainer.LangtrainerApp.trainingBus.trigger 'step:verificationError', that
nextStep: ->
that = @
$.ajax
url: @nextStepUrl()
dataType: 'json'
success: (response) ->
that.resetState()
that.set response
Langtrainer.LangtrainerApp.trainingBus.trigger('step:changed', that)
error: ->
Langtrainer.LangtrainerApp.trainingBus.trigger 'step:verificationError', that
showRightAnswer: ->
$.ajax
url: @showRightAnswerUrl()
dataType: 'json'
@stepsHelped += 1
| true | class Langtrainer.LangtrainerApp.Models.Step extends Backbone.Model
initialize: ->
@resetState()
resetState: ->
@wordsHelped = 0
@stepsHelped = 0
@wrongAnsers = 0
difficultyIndex: (answer) ->
wordsNumber = answer.split(' ').length
if wordsNumber == 0
return 1
return @stepsHelped + @wrongAnsers/2 + @wordsHelped/wordsNumber
baseParams: ->
result = '?token=' + LangPI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI.readAttribute('token')
result += '&unit=' + Langtrainer.LangtrainerApp.currentUser.getCurrentCourse().getCurrentUnit().get('id')
result += '&step=' + @id
result += '&native_language=' + Langtrainer.LangtrainerApp.currentUser.getCurrentNativeLanguage().get('slug')
result += '&language=' + Langtrainer.LangtrainerApp.currentUser.getCurrentForeignLanguage().get('slug')
nextWordUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/help_next_word'
result += @baseParams()
verifyAnswerUrl: (answer) ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/verify_answer'
result += @baseParams()
result += '&answer=' + answer
result += '&difficulty_index=' + @difficultyIndex(answer)
nextStepUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/next_step'
result += @baseParams()
showRightAnswerUrl: ->
result = Langtrainer.LangtrainerApp.apiEndpoint + '/show_right_answer'
result += @baseParams()
question: (language) ->
result = ''
question = @get("#{language.get('slug')}_question")
if question? && question.length > 0
result = question
if result.length == 0
answer = @answers(language)[0]
result = _.string.trim(answer)
_.string.capitalize result.trim()
answers: (language) ->
@get("#{language.get('slug')}_answers").split('|')
sanitizeText: (text) ->
result = text
result = result.replace(/(\n\r|\n|\r)/g, ' ')
result = result.replace(/\s{2,}/g, ' ')
result = result.trim()
sanitizeForRegex: (text) ->
result = text
result = result.replace(/\?/g, '\\?')
questionHelp: (language) ->
@get("#{language.get('slug')}_help")
matches: (answer, rightAnswer) ->
answerRegexp = XRegExp("^#{@sanitizeText(@sanitizeForRegex(answer))}", 'i')
answerRegexp.exec @sanitizeText(rightAnswer)
nextWordMatches: (answer, rightAnswer) ->
answerRegexp = XRegExp("^#{@sanitizeText(@sanitizeForRegex(answer))}([\\p{L}\\p{P}]*)\\s*([\\p{L}\\p{P}]*)")
answerRegexp.exec @sanitizeText(rightAnswer)
verifyAnswer: (answer, language, context) ->
that = @
rightAnswer = null
if answer.length is 0
Langtrainer.LangtrainerApp.trainingBus.trigger('step:emptyInput', @)
else
rightAnswer = _.find @answers(language), (rightAnswer) ->
!!that.matches(answer, rightAnswer)
if rightAnswer?
Langtrainer.LangtrainerApp.trainingBus.trigger('step:rightInput', @)
else
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongInput', @)
rightAnswer
triggerEvent: (context, eventName) ->
@trigger(context + ':' + eventName)
nextWord: (answer, language) ->
$.ajax
url: @nextWordUrl()
dataType: 'json'
that = @
result = null
_.find @answers(language), (rightAnswer) ->
result = that.nextWordMatches(answer, rightAnswer)
!!result
if result? && result[2].length > 0
@wordsHelped += 1
result
verifyAnswerOnServer: (answer, language) ->
if answer.length is 0
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongAnswer', that)
return
that = @
$.ajax
url: @verifyAnswerUrl(@sanitizeText(answer))
dataType: 'json'
success: (response) ->
if response
that.set response
Langtrainer.LangtrainerApp.trainingBus.trigger('step:changed', that)
Langtrainer.LangtrainerApp.trainingBus.trigger('step:rightAnswer', that)
that.resetState()
else
that.wrongAnsers += 1
Langtrainer.LangtrainerApp.trainingBus.trigger('step:wrongAnswer', that)
error: ->
Langtrainer.LangtrainerApp.trainingBus.trigger 'step:verificationError', that
nextStep: ->
that = @
$.ajax
url: @nextStepUrl()
dataType: 'json'
success: (response) ->
that.resetState()
that.set response
Langtrainer.LangtrainerApp.trainingBus.trigger('step:changed', that)
error: ->
Langtrainer.LangtrainerApp.trainingBus.trigger 'step:verificationError', that
showRightAnswer: ->
$.ajax
url: @showRightAnswerUrl()
dataType: 'json'
@stepsHelped += 1
|
[
{
"context": "ps.annotation.value\n identification._key ?= Math.random()\n\n answersByQuestion = @props.task.questi",
"end": 356,
"score": 0.9835053086280823,
"start": 345,
"tag": "KEY",
"value": "Math.random"
}
] | app/classifier/tasks/survey/annotation-view.cjsx | tlalka/Panoptes-Front-End | 0 | React = require 'react'
createReactClass = require 'create-react-class'
module.exports = createReactClass
displayName: 'SurveyAnnotationView'
getDefaultProperties: ->
task: null
classification: null
annotation: null
render: ->
<div>
{for identification, i in @props.annotation.value
identification._key ?= Math.random()
answersByQuestion = @props.task.questionsOrder.map (questionID) =>
if questionID of identification.answers
answerLabels = [].concat(identification.answers[questionID]).map (answerID) =>
@props.task.questions[questionID].answers[answerID].label
answerLabels.join ', '
answersList = answersByQuestion.filter(Boolean).join '; '
<span key={identification._key}>
<span className="survey-identification-proxy" title={answersList}>
{@props.task.choices[identification.choice].label}
{' '}
<button type="button" className="survey-identification-remove" title="Remove" onClick={@handleRemove.bind this, i}>×</button>
</span>
{' '}
</span>}
</div>
handleRemove: (index) ->
@props.annotation.value.splice index, 1
@props.onChange @props.annotation
| 107529 | React = require 'react'
createReactClass = require 'create-react-class'
module.exports = createReactClass
displayName: 'SurveyAnnotationView'
getDefaultProperties: ->
task: null
classification: null
annotation: null
render: ->
<div>
{for identification, i in @props.annotation.value
identification._key ?= <KEY>()
answersByQuestion = @props.task.questionsOrder.map (questionID) =>
if questionID of identification.answers
answerLabels = [].concat(identification.answers[questionID]).map (answerID) =>
@props.task.questions[questionID].answers[answerID].label
answerLabels.join ', '
answersList = answersByQuestion.filter(Boolean).join '; '
<span key={identification._key}>
<span className="survey-identification-proxy" title={answersList}>
{@props.task.choices[identification.choice].label}
{' '}
<button type="button" className="survey-identification-remove" title="Remove" onClick={@handleRemove.bind this, i}>×</button>
</span>
{' '}
</span>}
</div>
handleRemove: (index) ->
@props.annotation.value.splice index, 1
@props.onChange @props.annotation
| true | React = require 'react'
createReactClass = require 'create-react-class'
module.exports = createReactClass
displayName: 'SurveyAnnotationView'
getDefaultProperties: ->
task: null
classification: null
annotation: null
render: ->
<div>
{for identification, i in @props.annotation.value
identification._key ?= PI:KEY:<KEY>END_PI()
answersByQuestion = @props.task.questionsOrder.map (questionID) =>
if questionID of identification.answers
answerLabels = [].concat(identification.answers[questionID]).map (answerID) =>
@props.task.questions[questionID].answers[answerID].label
answerLabels.join ', '
answersList = answersByQuestion.filter(Boolean).join '; '
<span key={identification._key}>
<span className="survey-identification-proxy" title={answersList}>
{@props.task.choices[identification.choice].label}
{' '}
<button type="button" className="survey-identification-remove" title="Remove" onClick={@handleRemove.bind this, i}>×</button>
</span>
{' '}
</span>}
</div>
handleRemove: (index) ->
@props.annotation.value.splice index, 1
@props.onChange @props.annotation
|
[
{
"context": "signDocs = await @database.allDocs\n startkey: \"_design\"\n endkey: \"_design\\uf777\"\n include_docs",
"end": 1126,
"score": 0.9329729080200195,
"start": 1118,
"tag": "KEY",
"value": "\"_design"
},
{
"context": "se.allDocs\n startkey: \"_design\"\n... | _attachments/app/models/TertiaryIndex.coffee | jongoz/coconut-analytice | 3 | timestamp = require 'time-stamp'
#Case = require './Case'
class TertiaryIndex
constructor: (options) ->
@name = options.name
@docsToSaveOnReset = options.docsToSaveOnReset
@database = new PouchDB("#{Coconut.databaseURL}/zanzibar-index-#{@name.toLowerCase()}")
latestChangeForZanzibarDatabase: =>
new Promise (resolve,reject) =>
Coconut.database.changes
descending: true
include_docs: false
limit: 1
.on "complete", (mostRecentChange) ->
resolve(mostRecentChange.last_seq)
.on "error", (error) ->
reject error
latestChangeForCurrentIndexDocs: =>
@database.get "IndexData"
.catch (error) ->
console.error "Error while latestChangeForCurrentIndexDocs: #{error}"
if error.reason is "missing"
return Promise.resolve(null)
else
return Promise.reject("Non-missing error when latestChangeForCurrentIndexDocs")
.then (indexData) ->
return Promise.resolve(indexData?.lastChangeSequenceProcessed or null)
reset: =>
# Docs to save
designDocs = await @database.allDocs
startkey: "_design"
endkey: "_design\uf777"
include_docs: true
.then (result) ->
Promise.resolve _(result.rows).map (row) ->
doc = row.doc
delete doc._rev
doc
otherDocsToSave = await @database.allDocs
include_docs: true
keys: @docsToSaveOnReset
.then (result) ->
Promise.resolve( _(result.rows).chain().map (row) ->
doc = row.doc
delete doc._rev if doc
doc
.compact().value()
)
docsToSave = designDocs.concat(otherDocsToSave)
databaseNameWithCredentials = @database.name
await @database.destroy()
.catch (error) ->
console.error error
throw "Error while destroying database"
@database = new PouchDB(databaseNameWithCredentials)
await @database.bulkDocs docsToSave
try
latestChangeForZanzibarDatabase = await @latestChangeForZanzibarDatabase()
console.log "Latest change: #{latestChangeForZanzibarDatabase}"
console.log "Retrieving all available case IDs"
Coconut.database.query "cases/cases"
#Coconut.database.query "cases/cases",
# startkey: "0"
# endkey: "2"
.then (result) =>
allCases = _(result.rows).chain().pluck("key").uniq(true).reverse().value()
console.log "Updating #{allCases.length} cases"
await @updateIndexForCases
caseIDs: allCases
console.log "Updated #{@name} index from #{allCases.length} cases"
@database.upsert "IndexData", (doc) =>
doc.lastChangeSequenceProcessed = latestChangeForZanzibarDatabase
doc
catch error
console.error
updateIndexDocs: =>
latestChangeForZanzibarDatabase = await @latestChangeForZanzibarDatabase()
latestChangeForCurrentIndexDocs = await @latestChangeForCurrentIndexDocs()
#
console.log "latestChangeForZanzibarDatabase: #{latestChangeForZanzibarDatabase?.replace(/-.*/, "")}, latestChangeForCurrentIndexDocs: #{latestChangeForCurrentIndexDocs?.replace(/-.*/,"")}"
if latestChangeForCurrentIndexDocs
numberLatestChangeForDatabase = parseInt(latestChangeForZanzibarDatabase?.replace(/-.*/,""))
numberLatestChangeForCurrentIndexDocs = parseInt(latestChangeForCurrentIndexDocs?.replace(/-.*/,""))
if numberLatestChangeForDatabase - numberLatestChangeForCurrentIndexDocs > 10000
console.log "Large number of changes, so just resetting since this is more efficient that reviewing every change."
return @reset()
unless latestChangeForCurrentIndexDocs
console.log "No recorded change for current index docs, so resetting"
@reset()
else
#console.log "Getting changes since #{latestChangeForCurrentSummaryDataDocs.replace(/-.*/, "")}"
# Get list of cases changed since latestChangeForCurrentSummaryDataDocs
Coconut.database.changes
since: latestChangeForCurrentIndexDocs
include_docs: true
filter: "_view"
view: "cases/cases"
.then (result) =>
return if result.results.length is 0
#console.log "Found changes, now plucking case ids"
changedCases = _(result.results).chain().map (change) ->
change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question?
.compact().uniq().value()
#console.log "Changed cases: #{_(changedCases).length}"
await @updateIndexForCases
caseIDs: changedCases
console.log "Updated: #{changedCases.length} cases"
@database.upsert "IndexData", (doc) =>
doc.lastChangeSequenceProcessed = latestChangeForZanzibarDatabase
doc
.catch (error) => console.error error
.then =>
console.log "Index #{@name} Data updated through sequence: #{latestChangeForZanzibarDatabase}"
updateIndexForCases: (options) =>
new Promise (resolve, reject) =>
return resolve() if options.caseIDs.length is 0
numberOfCasesToProcess = options.caseIDs.length
numberOfCasesProcessed = 0
numberOfCasesToProcessPerIteration = 100
while options.caseIDs.length > 0
caseIDs = options.caseIDs.splice(0,numberOfCasesToProcessPerIteration) # remove 100 caseids
cases = await (Case.getCases
caseIDs: caseIDs
)
docsToSave = []
for malariaCase in cases
for indexDoc in await @indexDocsForCase(malariaCase)
docsToSave.push indexDoc
try
await @database.bulkDocs(docsToSave)
catch
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
numberOfCasesProcessed += caseIDs.length
console.log "#{numberOfCasesProcessed}/#{numberOfCasesToProcess} #{Math.floor(numberOfCasesProcessed/numberOfCasesToProcess*100)}% (last ID: #{caseIDs.pop()})"
resolve()
###
updateIndexForCases: (options) =>
new Promise (resolve, reject) =>
docsToSave = []
return resolve() if options.caseIDs.length is 0
for caseID, counter in options.caseIDs
console.log "#{caseID}: (#{counter+1}/#{options.caseIDs.length} #{Math.floor(((counter+1) / options.caseIDs.length) * 100)}%)"
# See app/models/Reports.coffee for a way to load multiple cases at once, instead of one query per case
malariaCase = new Case
caseID: caseID
try
await malariaCase.fetch()
catch
console.error "ERROR fetching case: #{caseID}"
console.error error
for indexDoc in @indexDocsForCase(malariaCase)
docsToSave.push indexDoc
if docsToSave.length > 500
try
await @database.bulkDocs(docsToSave)
catch
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
docsToSave.length = 0 # Clear the array: https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript
try
await @database.bulkDocs(docsToSave)
console.log "Updated #{docsToSave.length} positive individuals for #{options.caseIDs.length} cases"
resolve()
catch error
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
###
indexDocsForCase: (malariaCase) =>
indexDocs = []
individuals = malariaCase.positiveAndNegativeIndividualObjects()
caseID = malariaCase.caseID
if individuals.length is 0
console.log "No individuals for case: #{caseID}"
for individual, index in individuals
docId = "ind_#{caseID}_#{index}"
currentIndividualIndexDoc = null
try
currentIndividualIndexDoc = await @database.get(docId)
catch
# Ignore if there is no document
try
updatedIndividualIndexDoc = individual.summaryCollection()
catch error
console.error error
updatedIndividualIndexDoc["_id"] = docId
updatedIndividualIndexDoc._rev = currentIndividualIndexDoc._rev if currentIndividualIndexDoc?
updatedIndividualIndexDoc.indexUpdatedAt = timestamp('YYYY-MM-DD HH:mm:ss')
indexDocs.push updatedIndividualIndexDoc
return indexDocs
module.exports = TertiaryIndex
| 66914 | timestamp = require 'time-stamp'
#Case = require './Case'
class TertiaryIndex
constructor: (options) ->
@name = options.name
@docsToSaveOnReset = options.docsToSaveOnReset
@database = new PouchDB("#{Coconut.databaseURL}/zanzibar-index-#{@name.toLowerCase()}")
latestChangeForZanzibarDatabase: =>
new Promise (resolve,reject) =>
Coconut.database.changes
descending: true
include_docs: false
limit: 1
.on "complete", (mostRecentChange) ->
resolve(mostRecentChange.last_seq)
.on "error", (error) ->
reject error
latestChangeForCurrentIndexDocs: =>
@database.get "IndexData"
.catch (error) ->
console.error "Error while latestChangeForCurrentIndexDocs: #{error}"
if error.reason is "missing"
return Promise.resolve(null)
else
return Promise.reject("Non-missing error when latestChangeForCurrentIndexDocs")
.then (indexData) ->
return Promise.resolve(indexData?.lastChangeSequenceProcessed or null)
reset: =>
# Docs to save
designDocs = await @database.allDocs
startkey: <KEY>"
endkey: <KEY>"
include_docs: true
.then (result) ->
Promise.resolve _(result.rows).map (row) ->
doc = row.doc
delete doc._rev
doc
otherDocsToSave = await @database.allDocs
include_docs: true
keys: @docsToSaveOnReset
.then (result) ->
Promise.resolve( _(result.rows).chain().map (row) ->
doc = row.doc
delete doc._rev if doc
doc
.compact().value()
)
docsToSave = designDocs.concat(otherDocsToSave)
databaseNameWithCredentials = @database.name
await @database.destroy()
.catch (error) ->
console.error error
throw "Error while destroying database"
@database = new PouchDB(databaseNameWithCredentials)
await @database.bulkDocs docsToSave
try
latestChangeForZanzibarDatabase = await @latestChangeForZanzibarDatabase()
console.log "Latest change: #{latestChangeForZanzibarDatabase}"
console.log "Retrieving all available case IDs"
Coconut.database.query "cases/cases"
#Coconut.database.query "cases/cases",
# startkey: "0"
# endkey: "<KEY>"
.then (result) =>
allCases = _(result.rows).chain().pluck("key").uniq(true).reverse().value()
console.log "Updating #{allCases.length} cases"
await @updateIndexForCases
caseIDs: allCases
console.log "Updated #{@name} index from #{allCases.length} cases"
@database.upsert "IndexData", (doc) =>
doc.lastChangeSequenceProcessed = latestChangeForZanzibarDatabase
doc
catch error
console.error
updateIndexDocs: =>
latestChangeForZanzibarDatabase = await @latestChangeForZanzibarDatabase()
latestChangeForCurrentIndexDocs = await @latestChangeForCurrentIndexDocs()
#
console.log "latestChangeForZanzibarDatabase: #{latestChangeForZanzibarDatabase?.replace(/-.*/, "")}, latestChangeForCurrentIndexDocs: #{latestChangeForCurrentIndexDocs?.replace(/-.*/,"")}"
if latestChangeForCurrentIndexDocs
numberLatestChangeForDatabase = parseInt(latestChangeForZanzibarDatabase?.replace(/-.*/,""))
numberLatestChangeForCurrentIndexDocs = parseInt(latestChangeForCurrentIndexDocs?.replace(/-.*/,""))
if numberLatestChangeForDatabase - numberLatestChangeForCurrentIndexDocs > 10000
console.log "Large number of changes, so just resetting since this is more efficient that reviewing every change."
return @reset()
unless latestChangeForCurrentIndexDocs
console.log "No recorded change for current index docs, so resetting"
@reset()
else
#console.log "Getting changes since #{latestChangeForCurrentSummaryDataDocs.replace(/-.*/, "")}"
# Get list of cases changed since latestChangeForCurrentSummaryDataDocs
Coconut.database.changes
since: latestChangeForCurrentIndexDocs
include_docs: true
filter: "_view"
view: "cases/cases"
.then (result) =>
return if result.results.length is 0
#console.log "Found changes, now plucking case ids"
changedCases = _(result.results).chain().map (change) ->
change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question?
.compact().uniq().value()
#console.log "Changed cases: #{_(changedCases).length}"
await @updateIndexForCases
caseIDs: changedCases
console.log "Updated: #{changedCases.length} cases"
@database.upsert "IndexData", (doc) =>
doc.lastChangeSequenceProcessed = latestChangeForZanzibarDatabase
doc
.catch (error) => console.error error
.then =>
console.log "Index #{@name} Data updated through sequence: #{latestChangeForZanzibarDatabase}"
updateIndexForCases: (options) =>
new Promise (resolve, reject) =>
return resolve() if options.caseIDs.length is 0
numberOfCasesToProcess = options.caseIDs.length
numberOfCasesProcessed = 0
numberOfCasesToProcessPerIteration = 100
while options.caseIDs.length > 0
caseIDs = options.caseIDs.splice(0,numberOfCasesToProcessPerIteration) # remove 100 caseids
cases = await (Case.getCases
caseIDs: caseIDs
)
docsToSave = []
for malariaCase in cases
for indexDoc in await @indexDocsForCase(malariaCase)
docsToSave.push indexDoc
try
await @database.bulkDocs(docsToSave)
catch
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
numberOfCasesProcessed += caseIDs.length
console.log "#{numberOfCasesProcessed}/#{numberOfCasesToProcess} #{Math.floor(numberOfCasesProcessed/numberOfCasesToProcess*100)}% (last ID: #{caseIDs.pop()})"
resolve()
###
updateIndexForCases: (options) =>
new Promise (resolve, reject) =>
docsToSave = []
return resolve() if options.caseIDs.length is 0
for caseID, counter in options.caseIDs
console.log "#{caseID}: (#{counter+1}/#{options.caseIDs.length} #{Math.floor(((counter+1) / options.caseIDs.length) * 100)}%)"
# See app/models/Reports.coffee for a way to load multiple cases at once, instead of one query per case
malariaCase = new Case
caseID: caseID
try
await malariaCase.fetch()
catch
console.error "ERROR fetching case: #{caseID}"
console.error error
for indexDoc in @indexDocsForCase(malariaCase)
docsToSave.push indexDoc
if docsToSave.length > 500
try
await @database.bulkDocs(docsToSave)
catch
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
docsToSave.length = 0 # Clear the array: https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript
try
await @database.bulkDocs(docsToSave)
console.log "Updated #{docsToSave.length} positive individuals for #{options.caseIDs.length} cases"
resolve()
catch error
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
###
indexDocsForCase: (malariaCase) =>
indexDocs = []
individuals = malariaCase.positiveAndNegativeIndividualObjects()
caseID = malariaCase.caseID
if individuals.length is 0
console.log "No individuals for case: #{caseID}"
for individual, index in individuals
docId = "ind_#{caseID}_#{index}"
currentIndividualIndexDoc = null
try
currentIndividualIndexDoc = await @database.get(docId)
catch
# Ignore if there is no document
try
updatedIndividualIndexDoc = individual.summaryCollection()
catch error
console.error error
updatedIndividualIndexDoc["_id"] = docId
updatedIndividualIndexDoc._rev = currentIndividualIndexDoc._rev if currentIndividualIndexDoc?
updatedIndividualIndexDoc.indexUpdatedAt = timestamp('YYYY-MM-DD HH:mm:ss')
indexDocs.push updatedIndividualIndexDoc
return indexDocs
module.exports = TertiaryIndex
| true | timestamp = require 'time-stamp'
#Case = require './Case'
class TertiaryIndex
constructor: (options) ->
@name = options.name
@docsToSaveOnReset = options.docsToSaveOnReset
@database = new PouchDB("#{Coconut.databaseURL}/zanzibar-index-#{@name.toLowerCase()}")
latestChangeForZanzibarDatabase: =>
new Promise (resolve,reject) =>
Coconut.database.changes
descending: true
include_docs: false
limit: 1
.on "complete", (mostRecentChange) ->
resolve(mostRecentChange.last_seq)
.on "error", (error) ->
reject error
latestChangeForCurrentIndexDocs: =>
@database.get "IndexData"
.catch (error) ->
console.error "Error while latestChangeForCurrentIndexDocs: #{error}"
if error.reason is "missing"
return Promise.resolve(null)
else
return Promise.reject("Non-missing error when latestChangeForCurrentIndexDocs")
.then (indexData) ->
return Promise.resolve(indexData?.lastChangeSequenceProcessed or null)
reset: =>
# Docs to save
designDocs = await @database.allDocs
startkey: PI:KEY:<KEY>END_PI"
endkey: PI:KEY:<KEY>END_PI"
include_docs: true
.then (result) ->
Promise.resolve _(result.rows).map (row) ->
doc = row.doc
delete doc._rev
doc
otherDocsToSave = await @database.allDocs
include_docs: true
keys: @docsToSaveOnReset
.then (result) ->
Promise.resolve( _(result.rows).chain().map (row) ->
doc = row.doc
delete doc._rev if doc
doc
.compact().value()
)
docsToSave = designDocs.concat(otherDocsToSave)
databaseNameWithCredentials = @database.name
await @database.destroy()
.catch (error) ->
console.error error
throw "Error while destroying database"
@database = new PouchDB(databaseNameWithCredentials)
await @database.bulkDocs docsToSave
try
latestChangeForZanzibarDatabase = await @latestChangeForZanzibarDatabase()
console.log "Latest change: #{latestChangeForZanzibarDatabase}"
console.log "Retrieving all available case IDs"
Coconut.database.query "cases/cases"
#Coconut.database.query "cases/cases",
# startkey: "0"
# endkey: "PI:KEY:<KEY>END_PI"
.then (result) =>
allCases = _(result.rows).chain().pluck("key").uniq(true).reverse().value()
console.log "Updating #{allCases.length} cases"
await @updateIndexForCases
caseIDs: allCases
console.log "Updated #{@name} index from #{allCases.length} cases"
@database.upsert "IndexData", (doc) =>
doc.lastChangeSequenceProcessed = latestChangeForZanzibarDatabase
doc
catch error
console.error
updateIndexDocs: =>
latestChangeForZanzibarDatabase = await @latestChangeForZanzibarDatabase()
latestChangeForCurrentIndexDocs = await @latestChangeForCurrentIndexDocs()
#
console.log "latestChangeForZanzibarDatabase: #{latestChangeForZanzibarDatabase?.replace(/-.*/, "")}, latestChangeForCurrentIndexDocs: #{latestChangeForCurrentIndexDocs?.replace(/-.*/,"")}"
if latestChangeForCurrentIndexDocs
numberLatestChangeForDatabase = parseInt(latestChangeForZanzibarDatabase?.replace(/-.*/,""))
numberLatestChangeForCurrentIndexDocs = parseInt(latestChangeForCurrentIndexDocs?.replace(/-.*/,""))
if numberLatestChangeForDatabase - numberLatestChangeForCurrentIndexDocs > 10000
console.log "Large number of changes, so just resetting since this is more efficient that reviewing every change."
return @reset()
unless latestChangeForCurrentIndexDocs
console.log "No recorded change for current index docs, so resetting"
@reset()
else
#console.log "Getting changes since #{latestChangeForCurrentSummaryDataDocs.replace(/-.*/, "")}"
# Get list of cases changed since latestChangeForCurrentSummaryDataDocs
Coconut.database.changes
since: latestChangeForCurrentIndexDocs
include_docs: true
filter: "_view"
view: "cases/cases"
.then (result) =>
return if result.results.length is 0
#console.log "Found changes, now plucking case ids"
changedCases = _(result.results).chain().map (change) ->
change.doc.MalariaCaseID if change.doc.MalariaCaseID? and change.doc.question?
.compact().uniq().value()
#console.log "Changed cases: #{_(changedCases).length}"
await @updateIndexForCases
caseIDs: changedCases
console.log "Updated: #{changedCases.length} cases"
@database.upsert "IndexData", (doc) =>
doc.lastChangeSequenceProcessed = latestChangeForZanzibarDatabase
doc
.catch (error) => console.error error
.then =>
console.log "Index #{@name} Data updated through sequence: #{latestChangeForZanzibarDatabase}"
updateIndexForCases: (options) =>
new Promise (resolve, reject) =>
return resolve() if options.caseIDs.length is 0
numberOfCasesToProcess = options.caseIDs.length
numberOfCasesProcessed = 0
numberOfCasesToProcessPerIteration = 100
while options.caseIDs.length > 0
caseIDs = options.caseIDs.splice(0,numberOfCasesToProcessPerIteration) # remove 100 caseids
cases = await (Case.getCases
caseIDs: caseIDs
)
docsToSave = []
for malariaCase in cases
for indexDoc in await @indexDocsForCase(malariaCase)
docsToSave.push indexDoc
try
await @database.bulkDocs(docsToSave)
catch
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
numberOfCasesProcessed += caseIDs.length
console.log "#{numberOfCasesProcessed}/#{numberOfCasesToProcess} #{Math.floor(numberOfCasesProcessed/numberOfCasesToProcess*100)}% (last ID: #{caseIDs.pop()})"
resolve()
###
updateIndexForCases: (options) =>
new Promise (resolve, reject) =>
docsToSave = []
return resolve() if options.caseIDs.length is 0
for caseID, counter in options.caseIDs
console.log "#{caseID}: (#{counter+1}/#{options.caseIDs.length} #{Math.floor(((counter+1) / options.caseIDs.length) * 100)}%)"
# See app/models/Reports.coffee for a way to load multiple cases at once, instead of one query per case
malariaCase = new Case
caseID: caseID
try
await malariaCase.fetch()
catch
console.error "ERROR fetching case: #{caseID}"
console.error error
for indexDoc in @indexDocsForCase(malariaCase)
docsToSave.push indexDoc
if docsToSave.length > 500
try
await @database.bulkDocs(docsToSave)
catch
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
docsToSave.length = 0 # Clear the array: https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript
try
await @database.bulkDocs(docsToSave)
console.log "Updated #{docsToSave.length} positive individuals for #{options.caseIDs.length} cases"
resolve()
catch error
console.error "ERROR SAVING #{docsToSave.length} case summaries: #{caseIDs.join ","}"
console.error error
###
indexDocsForCase: (malariaCase) =>
indexDocs = []
individuals = malariaCase.positiveAndNegativeIndividualObjects()
caseID = malariaCase.caseID
if individuals.length is 0
console.log "No individuals for case: #{caseID}"
for individual, index in individuals
docId = "ind_#{caseID}_#{index}"
currentIndividualIndexDoc = null
try
currentIndividualIndexDoc = await @database.get(docId)
catch
# Ignore if there is no document
try
updatedIndividualIndexDoc = individual.summaryCollection()
catch error
console.error error
updatedIndividualIndexDoc["_id"] = docId
updatedIndividualIndexDoc._rev = currentIndividualIndexDoc._rev if currentIndividualIndexDoc?
updatedIndividualIndexDoc.indexUpdatedAt = timestamp('YYYY-MM-DD HH:mm:ss')
indexDocs.push updatedIndividualIndexDoc
return indexDocs
module.exports = TertiaryIndex
|
[
{
"context": "r name> \\n create user <user name> with password <password> \\n delete user <user name> \\n assign role <role ",
"end": 5847,
"score": 0.9889590740203857,
"start": 5839,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ta.approver;\n\t\t\t\t\t\tcreaterepo.create... | scripts/xldeploy/scripts-slack/xldeploy_repo.coffee | akash1233/OnBot_Demo | 4 | #-------------------------------------------------------------------------------
# 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.
#-------------------------------------------------------------------------------
###
Configuration:
1. XLDEPLOY_URL
2. XLDEPLOY_USERNAME
3. XLDEPLOY_PASSWORD
4. HUBOT_NAME
Bot commands
1. deploy <filename> -> to deploy artifact
2. undeploy <version> from <environment> -> to undeploy artifact from environment
3. create repo <repoid> with file <filename> -> to create environment/host/server/virtualhost
4. update repo <repoid> with file <filename> -> to update environment/host/server/virtualhost
5. delete repo <repoid>
6. create role <rolename>
Dependencies:
1. "elasticSearch": "^0.9.2"
2. "request": "2.81.0"
###
eindex = require('./index')
request= require('request')
xldeploy_url = process.env.XLDEPLOY_URL
username = process.env.XLDEPLOY_USERNAME
pawwsord = process.env.XLDEPLOY_PASSWORD
botname = process.env.HUBOT_NAME
deployapi = require('./xldeploy.js')
createrepo = require('./addinfra.js')
updaterepo = require('./updateinfra.js')
deleterepo = require('./deleteinfra.js')
undeploy = require('./undeploy.js')
deleterepo = require('./deleteinfra.js')
createrole = require('./createrole.js')
deleterole = require('./deleterole.js')
getrole = require('./getrole.js')
getuser = require('./getuser.js')
createuser = require('./createuser.js')
deleteuser = require('./deleteuser.js')
assignrole = require('./assignrole.js')
delassignrole = require('./delassignrole.js')
getrepo = require('./getrepo.js')
getjson = require './getjson.js'
generate_id = require('./mongoConnt')
module.exports = (robot) ->
robot.respond /deploy (.*)/i, (msg) ->
filename = msg.match[1]
console.log(filename)
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.deploy.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_deploy","filename":filename}
message = {"text": "Request from "+msg.message.user.name+" for deployment with file "+filename,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_deploy","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.deploy.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.deploy.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
deployapi.deployment xldeploy_url, username, pawwsord, filename, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while deploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy deployment done"
actionmsg = "xldeploy deployment done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_deploy', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
deployapi.deployment xldeploy_url, username, pawwsord, data.filename, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while deploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repoupdate done"
actionmsg = "xldeploy repoupdate done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /help/i, (msg) ->
msg.send 'deploy <filename> \n create repo <id> with file <filename> \n update repo <id> with file <filename> \n undeploy <version> from <environment> \n delete repo <id> \n create role <role name> \n delete role <role name> \n get role \n get user <user name> \n create user <user name> with password <password> \n delete user <user name> \n assign role <role name> from user <usr name> \n delete assignedrole <role name> from user <usr name> \n get repo'
robot.respond /create repo (.*) with file (.*)/i, (msg) ->
filename = msg.match[2]
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.create.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_create","filename":filename,"repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for creating repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_create","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.create.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.create.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
createrepo.create xldeploy_url, username, pawwsord, filename, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while creating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo created"
actionmsg = "xldeploy repo created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_create', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
createrepo.create xldeploy_url, username, pawwsord, data.filename, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while creating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo created"
actionmsg = "xldeploy repo created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /update repo (.*) with file (.*)/i, (msg) ->
filename = msg.match[2]
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.update.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_update","filename":filename,"repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for updating repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_update","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.update.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.update.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
updaterepo.update xldeploy_url, username, pawwsord, filename, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while updating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "rundeck project created"
actionmsg = "rundeck project created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_update', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
updaterepo.update xldeploy_url, username, pawwsord, data.filename, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while updating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repoupdate done"
actionmsg = "xldeploy repoupdate done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /undeploy (.*) from (.*)/i, (msg) ->
version = msg.match[1]
environ = msg.match[2]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.undeploy.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_undeploy","version":version,"environ":environ}
message = {"text": "Request from "+msg.message.user.name+" for undeploying "+version+" from"+environ,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_undeploy","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.undeploy.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.undeploy.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
undeploy.undeployment xldeploy_url, username, pawwsord, version, environ, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while undeploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy undeployment done"
actionmsg = "xldeploy undeployment done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout)
config=JSON.stringify(stdout)
msg.send config;
#Listening the post url
robot.router.post '/xldeploy_undeploy', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
undeploy.undeployment xldeploy_url, username, pawwsord, data.version, data.environ, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while undeploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo update "
actionmsg = "xldeploy repo update "
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout)
config=JSON.stringify(stdout)
robot.messageRoom data.userid, config;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /delete repo (.*)/i, (msg) ->
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.deleterepo.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_deleterepo","repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for deleting repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_deleterepo","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.deleterepo.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.deleterepo.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
deleterepo.deleteinfra xldeploy_url, username, pawwsord, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while deleting repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo deleted"
actionmsg = "xldeploy repo deleted"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_deleterepo', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
deleterepo.deleteinfra xldeploy_url, username, pawwsord, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while deleting repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo deleted"
actionmsg = "xldeploy repo deleted"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /create role (.*)/i, (msg) ->
name = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.createrole.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_createrole","name":name}
message = {"text": "Request from "+msg.message.user.name+" for creating role "+name,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_createrole","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.createrole.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.createrole.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
createrole.createrole xldeploy_url, username, pawwsord, name, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while creating role";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy role created"
actionmsg = "xldeploy role created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_createrole', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
createrole.createrole xldeploy_url, username, pawwsord, data.name, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while creating role";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy role created"
actionmsg = "xldeploy role created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
| 80731 | #-------------------------------------------------------------------------------
# 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.
#-------------------------------------------------------------------------------
###
Configuration:
1. XLDEPLOY_URL
2. XLDEPLOY_USERNAME
3. XLDEPLOY_PASSWORD
4. HUBOT_NAME
Bot commands
1. deploy <filename> -> to deploy artifact
2. undeploy <version> from <environment> -> to undeploy artifact from environment
3. create repo <repoid> with file <filename> -> to create environment/host/server/virtualhost
4. update repo <repoid> with file <filename> -> to update environment/host/server/virtualhost
5. delete repo <repoid>
6. create role <rolename>
Dependencies:
1. "elasticSearch": "^0.9.2"
2. "request": "2.81.0"
###
eindex = require('./index')
request= require('request')
xldeploy_url = process.env.XLDEPLOY_URL
username = process.env.XLDEPLOY_USERNAME
pawwsord = process.env.XLDEPLOY_PASSWORD
botname = process.env.HUBOT_NAME
deployapi = require('./xldeploy.js')
createrepo = require('./addinfra.js')
updaterepo = require('./updateinfra.js')
deleterepo = require('./deleteinfra.js')
undeploy = require('./undeploy.js')
deleterepo = require('./deleteinfra.js')
createrole = require('./createrole.js')
deleterole = require('./deleterole.js')
getrole = require('./getrole.js')
getuser = require('./getuser.js')
createuser = require('./createuser.js')
deleteuser = require('./deleteuser.js')
assignrole = require('./assignrole.js')
delassignrole = require('./delassignrole.js')
getrepo = require('./getrepo.js')
getjson = require './getjson.js'
generate_id = require('./mongoConnt')
module.exports = (robot) ->
robot.respond /deploy (.*)/i, (msg) ->
filename = msg.match[1]
console.log(filename)
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.deploy.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_deploy","filename":filename}
message = {"text": "Request from "+msg.message.user.name+" for deployment with file "+filename,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_deploy","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.deploy.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.deploy.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
deployapi.deployment xldeploy_url, username, pawwsord, filename, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while deploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy deployment done"
actionmsg = "xldeploy deployment done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_deploy', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
deployapi.deployment xldeploy_url, username, pawwsord, data.filename, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while deploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repoupdate done"
actionmsg = "xldeploy repoupdate done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /help/i, (msg) ->
msg.send 'deploy <filename> \n create repo <id> with file <filename> \n update repo <id> with file <filename> \n undeploy <version> from <environment> \n delete repo <id> \n create role <role name> \n delete role <role name> \n get role \n get user <user name> \n create user <user name> with password <<PASSWORD>> \n delete user <user name> \n assign role <role name> from user <usr name> \n delete assignedrole <role name> from user <usr name> \n get repo'
robot.respond /create repo (.*) with file (.*)/i, (msg) ->
filename = msg.match[2]
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.create.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_create","filename":filename,"repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for creating repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_create","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.create.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.create.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
createrepo.create xldeploy_url, username, pawwsord, filename, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while creating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo created"
actionmsg = "xldeploy repo created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_create', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
createrepo.create xldeploy_url, username, pawwsord, data.filename, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while creating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo created"
actionmsg = "xldeploy repo created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /update repo (.*) with file (.*)/i, (msg) ->
filename = msg.match[2]
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.update.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_update","filename":filename,"repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for updating repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_update","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.update.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.update.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
updaterepo.update xldeploy_url, username, pawwsord, filename, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while updating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "rundeck project created"
actionmsg = "rundeck project created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_update', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
updaterepo.update xldeploy_url, username, pawwsord, data.filename, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while updating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repoupdate done"
actionmsg = "xldeploy repoupdate done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /undeploy (.*) from (.*)/i, (msg) ->
version = msg.match[1]
environ = msg.match[2]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.undeploy.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_undeploy","version":version,"environ":environ}
message = {"text": "Request from "+msg.message.user.name+" for undeploying "+version+" from"+environ,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_undeploy","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.undeploy.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.undeploy.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
undeploy.undeployment xldeploy_url, username, pawwsord, version, environ, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while undeploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy undeployment done"
actionmsg = "xldeploy undeployment done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout)
config=JSON.stringify(stdout)
msg.send config;
#Listening the post url
robot.router.post '/xldeploy_undeploy', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
undeploy.undeployment xldeploy_url, username, pawwsord, data.version, data.environ, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while undeploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo update "
actionmsg = "xldeploy repo update "
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout)
config=JSON.stringify(stdout)
robot.messageRoom data.userid, config;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /delete repo (.*)/i, (msg) ->
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.deleterepo.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_deleterepo","repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for deleting repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_deleterepo","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.deleterepo.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.deleterepo.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
deleterepo.deleteinfra xldeploy_url, username, pawwsord, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while deleting repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo deleted"
actionmsg = "xldeploy repo deleted"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_deleterepo', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
deleterepo.deleteinfra xldeploy_url, username, pawwsord, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while deleting repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo deleted"
actionmsg = "xldeploy repo deleted"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /create role (.*)/i, (msg) ->
name = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.createrole.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_createrole","name":name}
message = {"text": "Request from "+msg.message.user.name+" for creating role "+name,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_createrole","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.createrole.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.createrole.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
createrole.createrole xldeploy_url, username, pawwsord, name, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while creating role";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy role created"
actionmsg = "xldeploy role created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_createrole', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
createrole.createrole xldeploy_url, username, pawwsord, data.name, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while creating role";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy role created"
actionmsg = "xldeploy role created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
| 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.
#-------------------------------------------------------------------------------
###
Configuration:
1. XLDEPLOY_URL
2. XLDEPLOY_USERNAME
3. XLDEPLOY_PASSWORD
4. HUBOT_NAME
Bot commands
1. deploy <filename> -> to deploy artifact
2. undeploy <version> from <environment> -> to undeploy artifact from environment
3. create repo <repoid> with file <filename> -> to create environment/host/server/virtualhost
4. update repo <repoid> with file <filename> -> to update environment/host/server/virtualhost
5. delete repo <repoid>
6. create role <rolename>
Dependencies:
1. "elasticSearch": "^0.9.2"
2. "request": "2.81.0"
###
eindex = require('./index')
request= require('request')
xldeploy_url = process.env.XLDEPLOY_URL
username = process.env.XLDEPLOY_USERNAME
pawwsord = process.env.XLDEPLOY_PASSWORD
botname = process.env.HUBOT_NAME
deployapi = require('./xldeploy.js')
createrepo = require('./addinfra.js')
updaterepo = require('./updateinfra.js')
deleterepo = require('./deleteinfra.js')
undeploy = require('./undeploy.js')
deleterepo = require('./deleteinfra.js')
createrole = require('./createrole.js')
deleterole = require('./deleterole.js')
getrole = require('./getrole.js')
getuser = require('./getuser.js')
createuser = require('./createuser.js')
deleteuser = require('./deleteuser.js')
assignrole = require('./assignrole.js')
delassignrole = require('./delassignrole.js')
getrepo = require('./getrepo.js')
getjson = require './getjson.js'
generate_id = require('./mongoConnt')
module.exports = (robot) ->
robot.respond /deploy (.*)/i, (msg) ->
filename = msg.match[1]
console.log(filename)
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.deploy.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_deploy","filename":filename}
message = {"text": "Request from "+msg.message.user.name+" for deployment with file "+filename,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_deploy","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.deploy.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.deploy.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
deployapi.deployment xldeploy_url, username, pawwsord, filename, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while deploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy deployment done"
actionmsg = "xldeploy deployment done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_deploy', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
deployapi.deployment xldeploy_url, username, pawwsord, data.filename, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while deploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repoupdate done"
actionmsg = "xldeploy repoupdate done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /help/i, (msg) ->
msg.send 'deploy <filename> \n create repo <id> with file <filename> \n update repo <id> with file <filename> \n undeploy <version> from <environment> \n delete repo <id> \n create role <role name> \n delete role <role name> \n get role \n get user <user name> \n create user <user name> with password <PI:PASSWORD:<PASSWORD>END_PI> \n delete user <user name> \n assign role <role name> from user <usr name> \n delete assignedrole <role name> from user <usr name> \n get repo'
robot.respond /create repo (.*) with file (.*)/i, (msg) ->
filename = msg.match[2]
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.create.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_create","filename":filename,"repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for creating repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_create","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.create.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.create.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
createrepo.create xldeploy_url, username, pawwsord, filename, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while creating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo created"
actionmsg = "xldeploy repo created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_create', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
createrepo.create xldeploy_url, username, pawwsord, data.filename, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while creating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo created"
actionmsg = "xldeploy repo created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /update repo (.*) with file (.*)/i, (msg) ->
filename = msg.match[2]
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.update.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_update","filename":filename,"repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for updating repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_update","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.update.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.update.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
updaterepo.update xldeploy_url, username, pawwsord, filename, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while updating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "rundeck project created"
actionmsg = "rundeck project created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_update', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
updaterepo.update xldeploy_url, username, pawwsord, data.filename, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while updating repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repoupdate done"
actionmsg = "xldeploy repoupdate done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /undeploy (.*) from (.*)/i, (msg) ->
version = msg.match[1]
environ = msg.match[2]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.undeploy.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_undeploy","version":version,"environ":environ}
message = {"text": "Request from "+msg.message.user.name+" for undeploying "+version+" from"+environ,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_undeploy","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.undeploy.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.undeploy.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
undeploy.undeployment xldeploy_url, username, pawwsord, version, environ, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while undeploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy undeployment done"
actionmsg = "xldeploy undeployment done"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout)
config=JSON.stringify(stdout)
msg.send config;
#Listening the post url
robot.router.post '/xldeploy_undeploy', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
undeploy.undeployment xldeploy_url, username, pawwsord, data.version, data.environ, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while undeploying artifact";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo update "
actionmsg = "xldeploy repo update "
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout)
config=JSON.stringify(stdout)
robot.messageRoom data.userid, config;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /delete repo (.*)/i, (msg) ->
repoid = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.deleterepo.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_deleterepo","repoid":repoid}
message = {"text": "Request from "+msg.message.user.name+" for deleting repo "+repoid,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_deleterepo","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.deleterepo.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.deleterepo.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
deleterepo.deleteinfra xldeploy_url, username, pawwsord, repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while deleting repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo deleted"
actionmsg = "xldeploy repo deleted"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_deleterepo', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
deleterepo.deleteinfra xldeploy_url, username, pawwsord, data.repoid, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while deleting repo";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy repo deleted"
actionmsg = "xldeploy repo deleted"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
robot.respond /create role (.*)/i, (msg) ->
name = msg.match[1]
getjson.getworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if(stdout.createrole.workflowflag)
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
#Prepare payload for slack
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.id,podIp:process.env.MY_POD_IP,"callback_id":"xldeploy_createrole","name":name}
message = {"text": "Request from "+msg.message.user.name+" for creating role "+name,"attachments": [{"text": "U can Approve or Reject","fallback": "failed to respond","callback_id": "xldeploy_createrole","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"Approved","text":"Approve","type":"button","value":tckid},{"name":"Rejected","text": "Reject","type": "button","value": tckid,"style": "danger",confirm: {'title': 'Are you sure?','text': 'Do you want to Reject?','ok_text': 'Reject','dismiss_text': 'No'}}]}]}
robot.messageRoom(stdout.createrole.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.createrole.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Normal action without workflow flag
else
createrole.createrole xldeploy_url, username, pawwsord, name, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
msg.send "Error occured while creating role";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
msg.send stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy role created"
actionmsg = "xldeploy role created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
msg.send stdout;
#Listening the post url
robot.router.post '/xldeploy_createrole', (request,response) ->
data= if request.body.payload? then JSON.parse request.body.payload else request.body
#Action flow after approve
if data.action=='Approved'
robot.messageRoom data.userid, 'your request is approved by '+data.approver;
createrole.createrole xldeploy_url, username, pawwsord, data.name, (error, stdout, stderr) ->
if error
setTimeout (->eindex.passData error),1000
console.log(error)
robot.messageRoom data.userid, "Error occured while creating role";
if stderr
setTimeout (->eindex.passData stderr),1000
console.log(stderr)
robot.messageRoom data.userid, stderr;
if stdout
setTimeout (->eindex.passData stdout),1000
message = "xldeploy role created"
actionmsg = "xldeploy role created"
statusmsg = "sucess"
eindex.wallData botname, message, actionmsg, statusmsg;
console.log(stdout);
robot.messageRoom data.userid, stdout;
#Action flow after reject
else
robot.messageRoom data.userid, 'your request is rejected by '+data.approver;
response.send 'success http call'
|
[
{
"context": "module.exports =\n origin: \"monkey\"\n name: \"shines\"\n tags: [\"in\", \"the\", \"closet\"]\n timestamp: Dat",
"end": 51,
"score": 0.9889972805976868,
"start": 45,
"tag": "NAME",
"value": "shines"
}
] | benchmarks/draft4/trivial/valid_doc.coffee | pandastrike/jsck | 176 | module.exports =
origin: "monkey"
name: "shines"
tags: ["in", "the", "closet"]
timestamp: Date.now()
data:
uno: 1
dos: 2
| 225425 | module.exports =
origin: "monkey"
name: "<NAME>"
tags: ["in", "the", "closet"]
timestamp: Date.now()
data:
uno: 1
dos: 2
| true | module.exports =
origin: "monkey"
name: "PI:NAME:<NAME>END_PI"
tags: ["in", "the", "closet"]
timestamp: Date.now()
data:
uno: 1
dos: 2
|
[
{
"context": "\nnikita = require '@nikitajs/core/lib'\n{tags, config, ipa} = require '../test'",
"end": 28,
"score": 0.6361687779426575,
"start": 26,
"tag": "USERNAME",
"value": "js"
},
{
"context": "s', ->\n nikita\n .ipa.user\n uid: 'username'\n attributes: ... | packages/ipa/test/user/index.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
nikita = require '@nikitajs/core/lib'
{tags, config, ipa} = require '../test'
they = require('mocha-they')(config)
return unless tags.ipa
describe 'ipa.user', ->
describe 'schema', ->
it 'schema root properties', ->
nikita
.ipa.user
uid: [1,2,3]
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `ipa.user`:'
'#/properties/uid/type config/uid must be string, type is "string";'
'#/required config must have required property \'attributes\';'
'#/required config must have required property \'connection\'.'
].join ' '
it 'schema connection properties', ->
nikita
.ipa.user
uid: 'username'
attributes: {}
connection: principal: [1,2,3]
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `ipa.user`:'
'#/properties/connection/required config/connection must have required property \'password\';'
'#/properties/principal/type config/connection/principal must be string, type is "string";'
'#/required config/connection must have required property \'url\'.'
].join ' '
it 'coercion of `mail` attribute', ->
nikita
.ipa.user
uid: 'username'
attributes:
givenname: 'Firstname'
sn: 'Lastname'
mail: 'user@nikita.js.org'
connection: ipa
describe 'action', ->
they 'create a user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
uid: 'user_add'
connection: ipa
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
connection: ipa
$status.should.be.true()
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
connection: ipa
$status.should.be.false()
they 'modify a user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del connection: ipa,
uid: 'user_add'
@ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
connection: ipa
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname 2'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
connection: ipa
$status.should.be.true()
{result} = await @ipa.user.show
uid: 'user_add'
connection: ipa
result.givenname.should.eql ['Firstname 2']
they 'modify password', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
connection: ipa
uid: 'user_add'
@ipa.user
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
userpassword: 'toto'
connection: ipa
uid: 'user_add'
{$status} = await @ipa.user
uid: 'user_add'
attributes:
userpassword: 'toto'
connection: ipa
$status.should.be.false()
they 'modify password', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
connection: ipa
uid: 'user_add'
@ipa.user
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
userpassword: 'toto'
connection: ipa
uid: 'user_add'
{$status} = await @ipa.user
attributes:
userpassword: 'toto'
connection: ipa
force_userpassword: true
uid: 'user_add'
$status.should.be.true()
| 13851 |
nikita = require '@nikitajs/core/lib'
{tags, config, ipa} = require '../test'
they = require('mocha-they')(config)
return unless tags.ipa
describe 'ipa.user', ->
describe 'schema', ->
it 'schema root properties', ->
nikita
.ipa.user
uid: [1,2,3]
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `ipa.user`:'
'#/properties/uid/type config/uid must be string, type is "string";'
'#/required config must have required property \'attributes\';'
'#/required config must have required property \'connection\'.'
].join ' '
it 'schema connection properties', ->
nikita
.ipa.user
uid: 'username'
attributes: {}
connection: principal: [1,2,3]
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `ipa.user`:'
'#/properties/connection/required config/connection must have required property \'password\';'
'#/properties/principal/type config/connection/principal must be string, type is "string";'
'#/required config/connection must have required property \'url\'.'
].join ' '
it 'coercion of `mail` attribute', ->
nikita
.ipa.user
uid: 'username'
attributes:
givenname: '<NAME>name'
sn: 'Lastname'
mail: '<EMAIL>'
connection: ipa
describe 'action', ->
they 'create a user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
uid: 'user_add'
connection: ipa
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: '<NAME>'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
connection: ipa
$status.should.be.true()
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
connection: ipa
$status.should.be.false()
they 'modify a user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del connection: ipa,
uid: 'user_add'
@ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
connection: ipa
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname 2'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
connection: ipa
$status.should.be.true()
{result} = await @ipa.user.show
uid: 'user_add'
connection: ipa
result.givenname.should.eql ['Firstname 2']
they 'modify password', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
connection: ipa
uid: 'user_add'
@ipa.user
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
userpassword: '<PASSWORD>'
connection: ipa
uid: 'user_add'
{$status} = await @ipa.user
uid: 'user_add'
attributes:
userpassword: '<PASSWORD>'
connection: ipa
$status.should.be.false()
they 'modify password', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
connection: ipa
uid: 'user_add'
@ipa.user
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
userpassword: '<PASSWORD>'
connection: ipa
uid: 'user_add'
{$status} = await @ipa.user
attributes:
userpassword: '<PASSWORD>'
connection: ipa
force_userpassword: true
uid: 'user_add'
$status.should.be.true()
| true |
nikita = require '@nikitajs/core/lib'
{tags, config, ipa} = require '../test'
they = require('mocha-they')(config)
return unless tags.ipa
describe 'ipa.user', ->
describe 'schema', ->
it 'schema root properties', ->
nikita
.ipa.user
uid: [1,2,3]
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `ipa.user`:'
'#/properties/uid/type config/uid must be string, type is "string";'
'#/required config must have required property \'attributes\';'
'#/required config must have required property \'connection\'.'
].join ' '
it 'schema connection properties', ->
nikita
.ipa.user
uid: 'username'
attributes: {}
connection: principal: [1,2,3]
.should.be.rejectedWith
code: 'NIKITA_SCHEMA_VALIDATION_CONFIG'
message: [
'NIKITA_SCHEMA_VALIDATION_CONFIG:'
'multiple errors were found in the configuration of action `ipa.user`:'
'#/properties/connection/required config/connection must have required property \'password\';'
'#/properties/principal/type config/connection/principal must be string, type is "string";'
'#/required config/connection must have required property \'url\'.'
].join ' '
it 'coercion of `mail` attribute', ->
nikita
.ipa.user
uid: 'username'
attributes:
givenname: 'PI:NAME:<NAME>END_PIname'
sn: 'Lastname'
mail: 'PI:EMAIL:<EMAIL>END_PI'
connection: ipa
describe 'action', ->
they 'create a user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
uid: 'user_add'
connection: ipa
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'PI:NAME:<NAME>END_PI'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
connection: ipa
$status.should.be.true()
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
connection: ipa
$status.should.be.false()
they 'modify a user', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del connection: ipa,
uid: 'user_add'
@ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
connection: ipa
{$status} = await @ipa.user
uid: 'user_add'
attributes:
givenname: 'Firstname 2'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
connection: ipa
$status.should.be.true()
{result} = await @ipa.user.show
uid: 'user_add'
connection: ipa
result.givenname.should.eql ['Firstname 2']
they 'modify password', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
connection: ipa
uid: 'user_add'
@ipa.user
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
userpassword: 'PI:PASSWORD:<PASSWORD>END_PI'
connection: ipa
uid: 'user_add'
{$status} = await @ipa.user
uid: 'user_add'
attributes:
userpassword: 'PI:PASSWORD:<PASSWORD>END_PI'
connection: ipa
$status.should.be.false()
they 'modify password', ({ssh}) ->
nikita
$ssh: ssh
, ->
@ipa.user.del
connection: ipa
uid: 'user_add'
@ipa.user
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
userpassword: 'PI:PASSWORD:<PASSWORD>END_PI'
connection: ipa
uid: 'user_add'
{$status} = await @ipa.user
attributes:
userpassword: 'PI:PASSWORD:<PASSWORD>END_PI'
connection: ipa
force_userpassword: true
uid: 'user_add'
$status.should.be.true()
|
[
{
"context": "h args\", args\n\n manager.sendTask\n name: name\n options: @taskRegistry[name].options\n ",
"end": 4145,
"score": 0.8609194755554199,
"start": 4141,
"tag": "NAME",
"value": "name"
}
] | src/ivy.coffee | apiaryio/ivy | 5 |
{EventEmitter} = require 'events'
logger = require './logger'
queues = require './queues'
{notifier} = require './notifiers'
manager = queues.queue
class Ivy extends EventEmitter
constructor: (options) ->
{
@config
} = options
@taskRegistry = {}
@taskObjectRegistry = {}
super("Ivy")
# Setup main "singleton" instance of ivy that is used when requiring it
setupMain: ->
manager.on 'scheduledTaskRetrieved', @onScheduledTaskRetrieved.bind(@)
manager.setupMain @
notifier.setupMain @
onScheduledTaskRetrieved: ->
@scheduledTaskRetrieved.apply @, arguments
###
# Producer & Consumer: Task registration and handling
###
registerTask: (func, funcCb, options={}) ->
if typeof funcCb is 'object'
options = funcCb
funcCb = null
if typeof func isnt 'function'
throw new Error "First parameter 'func' isn't function is #{func}"
{name} = options
if not name
name = func.name
if not name
logger.error "Cannot determine task name. Please pass it explicitly through options."
throw new Error "Cannot determine task name. Please pass it explicitly through options."
else
delete options.name
queueName = options.queue
if queueName
delete options.queue
@taskRegistry[name] = {
func
funcCb
options
queue: queueName
}
@taskObjectRegistry[func] = name
logger.silly "Registered task #{name} into queue #{queueName}"
###
# Producer & Consumer testing: Clear tasks between tests
###
clearTasks: ->
@taskRegistry = {}
@taskObjectRegistry = {}
###
# Consumer: Resolving tasks recieved from queue and calling them
###
scheduledTaskRetrieved: ({id, name, args, options, queue}) ->
called = false
logger.silly "Retrieved task id #{id}"
@executeTask name, args, (err, result...) =>
if called
logger.error "IVY_ERROR Task #{name} called callback multiple times. It shouldn't do that."
else
called = true
notify = !!@taskRegistry[name].funcCb
# last argument is the callback I am in
args.pop()
@emit 'taskExecuted', err, {id, name, args, options, result, notify, queue}
executeTask: (name, args, cb) ->
if not @taskRegistry[name]
cb new Error "Task #{name} not found in registry on consumer"
else
logger.silly "Executing task #{name}"
try
args.push cb
@taskRegistry[name].func.apply @taskRegistry[name].func, args
catch err
logger.error "IVY_ERROR Ivy task #{name} has thrown an exception. It should call back instead", err
cb err
###
# Producer: Resolving task return/call values back to callback/handler
# and resuming workflow
###
taskResultRetrieved: (data) ->
try
result = JSON.parse data
catch err
logger.error 'IVY_BAD_ARGUMENTS Recieved JSON unparseable function description. Error is: ', err
return false
@resumeCaller result.name, result.args
resumeCaller: (name, args) ->
@taskRegistry[name].funcCb.apply @taskRegistry[name].funcCb, args
@emit 'callerResumed', name, args
###
# Producer: Main "start it all" API: Calling "delayed/remote" functions as if they were local
###
cleanArguments: (args) ->
JSON.parse JSON.stringify args
# Signature: ivy.delayedCall function, [arg1, arg2, argN],
# placedIntoQueueSuccessfullyCallback
delayedCall: ->
fargs = Array.prototype.slice.call(arguments)
func = fargs.slice(0, 1)[0]
cb = fargs.slice(arguments.length-1)[0]
if fargs.length > 2
args = fargs.slice 1, arguments.length-1
else
args = []
try
args = @cleanArguments args
catch err
return cb err
name = @taskObjectRegistry[func]
queueName = manager.queue.getQueueName(@taskRegistry[name].queue or @taskRegistry[name].queueName)
logger.silly "Sending delayedCall for function #{name} into queue #{queueName} to backend #{manager.currentQueueType} with args", args
manager.sendTask
name: name
options: @taskRegistry[name].options
queue: queueName
args: args
, (err) ->
cb err
###
# Producer: Knowing where to queue tasks
###
setupQueue: ->
manager.setupQueue.apply manager, arguments
###
# Consumer: listening to queue events
###
listen: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
logger.silly "Starting to listen to queue #{manager.queue.BACKEND_NAME}, options", options
manager.listen.apply manager, [options, cb]
stopListening: ->
logger.silly "Stopping queue listener"
manager.stopListening.apply manager, arguments
###
# Consumer & Producer: consuming/producing task notifications
###
startNotificationProducer: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.startProducer options, cb
startNotificationConsumer: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.startConsumer options, cb
pauseNotifier: (cb) ->
notifier.pause cb
resumeNotifier: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.resume options, cb
# resumeQueue: ->
# manager.pause.apply manager, arguments
# pauseQueue: ->
# manager.resume.apply manager, arguments
module.exports = {
Ivy
}
| 40218 |
{EventEmitter} = require 'events'
logger = require './logger'
queues = require './queues'
{notifier} = require './notifiers'
manager = queues.queue
class Ivy extends EventEmitter
constructor: (options) ->
{
@config
} = options
@taskRegistry = {}
@taskObjectRegistry = {}
super("Ivy")
# Setup main "singleton" instance of ivy that is used when requiring it
setupMain: ->
manager.on 'scheduledTaskRetrieved', @onScheduledTaskRetrieved.bind(@)
manager.setupMain @
notifier.setupMain @
onScheduledTaskRetrieved: ->
@scheduledTaskRetrieved.apply @, arguments
###
# Producer & Consumer: Task registration and handling
###
registerTask: (func, funcCb, options={}) ->
if typeof funcCb is 'object'
options = funcCb
funcCb = null
if typeof func isnt 'function'
throw new Error "First parameter 'func' isn't function is #{func}"
{name} = options
if not name
name = func.name
if not name
logger.error "Cannot determine task name. Please pass it explicitly through options."
throw new Error "Cannot determine task name. Please pass it explicitly through options."
else
delete options.name
queueName = options.queue
if queueName
delete options.queue
@taskRegistry[name] = {
func
funcCb
options
queue: queueName
}
@taskObjectRegistry[func] = name
logger.silly "Registered task #{name} into queue #{queueName}"
###
# Producer & Consumer testing: Clear tasks between tests
###
clearTasks: ->
@taskRegistry = {}
@taskObjectRegistry = {}
###
# Consumer: Resolving tasks recieved from queue and calling them
###
scheduledTaskRetrieved: ({id, name, args, options, queue}) ->
called = false
logger.silly "Retrieved task id #{id}"
@executeTask name, args, (err, result...) =>
if called
logger.error "IVY_ERROR Task #{name} called callback multiple times. It shouldn't do that."
else
called = true
notify = !!@taskRegistry[name].funcCb
# last argument is the callback I am in
args.pop()
@emit 'taskExecuted', err, {id, name, args, options, result, notify, queue}
executeTask: (name, args, cb) ->
if not @taskRegistry[name]
cb new Error "Task #{name} not found in registry on consumer"
else
logger.silly "Executing task #{name}"
try
args.push cb
@taskRegistry[name].func.apply @taskRegistry[name].func, args
catch err
logger.error "IVY_ERROR Ivy task #{name} has thrown an exception. It should call back instead", err
cb err
###
# Producer: Resolving task return/call values back to callback/handler
# and resuming workflow
###
taskResultRetrieved: (data) ->
try
result = JSON.parse data
catch err
logger.error 'IVY_BAD_ARGUMENTS Recieved JSON unparseable function description. Error is: ', err
return false
@resumeCaller result.name, result.args
resumeCaller: (name, args) ->
@taskRegistry[name].funcCb.apply @taskRegistry[name].funcCb, args
@emit 'callerResumed', name, args
###
# Producer: Main "start it all" API: Calling "delayed/remote" functions as if they were local
###
cleanArguments: (args) ->
JSON.parse JSON.stringify args
# Signature: ivy.delayedCall function, [arg1, arg2, argN],
# placedIntoQueueSuccessfullyCallback
delayedCall: ->
fargs = Array.prototype.slice.call(arguments)
func = fargs.slice(0, 1)[0]
cb = fargs.slice(arguments.length-1)[0]
if fargs.length > 2
args = fargs.slice 1, arguments.length-1
else
args = []
try
args = @cleanArguments args
catch err
return cb err
name = @taskObjectRegistry[func]
queueName = manager.queue.getQueueName(@taskRegistry[name].queue or @taskRegistry[name].queueName)
logger.silly "Sending delayedCall for function #{name} into queue #{queueName} to backend #{manager.currentQueueType} with args", args
manager.sendTask
name: <NAME>
options: @taskRegistry[name].options
queue: queueName
args: args
, (err) ->
cb err
###
# Producer: Knowing where to queue tasks
###
setupQueue: ->
manager.setupQueue.apply manager, arguments
###
# Consumer: listening to queue events
###
listen: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
logger.silly "Starting to listen to queue #{manager.queue.BACKEND_NAME}, options", options
manager.listen.apply manager, [options, cb]
stopListening: ->
logger.silly "Stopping queue listener"
manager.stopListening.apply manager, arguments
###
# Consumer & Producer: consuming/producing task notifications
###
startNotificationProducer: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.startProducer options, cb
startNotificationConsumer: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.startConsumer options, cb
pauseNotifier: (cb) ->
notifier.pause cb
resumeNotifier: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.resume options, cb
# resumeQueue: ->
# manager.pause.apply manager, arguments
# pauseQueue: ->
# manager.resume.apply manager, arguments
module.exports = {
Ivy
}
| true |
{EventEmitter} = require 'events'
logger = require './logger'
queues = require './queues'
{notifier} = require './notifiers'
manager = queues.queue
class Ivy extends EventEmitter
constructor: (options) ->
{
@config
} = options
@taskRegistry = {}
@taskObjectRegistry = {}
super("Ivy")
# Setup main "singleton" instance of ivy that is used when requiring it
setupMain: ->
manager.on 'scheduledTaskRetrieved', @onScheduledTaskRetrieved.bind(@)
manager.setupMain @
notifier.setupMain @
onScheduledTaskRetrieved: ->
@scheduledTaskRetrieved.apply @, arguments
###
# Producer & Consumer: Task registration and handling
###
registerTask: (func, funcCb, options={}) ->
if typeof funcCb is 'object'
options = funcCb
funcCb = null
if typeof func isnt 'function'
throw new Error "First parameter 'func' isn't function is #{func}"
{name} = options
if not name
name = func.name
if not name
logger.error "Cannot determine task name. Please pass it explicitly through options."
throw new Error "Cannot determine task name. Please pass it explicitly through options."
else
delete options.name
queueName = options.queue
if queueName
delete options.queue
@taskRegistry[name] = {
func
funcCb
options
queue: queueName
}
@taskObjectRegistry[func] = name
logger.silly "Registered task #{name} into queue #{queueName}"
###
# Producer & Consumer testing: Clear tasks between tests
###
clearTasks: ->
@taskRegistry = {}
@taskObjectRegistry = {}
###
# Consumer: Resolving tasks recieved from queue and calling them
###
scheduledTaskRetrieved: ({id, name, args, options, queue}) ->
called = false
logger.silly "Retrieved task id #{id}"
@executeTask name, args, (err, result...) =>
if called
logger.error "IVY_ERROR Task #{name} called callback multiple times. It shouldn't do that."
else
called = true
notify = !!@taskRegistry[name].funcCb
# last argument is the callback I am in
args.pop()
@emit 'taskExecuted', err, {id, name, args, options, result, notify, queue}
executeTask: (name, args, cb) ->
if not @taskRegistry[name]
cb new Error "Task #{name} not found in registry on consumer"
else
logger.silly "Executing task #{name}"
try
args.push cb
@taskRegistry[name].func.apply @taskRegistry[name].func, args
catch err
logger.error "IVY_ERROR Ivy task #{name} has thrown an exception. It should call back instead", err
cb err
###
# Producer: Resolving task return/call values back to callback/handler
# and resuming workflow
###
taskResultRetrieved: (data) ->
try
result = JSON.parse data
catch err
logger.error 'IVY_BAD_ARGUMENTS Recieved JSON unparseable function description. Error is: ', err
return false
@resumeCaller result.name, result.args
resumeCaller: (name, args) ->
@taskRegistry[name].funcCb.apply @taskRegistry[name].funcCb, args
@emit 'callerResumed', name, args
###
# Producer: Main "start it all" API: Calling "delayed/remote" functions as if they were local
###
cleanArguments: (args) ->
JSON.parse JSON.stringify args
# Signature: ivy.delayedCall function, [arg1, arg2, argN],
# placedIntoQueueSuccessfullyCallback
delayedCall: ->
fargs = Array.prototype.slice.call(arguments)
func = fargs.slice(0, 1)[0]
cb = fargs.slice(arguments.length-1)[0]
if fargs.length > 2
args = fargs.slice 1, arguments.length-1
else
args = []
try
args = @cleanArguments args
catch err
return cb err
name = @taskObjectRegistry[func]
queueName = manager.queue.getQueueName(@taskRegistry[name].queue or @taskRegistry[name].queueName)
logger.silly "Sending delayedCall for function #{name} into queue #{queueName} to backend #{manager.currentQueueType} with args", args
manager.sendTask
name: PI:NAME:<NAME>END_PI
options: @taskRegistry[name].options
queue: queueName
args: args
, (err) ->
cb err
###
# Producer: Knowing where to queue tasks
###
setupQueue: ->
manager.setupQueue.apply manager, arguments
###
# Consumer: listening to queue events
###
listen: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
logger.silly "Starting to listen to queue #{manager.queue.BACKEND_NAME}, options", options
manager.listen.apply manager, [options, cb]
stopListening: ->
logger.silly "Stopping queue listener"
manager.stopListening.apply manager, arguments
###
# Consumer & Producer: consuming/producing task notifications
###
startNotificationProducer: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.startProducer options, cb
startNotificationConsumer: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.startConsumer options, cb
pauseNotifier: (cb) ->
notifier.pause cb
resumeNotifier: (options, cb) ->
if typeof options is 'function'
cb = options
options = {}
notifier.resume options, cb
# resumeQueue: ->
# manager.pause.apply manager, arguments
# pauseQueue: ->
# manager.resume.apply manager, arguments
module.exports = {
Ivy
}
|
[
{
"context": ": \"./public/app.min.js\"\n\t\tuglify:\n\t\t\tbanner: \"/* ©Laurent Margirier */\"\n\t\t\tprod:\n\t\t\t\tfiles: [{\n\t\t\t\t\tdest: \"./public/a",
"end": 919,
"score": 0.9998475909233093,
"start": 902,
"tag": "NAME",
"value": "Laurent Margirier"
}
] | Gruntfile.coffee | inaka/angular-img-onload | 2 | module.exports = (grunt) ->
grunt.loadNpmTasks "grunt-karma"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-contrib-clean"
grunt.loadNpmTasks "grunt-contrib-jade"
grunt.loadNpmTasks "grunt-contrib-less"
grunt.loadNpmTasks "grunt-contrib-concat"
grunt.loadNpmTasks "grunt-ngmin"
grunt.loadNpmTasks "grunt-contrib-uglify"
grunt.initConfig
pkg: grunt.file.readJSON('package.json'),
coffee:
dev:
options:
join: false
sourceMap: true
files:
'./public/app.js': ['assets/coffee/*.coffee']
prod:
files:
'./public/app.js': ['assets/coffee/*.coffee']
dist:
files:
'./dist/angular-img-onload.js': ['assets/coffee/*.coffee']
ngmin:
dist:
src: ["./dist/angular-img-onload.js"]
dest: "./dist/angular-img-onload.min.js"
prod:
src: ["./public/app.js"]
dest: "./public/app.min.js"
uglify:
banner: "/* ©Laurent Margirier */"
prod:
files: [{
dest: "./public/app.min.js"
src: ["./public/app.min.js"]
}]
dist:
files: [{
dest: "./dist/angular-img-onload.min.js"
src: ["./dist/angular-img-onload.min.js"]
}]
jade:
dev:
options:
pretty: true
files: [{
expand: true,
cwd: 'assets/jade/'
src: ['*.jade']
dest: 'public/'
ext: '.html'
}]
prod:
files: [{
expand: true,
cwd: 'assets/jade/'
src: ['*.jade']
dest: 'public/'
ext: '.html'
}]
less:
dev:
options:
sourceMap: true
files:
'./public/app.css': ['assets/less/*.less']
prod:
files:
'./public/app.css': ['assets/less/*.less']
clean: ['public']
concat:
dev:
options:
separator: ";"
dest: "public/deps.js"
src: [
"bower_components/angular/angular.js"
"bower_components/angular-animate/angular-animate.min.js"
"bower_components/angular-ui-router/release/angular-ui-router.min.js"
"bower_components/lodash/dist/lodash.min.js"
]
prod:
options:
separator: ";"
dest: "public/deps.js"
src: [
"bower_components/angular/angular.min.js"
"bower_components/angular-animate/angular-animate.min.js"
"bower_components/angular-ui-router/release/angular-ui-router.min.js"
"bower_components/lodash/dist/lodash.min.js"
]
watch:
assets:
files: ['assets/**/*']
tasks: ['default']
karma:
unit:
configFile: "./test/karma-unit.conf.js"
autoWatch: false
singleRun: true
grunt.registerTask 'build', ['coffee:dist','ngmin','uglify:dist']
grunt.registerTask 'default', ['clean','concat:dev','coffee:dev','jade:dev','less:dev']
grunt.registerTask 'prod', ['clean','concat:prod','coffee:prod','jade:prod','less:prod']
grunt.registerTask 'watch', ['clean','coffee:dev','jade:dev','less:dev','watch:assets']
grunt.registerTask 'w', ['watch']
grunt.registerTask "test:unit", [
"karma:unit"
]
| 115103 | module.exports = (grunt) ->
grunt.loadNpmTasks "grunt-karma"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-contrib-clean"
grunt.loadNpmTasks "grunt-contrib-jade"
grunt.loadNpmTasks "grunt-contrib-less"
grunt.loadNpmTasks "grunt-contrib-concat"
grunt.loadNpmTasks "grunt-ngmin"
grunt.loadNpmTasks "grunt-contrib-uglify"
grunt.initConfig
pkg: grunt.file.readJSON('package.json'),
coffee:
dev:
options:
join: false
sourceMap: true
files:
'./public/app.js': ['assets/coffee/*.coffee']
prod:
files:
'./public/app.js': ['assets/coffee/*.coffee']
dist:
files:
'./dist/angular-img-onload.js': ['assets/coffee/*.coffee']
ngmin:
dist:
src: ["./dist/angular-img-onload.js"]
dest: "./dist/angular-img-onload.min.js"
prod:
src: ["./public/app.js"]
dest: "./public/app.min.js"
uglify:
banner: "/* ©<NAME> */"
prod:
files: [{
dest: "./public/app.min.js"
src: ["./public/app.min.js"]
}]
dist:
files: [{
dest: "./dist/angular-img-onload.min.js"
src: ["./dist/angular-img-onload.min.js"]
}]
jade:
dev:
options:
pretty: true
files: [{
expand: true,
cwd: 'assets/jade/'
src: ['*.jade']
dest: 'public/'
ext: '.html'
}]
prod:
files: [{
expand: true,
cwd: 'assets/jade/'
src: ['*.jade']
dest: 'public/'
ext: '.html'
}]
less:
dev:
options:
sourceMap: true
files:
'./public/app.css': ['assets/less/*.less']
prod:
files:
'./public/app.css': ['assets/less/*.less']
clean: ['public']
concat:
dev:
options:
separator: ";"
dest: "public/deps.js"
src: [
"bower_components/angular/angular.js"
"bower_components/angular-animate/angular-animate.min.js"
"bower_components/angular-ui-router/release/angular-ui-router.min.js"
"bower_components/lodash/dist/lodash.min.js"
]
prod:
options:
separator: ";"
dest: "public/deps.js"
src: [
"bower_components/angular/angular.min.js"
"bower_components/angular-animate/angular-animate.min.js"
"bower_components/angular-ui-router/release/angular-ui-router.min.js"
"bower_components/lodash/dist/lodash.min.js"
]
watch:
assets:
files: ['assets/**/*']
tasks: ['default']
karma:
unit:
configFile: "./test/karma-unit.conf.js"
autoWatch: false
singleRun: true
grunt.registerTask 'build', ['coffee:dist','ngmin','uglify:dist']
grunt.registerTask 'default', ['clean','concat:dev','coffee:dev','jade:dev','less:dev']
grunt.registerTask 'prod', ['clean','concat:prod','coffee:prod','jade:prod','less:prod']
grunt.registerTask 'watch', ['clean','coffee:dev','jade:dev','less:dev','watch:assets']
grunt.registerTask 'w', ['watch']
grunt.registerTask "test:unit", [
"karma:unit"
]
| true | module.exports = (grunt) ->
grunt.loadNpmTasks "grunt-karma"
grunt.loadNpmTasks "grunt-contrib-coffee"
grunt.loadNpmTasks "grunt-contrib-clean"
grunt.loadNpmTasks "grunt-contrib-jade"
grunt.loadNpmTasks "grunt-contrib-less"
grunt.loadNpmTasks "grunt-contrib-concat"
grunt.loadNpmTasks "grunt-ngmin"
grunt.loadNpmTasks "grunt-contrib-uglify"
grunt.initConfig
pkg: grunt.file.readJSON('package.json'),
coffee:
dev:
options:
join: false
sourceMap: true
files:
'./public/app.js': ['assets/coffee/*.coffee']
prod:
files:
'./public/app.js': ['assets/coffee/*.coffee']
dist:
files:
'./dist/angular-img-onload.js': ['assets/coffee/*.coffee']
ngmin:
dist:
src: ["./dist/angular-img-onload.js"]
dest: "./dist/angular-img-onload.min.js"
prod:
src: ["./public/app.js"]
dest: "./public/app.min.js"
uglify:
banner: "/* ©PI:NAME:<NAME>END_PI */"
prod:
files: [{
dest: "./public/app.min.js"
src: ["./public/app.min.js"]
}]
dist:
files: [{
dest: "./dist/angular-img-onload.min.js"
src: ["./dist/angular-img-onload.min.js"]
}]
jade:
dev:
options:
pretty: true
files: [{
expand: true,
cwd: 'assets/jade/'
src: ['*.jade']
dest: 'public/'
ext: '.html'
}]
prod:
files: [{
expand: true,
cwd: 'assets/jade/'
src: ['*.jade']
dest: 'public/'
ext: '.html'
}]
less:
dev:
options:
sourceMap: true
files:
'./public/app.css': ['assets/less/*.less']
prod:
files:
'./public/app.css': ['assets/less/*.less']
clean: ['public']
concat:
dev:
options:
separator: ";"
dest: "public/deps.js"
src: [
"bower_components/angular/angular.js"
"bower_components/angular-animate/angular-animate.min.js"
"bower_components/angular-ui-router/release/angular-ui-router.min.js"
"bower_components/lodash/dist/lodash.min.js"
]
prod:
options:
separator: ";"
dest: "public/deps.js"
src: [
"bower_components/angular/angular.min.js"
"bower_components/angular-animate/angular-animate.min.js"
"bower_components/angular-ui-router/release/angular-ui-router.min.js"
"bower_components/lodash/dist/lodash.min.js"
]
watch:
assets:
files: ['assets/**/*']
tasks: ['default']
karma:
unit:
configFile: "./test/karma-unit.conf.js"
autoWatch: false
singleRun: true
grunt.registerTask 'build', ['coffee:dist','ngmin','uglify:dist']
grunt.registerTask 'default', ['clean','concat:dev','coffee:dev','jade:dev','less:dev']
grunt.registerTask 'prod', ['clean','concat:prod','coffee:prod','jade:prod','less:prod']
grunt.registerTask 'watch', ['clean','coffee:dev','jade:dev','less:dev','watch:assets']
grunt.registerTask 'w', ['watch']
grunt.registerTask "test:unit", [
"karma:unit"
]
|
[
{
"context": "t.brain.userForId(data.userId)\n user.name = data.name\n user.room = 'iMessage'\n\n msg ",
"end": 1037,
"score": 0.6181147694587708,
"start": 1033,
"tag": "NAME",
"value": "data"
}
] | src/imessage.coffee | lazerwalker/hubot-imessage | 119 | {User, Robot, Adapter, Message, TextMessage, Response} = require('hubot')
AppleScript = require('applescript')
path = require('path')
Redis = require('redis')
Pubsub = Redis.createClient()
Pubsub.subscribe('hubot:incoming-imessage')
class iMessageAdapter extends Adapter
constructor: (robot) ->
@robot = robot
send: (envelope, strings...) ->
user = envelope.user.id
if user in @allowedUsers
script = path.resolve(__dirname, 'Send iMessage.applescript')
for message in strings
AppleScript.execFile script,
[user, message],
(err, rtn) ->
else
@robot.logger.info 'Refusing to send message to unauthorized iMessage user ' + user
reply: (envelope, strings...) ->
@send envelope, strings...
run: ->
@allowedUsers = process.env.HUBOT_IMESSAGE_HANDLES.split(',')
Pubsub.on 'message', (channel, dataString) =>
data = JSON.parse(dataString)
if data.userId in @allowedUsers
user = @robot.brain.userForId(data.userId)
user.name = data.name
user.room = 'iMessage'
msg = "#{@robot.name} #{data.message}"
@receive new TextMessage(user, msg)
else
@robot.logger.info 'Ignoring message from unauthorized iMessage user ' + data.userId
@emit 'connected'
exports.use = (robot) ->
new iMessageAdapter robot
| 49684 | {User, Robot, Adapter, Message, TextMessage, Response} = require('hubot')
AppleScript = require('applescript')
path = require('path')
Redis = require('redis')
Pubsub = Redis.createClient()
Pubsub.subscribe('hubot:incoming-imessage')
class iMessageAdapter extends Adapter
constructor: (robot) ->
@robot = robot
send: (envelope, strings...) ->
user = envelope.user.id
if user in @allowedUsers
script = path.resolve(__dirname, 'Send iMessage.applescript')
for message in strings
AppleScript.execFile script,
[user, message],
(err, rtn) ->
else
@robot.logger.info 'Refusing to send message to unauthorized iMessage user ' + user
reply: (envelope, strings...) ->
@send envelope, strings...
run: ->
@allowedUsers = process.env.HUBOT_IMESSAGE_HANDLES.split(',')
Pubsub.on 'message', (channel, dataString) =>
data = JSON.parse(dataString)
if data.userId in @allowedUsers
user = @robot.brain.userForId(data.userId)
user.name = <NAME>.name
user.room = 'iMessage'
msg = "#{@robot.name} #{data.message}"
@receive new TextMessage(user, msg)
else
@robot.logger.info 'Ignoring message from unauthorized iMessage user ' + data.userId
@emit 'connected'
exports.use = (robot) ->
new iMessageAdapter robot
| true | {User, Robot, Adapter, Message, TextMessage, Response} = require('hubot')
AppleScript = require('applescript')
path = require('path')
Redis = require('redis')
Pubsub = Redis.createClient()
Pubsub.subscribe('hubot:incoming-imessage')
class iMessageAdapter extends Adapter
constructor: (robot) ->
@robot = robot
send: (envelope, strings...) ->
user = envelope.user.id
if user in @allowedUsers
script = path.resolve(__dirname, 'Send iMessage.applescript')
for message in strings
AppleScript.execFile script,
[user, message],
(err, rtn) ->
else
@robot.logger.info 'Refusing to send message to unauthorized iMessage user ' + user
reply: (envelope, strings...) ->
@send envelope, strings...
run: ->
@allowedUsers = process.env.HUBOT_IMESSAGE_HANDLES.split(',')
Pubsub.on 'message', (channel, dataString) =>
data = JSON.parse(dataString)
if data.userId in @allowedUsers
user = @robot.brain.userForId(data.userId)
user.name = PI:NAME:<NAME>END_PI.name
user.room = 'iMessage'
msg = "#{@robot.name} #{data.message}"
@receive new TextMessage(user, msg)
else
@robot.logger.info 'Ignoring message from unauthorized iMessage user ' + data.userId
@emit 'connected'
exports.use = (robot) ->
new iMessageAdapter robot
|
[
{
"context": "@loadSeedData: ->\n animalData = [\n name: \"Kelsey\"\n type: \"dog\"\n age: 2\n breed: \"Lab",
"end": 574,
"score": 0.9997680187225342,
"start": 568,
"tag": "NAME",
"value": "Kelsey"
},
{
"context": "mes drinks out of the toilet.\"\n ,\n ... | src/animal.coffee | keisei77/coffee_demo | 0 | class window.Animal
@CATEGORIES = ["All", "Dog", "Cat", "Rabbit", "Horse"]
behaviors: ->
switch @type
when "cat" then ["meow", null]
when "dog" then ["bark", "wag"]
when "rabbit" then [null, "hop hop"]
when "horse", "donkey"
["neigh", null]
else
[null,null]
matchesFilter: (criteria='All') ->
criteria is "All" or criteria.toLowerCase() is @type
@fromHash: (data) ->
animal = new @
animal[key] = val for key, val of data
animal
@loadSeedData: ->
animalData = [
name: "Kelsey"
type: "dog"
age: 2
breed: "Labrador"
image: ""
description: "A sweet and loyal dog. Loves to play fetch. Sometimes drinks out of the toilet."
,
name: "Sgt. Snuffles"
type: "dog"
age: 4
breed: "Pug"
image: ""
description: "Small in stature, but big in heart, Sgt. Snuffles is never one to back down from a mission."
,
name: "Chomps"
type: "rabbit"
age: 5
breed: "Giant Angora"
image: ""
description: "Chomps is usually very good-natured, but he does not take kindly to being mistaken for an ottoman. Come see him in person and you'll understand why that may happen."
,
name: "Flops"
type: "rabbit"
age: 3
breed: "French Lop"
image: "flops.jpg"
description: "Enjoys nothing more than a good roll in the grass and a nap in the sun."
,
name: "Bopper"
type: "rabbit"
age: 3
breed: "Checkered Giant"
image: ""
description: "The quiet one of the group. Loves celery."
,
name: "Chairman Meow"
type: "cat"
age: 1
breed: "Snowshoe"
image: ""
description: "True to his name, Chairman Meow fancies himself in charge."
,
name: "Jacques"
type: "cat"
age: 2
breed: "Manx"
image: ""
description: "A happy-go-lucky cat who occasionally finds himself at odds with Chairman Meow over who gets to sit at the top of the cat tree."
,
name: "Chupa"
type: "cat"
age: 2
breed: "Scottish Fold"
image: "chupa.jpg"
description: "Chupa always appears perplexed with the world, but don't be fooled. That's just the way his face is shaped."
,
name: "Alfred"
type: "horse"
age: 6
breed: "Breton"
image: ""
description: "The resident shop patriarch. Very calm and tolerates the antics of the other animals when they sneak into his pen."
]
for animal in animalData
@fromHash animal | 117723 | class window.Animal
@CATEGORIES = ["All", "Dog", "Cat", "Rabbit", "Horse"]
behaviors: ->
switch @type
when "cat" then ["meow", null]
when "dog" then ["bark", "wag"]
when "rabbit" then [null, "hop hop"]
when "horse", "donkey"
["neigh", null]
else
[null,null]
matchesFilter: (criteria='All') ->
criteria is "All" or criteria.toLowerCase() is @type
@fromHash: (data) ->
animal = new @
animal[key] = val for key, val of data
animal
@loadSeedData: ->
animalData = [
name: "<NAME>"
type: "dog"
age: 2
breed: "Labrador"
image: ""
description: "A sweet and loyal dog. Loves to play fetch. Sometimes drinks out of the toilet."
,
name: "<NAME>"
type: "dog"
age: 4
breed: "Pug"
image: ""
description: "Small in stature, but big in heart, Sgt. Snuffles is never one to back down from a mission."
,
name: "<NAME>"
type: "rabbit"
age: 5
breed: "Giant Angora"
image: ""
description: "<NAME>s is usually very good-natured, but he does not take kindly to being mistaken for an ottoman. Come see him in person and you'll understand why that may happen."
,
name: "<NAME>"
type: "rabbit"
age: 3
breed: "French Lop"
image: "flops.jpg"
description: "Enjoys nothing more than a good roll in the grass and a nap in the sun."
,
name: "<NAME>"
type: "rabbit"
age: 3
breed: "Checkered Giant"
image: ""
description: "The quiet one of the group. Loves celery."
,
name: "<NAME>"
type: "cat"
age: 1
breed: "Snowshoe"
image: ""
description: "True to his name, <NAME> fancies himself in charge."
,
name: "<NAME>"
type: "cat"
age: 2
breed: "Manx"
image: ""
description: "A happy-go-lucky cat who occasionally finds himself at odds with <NAME> over who gets to sit at the top of the cat tree."
,
name: "<NAME>"
type: "cat"
age: 2
breed: "Scottish Fold"
image: "chupa.jpg"
description: "Chupa always appears perplexed with the world, but don't be fooled. That's just the way his face is shaped."
,
name: "<NAME>"
type: "horse"
age: 6
breed: "Breton"
image: ""
description: "The resident shop patriarch. Very calm and tolerates the antics of the other animals when they sneak into his pen."
]
for animal in animalData
@fromHash animal | true | class window.Animal
@CATEGORIES = ["All", "Dog", "Cat", "Rabbit", "Horse"]
behaviors: ->
switch @type
when "cat" then ["meow", null]
when "dog" then ["bark", "wag"]
when "rabbit" then [null, "hop hop"]
when "horse", "donkey"
["neigh", null]
else
[null,null]
matchesFilter: (criteria='All') ->
criteria is "All" or criteria.toLowerCase() is @type
@fromHash: (data) ->
animal = new @
animal[key] = val for key, val of data
animal
@loadSeedData: ->
animalData = [
name: "PI:NAME:<NAME>END_PI"
type: "dog"
age: 2
breed: "Labrador"
image: ""
description: "A sweet and loyal dog. Loves to play fetch. Sometimes drinks out of the toilet."
,
name: "PI:NAME:<NAME>END_PI"
type: "dog"
age: 4
breed: "Pug"
image: ""
description: "Small in stature, but big in heart, Sgt. Snuffles is never one to back down from a mission."
,
name: "PI:NAME:<NAME>END_PI"
type: "rabbit"
age: 5
breed: "Giant Angora"
image: ""
description: "PI:NAME:<NAME>END_PIs is usually very good-natured, but he does not take kindly to being mistaken for an ottoman. Come see him in person and you'll understand why that may happen."
,
name: "PI:NAME:<NAME>END_PI"
type: "rabbit"
age: 3
breed: "French Lop"
image: "flops.jpg"
description: "Enjoys nothing more than a good roll in the grass and a nap in the sun."
,
name: "PI:NAME:<NAME>END_PI"
type: "rabbit"
age: 3
breed: "Checkered Giant"
image: ""
description: "The quiet one of the group. Loves celery."
,
name: "PI:NAME:<NAME>END_PI"
type: "cat"
age: 1
breed: "Snowshoe"
image: ""
description: "True to his name, PI:NAME:<NAME>END_PI fancies himself in charge."
,
name: "PI:NAME:<NAME>END_PI"
type: "cat"
age: 2
breed: "Manx"
image: ""
description: "A happy-go-lucky cat who occasionally finds himself at odds with PI:NAME:<NAME>END_PI over who gets to sit at the top of the cat tree."
,
name: "PI:NAME:<NAME>END_PI"
type: "cat"
age: 2
breed: "Scottish Fold"
image: "chupa.jpg"
description: "Chupa always appears perplexed with the world, but don't be fooled. That's just the way his face is shaped."
,
name: "PI:NAME:<NAME>END_PI"
type: "horse"
age: 6
breed: "Breton"
image: ""
description: "The resident shop patriarch. Very calm and tolerates the antics of the other animals when they sneak into his pen."
]
for animal in animalData
@fromHash animal |
[
{
"context": " The `Hash` unit tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\neval(Test.bu",
"end": 71,
"score": 0.9998853802680969,
"start": 54,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/core/test/hash_test.coffee | lovely-io/lovely.io-stl | 2 | #
# The `Hash` unit tests
#
# Copyright (C) 2011-2013 Nikolay Nemshilov
#
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
describe 'Hash', ->
Hash = Lovely.Hash
#
# A dummy class to check the prototype
# values filtration
#
# @param {Object} own properties
# @return undefined
#
Foo = (object) ->
object or= {}
for key, value of object
this[key] = value
this
Foo.prototype.boo = 'boo'
Foo.prototype.hoo = 'hoo'
describe '\b#constructor', ->
hash = new Hash(object = {})
it "should create an instance of Hash", ->
hash.should.be.instanceOf Hash
it "should refer to the original object via the '_' attribute", ->
hash._.should.equal object
describe '\b#keys()', ->
it "should return an array of the keys", ->
new Hash(a: 1, b: 2).keys().should.eql ['a', 'b']
it "should skip prototype keys", ->
new Hash(new Foo(a: 1, b: 2)).keys().should.eql ['a', 'b']
describe '\b#values()', ->
it "should return an array of values", ->
new Hash(a: 1, b: 2).values().should.eql [1, 2]
it "should skip any prototype values", ->
new Hash(new Foo(a: 1, b: 2)).values().should.eql [1, 2]
describe '\b#empty()', ->
it "should say 'true' for empty hashes", ->
new Hash({}).empty().should.be.true
it "should say 'false' for non empty hashes", ->
new Hash(a: 1).empty().should.be.false
it "should filter out prototype properties", ->
new Hash(new Foo()).empty().should.be.true
new Hash(new Foo(a: 1)).empty().should.be.false
describe '\b#clone()', ->
data = {a:1, b:2}
it "should create a new Hash with cloned data", ->
original = new Hash(data)
clone = original.clone()
clone.should.be.instanceOf Hash
clone.should.not.equal original
clone._.should.eql data
clone._.should.not.equal data
it "should skip any prototype data", ->
original = new Hash(new Foo(data))
clone = original.clone()
clone.should.be.instanceOf Hash
clone.should.not.equal original
clone._.should.eql data
clone._.should.not.equal data
describe '\b#forEach(callback)', ->
it "should go through every key-value pair", ->
hash = new Hash(a:1, b:2)
result = []
ret = hash.forEach (key, value, hash) ->
result.push([key, value, hash])
ret.should.equal hash
result.should.eql [
['a', 1, {a:1, b:2}],
['b', 2, {a:1, b:2}]
]
it "should skip the prototype keys and values", ->
result = []
new Hash(new Foo(a:1, b:2)).forEach (key, value) ->
result.push([key, value])
result.should.eql [['a', 1], ['b', 2]]
describe '\b#map(callback)', ->
it "should map result of key-value calls on the callback", ->
hash = a:1, b:2
result = new Hash(hash).map (key, value, hash) ->
[key, value, hash]
result.should.eql [
['a', 1, hash], ['b', 2, hash]
]
it "should skip prototype key-value pairs", ->
data = a: 1, b:2
result = new Hash(new Foo(data)).map (key, value, hash) ->
[key, value]
result.should.eql [
['a', 1], ['b', 2]
]
describe '\b#filter(callback)', ->
original = new Hash(a:1, b:2, c:3)
hash = original.filter (key, value) ->
key is 'a' || key is 'c'
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should filter the related object", ->
hash._.should.eql {a:1, c:3}
describe '\b#reject(callback)', ->
original = new Hash(a:1, b:2, c:3)
hash = original.reject (key, value) ->
key is 'a' || key is 'c'
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should filter the related object", ->
hash._.should.eql {b:2}
describe '\b#merge(o1, o2,..)', ->
original = new Hash(a:3)
hash = original.merge(
{a:1, b:3},
new Foo(b:2, c:4), # checking prototypes filtering
new Hash(c:3) # checking Hashes processing
)
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should merge the objects", ->
hash._.should.eql {a:1, b:2, c:3}
describe '\b#merge(o1, o2, ..) - deep -', ->
o1 = {a: {b: {c: 'd'}, e: 'f'}}
o2 = {a: {b: {c: 'd', e: 'f'}}}
hash = new Hash({}).merge(o1, o2)
it "should perform a deep merge of the data", ->
hash._.should.eql {a: {b: {c: 'd', e: 'f'}, e: 'f'}}
it "should delink the keys", ->
o = hash._
(
o.a isnt o1.a and o.a isnt o2.a and o.a.b isnt o1.a.b && o.a.b isnt o2.a.b
).should.be.true
describe '\b.keys', ->
it "should return keys of an object", ->
Hash.keys(a:1, b:2).should.eql ['a', 'b']
describe '\b.values', ->
it "should return values of an object", ->
Hash.values(a: 1, b:2).should.eql [1,2]
describe '\b.empty', ->
it "should check if an object is empty", ->
Hash.empty({}).should.be.true
Hash.empty(a: 1).should.be.false
describe "\b.clone", ->
it "should clone an object", ->
object = a: 1
clone = Hash.clone(object)
clone.should.eql object
clone.should.not.equal object
describe "\b.forEach", ->
args = []
obj = a: 1, b: 2
hash = Hash.forEach obj, (key, value, object) ->
args.push([key, value, object])
it "should run through every key-value pair in the object", ->
args.should.eql [
['a', 1, obj], ['b', 2, obj]
]
it "should return the object itself back", ->
hash.should.equal obj
describe "\b.map", ->
it "should map the results of callbacks on every key-value pairs", ->
result = Hash.map {a: 1, b: 2}, (key, value) ->
key + "-" + value
result.should.eql ["a-1", "b-2"]
describe "\b.filter", ->
it "should create a filtered object", ->
hash = a: 1, b: 2, c: 3
data = Hash.filter hash, (key, value) -> value % 2
data.should.not.equal hash
data.should.eql {a:1, c:3}
describe "\b.reject", ->
it "should create a new object without rejected pairs", ->
hash = a: 1, b: 2, c: 3
data = Hash.reject hash, (key, value) -> value % 2
data.should.not.equal hash
data.should.eql {b:2}
describe "\b.merge", ->
it "should merge objects and hashes and make a new object", ->
object = a:1, b:3
result = Hash.merge object,
new Foo(b:2, c:4), # checking prototypes filtering
new Hash(c:3) # checking Hashes processing
result.should.not.equal object
result.should.eql {a: 1, b: 2, c: 3}
| 152328 | #
# The `Hash` unit tests
#
# Copyright (C) 2011-2013 <NAME>
#
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
describe 'Hash', ->
Hash = Lovely.Hash
#
# A dummy class to check the prototype
# values filtration
#
# @param {Object} own properties
# @return undefined
#
Foo = (object) ->
object or= {}
for key, value of object
this[key] = value
this
Foo.prototype.boo = 'boo'
Foo.prototype.hoo = 'hoo'
describe '\b#constructor', ->
hash = new Hash(object = {})
it "should create an instance of Hash", ->
hash.should.be.instanceOf Hash
it "should refer to the original object via the '_' attribute", ->
hash._.should.equal object
describe '\b#keys()', ->
it "should return an array of the keys", ->
new Hash(a: 1, b: 2).keys().should.eql ['a', 'b']
it "should skip prototype keys", ->
new Hash(new Foo(a: 1, b: 2)).keys().should.eql ['a', 'b']
describe '\b#values()', ->
it "should return an array of values", ->
new Hash(a: 1, b: 2).values().should.eql [1, 2]
it "should skip any prototype values", ->
new Hash(new Foo(a: 1, b: 2)).values().should.eql [1, 2]
describe '\b#empty()', ->
it "should say 'true' for empty hashes", ->
new Hash({}).empty().should.be.true
it "should say 'false' for non empty hashes", ->
new Hash(a: 1).empty().should.be.false
it "should filter out prototype properties", ->
new Hash(new Foo()).empty().should.be.true
new Hash(new Foo(a: 1)).empty().should.be.false
describe '\b#clone()', ->
data = {a:1, b:2}
it "should create a new Hash with cloned data", ->
original = new Hash(data)
clone = original.clone()
clone.should.be.instanceOf Hash
clone.should.not.equal original
clone._.should.eql data
clone._.should.not.equal data
it "should skip any prototype data", ->
original = new Hash(new Foo(data))
clone = original.clone()
clone.should.be.instanceOf Hash
clone.should.not.equal original
clone._.should.eql data
clone._.should.not.equal data
describe '\b#forEach(callback)', ->
it "should go through every key-value pair", ->
hash = new Hash(a:1, b:2)
result = []
ret = hash.forEach (key, value, hash) ->
result.push([key, value, hash])
ret.should.equal hash
result.should.eql [
['a', 1, {a:1, b:2}],
['b', 2, {a:1, b:2}]
]
it "should skip the prototype keys and values", ->
result = []
new Hash(new Foo(a:1, b:2)).forEach (key, value) ->
result.push([key, value])
result.should.eql [['a', 1], ['b', 2]]
describe '\b#map(callback)', ->
it "should map result of key-value calls on the callback", ->
hash = a:1, b:2
result = new Hash(hash).map (key, value, hash) ->
[key, value, hash]
result.should.eql [
['a', 1, hash], ['b', 2, hash]
]
it "should skip prototype key-value pairs", ->
data = a: 1, b:2
result = new Hash(new Foo(data)).map (key, value, hash) ->
[key, value]
result.should.eql [
['a', 1], ['b', 2]
]
describe '\b#filter(callback)', ->
original = new Hash(a:1, b:2, c:3)
hash = original.filter (key, value) ->
key is 'a' || key is 'c'
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should filter the related object", ->
hash._.should.eql {a:1, c:3}
describe '\b#reject(callback)', ->
original = new Hash(a:1, b:2, c:3)
hash = original.reject (key, value) ->
key is 'a' || key is 'c'
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should filter the related object", ->
hash._.should.eql {b:2}
describe '\b#merge(o1, o2,..)', ->
original = new Hash(a:3)
hash = original.merge(
{a:1, b:3},
new Foo(b:2, c:4), # checking prototypes filtering
new Hash(c:3) # checking Hashes processing
)
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should merge the objects", ->
hash._.should.eql {a:1, b:2, c:3}
describe '\b#merge(o1, o2, ..) - deep -', ->
o1 = {a: {b: {c: 'd'}, e: 'f'}}
o2 = {a: {b: {c: 'd', e: 'f'}}}
hash = new Hash({}).merge(o1, o2)
it "should perform a deep merge of the data", ->
hash._.should.eql {a: {b: {c: 'd', e: 'f'}, e: 'f'}}
it "should delink the keys", ->
o = hash._
(
o.a isnt o1.a and o.a isnt o2.a and o.a.b isnt o1.a.b && o.a.b isnt o2.a.b
).should.be.true
describe '\b.keys', ->
it "should return keys of an object", ->
Hash.keys(a:1, b:2).should.eql ['a', 'b']
describe '\b.values', ->
it "should return values of an object", ->
Hash.values(a: 1, b:2).should.eql [1,2]
describe '\b.empty', ->
it "should check if an object is empty", ->
Hash.empty({}).should.be.true
Hash.empty(a: 1).should.be.false
describe "\b.clone", ->
it "should clone an object", ->
object = a: 1
clone = Hash.clone(object)
clone.should.eql object
clone.should.not.equal object
describe "\b.forEach", ->
args = []
obj = a: 1, b: 2
hash = Hash.forEach obj, (key, value, object) ->
args.push([key, value, object])
it "should run through every key-value pair in the object", ->
args.should.eql [
['a', 1, obj], ['b', 2, obj]
]
it "should return the object itself back", ->
hash.should.equal obj
describe "\b.map", ->
it "should map the results of callbacks on every key-value pairs", ->
result = Hash.map {a: 1, b: 2}, (key, value) ->
key + "-" + value
result.should.eql ["a-1", "b-2"]
describe "\b.filter", ->
it "should create a filtered object", ->
hash = a: 1, b: 2, c: 3
data = Hash.filter hash, (key, value) -> value % 2
data.should.not.equal hash
data.should.eql {a:1, c:3}
describe "\b.reject", ->
it "should create a new object without rejected pairs", ->
hash = a: 1, b: 2, c: 3
data = Hash.reject hash, (key, value) -> value % 2
data.should.not.equal hash
data.should.eql {b:2}
describe "\b.merge", ->
it "should merge objects and hashes and make a new object", ->
object = a:1, b:3
result = Hash.merge object,
new Foo(b:2, c:4), # checking prototypes filtering
new Hash(c:3) # checking Hashes processing
result.should.not.equal object
result.should.eql {a: 1, b: 2, c: 3}
| true | #
# The `Hash` unit tests
#
# Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI
#
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
describe 'Hash', ->
Hash = Lovely.Hash
#
# A dummy class to check the prototype
# values filtration
#
# @param {Object} own properties
# @return undefined
#
Foo = (object) ->
object or= {}
for key, value of object
this[key] = value
this
Foo.prototype.boo = 'boo'
Foo.prototype.hoo = 'hoo'
describe '\b#constructor', ->
hash = new Hash(object = {})
it "should create an instance of Hash", ->
hash.should.be.instanceOf Hash
it "should refer to the original object via the '_' attribute", ->
hash._.should.equal object
describe '\b#keys()', ->
it "should return an array of the keys", ->
new Hash(a: 1, b: 2).keys().should.eql ['a', 'b']
it "should skip prototype keys", ->
new Hash(new Foo(a: 1, b: 2)).keys().should.eql ['a', 'b']
describe '\b#values()', ->
it "should return an array of values", ->
new Hash(a: 1, b: 2).values().should.eql [1, 2]
it "should skip any prototype values", ->
new Hash(new Foo(a: 1, b: 2)).values().should.eql [1, 2]
describe '\b#empty()', ->
it "should say 'true' for empty hashes", ->
new Hash({}).empty().should.be.true
it "should say 'false' for non empty hashes", ->
new Hash(a: 1).empty().should.be.false
it "should filter out prototype properties", ->
new Hash(new Foo()).empty().should.be.true
new Hash(new Foo(a: 1)).empty().should.be.false
describe '\b#clone()', ->
data = {a:1, b:2}
it "should create a new Hash with cloned data", ->
original = new Hash(data)
clone = original.clone()
clone.should.be.instanceOf Hash
clone.should.not.equal original
clone._.should.eql data
clone._.should.not.equal data
it "should skip any prototype data", ->
original = new Hash(new Foo(data))
clone = original.clone()
clone.should.be.instanceOf Hash
clone.should.not.equal original
clone._.should.eql data
clone._.should.not.equal data
describe '\b#forEach(callback)', ->
it "should go through every key-value pair", ->
hash = new Hash(a:1, b:2)
result = []
ret = hash.forEach (key, value, hash) ->
result.push([key, value, hash])
ret.should.equal hash
result.should.eql [
['a', 1, {a:1, b:2}],
['b', 2, {a:1, b:2}]
]
it "should skip the prototype keys and values", ->
result = []
new Hash(new Foo(a:1, b:2)).forEach (key, value) ->
result.push([key, value])
result.should.eql [['a', 1], ['b', 2]]
describe '\b#map(callback)', ->
it "should map result of key-value calls on the callback", ->
hash = a:1, b:2
result = new Hash(hash).map (key, value, hash) ->
[key, value, hash]
result.should.eql [
['a', 1, hash], ['b', 2, hash]
]
it "should skip prototype key-value pairs", ->
data = a: 1, b:2
result = new Hash(new Foo(data)).map (key, value, hash) ->
[key, value]
result.should.eql [
['a', 1], ['b', 2]
]
describe '\b#filter(callback)', ->
original = new Hash(a:1, b:2, c:3)
hash = original.filter (key, value) ->
key is 'a' || key is 'c'
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should filter the related object", ->
hash._.should.eql {a:1, c:3}
describe '\b#reject(callback)', ->
original = new Hash(a:1, b:2, c:3)
hash = original.reject (key, value) ->
key is 'a' || key is 'c'
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should filter the related object", ->
hash._.should.eql {b:2}
describe '\b#merge(o1, o2,..)', ->
original = new Hash(a:3)
hash = original.merge(
{a:1, b:3},
new Foo(b:2, c:4), # checking prototypes filtering
new Hash(c:3) # checking Hashes processing
)
it "should create a new Hash object", ->
hash.should.be.instanceOf Hash
hash.should.not.equal original
it "should merge the objects", ->
hash._.should.eql {a:1, b:2, c:3}
describe '\b#merge(o1, o2, ..) - deep -', ->
o1 = {a: {b: {c: 'd'}, e: 'f'}}
o2 = {a: {b: {c: 'd', e: 'f'}}}
hash = new Hash({}).merge(o1, o2)
it "should perform a deep merge of the data", ->
hash._.should.eql {a: {b: {c: 'd', e: 'f'}, e: 'f'}}
it "should delink the keys", ->
o = hash._
(
o.a isnt o1.a and o.a isnt o2.a and o.a.b isnt o1.a.b && o.a.b isnt o2.a.b
).should.be.true
describe '\b.keys', ->
it "should return keys of an object", ->
Hash.keys(a:1, b:2).should.eql ['a', 'b']
describe '\b.values', ->
it "should return values of an object", ->
Hash.values(a: 1, b:2).should.eql [1,2]
describe '\b.empty', ->
it "should check if an object is empty", ->
Hash.empty({}).should.be.true
Hash.empty(a: 1).should.be.false
describe "\b.clone", ->
it "should clone an object", ->
object = a: 1
clone = Hash.clone(object)
clone.should.eql object
clone.should.not.equal object
describe "\b.forEach", ->
args = []
obj = a: 1, b: 2
hash = Hash.forEach obj, (key, value, object) ->
args.push([key, value, object])
it "should run through every key-value pair in the object", ->
args.should.eql [
['a', 1, obj], ['b', 2, obj]
]
it "should return the object itself back", ->
hash.should.equal obj
describe "\b.map", ->
it "should map the results of callbacks on every key-value pairs", ->
result = Hash.map {a: 1, b: 2}, (key, value) ->
key + "-" + value
result.should.eql ["a-1", "b-2"]
describe "\b.filter", ->
it "should create a filtered object", ->
hash = a: 1, b: 2, c: 3
data = Hash.filter hash, (key, value) -> value % 2
data.should.not.equal hash
data.should.eql {a:1, c:3}
describe "\b.reject", ->
it "should create a new object without rejected pairs", ->
hash = a: 1, b: 2, c: 3
data = Hash.reject hash, (key, value) -> value % 2
data.should.not.equal hash
data.should.eql {b:2}
describe "\b.merge", ->
it "should merge objects and hashes and make a new object", ->
object = a:1, b:3
result = Hash.merge object,
new Foo(b:2, c:4), # checking prototypes filtering
new Hash(c:3) # checking Hashes processing
result.should.not.equal object
result.should.eql {a: 1, b: 2, c: 3}
|
[
{
"context": "y (http://jquery.com)\n\n@source: http://github.com/rendro/easy-pie-chart/\n@autor: Robert Fleischmann\n@versi",
"end": 338,
"score": 0.788355827331543,
"start": 332,
"tag": "USERNAME",
"value": "rendro"
},
{
"context": ": http://github.com/rendro/easy-pie-chart/\n@auto... | vendor/assets/javascripts/easy-pie-chart/easy-pie-chart.coffee | hasyung/ace-theme-rails | 0 | ###
Easy pie chart is a jquery plugin to display simple animated pie charts for only one value
Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
Built on top of the jQuery library (http://jquery.com)
@source: http://github.com/rendro/easy-pie-chart/
@autor: Robert Fleischmann
@version: 1.2.5
Inspired by: http://dribbble.com/shots/631074-Simple-Pie-Charts-II?list=popular&offset=210
Thanks to Philip Thrasher for the jquery plugin boilerplate for coffee script
###
(($) ->
$.easyPieChart = (el, options) ->
@el = el
@$el = $ el
@$el.data "easyPieChart", @
@init = =>
@options = $.extend {}, $.easyPieChart.defaultOptions, options
#get relevant data
percent = parseInt @$el.data('percent'), 10
@percentage = 0
#create canvas element and set the origin to the center
@canvas = $("<canvas width='#{@options.size}' height='#{@options.size}'></canvas>").get(0)
@$el.append @canvas
G_vmlCanvasManager.initElement @canvas if G_vmlCanvasManager?
@ctx = @canvas.getContext '2d'
if window.devicePixelRatio > 1
scaleBy = window.devicePixelRatio
$(@canvas).css({
width: @options.size
height: @options.size
})
@canvas.width *= scaleBy
@canvas.height *= scaleBy
@ctx.scale scaleBy, scaleBy
@ctx.translate @options.size/2, @options.size/2
@ctx.rotate @options.rotate*Math.PI/180
@$el.addClass 'easyPieChart'
@$el.css {
width: @options.size
height: @options.size
lineHeight: "#{@options.size}px"
}
@update percent
@
@update = (percent) =>
percent = parseFloat(percent) or 0
if @options.animate == false
drawLine percent
else
if @options.delay
animateLine @percentage, 0
setTimeout(=>
animateLine @percentage, percent
, @options.delay)
else
animateLine @percentage, percent
@
renderScale = =>
@ctx.fillStyle = @options.scaleColor
@ctx.lineWidth = 1
addScaleLine i for i in [0..24]
addScaleLine = (i) =>
offset = if i%6==0 then 0 else @options.size*0.017
@ctx.save()
@ctx.rotate i * Math.PI / 12
@ctx.fillRect @options.size/2-offset, 0, -@options.size*0.05+offset, 1
@ctx.restore()
return
renderTrack = =>
offset = @options.size/2-@options.lineWidth/2
offset -= @options.size*0.08 if @options.scaleColor != false
@ctx.beginPath()
@ctx.arc 0, 0, offset, 0, Math.PI * 2, true
@ctx.closePath()
@ctx.strokeStyle = @options.trackColor
@ctx.lineWidth = @options.lineWidth
@ctx.stroke()
return
renderBackground = =>
do renderScale if @options.scaleColor != false
do renderTrack if @options.trackColor != false
return
drawLine = (percent) =>
do renderBackground
@ctx.strokeStyle = if $.isFunction @options.barColor then @options.barColor percent else @options.barColor
@ctx.lineCap = @options.lineCap
@ctx.lineWidth = @options.lineWidth
offset = @options.size/2-@options.lineWidth/2
offset -= @options.size*0.08 if @options.scaleColor != false
@ctx.save()
@ctx.rotate -Math.PI/2
@ctx.beginPath()
@ctx.arc 0, 0, offset, 0, Math.PI * 2 * percent/100, false
@ctx.stroke()
@ctx.restore()
return
rAF = do () -> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or (callback) -> window.setTimeout callback, 1000 / 60
animateLine = (from, to) =>
@options.onStart.call @
@percentage = to
# Setting Date.now for IE < IE9
Date.now ||= () -> +(new Date)
startTime = Date.now()
anim = () =>
process = Math.min(Date.now() - startTime, @options.animate)
@ctx.clearRect -@options.size/2, -@options.size/2, @options.size, @options.size
renderBackground.call @
currentValue = [easeInOutQuad process, from, to-from, @options.animate]
@options.onStep.call @, currentValue
drawLine.call @, currentValue
if process >= @options.animate
@options.onStop.call @, currentValue, to
else
rAF anim
rAF anim
return
#t=time;b=beginning value;c=change in value;d=duration
easeInOutQuad = (t, b, c, d) ->
easeIn = (t) ->
return Math.pow(t, 2) # Quad
easing = (t) ->
if (t < 1)
return easeIn(t)
else
return 2 - easeIn( (t/2) * -2 + 2 )
t /= d / 2
return c / 2 * easing(t) + b
@init()
$.easyPieChart.defaultOptions =
barColor: '#ef1e25'
trackColor: '#f2f2f2'
scaleColor: '#dfe0e0'
lineCap: 'round'
rotate: 0
size: 110
lineWidth: 3
animate: false
delay: false
onStart: $.noop
onStop: $.noop
onStep: $.noop
$.fn.easyPieChart = (options) ->
$.each @, (i, el) ->
$el = ($ el)
unless $el.data 'easyPieChart'
instanceOptions = $.extend {}, options , $el.data()
$el.data 'easyPieChart', new $.easyPieChart el, instanceOptions
undefined
)(jQuery) | 199572 | ###
Easy pie chart is a jquery plugin to display simple animated pie charts for only one value
Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
Built on top of the jQuery library (http://jquery.com)
@source: http://github.com/rendro/easy-pie-chart/
@autor: <NAME>
@version: 1.2.5
Inspired by: http://dribbble.com/shots/631074-Simple-Pie-Charts-II?list=popular&offset=210
Thanks to <NAME> for the jquery plugin boilerplate for coffee script
###
(($) ->
$.easyPieChart = (el, options) ->
@el = el
@$el = $ el
@$el.data "easyPieChart", @
@init = =>
@options = $.extend {}, $.easyPieChart.defaultOptions, options
#get relevant data
percent = parseInt @$el.data('percent'), 10
@percentage = 0
#create canvas element and set the origin to the center
@canvas = $("<canvas width='#{@options.size}' height='#{@options.size}'></canvas>").get(0)
@$el.append @canvas
G_vmlCanvasManager.initElement @canvas if G_vmlCanvasManager?
@ctx = @canvas.getContext '2d'
if window.devicePixelRatio > 1
scaleBy = window.devicePixelRatio
$(@canvas).css({
width: @options.size
height: @options.size
})
@canvas.width *= scaleBy
@canvas.height *= scaleBy
@ctx.scale scaleBy, scaleBy
@ctx.translate @options.size/2, @options.size/2
@ctx.rotate @options.rotate*Math.PI/180
@$el.addClass 'easyPieChart'
@$el.css {
width: @options.size
height: @options.size
lineHeight: "#{@options.size}px"
}
@update percent
@
@update = (percent) =>
percent = parseFloat(percent) or 0
if @options.animate == false
drawLine percent
else
if @options.delay
animateLine @percentage, 0
setTimeout(=>
animateLine @percentage, percent
, @options.delay)
else
animateLine @percentage, percent
@
renderScale = =>
@ctx.fillStyle = @options.scaleColor
@ctx.lineWidth = 1
addScaleLine i for i in [0..24]
addScaleLine = (i) =>
offset = if i%6==0 then 0 else @options.size*0.017
@ctx.save()
@ctx.rotate i * Math.PI / 12
@ctx.fillRect @options.size/2-offset, 0, -@options.size*0.05+offset, 1
@ctx.restore()
return
renderTrack = =>
offset = @options.size/2-@options.lineWidth/2
offset -= @options.size*0.08 if @options.scaleColor != false
@ctx.beginPath()
@ctx.arc 0, 0, offset, 0, Math.PI * 2, true
@ctx.closePath()
@ctx.strokeStyle = @options.trackColor
@ctx.lineWidth = @options.lineWidth
@ctx.stroke()
return
renderBackground = =>
do renderScale if @options.scaleColor != false
do renderTrack if @options.trackColor != false
return
drawLine = (percent) =>
do renderBackground
@ctx.strokeStyle = if $.isFunction @options.barColor then @options.barColor percent else @options.barColor
@ctx.lineCap = @options.lineCap
@ctx.lineWidth = @options.lineWidth
offset = @options.size/2-@options.lineWidth/2
offset -= @options.size*0.08 if @options.scaleColor != false
@ctx.save()
@ctx.rotate -Math.PI/2
@ctx.beginPath()
@ctx.arc 0, 0, offset, 0, Math.PI * 2 * percent/100, false
@ctx.stroke()
@ctx.restore()
return
rAF = do () -> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or (callback) -> window.setTimeout callback, 1000 / 60
animateLine = (from, to) =>
@options.onStart.call @
@percentage = to
# Setting Date.now for IE < IE9
Date.now ||= () -> +(new Date)
startTime = Date.now()
anim = () =>
process = Math.min(Date.now() - startTime, @options.animate)
@ctx.clearRect -@options.size/2, -@options.size/2, @options.size, @options.size
renderBackground.call @
currentValue = [easeInOutQuad process, from, to-from, @options.animate]
@options.onStep.call @, currentValue
drawLine.call @, currentValue
if process >= @options.animate
@options.onStop.call @, currentValue, to
else
rAF anim
rAF anim
return
#t=time;b=beginning value;c=change in value;d=duration
easeInOutQuad = (t, b, c, d) ->
easeIn = (t) ->
return Math.pow(t, 2) # Quad
easing = (t) ->
if (t < 1)
return easeIn(t)
else
return 2 - easeIn( (t/2) * -2 + 2 )
t /= d / 2
return c / 2 * easing(t) + b
@init()
$.easyPieChart.defaultOptions =
barColor: '#ef1e25'
trackColor: '#f2f2f2'
scaleColor: '#dfe0e0'
lineCap: 'round'
rotate: 0
size: 110
lineWidth: 3
animate: false
delay: false
onStart: $.noop
onStop: $.noop
onStep: $.noop
$.fn.easyPieChart = (options) ->
$.each @, (i, el) ->
$el = ($ el)
unless $el.data 'easyPieChart'
instanceOptions = $.extend {}, options , $el.data()
$el.data 'easyPieChart', new $.easyPieChart el, instanceOptions
undefined
)(jQuery) | true | ###
Easy pie chart is a jquery plugin to display simple animated pie charts for only one value
Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
Built on top of the jQuery library (http://jquery.com)
@source: http://github.com/rendro/easy-pie-chart/
@autor: PI:NAME:<NAME>END_PI
@version: 1.2.5
Inspired by: http://dribbble.com/shots/631074-Simple-Pie-Charts-II?list=popular&offset=210
Thanks to PI:NAME:<NAME>END_PI for the jquery plugin boilerplate for coffee script
###
(($) ->
$.easyPieChart = (el, options) ->
@el = el
@$el = $ el
@$el.data "easyPieChart", @
@init = =>
@options = $.extend {}, $.easyPieChart.defaultOptions, options
#get relevant data
percent = parseInt @$el.data('percent'), 10
@percentage = 0
#create canvas element and set the origin to the center
@canvas = $("<canvas width='#{@options.size}' height='#{@options.size}'></canvas>").get(0)
@$el.append @canvas
G_vmlCanvasManager.initElement @canvas if G_vmlCanvasManager?
@ctx = @canvas.getContext '2d'
if window.devicePixelRatio > 1
scaleBy = window.devicePixelRatio
$(@canvas).css({
width: @options.size
height: @options.size
})
@canvas.width *= scaleBy
@canvas.height *= scaleBy
@ctx.scale scaleBy, scaleBy
@ctx.translate @options.size/2, @options.size/2
@ctx.rotate @options.rotate*Math.PI/180
@$el.addClass 'easyPieChart'
@$el.css {
width: @options.size
height: @options.size
lineHeight: "#{@options.size}px"
}
@update percent
@
@update = (percent) =>
percent = parseFloat(percent) or 0
if @options.animate == false
drawLine percent
else
if @options.delay
animateLine @percentage, 0
setTimeout(=>
animateLine @percentage, percent
, @options.delay)
else
animateLine @percentage, percent
@
renderScale = =>
@ctx.fillStyle = @options.scaleColor
@ctx.lineWidth = 1
addScaleLine i for i in [0..24]
addScaleLine = (i) =>
offset = if i%6==0 then 0 else @options.size*0.017
@ctx.save()
@ctx.rotate i * Math.PI / 12
@ctx.fillRect @options.size/2-offset, 0, -@options.size*0.05+offset, 1
@ctx.restore()
return
renderTrack = =>
offset = @options.size/2-@options.lineWidth/2
offset -= @options.size*0.08 if @options.scaleColor != false
@ctx.beginPath()
@ctx.arc 0, 0, offset, 0, Math.PI * 2, true
@ctx.closePath()
@ctx.strokeStyle = @options.trackColor
@ctx.lineWidth = @options.lineWidth
@ctx.stroke()
return
renderBackground = =>
do renderScale if @options.scaleColor != false
do renderTrack if @options.trackColor != false
return
drawLine = (percent) =>
do renderBackground
@ctx.strokeStyle = if $.isFunction @options.barColor then @options.barColor percent else @options.barColor
@ctx.lineCap = @options.lineCap
@ctx.lineWidth = @options.lineWidth
offset = @options.size/2-@options.lineWidth/2
offset -= @options.size*0.08 if @options.scaleColor != false
@ctx.save()
@ctx.rotate -Math.PI/2
@ctx.beginPath()
@ctx.arc 0, 0, offset, 0, Math.PI * 2 * percent/100, false
@ctx.stroke()
@ctx.restore()
return
rAF = do () -> window.requestAnimationFrame or window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or (callback) -> window.setTimeout callback, 1000 / 60
animateLine = (from, to) =>
@options.onStart.call @
@percentage = to
# Setting Date.now for IE < IE9
Date.now ||= () -> +(new Date)
startTime = Date.now()
anim = () =>
process = Math.min(Date.now() - startTime, @options.animate)
@ctx.clearRect -@options.size/2, -@options.size/2, @options.size, @options.size
renderBackground.call @
currentValue = [easeInOutQuad process, from, to-from, @options.animate]
@options.onStep.call @, currentValue
drawLine.call @, currentValue
if process >= @options.animate
@options.onStop.call @, currentValue, to
else
rAF anim
rAF anim
return
#t=time;b=beginning value;c=change in value;d=duration
easeInOutQuad = (t, b, c, d) ->
easeIn = (t) ->
return Math.pow(t, 2) # Quad
easing = (t) ->
if (t < 1)
return easeIn(t)
else
return 2 - easeIn( (t/2) * -2 + 2 )
t /= d / 2
return c / 2 * easing(t) + b
@init()
$.easyPieChart.defaultOptions =
barColor: '#ef1e25'
trackColor: '#f2f2f2'
scaleColor: '#dfe0e0'
lineCap: 'round'
rotate: 0
size: 110
lineWidth: 3
animate: false
delay: false
onStart: $.noop
onStop: $.noop
onStep: $.noop
$.fn.easyPieChart = (options) ->
$.each @, (i, el) ->
$el = ($ el)
unless $el.data 'easyPieChart'
instanceOptions = $.extend {}, options , $el.data()
$el.data 'easyPieChart', new $.easyPieChart el, instanceOptions
undefined
)(jQuery) |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991719722747803,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-fs-truncate.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.
# truncateSync
# ftruncateSync
# async tests
testTruncate = (cb) ->
fs.writeFile filename, data, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024 * 16
fs.truncate filename, 1024, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024
fs.truncate filename, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 0
cb()
return
return
return
return
return
return
return
testFtruncate = (cb) ->
fs.writeFile filename, data, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024 * 16
fs.open filename, "w", (er, fd) ->
return cb(er) if er
fs.ftruncate fd, 1024, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024
fs.ftruncate fd, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 0
fs.close fd, cb
return
return
return
return
return
return
return
return
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
tmp = common.tmpDir
filename = path.resolve(tmp, "truncate-file.txt")
data = new Buffer(1024 * 16)
data.fill "x"
stat = undefined
fs.writeFileSync filename, data
stat = fs.statSync(filename)
assert.equal stat.size, 1024 * 16
fs.truncateSync filename, 1024
stat = fs.statSync(filename)
assert.equal stat.size, 1024
fs.truncateSync filename
stat = fs.statSync(filename)
assert.equal stat.size, 0
fs.writeFileSync filename, data
fd = fs.openSync(filename, "r+")
stat = fs.statSync(filename)
assert.equal stat.size, 1024 * 16
fs.ftruncateSync fd, 1024
stat = fs.statSync(filename)
assert.equal stat.size, 1024
fs.ftruncateSync fd
stat = fs.statSync(filename)
assert.equal stat.size, 0
fs.closeSync fd
success = 0
testTruncate (er) ->
throw er if er
success++
testFtruncate (er) ->
throw er if er
success++
return
return
process.on "exit", ->
assert.equal success, 2
console.log "ok"
return
| 201908 | # 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.
# truncateSync
# ftruncateSync
# async tests
testTruncate = (cb) ->
fs.writeFile filename, data, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024 * 16
fs.truncate filename, 1024, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024
fs.truncate filename, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 0
cb()
return
return
return
return
return
return
return
testFtruncate = (cb) ->
fs.writeFile filename, data, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024 * 16
fs.open filename, "w", (er, fd) ->
return cb(er) if er
fs.ftruncate fd, 1024, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024
fs.ftruncate fd, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 0
fs.close fd, cb
return
return
return
return
return
return
return
return
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
tmp = common.tmpDir
filename = path.resolve(tmp, "truncate-file.txt")
data = new Buffer(1024 * 16)
data.fill "x"
stat = undefined
fs.writeFileSync filename, data
stat = fs.statSync(filename)
assert.equal stat.size, 1024 * 16
fs.truncateSync filename, 1024
stat = fs.statSync(filename)
assert.equal stat.size, 1024
fs.truncateSync filename
stat = fs.statSync(filename)
assert.equal stat.size, 0
fs.writeFileSync filename, data
fd = fs.openSync(filename, "r+")
stat = fs.statSync(filename)
assert.equal stat.size, 1024 * 16
fs.ftruncateSync fd, 1024
stat = fs.statSync(filename)
assert.equal stat.size, 1024
fs.ftruncateSync fd
stat = fs.statSync(filename)
assert.equal stat.size, 0
fs.closeSync fd
success = 0
testTruncate (er) ->
throw er if er
success++
testFtruncate (er) ->
throw er if er
success++
return
return
process.on "exit", ->
assert.equal success, 2
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.
# truncateSync
# ftruncateSync
# async tests
testTruncate = (cb) ->
fs.writeFile filename, data, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024 * 16
fs.truncate filename, 1024, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024
fs.truncate filename, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 0
cb()
return
return
return
return
return
return
return
testFtruncate = (cb) ->
fs.writeFile filename, data, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024 * 16
fs.open filename, "w", (er, fd) ->
return cb(er) if er
fs.ftruncate fd, 1024, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 1024
fs.ftruncate fd, (er) ->
return cb(er) if er
fs.stat filename, (er, stat) ->
return cb(er) if er
assert.equal stat.size, 0
fs.close fd, cb
return
return
return
return
return
return
return
return
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
tmp = common.tmpDir
filename = path.resolve(tmp, "truncate-file.txt")
data = new Buffer(1024 * 16)
data.fill "x"
stat = undefined
fs.writeFileSync filename, data
stat = fs.statSync(filename)
assert.equal stat.size, 1024 * 16
fs.truncateSync filename, 1024
stat = fs.statSync(filename)
assert.equal stat.size, 1024
fs.truncateSync filename
stat = fs.statSync(filename)
assert.equal stat.size, 0
fs.writeFileSync filename, data
fd = fs.openSync(filename, "r+")
stat = fs.statSync(filename)
assert.equal stat.size, 1024 * 16
fs.ftruncateSync fd, 1024
stat = fs.statSync(filename)
assert.equal stat.size, 1024
fs.ftruncateSync fd
stat = fs.statSync(filename)
assert.equal stat.size, 0
fs.closeSync fd
success = 0
testTruncate (er) ->
throw er if er
success++
testFtruncate (er) ->
throw er if er
success++
return
return
process.on "exit", ->
assert.equal success, 2
console.log "ok"
return
|
[
{
"context": "# written by al.di 2018\n# help function\ntypes = [\n 'isString'\n 'is",
"end": 18,
"score": 0.9575021266937256,
"start": 13,
"tag": "NAME",
"value": "al.di"
},
{
"context": "ults = \n item1:'just string'\n item2:\n name: 'bob marley'\n year: 1985\n title: ... | coffees/flatten.coffee | android1and1/easti | 0 | # written by al.di 2018
# help function
types = [
'isString'
'isArray'
'isObject'
'isNumber'
'isRegExp'
'isDate'
'isBoolean'
]
helpFuncs = {}
for type in types
((x)->
# func name is 'x'
helpFuncs[x] = (check)->
('[object ' + x.substr(2) + ']') is (Object.prototype.toString.call check)
)(type)
objectSortByIndex = (obj)->
# in:an obj within score-like index
# out(return): a sorted array.
indexes = Object.keys(obj)
orded = indexes.sort (a,b)->a-b #from min to max
result = {}
counter = 0
for i in orded
result[counter++] = obj[i]
return result
scanresults =
item1:'just string'
item2:
name: 'bob marley'
year: 1985
title: 'no woman no cry'
peoples:[
'wang lin'
'hua shao'
'zeng ji yi'
'lu ping'
]
item3: 'just another string'
item4: [
'small'
'middle'
'large'
'extro large'
]
item5: 'just string,again'
flatten = (original,store,major=0,minor=0)->
# store is an outter-level array variable.
# major and minor initial all is 0,they maps the deep levels like filesystem
flag = switch
when helpFuncs.isString original then 'string'
when helpFuncs.isArray original then 'array'
when helpFuncs.isObject original then 'object'
when helpFuncs.isNumber original then 'number'
when helpFuncs.isDate original then 'date'
if flag is 'string' or flag is 'number' or flag is 'date'
index = major + '.' + minor
store[index] = original
else if flag is 'array'
for v,i in original
flatten v,store,major+1,minor++
else if flag is 'object'
for i,v of original
flatten v,store,major+1,minor++
else
flatten 'unknown',store,major,minor
null
exports.flatten = flatten
exports.sample = scanresults
exports.objectSortByIndex = objectSortByIndex
| 19792 | # written by <NAME> 2018
# help function
types = [
'isString'
'isArray'
'isObject'
'isNumber'
'isRegExp'
'isDate'
'isBoolean'
]
helpFuncs = {}
for type in types
((x)->
# func name is 'x'
helpFuncs[x] = (check)->
('[object ' + x.substr(2) + ']') is (Object.prototype.toString.call check)
)(type)
objectSortByIndex = (obj)->
# in:an obj within score-like index
# out(return): a sorted array.
indexes = Object.keys(obj)
orded = indexes.sort (a,b)->a-b #from min to max
result = {}
counter = 0
for i in orded
result[counter++] = obj[i]
return result
scanresults =
item1:'just string'
item2:
name: '<NAME>'
year: 1985
title: 'no woman no cry'
peoples:[
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
]
item3: 'just another string'
item4: [
'small'
'middle'
'large'
'extro large'
]
item5: 'just string,again'
flatten = (original,store,major=0,minor=0)->
# store is an outter-level array variable.
# major and minor initial all is 0,they maps the deep levels like filesystem
flag = switch
when helpFuncs.isString original then 'string'
when helpFuncs.isArray original then 'array'
when helpFuncs.isObject original then 'object'
when helpFuncs.isNumber original then 'number'
when helpFuncs.isDate original then 'date'
if flag is 'string' or flag is 'number' or flag is 'date'
index = major + '.' + minor
store[index] = original
else if flag is 'array'
for v,i in original
flatten v,store,major+1,minor++
else if flag is 'object'
for i,v of original
flatten v,store,major+1,minor++
else
flatten 'unknown',store,major,minor
null
exports.flatten = flatten
exports.sample = scanresults
exports.objectSortByIndex = objectSortByIndex
| true | # written by PI:NAME:<NAME>END_PI 2018
# help function
types = [
'isString'
'isArray'
'isObject'
'isNumber'
'isRegExp'
'isDate'
'isBoolean'
]
helpFuncs = {}
for type in types
((x)->
# func name is 'x'
helpFuncs[x] = (check)->
('[object ' + x.substr(2) + ']') is (Object.prototype.toString.call check)
)(type)
objectSortByIndex = (obj)->
# in:an obj within score-like index
# out(return): a sorted array.
indexes = Object.keys(obj)
orded = indexes.sort (a,b)->a-b #from min to max
result = {}
counter = 0
for i in orded
result[counter++] = obj[i]
return result
scanresults =
item1:'just string'
item2:
name: 'PI:NAME:<NAME>END_PI'
year: 1985
title: 'no woman no cry'
peoples:[
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
]
item3: 'just another string'
item4: [
'small'
'middle'
'large'
'extro large'
]
item5: 'just string,again'
flatten = (original,store,major=0,minor=0)->
# store is an outter-level array variable.
# major and minor initial all is 0,they maps the deep levels like filesystem
flag = switch
when helpFuncs.isString original then 'string'
when helpFuncs.isArray original then 'array'
when helpFuncs.isObject original then 'object'
when helpFuncs.isNumber original then 'number'
when helpFuncs.isDate original then 'date'
if flag is 'string' or flag is 'number' or flag is 'date'
index = major + '.' + minor
store[index] = original
else if flag is 'array'
for v,i in original
flatten v,store,major+1,minor++
else if flag is 'object'
for i,v of original
flatten v,store,major+1,minor++
else
flatten 'unknown',store,major,minor
null
exports.flatten = flatten
exports.sample = scanresults
exports.objectSortByIndex = objectSortByIndex
|
[
{
"context": " {\n \"user\":{\n \"id\":1\n \"login\":\"admin\"\n \"firstname\":\"Redmine\"\n \"lastname\"",
"end": 5247,
"score": 0.9930025339126587,
"start": 5242,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "d\":1\n \"login\":\"admin\... | test/testData.coffee | Chanshi712/RedmineTimeTracker | 73 | timeTracker.value "TestData", ()->
SHOW = { DEFAULT: 0, NOT: 1, SHOW: 2 }
return {
prj1: [
{
url: "http://redmine.com"
urlIndex: 0
id: 0
text: "prj1_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 1
text: "prj1_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 2
text: "prj1_2"
show: SHOW.DEFAULT
}
]
prj2: [
{
url: "http://redmine.com2"
urlIndex: 1
id: 0
text: "prj2_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com2"
urlIndex: 1
id: 1
text: "prj2_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com2"
urlIndex: 1
id: 2
text: "prj2_2"
show: SHOW.DEFAULT
}
]
prj3: [
{
url: "http://redmine.com3"
urlIndex: 2
id: 0
text: "prj3_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com3"
urlIndex: 2
id: 1
text: "prj3_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com3"
urlIndex: 2
id: 2
text: "prj3_2"
show: SHOW.DEFAULT
}
]
prj10: [
{
url: "http://redmine.com"
urlIndex: 0
id: 0
text: "prj1_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 1
text: "prj1_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 2
text: "prj1_2"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 3
text: "prj1_3"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 4
text: "prj1_4"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 5
text: "prj1_5"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 6
text: "prj1_6"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 7
text: "prj1_7"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 8
text: "prj1_8"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 9
text: "prj1_9"
show: SHOW.DEFAULT
}
]
prjObj:
"http://redmine.com" :
index: 0
0:
text: "prj1_0"
show: SHOW.DEFAULT
"http://redmine.com2" :
index: 1
0:
text: "prj2_0"
show: SHOW.DEFAULT
"http://redmine.com3" :
index: 2
0:
text: "prj3_0"
show: SHOW.DEFAULT
prjOldFormat: # version <= 0.5.7
"http://redmine.com" :
index: 2
0:
text: "prj1_0"
show: SHOW.DEFAULT
"http://redmine.com2" :
index: 3
0:
text: "prj2_0"
show: SHOW.DEFAULT
"http://redmine.com3" :
index: 4
0:
text: "prj3_0"
show: SHOW.DEFAULT
ticketList: [
{
id: 0,
text: "ticket0",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.DEFAULT
}, {
id: 1,
text: "ticket1",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.NOT
}, {
id: 2,
text: "ticket2",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.SHOW
}
]
ticketList2: [
{
id: 0,
text: "ticket0",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.DEFAULT
}, {
id: 0,
text: "ticket2",
url: "http://redmine.com2",
project:
id: 0
text: "prj2_0",
show: SHOW.NOT
}, {
id: 0,
text: "ticket3",
url: "http://redmine.com3",
project:
id: 0
text: "prj3_0",
show: SHOW.SHOW
}
]
ticketOnChrome: [
# id | text | url_index | prj_id | show
[ 0, "ticket0", 0, 0, SHOW.DEFAULT ],
[ 0, "ticket2", 1, 0, SHOW.NOT ],
[ 0, "ticket3", 2, 0, SHOW.SHOW ]
]
ticketOnChromeOld: [
# id | text | url_index | prj_id | show
[ 0, "ticket0", 2, 0, SHOW.DEFAULT ],
[ 0, "ticket2", 3, 0, SHOW.NOT ],
[ 0, "ticket3", 4, 0, SHOW.SHOW ]
]
queries: {
"queries": [{"id":0, "name":"aaa", "is_public":true}, {"id":2, "name":"bbb"}]
"total_count":2
"offset":0
"limit":25
}
user: {
"user":{
"id":1
"login":"admin"
"firstname":"Redmine"
"lastname":"Admin"
"mail":"test@gmail.com"
"created_on":"2013-08-22T14:24:27Z"
}
}
time_entries: {
"time_entries":[{"id":1097,"project":{"id":9,"name":"その他"},"issue":{"id":235},"user":{"id":3,"name":"yujiro takeda"},"activity":{"id":8,"name":"設計作業"},"hours":1.25,"comments":"スケジュール修正","spent_on":"2014-07-03","created_on":"2014-07-03T13:32:56Z","updated_on":"2014-07-03T13:32:56Z"},{"id":1096,"project":{"id":9,"name":"その他"},"issue":{"id":235},"user":{"id":3,"name":"yujiro takeda"},"activity":{"id":8,"name":"設計作業"},"hours":1.25,"comments":"メール送信","spent_on":"2014-07-03","created_on":"2014-07-03T11:25:00Z","updated_on":"2014-07-03T11:25:00Z"}]
"total_count":2
"offset":0
"limit":25
}
statuses: [
{
id: 1
name: "New"
is_default: true
is_closed: false
}, {
id: 2
name: "Closed"
is_default: false
is_closed: true
}
]
}
| 49198 | timeTracker.value "TestData", ()->
SHOW = { DEFAULT: 0, NOT: 1, SHOW: 2 }
return {
prj1: [
{
url: "http://redmine.com"
urlIndex: 0
id: 0
text: "prj1_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 1
text: "prj1_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 2
text: "prj1_2"
show: SHOW.DEFAULT
}
]
prj2: [
{
url: "http://redmine.com2"
urlIndex: 1
id: 0
text: "prj2_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com2"
urlIndex: 1
id: 1
text: "prj2_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com2"
urlIndex: 1
id: 2
text: "prj2_2"
show: SHOW.DEFAULT
}
]
prj3: [
{
url: "http://redmine.com3"
urlIndex: 2
id: 0
text: "prj3_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com3"
urlIndex: 2
id: 1
text: "prj3_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com3"
urlIndex: 2
id: 2
text: "prj3_2"
show: SHOW.DEFAULT
}
]
prj10: [
{
url: "http://redmine.com"
urlIndex: 0
id: 0
text: "prj1_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 1
text: "prj1_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 2
text: "prj1_2"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 3
text: "prj1_3"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 4
text: "prj1_4"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 5
text: "prj1_5"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 6
text: "prj1_6"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 7
text: "prj1_7"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 8
text: "prj1_8"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 9
text: "prj1_9"
show: SHOW.DEFAULT
}
]
prjObj:
"http://redmine.com" :
index: 0
0:
text: "prj1_0"
show: SHOW.DEFAULT
"http://redmine.com2" :
index: 1
0:
text: "prj2_0"
show: SHOW.DEFAULT
"http://redmine.com3" :
index: 2
0:
text: "prj3_0"
show: SHOW.DEFAULT
prjOldFormat: # version <= 0.5.7
"http://redmine.com" :
index: 2
0:
text: "prj1_0"
show: SHOW.DEFAULT
"http://redmine.com2" :
index: 3
0:
text: "prj2_0"
show: SHOW.DEFAULT
"http://redmine.com3" :
index: 4
0:
text: "prj3_0"
show: SHOW.DEFAULT
ticketList: [
{
id: 0,
text: "ticket0",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.DEFAULT
}, {
id: 1,
text: "ticket1",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.NOT
}, {
id: 2,
text: "ticket2",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.SHOW
}
]
ticketList2: [
{
id: 0,
text: "ticket0",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.DEFAULT
}, {
id: 0,
text: "ticket2",
url: "http://redmine.com2",
project:
id: 0
text: "prj2_0",
show: SHOW.NOT
}, {
id: 0,
text: "ticket3",
url: "http://redmine.com3",
project:
id: 0
text: "prj3_0",
show: SHOW.SHOW
}
]
ticketOnChrome: [
# id | text | url_index | prj_id | show
[ 0, "ticket0", 0, 0, SHOW.DEFAULT ],
[ 0, "ticket2", 1, 0, SHOW.NOT ],
[ 0, "ticket3", 2, 0, SHOW.SHOW ]
]
ticketOnChromeOld: [
# id | text | url_index | prj_id | show
[ 0, "ticket0", 2, 0, SHOW.DEFAULT ],
[ 0, "ticket2", 3, 0, SHOW.NOT ],
[ 0, "ticket3", 4, 0, SHOW.SHOW ]
]
queries: {
"queries": [{"id":0, "name":"aaa", "is_public":true}, {"id":2, "name":"bbb"}]
"total_count":2
"offset":0
"limit":25
}
user: {
"user":{
"id":1
"login":"admin"
"firstname":"<NAME>"
"lastname":"<NAME>"
"mail":"<EMAIL>"
"created_on":"2013-08-22T14:24:27Z"
}
}
time_entries: {
"time_entries":[{"id":1097,"project":{"id":9,"name":"その他"},"issue":{"id":235},"user":{"id":3,"name":"yuji<NAME>"},"activity":{"id":8,"name":"設計作業"},"hours":1.25,"comments":"スケジュール修正","spent_on":"2014-07-03","created_on":"2014-07-03T13:32:56Z","updated_on":"2014-07-03T13:32:56Z"},{"id":1096,"project":{"id":9,"name":"その他"},"issue":{"id":235},"user":{"id":3,"name":"<NAME>"},"activity":{"id":8,"name":"設計作業"},"hours":1.25,"comments":"メール送信","spent_on":"2014-07-03","created_on":"2014-07-03T11:25:00Z","updated_on":"2014-07-03T11:25:00Z"}]
"total_count":2
"offset":0
"limit":25
}
statuses: [
{
id: 1
name: "New"
is_default: true
is_closed: false
}, {
id: 2
name: "Closed"
is_default: false
is_closed: true
}
]
}
| true | timeTracker.value "TestData", ()->
SHOW = { DEFAULT: 0, NOT: 1, SHOW: 2 }
return {
prj1: [
{
url: "http://redmine.com"
urlIndex: 0
id: 0
text: "prj1_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 1
text: "prj1_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 2
text: "prj1_2"
show: SHOW.DEFAULT
}
]
prj2: [
{
url: "http://redmine.com2"
urlIndex: 1
id: 0
text: "prj2_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com2"
urlIndex: 1
id: 1
text: "prj2_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com2"
urlIndex: 1
id: 2
text: "prj2_2"
show: SHOW.DEFAULT
}
]
prj3: [
{
url: "http://redmine.com3"
urlIndex: 2
id: 0
text: "prj3_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com3"
urlIndex: 2
id: 1
text: "prj3_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com3"
urlIndex: 2
id: 2
text: "prj3_2"
show: SHOW.DEFAULT
}
]
prj10: [
{
url: "http://redmine.com"
urlIndex: 0
id: 0
text: "prj1_0"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 1
text: "prj1_1"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 2
text: "prj1_2"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 3
text: "prj1_3"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 4
text: "prj1_4"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 5
text: "prj1_5"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 6
text: "prj1_6"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 7
text: "prj1_7"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 8
text: "prj1_8"
show: SHOW.DEFAULT
}, {
url: "http://redmine.com"
urlIndex: 0
id: 9
text: "prj1_9"
show: SHOW.DEFAULT
}
]
prjObj:
"http://redmine.com" :
index: 0
0:
text: "prj1_0"
show: SHOW.DEFAULT
"http://redmine.com2" :
index: 1
0:
text: "prj2_0"
show: SHOW.DEFAULT
"http://redmine.com3" :
index: 2
0:
text: "prj3_0"
show: SHOW.DEFAULT
prjOldFormat: # version <= 0.5.7
"http://redmine.com" :
index: 2
0:
text: "prj1_0"
show: SHOW.DEFAULT
"http://redmine.com2" :
index: 3
0:
text: "prj2_0"
show: SHOW.DEFAULT
"http://redmine.com3" :
index: 4
0:
text: "prj3_0"
show: SHOW.DEFAULT
ticketList: [
{
id: 0,
text: "ticket0",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.DEFAULT
}, {
id: 1,
text: "ticket1",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.NOT
}, {
id: 2,
text: "ticket2",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.SHOW
}
]
ticketList2: [
{
id: 0,
text: "ticket0",
url: "http://redmine.com",
project:
id: 0
text: "prj1_0",
show: SHOW.DEFAULT
}, {
id: 0,
text: "ticket2",
url: "http://redmine.com2",
project:
id: 0
text: "prj2_0",
show: SHOW.NOT
}, {
id: 0,
text: "ticket3",
url: "http://redmine.com3",
project:
id: 0
text: "prj3_0",
show: SHOW.SHOW
}
]
ticketOnChrome: [
# id | text | url_index | prj_id | show
[ 0, "ticket0", 0, 0, SHOW.DEFAULT ],
[ 0, "ticket2", 1, 0, SHOW.NOT ],
[ 0, "ticket3", 2, 0, SHOW.SHOW ]
]
ticketOnChromeOld: [
# id | text | url_index | prj_id | show
[ 0, "ticket0", 2, 0, SHOW.DEFAULT ],
[ 0, "ticket2", 3, 0, SHOW.NOT ],
[ 0, "ticket3", 4, 0, SHOW.SHOW ]
]
queries: {
"queries": [{"id":0, "name":"aaa", "is_public":true}, {"id":2, "name":"bbb"}]
"total_count":2
"offset":0
"limit":25
}
user: {
"user":{
"id":1
"login":"admin"
"firstname":"PI:NAME:<NAME>END_PI"
"lastname":"PI:NAME:<NAME>END_PI"
"mail":"PI:EMAIL:<EMAIL>END_PI"
"created_on":"2013-08-22T14:24:27Z"
}
}
time_entries: {
"time_entries":[{"id":1097,"project":{"id":9,"name":"その他"},"issue":{"id":235},"user":{"id":3,"name":"yujiPI:NAME:<NAME>END_PI"},"activity":{"id":8,"name":"設計作業"},"hours":1.25,"comments":"スケジュール修正","spent_on":"2014-07-03","created_on":"2014-07-03T13:32:56Z","updated_on":"2014-07-03T13:32:56Z"},{"id":1096,"project":{"id":9,"name":"その他"},"issue":{"id":235},"user":{"id":3,"name":"PI:NAME:<NAME>END_PI"},"activity":{"id":8,"name":"設計作業"},"hours":1.25,"comments":"メール送信","spent_on":"2014-07-03","created_on":"2014-07-03T11:25:00Z","updated_on":"2014-07-03T11:25:00Z"}]
"total_count":2
"offset":0
"limit":25
}
statuses: [
{
id: 1
name: "New"
is_default: true
is_closed: false
}, {
id: 2
name: "Closed"
is_default: false
is_closed: true
}
]
}
|
[
{
"context": " = new Document()\n m = new SomeModel({ name : \"foo\" })\n m2 = new AnotherModel({ name : \"bar\" })\n ",
"end": 6412,
"score": 0.8691739439964294,
"start": 6409,
"tag": "NAME",
"value": "foo"
},
{
"context": " = new Document()\n m = new SomeModel({ name : \"f... | bokehjs/test/document/document.coffee | aparamon/bokeh | 1 | {expect} = require "chai"
sinon = require "sinon"
{ stdoutTrap, stderrTrap } = require 'logtrap'
{values, size} = require("core/util/object")
{Document, ModelChangedEvent, TitleChangedEvent, RootAddedEvent, RootRemovedEvent, DEFAULT_TITLE} = require "document"
js_version = require("version").version
{Models} = require "base"
{Model} = require "model"
logging = require "core/logging"
p = require "core/properties"
class AnotherModel extends Model
type: 'AnotherModel'
@define {
bar: [ p.Number, 1 ]
}
Models.register('AnotherModel', AnotherModel)
class SomeModel extends Model
type: 'SomeModel'
@define {
foo: [ p.Number, 2 ]
child: [ p.Instance, null ]
}
Models.register('SomeModel', SomeModel)
class SomeModelWithChildren extends Model
type: 'SomeModelWithChildren'
@define {
children: [ p.Array, [] ]
}
Models.register('SomeModelWithChildren', SomeModelWithChildren)
class ModelWithConstructTimeChanges extends Model
type: 'ModelWithConstructTimeChanges'
initialize: (attributes, options) ->
super(attributes, options)
@foo = 4
@child = new AnotherModel()
@define {
foo: [ p.Number, 2 ]
child: [ p.Instance, null ]
}
Models.register('ModelWithConstructTimeChanges', ModelWithConstructTimeChanges)
class ComplicatedModelWithConstructTimeChanges extends Model
type: 'ComplicatedModelWithConstructTimeChanges'
initialize: (attributes, options) ->
super(attributes, options)
@list_prop = [new AnotherModel()]
@dict_prop = { foo: new AnotherModel() }
@obj_prop = new ModelWithConstructTimeChanges()
@dict_of_list_prop = { foo: [new AnotherModel()] }
@define {
list_prop: [ p.Array ]
dict_prop: [ p.Any ]
obj_prop: [ p.Instance ]
dict_of_list_prop: [ p.Any ]
}
Models.register('ComplicatedModelWithConstructTimeChanges', ComplicatedModelWithConstructTimeChanges)
describe "Document", ->
it "should be constructable", ->
d = new Document()
expect(d.roots().length).to.equal 0
it "has working add_root", ->
d = new Document()
expect(d.roots().length).to.equal 0
d.add_root(new AnotherModel())
expect(d.roots().length).to.equal 1
it "manages noting interactivity periods", sinon.test () ->
d = new Document()
expect(d._interactive_plot).to.be.null
expect(d._interactive_timestamp).to.be.null
expect(d.interactive_duration()).to.equal -1
stub = sinon.stub(Date, 'now')
stub.onCall(0).returns(10);
stub.onCall(1).returns(12);
stub.onCall(2).returns(15);
stub.onCall(3).returns(18);
m1 = new SomeModel()
m2 = new AnotherModel()
d.interactive_start(m1) # first stub value 10
expect(d._interactive_plot.id).to.equal m1.id
expect(d._interactive_timestamp).to.be.equal 10
expect(d.interactive_duration()).to.be.equal 2 # second stub value 12
d.interactive_start(m2) # third stub value 15
expect(d._interactive_plot.id).to.equal m1.id
expect(d._interactive_timestamp).to.be.equal 15
expect(d.interactive_duration()).to.be.equal 3 # second stub value 18
d.interactive_stop(m1)
expect(d._interactive_plot).to.be.null
expect(d._interactive_timestamp).to.be.null
expect(d.interactive_duration()).to.equal -1
it "has working set_title", ->
d = new Document()
expect(d.title()).to.equal "Bokeh Application"
d.set_title("Foo")
expect(d.title()).to.equal "Foo"
it "tracks all_models", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModel()
m2 = new AnotherModel()
m.child = m2
expect(m.child).to.equal m2
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 2
m.child = null
expect(Object.keys(d._all_models).length).to.equal 1
m.child = m2
expect(Object.keys(d._all_models).length).to.equal 2
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "tracks all_models with list property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModelWithChildren()
m2 = new AnotherModel()
m.children = [m2]
expect(m.children).to.deep.equal [ m2 ]
# check that we get the right all_models on initial add_root
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 2
# check that removing children list drops the models beneath it
m.children = []
expect(Object.keys(d._all_models).length).to.equal 1
# check that adding children back re-adds the models
m.children = [m2]
expect(Object.keys(d._all_models).length).to.equal 2
# check that removing root removes the models
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "tracks all_models with list property where list elements have a child", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModelWithChildren()
m3 = new AnotherModel()
m2 = new SomeModel({ child: m3 })
m.children = [m2]
expect(m.children).to.deep.equal [ m2 ]
# check that we get the right all_models on initial add_root
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 3
# check that removing children list drops the models beneath it
m.children = []
expect(Object.keys(d._all_models).length).to.equal 1
# check that adding children back re-adds the models
m.children = [m2]
expect(Object.keys(d._all_models).length).to.equal 3
# check that removing root removes the models
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "lets us get_model_by_id", ->
d = new Document()
m = new SomeModel()
m2 = new AnotherModel()
m.child = m2
d.add_root(m)
expect(d.get_model_by_id(m.id)).to.equal(m)
expect(d.get_model_by_id(m2.id)).to.equal(m2)
expect(d.get_model_by_id("invalidid")).to.equal(null)
it "lets us get_model_by_name", ->
d = new Document()
m = new SomeModel({ name : "foo" })
m2 = new AnotherModel({ name : "bar" })
m.child = m2
d.add_root(m)
expect(d.get_model_by_name(m.name)).to.equal(m)
expect(d.get_model_by_name(m2.name)).to.equal(m2)
expect(d.get_model_by_name("invalidid")).to.equal(null)
it "lets us get_model_by_name after changing name", ->
d = new Document()
m = new SomeModel({ name : "foo" })
d.add_root(m)
expect(d.get_model_by_name("foo")).to.equal(m)
expect(d.get_model_by_name("bar")).to.equal(null)
m.name = "bar"
expect(d.get_model_by_name("foo")).to.equal(null)
expect(d.get_model_by_name("bar")).to.equal(m)
it "throws on get_model_by_name with duplicate name", ->
d = new Document()
m = new SomeModel({ name : "foo" })
m2 = new AnotherModel({ name : "foo" })
d.add_root(m)
d.add_root(m2)
got_error = false
try
d.get_model_by_name('foo')
catch e
got_error = true
expect(e.message).to.include('Multiple models')
expect(got_error).to.equal(true)
it "can have all_models with multiple references", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModel()
root2 = new SomeModel()
child1 = new AnotherModel()
root1.child = child1
root2.child = child1
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.child = null
expect(size(d._all_models)).to.equal 3
root2.child = null
expect(size(d._all_models)).to.equal 2
root1.child = child1
expect(size(d._all_models)).to.equal 3
root2.child = child1
expect(size(d._all_models)).to.equal 3
d.remove_root(root1)
expect(size(d._all_models)).to.equal 2
d.remove_root(root2)
expect(size(d._all_models)).to.equal 0
it "can have all_models with cycles", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModel()
root2 = new SomeModel()
child1 = new SomeModel()
root1.child = child1
root2.child = child1
child1.child = root1
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.child = null
expect(size(d._all_models)).to.equal 3
root2.child = null
expect(size(d._all_models)).to.equal 2
root1.child = child1
expect(size(d._all_models)).to.equal 3
it "can have all_models with cycles through lists", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModelWithChildren()
root2 = new SomeModelWithChildren()
child1 = new SomeModelWithChildren()
root1.children = [child1]
root2.children = [child1]
child1.children = [root1]
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.children = []
expect(size(d._all_models)).to.equal 3
root2.children = []
expect(size(d._all_models)).to.equal 2
root1.children = [child1]
expect(size(d._all_models)).to.equal 3
it "can notify on changes", ->
d = new Document()
expect(d.roots().length).to.equal 0
m = new AnotherModel()
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(m.bar).to.equal 1
events = []
curdoc_from_listener = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m.bar = 42
expect(events.length).to.equal 1
expect(events[0]).is.instanceof ModelChangedEvent
expect(events[0].document).to.equal d
expect(events[0].model).to.equal m
expect(events[0].attr).to.equal 'bar'
expect(events[0].old).to.equal 1
expect(events[0].new_).to.equal 42
it "can remove notification changes", ->
d = new Document()
expect(d.roots().length).to.equal 0
m = new AnotherModel()
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(m.bar).to.equal 1
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m.bar = 42
expect(events.length).to.equal 1
expect(events[0].new_).to.equal 42
d.remove_on_change(listener)
m.bar = 43
expect(events.length).to.equal 1
it "should notify on roots change", ->
d = new Document()
expect(d.roots().length).to.equal 0
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m = new AnotherModel({bar:1})
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(events.length).to.equal 1
expect(events[0]).is.instanceof RootAddedEvent
expect(events[0].model).to.equal m
m2 = new AnotherModel({bar:2})
d.add_root(m2)
expect(d.roots().length).to.equal 2
expect(events.length).to.equal 2
expect(events[1]).is.instanceof RootAddedEvent
expect(events[1].model).to.equal m2
d.remove_root(m)
expect(d.roots().length).to.equal 1
expect(events.length).to.equal 3
expect(events[2]).is.instanceof RootRemovedEvent
expect(events[2].model).to.equal m
d.remove_root(m2)
expect(d.roots().length).to.equal 0
expect(events.length).to.equal 4
expect(events[3]).is.instanceof RootRemovedEvent
expect(events[3].model).to.equal m2
it "should notify on title change", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
d.set_title('Foo')
expect(d.title()).to.equal 'Foo'
expect(events.length).to.equal 1
expect(events[0]).is.instanceof TitleChangedEvent
expect(events[0].document).to.equal d
expect(events[0].title).to.equal 'Foo'
it "can clear", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
d.clear()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
# does not reset title
expect(d.title()).to.equal 'Foo'
it "throws on destructive move of itself", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
try
d.destructively_move(d)
catch e
got_error = true
expect(e.message).to.include('Attempted to overwrite a document with itself')
expect(got_error).to.equal(true)
it "can destructively move", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
d2 = new Document()
expect(d2.roots().length).to.equal 0
expect(d2.title()).to.equal DEFAULT_TITLE
d2.add_root(new SomeModel())
d2.set_title('Bar')
expect(d2.roots().length).to.equal 1
expect(d2.title()).to.equal 'Bar'
d2.destructively_move(d)
expect(d.roots().length).to.equal 1
expect(d.roots()[0].foo).to.equal 2
expect(d.title()).to.equal 'Bar'
expect(d2.roots().length).to.equal 0
it "checks for versions matching", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
d.add_root(root1)
expect(d.roots().length).to.equal 1
d.set_title("Foo")
old_log_level = logging.logger.level.name
logging.set_log_level("warn")
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = "#{js_version}"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "0.0.1"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}rc123"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}dev123"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}-foo"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "#{js_version}rc123-foo"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "#{js_version}dev123-bar"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
# need to reset old log level
logging.set_log_level(old_log_level)
it "can serialize with one model in it", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
d.add_root(root1)
expect(d.roots().length).to.equal 1
d.set_title("Foo")
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
expect(copy.roots().length).to.equal 1
expect(copy.roots()[0]).to.be.an.instanceof(SomeModel)
expect(copy.title()).to.equal "Foo"
it "can serialize excluding defaults", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
root1.name = 'bar'
d.add_root(root1)
expect(d.roots().length).to.equal 1
json = d.to_json_string(include_defaults=false)
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
expect(copy.roots().length).to.equal 1
expect(copy.roots()[0]).to.be.an.instanceof(SomeModel)
expect(copy.roots()[0].name).to.be.equal 'bar'
# be sure defaults were NOT included
attrs = parsed['roots']['references'][0]['attributes']
expect('tags' of attrs).to.be.equal false
expect('foo' of attrs).to.be.equal false
expect('child' of attrs).to.be.equal false
# this should be included, non-default
expect('name' of attrs).to.be.equal true
# double-check different results if we do include_defaults
parsed_with_defaults = JSON.parse(d.to_json_string(include_defaults=true))
attrs = parsed_with_defaults['roots']['references'][0]['attributes']
#expect('tags' of attrs).to.be.equal true
expect('foo' of attrs).to.be.equal true
expect('child' of attrs).to.be.equal true
expect('name' of attrs).to.be.equal true
# TODO copy the following tests from test_document.py here
# TODO(havocp) test_serialization_more_models
it "can patch an integer property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
root2 = new SomeModel({ foo: 43 })
child1 = new SomeModel({ foo: 44 })
root1.setv({ child: child1 })
root2.setv({ child: child1 })
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
event1 = new ModelChangedEvent(d, root1, 'foo', root1.foo, 57)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.foo).to.equal 57
event2 = new ModelChangedEvent(d, child1, 'foo', child1.foo, 67)
patch2 = d.create_json_patch_string([event2])
d.apply_json_patch(JSON.parse(patch2))
expect(child1.foo).to.equal 67
it "can patch a reference property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
root2 = new SomeModel({ foo: 43 })
child1 = new SomeModel({ foo: 44 })
child2 = new SomeModel({ foo: 45 })
child3 = new SomeModel({ foo: 46, child: child2})
root1.setv({ child: child1 })
root2.setv({ child: child1 })
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.not.have.property(child2.id)
expect(d._all_models).to.not.have.property(child3.id)
event1 = new ModelChangedEvent(d, root1, 'child', root1.child, child3)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.child.id).to.equal child3.id
expect(root1.child.child.id).to.equal child2.id
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.have.property(child2.id)
expect(d._all_models).to.have.property(child3.id)
# put it back how it was before
event2 = new ModelChangedEvent(d, root1, 'child', child1.child, child1)
patch2 = d.create_json_patch_string([event2])
d.apply_json_patch(JSON.parse(patch2))
expect(root1.child.id).to.equal child1.id
expect(root1.child.child).to.be.equal null
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.not.have.property(child2.id)
expect(d._all_models).to.not.have.property(child3.id)
it "can patch two properties at once", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
child1 = new SomeModel({ foo: 43 })
root1.setv({ child: child1 })
d.add_root(root1)
expect(d.roots().length).to.equal 1
child2 = new SomeModel({ foo: 44 })
event1 = new ModelChangedEvent(d, root1, 'foo', root1.foo, 57)
event2 = new ModelChangedEvent(d, root1, 'child', root1.child, child2)
patch1 = d.create_json_patch_string([event1, event2])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.foo).to.equal 57
expect(root1.child.foo).to.be.equal 44
it "sets proper document on models added during patching", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
child1 = new SomeModel({ foo: 44 })
d.add_root(root1)
expect(d.roots().length).to.equal 1
# can't create copy of doc here like other test. Testing explicitly that
# doc attach happens when *not* creating a new document (i.e only patching)
# Testing only for/against null .document is not the strongest test but it
# should suffice.
expect(root1.document.roots().length).equal 1
expect(root1.child).to.equal null
event1 = new ModelChangedEvent(d, root1, 'child', root1.child, child1)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.document.roots().length).equal 1
expect(root1.child.document.roots().length).equal 1
it "sets proper document on models added during construction", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
root1.foo = 3
root1.child = null
d.add_root(root1)
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
root1_copy = copy.get_model_by_id(root1.id)
expect(root1.foo).to.equal 3
expect(root1.child).to.equal null
# when unpacking the copy, initialize() was supposed to overwrite
# what we unpacked.
expect(root1_copy.foo).to.equal 4
expect(root1_copy.child).to.be.an.instanceof(AnotherModel)
expect(root1_copy.document).to.equal copy
expect(root1_copy.child.document).to.equal copy
it "computes patch for models added during construction", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
root1.foo = 3
root1.child = null
d.add_root(root1)
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
patch = Document._compute_patch_since_json(JSON.parse(json), copy)
expect(patch.events.length).to.equal 2
expect(root1.foo).to.equal 3
expect(root1.child).to.equal null
d.apply_json_patch(patch)
expect(root1.foo).to.equal 4
expect(root1.child).to.be.an.instanceof(AnotherModel)
it "computes complicated patch for models added during construction", ->
# this test simulates how from_json has to compute changes
# to send back to the server, when the client side makes
# changes while constructing the parsed document.
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ComplicatedModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
serialized_values = {
'name' : 'foo',
'tags' : ['bar'],
'list_prop' : [new AnotherModel({ 'bar' : 42 })],
'dict_prop' : { foo: new AnotherModel({ 'bar' : 43 }) },
'obj_prop' : new ModelWithConstructTimeChanges(),
'dict_of_list_prop' : { foo: [new AnotherModel({ 'bar' : 44 })] }
}
root1.setv(serialized_values)
d.add_root(root1)
# in computing this, we will construct a
# ComplicatedModelWithConstructTimeChanges which will set
# stuff in initialize(), overwriting serialized_values above.
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
patch = Document._compute_patch_since_json(JSON.parse(json), copy)
# document should have the values we set above
for own key, value of serialized_values
expect(root1.getv(key)).to.deep.equal value
expect(root1.list_prop[0].bar).to.equal 42
expect(root1.dict_prop['foo'].bar).to.equal 43
expect(patch.events.length).to.equal 4
# but when we apply the patch, initialize() should override
# what we had in the json only for the four things that
# ComplicatedModelWithConstructTimeChanges changes (not name
# and tags)
d.apply_json_patch(patch)
expect(root1.name).to.equal 'foo'
expect(root1.tags).to.deep.equal ['bar']
expect(root1.list_prop.length).to.equal 1
expect(root1.list_prop[0].bar).to.equal 1
expect(Object.keys(root1.dict_prop).length).to.equal 1
expect(root1.dict_prop['foo'].bar).to.equal 1
expect(root1.obj_prop).to.be.an.instanceof(ModelWithConstructTimeChanges)
expect(root1.obj_prop.child).to.be.an.instanceof(AnotherModel)
expect(Object.keys(root1.dict_of_list_prop).length).to.equal 1
expect(values(root1.dict_of_list_prop)[0].length).to.equal 1
| 98984 | {expect} = require "chai"
sinon = require "sinon"
{ stdoutTrap, stderrTrap } = require 'logtrap'
{values, size} = require("core/util/object")
{Document, ModelChangedEvent, TitleChangedEvent, RootAddedEvent, RootRemovedEvent, DEFAULT_TITLE} = require "document"
js_version = require("version").version
{Models} = require "base"
{Model} = require "model"
logging = require "core/logging"
p = require "core/properties"
class AnotherModel extends Model
type: 'AnotherModel'
@define {
bar: [ p.Number, 1 ]
}
Models.register('AnotherModel', AnotherModel)
class SomeModel extends Model
type: 'SomeModel'
@define {
foo: [ p.Number, 2 ]
child: [ p.Instance, null ]
}
Models.register('SomeModel', SomeModel)
class SomeModelWithChildren extends Model
type: 'SomeModelWithChildren'
@define {
children: [ p.Array, [] ]
}
Models.register('SomeModelWithChildren', SomeModelWithChildren)
class ModelWithConstructTimeChanges extends Model
type: 'ModelWithConstructTimeChanges'
initialize: (attributes, options) ->
super(attributes, options)
@foo = 4
@child = new AnotherModel()
@define {
foo: [ p.Number, 2 ]
child: [ p.Instance, null ]
}
Models.register('ModelWithConstructTimeChanges', ModelWithConstructTimeChanges)
class ComplicatedModelWithConstructTimeChanges extends Model
type: 'ComplicatedModelWithConstructTimeChanges'
initialize: (attributes, options) ->
super(attributes, options)
@list_prop = [new AnotherModel()]
@dict_prop = { foo: new AnotherModel() }
@obj_prop = new ModelWithConstructTimeChanges()
@dict_of_list_prop = { foo: [new AnotherModel()] }
@define {
list_prop: [ p.Array ]
dict_prop: [ p.Any ]
obj_prop: [ p.Instance ]
dict_of_list_prop: [ p.Any ]
}
Models.register('ComplicatedModelWithConstructTimeChanges', ComplicatedModelWithConstructTimeChanges)
describe "Document", ->
it "should be constructable", ->
d = new Document()
expect(d.roots().length).to.equal 0
it "has working add_root", ->
d = new Document()
expect(d.roots().length).to.equal 0
d.add_root(new AnotherModel())
expect(d.roots().length).to.equal 1
it "manages noting interactivity periods", sinon.test () ->
d = new Document()
expect(d._interactive_plot).to.be.null
expect(d._interactive_timestamp).to.be.null
expect(d.interactive_duration()).to.equal -1
stub = sinon.stub(Date, 'now')
stub.onCall(0).returns(10);
stub.onCall(1).returns(12);
stub.onCall(2).returns(15);
stub.onCall(3).returns(18);
m1 = new SomeModel()
m2 = new AnotherModel()
d.interactive_start(m1) # first stub value 10
expect(d._interactive_plot.id).to.equal m1.id
expect(d._interactive_timestamp).to.be.equal 10
expect(d.interactive_duration()).to.be.equal 2 # second stub value 12
d.interactive_start(m2) # third stub value 15
expect(d._interactive_plot.id).to.equal m1.id
expect(d._interactive_timestamp).to.be.equal 15
expect(d.interactive_duration()).to.be.equal 3 # second stub value 18
d.interactive_stop(m1)
expect(d._interactive_plot).to.be.null
expect(d._interactive_timestamp).to.be.null
expect(d.interactive_duration()).to.equal -1
it "has working set_title", ->
d = new Document()
expect(d.title()).to.equal "Bokeh Application"
d.set_title("Foo")
expect(d.title()).to.equal "Foo"
it "tracks all_models", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModel()
m2 = new AnotherModel()
m.child = m2
expect(m.child).to.equal m2
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 2
m.child = null
expect(Object.keys(d._all_models).length).to.equal 1
m.child = m2
expect(Object.keys(d._all_models).length).to.equal 2
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "tracks all_models with list property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModelWithChildren()
m2 = new AnotherModel()
m.children = [m2]
expect(m.children).to.deep.equal [ m2 ]
# check that we get the right all_models on initial add_root
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 2
# check that removing children list drops the models beneath it
m.children = []
expect(Object.keys(d._all_models).length).to.equal 1
# check that adding children back re-adds the models
m.children = [m2]
expect(Object.keys(d._all_models).length).to.equal 2
# check that removing root removes the models
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "tracks all_models with list property where list elements have a child", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModelWithChildren()
m3 = new AnotherModel()
m2 = new SomeModel({ child: m3 })
m.children = [m2]
expect(m.children).to.deep.equal [ m2 ]
# check that we get the right all_models on initial add_root
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 3
# check that removing children list drops the models beneath it
m.children = []
expect(Object.keys(d._all_models).length).to.equal 1
# check that adding children back re-adds the models
m.children = [m2]
expect(Object.keys(d._all_models).length).to.equal 3
# check that removing root removes the models
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "lets us get_model_by_id", ->
d = new Document()
m = new SomeModel()
m2 = new AnotherModel()
m.child = m2
d.add_root(m)
expect(d.get_model_by_id(m.id)).to.equal(m)
expect(d.get_model_by_id(m2.id)).to.equal(m2)
expect(d.get_model_by_id("invalidid")).to.equal(null)
it "lets us get_model_by_name", ->
d = new Document()
m = new SomeModel({ name : "<NAME>" })
m2 = new AnotherModel({ name : "bar" })
m.child = m2
d.add_root(m)
expect(d.get_model_by_name(m.name)).to.equal(m)
expect(d.get_model_by_name(m2.name)).to.equal(m2)
expect(d.get_model_by_name("invalidid")).to.equal(null)
it "lets us get_model_by_name after changing name", ->
d = new Document()
m = new SomeModel({ name : "<NAME>" })
d.add_root(m)
expect(d.get_model_by_name("foo")).to.equal(m)
expect(d.get_model_by_name("bar")).to.equal(null)
m.name = "bar"
expect(d.get_model_by_name("foo")).to.equal(null)
expect(d.get_model_by_name("bar")).to.equal(m)
it "throws on get_model_by_name with duplicate name", ->
d = new Document()
m = new SomeModel({ name : "<NAME>" })
m2 = new AnotherModel({ name : "<NAME>" })
d.add_root(m)
d.add_root(m2)
got_error = false
try
d.get_model_by_name('foo')
catch e
got_error = true
expect(e.message).to.include('Multiple models')
expect(got_error).to.equal(true)
it "can have all_models with multiple references", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModel()
root2 = new SomeModel()
child1 = new AnotherModel()
root1.child = child1
root2.child = child1
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.child = null
expect(size(d._all_models)).to.equal 3
root2.child = null
expect(size(d._all_models)).to.equal 2
root1.child = child1
expect(size(d._all_models)).to.equal 3
root2.child = child1
expect(size(d._all_models)).to.equal 3
d.remove_root(root1)
expect(size(d._all_models)).to.equal 2
d.remove_root(root2)
expect(size(d._all_models)).to.equal 0
it "can have all_models with cycles", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModel()
root2 = new SomeModel()
child1 = new SomeModel()
root1.child = child1
root2.child = child1
child1.child = root1
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.child = null
expect(size(d._all_models)).to.equal 3
root2.child = null
expect(size(d._all_models)).to.equal 2
root1.child = child1
expect(size(d._all_models)).to.equal 3
it "can have all_models with cycles through lists", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModelWithChildren()
root2 = new SomeModelWithChildren()
child1 = new SomeModelWithChildren()
root1.children = [child1]
root2.children = [child1]
child1.children = [root1]
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.children = []
expect(size(d._all_models)).to.equal 3
root2.children = []
expect(size(d._all_models)).to.equal 2
root1.children = [child1]
expect(size(d._all_models)).to.equal 3
it "can notify on changes", ->
d = new Document()
expect(d.roots().length).to.equal 0
m = new AnotherModel()
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(m.bar).to.equal 1
events = []
curdoc_from_listener = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m.bar = 42
expect(events.length).to.equal 1
expect(events[0]).is.instanceof ModelChangedEvent
expect(events[0].document).to.equal d
expect(events[0].model).to.equal m
expect(events[0].attr).to.equal 'bar'
expect(events[0].old).to.equal 1
expect(events[0].new_).to.equal 42
it "can remove notification changes", ->
d = new Document()
expect(d.roots().length).to.equal 0
m = new AnotherModel()
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(m.bar).to.equal 1
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m.bar = 42
expect(events.length).to.equal 1
expect(events[0].new_).to.equal 42
d.remove_on_change(listener)
m.bar = 43
expect(events.length).to.equal 1
it "should notify on roots change", ->
d = new Document()
expect(d.roots().length).to.equal 0
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m = new AnotherModel({bar:1})
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(events.length).to.equal 1
expect(events[0]).is.instanceof RootAddedEvent
expect(events[0].model).to.equal m
m2 = new AnotherModel({bar:2})
d.add_root(m2)
expect(d.roots().length).to.equal 2
expect(events.length).to.equal 2
expect(events[1]).is.instanceof RootAddedEvent
expect(events[1].model).to.equal m2
d.remove_root(m)
expect(d.roots().length).to.equal 1
expect(events.length).to.equal 3
expect(events[2]).is.instanceof RootRemovedEvent
expect(events[2].model).to.equal m
d.remove_root(m2)
expect(d.roots().length).to.equal 0
expect(events.length).to.equal 4
expect(events[3]).is.instanceof RootRemovedEvent
expect(events[3].model).to.equal m2
it "should notify on title change", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
d.set_title('Foo')
expect(d.title()).to.equal 'Foo'
expect(events.length).to.equal 1
expect(events[0]).is.instanceof TitleChangedEvent
expect(events[0].document).to.equal d
expect(events[0].title).to.equal 'Foo'
it "can clear", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
d.clear()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
# does not reset title
expect(d.title()).to.equal 'Foo'
it "throws on destructive move of itself", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
try
d.destructively_move(d)
catch e
got_error = true
expect(e.message).to.include('Attempted to overwrite a document with itself')
expect(got_error).to.equal(true)
it "can destructively move", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
d2 = new Document()
expect(d2.roots().length).to.equal 0
expect(d2.title()).to.equal DEFAULT_TITLE
d2.add_root(new SomeModel())
d2.set_title('Bar')
expect(d2.roots().length).to.equal 1
expect(d2.title()).to.equal 'Bar'
d2.destructively_move(d)
expect(d.roots().length).to.equal 1
expect(d.roots()[0].foo).to.equal 2
expect(d.title()).to.equal 'Bar'
expect(d2.roots().length).to.equal 0
it "checks for versions matching", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
d.add_root(root1)
expect(d.roots().length).to.equal 1
d.set_title("Foo")
old_log_level = logging.logger.level.name
logging.set_log_level("warn")
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = "#{js_version}"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "0.0.1"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}rc123"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}dev123"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}-foo"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "#{js_version}rc123-foo"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "#{js_version}dev123-bar"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
# need to reset old log level
logging.set_log_level(old_log_level)
it "can serialize with one model in it", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
d.add_root(root1)
expect(d.roots().length).to.equal 1
d.set_title("Foo")
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
expect(copy.roots().length).to.equal 1
expect(copy.roots()[0]).to.be.an.instanceof(SomeModel)
expect(copy.title()).to.equal "Foo"
it "can serialize excluding defaults", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
root1.name = 'bar'
d.add_root(root1)
expect(d.roots().length).to.equal 1
json = d.to_json_string(include_defaults=false)
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
expect(copy.roots().length).to.equal 1
expect(copy.roots()[0]).to.be.an.instanceof(SomeModel)
expect(copy.roots()[0].name).to.be.equal 'bar'
# be sure defaults were NOT included
attrs = parsed['roots']['references'][0]['attributes']
expect('tags' of attrs).to.be.equal false
expect('foo' of attrs).to.be.equal false
expect('child' of attrs).to.be.equal false
# this should be included, non-default
expect('name' of attrs).to.be.equal true
# double-check different results if we do include_defaults
parsed_with_defaults = JSON.parse(d.to_json_string(include_defaults=true))
attrs = parsed_with_defaults['roots']['references'][0]['attributes']
#expect('tags' of attrs).to.be.equal true
expect('foo' of attrs).to.be.equal true
expect('child' of attrs).to.be.equal true
expect('name' of attrs).to.be.equal true
# TODO copy the following tests from test_document.py here
# TODO(havocp) test_serialization_more_models
it "can patch an integer property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
root2 = new SomeModel({ foo: 43 })
child1 = new SomeModel({ foo: 44 })
root1.setv({ child: child1 })
root2.setv({ child: child1 })
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
event1 = new ModelChangedEvent(d, root1, 'foo', root1.foo, 57)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.foo).to.equal 57
event2 = new ModelChangedEvent(d, child1, 'foo', child1.foo, 67)
patch2 = d.create_json_patch_string([event2])
d.apply_json_patch(JSON.parse(patch2))
expect(child1.foo).to.equal 67
it "can patch a reference property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
root2 = new SomeModel({ foo: 43 })
child1 = new SomeModel({ foo: 44 })
child2 = new SomeModel({ foo: 45 })
child3 = new SomeModel({ foo: 46, child: child2})
root1.setv({ child: child1 })
root2.setv({ child: child1 })
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.not.have.property(child2.id)
expect(d._all_models).to.not.have.property(child3.id)
event1 = new ModelChangedEvent(d, root1, 'child', root1.child, child3)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.child.id).to.equal child3.id
expect(root1.child.child.id).to.equal child2.id
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.have.property(child2.id)
expect(d._all_models).to.have.property(child3.id)
# put it back how it was before
event2 = new ModelChangedEvent(d, root1, 'child', child1.child, child1)
patch2 = d.create_json_patch_string([event2])
d.apply_json_patch(JSON.parse(patch2))
expect(root1.child.id).to.equal child1.id
expect(root1.child.child).to.be.equal null
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.not.have.property(child2.id)
expect(d._all_models).to.not.have.property(child3.id)
it "can patch two properties at once", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
child1 = new SomeModel({ foo: 43 })
root1.setv({ child: child1 })
d.add_root(root1)
expect(d.roots().length).to.equal 1
child2 = new SomeModel({ foo: 44 })
event1 = new ModelChangedEvent(d, root1, 'foo', root1.foo, 57)
event2 = new ModelChangedEvent(d, root1, 'child', root1.child, child2)
patch1 = d.create_json_patch_string([event1, event2])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.foo).to.equal 57
expect(root1.child.foo).to.be.equal 44
it "sets proper document on models added during patching", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
child1 = new SomeModel({ foo: 44 })
d.add_root(root1)
expect(d.roots().length).to.equal 1
# can't create copy of doc here like other test. Testing explicitly that
# doc attach happens when *not* creating a new document (i.e only patching)
# Testing only for/against null .document is not the strongest test but it
# should suffice.
expect(root1.document.roots().length).equal 1
expect(root1.child).to.equal null
event1 = new ModelChangedEvent(d, root1, 'child', root1.child, child1)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.document.roots().length).equal 1
expect(root1.child.document.roots().length).equal 1
it "sets proper document on models added during construction", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
root1.foo = 3
root1.child = null
d.add_root(root1)
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
root1_copy = copy.get_model_by_id(root1.id)
expect(root1.foo).to.equal 3
expect(root1.child).to.equal null
# when unpacking the copy, initialize() was supposed to overwrite
# what we unpacked.
expect(root1_copy.foo).to.equal 4
expect(root1_copy.child).to.be.an.instanceof(AnotherModel)
expect(root1_copy.document).to.equal copy
expect(root1_copy.child.document).to.equal copy
it "computes patch for models added during construction", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
root1.foo = 3
root1.child = null
d.add_root(root1)
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
patch = Document._compute_patch_since_json(JSON.parse(json), copy)
expect(patch.events.length).to.equal 2
expect(root1.foo).to.equal 3
expect(root1.child).to.equal null
d.apply_json_patch(patch)
expect(root1.foo).to.equal 4
expect(root1.child).to.be.an.instanceof(AnotherModel)
it "computes complicated patch for models added during construction", ->
# this test simulates how from_json has to compute changes
# to send back to the server, when the client side makes
# changes while constructing the parsed document.
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ComplicatedModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
serialized_values = {
'name' : 'foo',
'tags' : ['bar'],
'list_prop' : [new AnotherModel({ 'bar' : 42 })],
'dict_prop' : { foo: new AnotherModel({ 'bar' : 43 }) },
'obj_prop' : new ModelWithConstructTimeChanges(),
'dict_of_list_prop' : { foo: [new AnotherModel({ 'bar' : 44 })] }
}
root1.setv(serialized_values)
d.add_root(root1)
# in computing this, we will construct a
# ComplicatedModelWithConstructTimeChanges which will set
# stuff in initialize(), overwriting serialized_values above.
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
patch = Document._compute_patch_since_json(JSON.parse(json), copy)
# document should have the values we set above
for own key, value of serialized_values
expect(root1.getv(key)).to.deep.equal value
expect(root1.list_prop[0].bar).to.equal 42
expect(root1.dict_prop['foo'].bar).to.equal 43
expect(patch.events.length).to.equal 4
# but when we apply the patch, initialize() should override
# what we had in the json only for the four things that
# ComplicatedModelWithConstructTimeChanges changes (not name
# and tags)
d.apply_json_patch(patch)
expect(root1.name).to.equal 'foo'
expect(root1.tags).to.deep.equal ['bar']
expect(root1.list_prop.length).to.equal 1
expect(root1.list_prop[0].bar).to.equal 1
expect(Object.keys(root1.dict_prop).length).to.equal 1
expect(root1.dict_prop['foo'].bar).to.equal 1
expect(root1.obj_prop).to.be.an.instanceof(ModelWithConstructTimeChanges)
expect(root1.obj_prop.child).to.be.an.instanceof(AnotherModel)
expect(Object.keys(root1.dict_of_list_prop).length).to.equal 1
expect(values(root1.dict_of_list_prop)[0].length).to.equal 1
| true | {expect} = require "chai"
sinon = require "sinon"
{ stdoutTrap, stderrTrap } = require 'logtrap'
{values, size} = require("core/util/object")
{Document, ModelChangedEvent, TitleChangedEvent, RootAddedEvent, RootRemovedEvent, DEFAULT_TITLE} = require "document"
js_version = require("version").version
{Models} = require "base"
{Model} = require "model"
logging = require "core/logging"
p = require "core/properties"
class AnotherModel extends Model
type: 'AnotherModel'
@define {
bar: [ p.Number, 1 ]
}
Models.register('AnotherModel', AnotherModel)
class SomeModel extends Model
type: 'SomeModel'
@define {
foo: [ p.Number, 2 ]
child: [ p.Instance, null ]
}
Models.register('SomeModel', SomeModel)
class SomeModelWithChildren extends Model
type: 'SomeModelWithChildren'
@define {
children: [ p.Array, [] ]
}
Models.register('SomeModelWithChildren', SomeModelWithChildren)
class ModelWithConstructTimeChanges extends Model
type: 'ModelWithConstructTimeChanges'
initialize: (attributes, options) ->
super(attributes, options)
@foo = 4
@child = new AnotherModel()
@define {
foo: [ p.Number, 2 ]
child: [ p.Instance, null ]
}
Models.register('ModelWithConstructTimeChanges', ModelWithConstructTimeChanges)
class ComplicatedModelWithConstructTimeChanges extends Model
type: 'ComplicatedModelWithConstructTimeChanges'
initialize: (attributes, options) ->
super(attributes, options)
@list_prop = [new AnotherModel()]
@dict_prop = { foo: new AnotherModel() }
@obj_prop = new ModelWithConstructTimeChanges()
@dict_of_list_prop = { foo: [new AnotherModel()] }
@define {
list_prop: [ p.Array ]
dict_prop: [ p.Any ]
obj_prop: [ p.Instance ]
dict_of_list_prop: [ p.Any ]
}
Models.register('ComplicatedModelWithConstructTimeChanges', ComplicatedModelWithConstructTimeChanges)
describe "Document", ->
it "should be constructable", ->
d = new Document()
expect(d.roots().length).to.equal 0
it "has working add_root", ->
d = new Document()
expect(d.roots().length).to.equal 0
d.add_root(new AnotherModel())
expect(d.roots().length).to.equal 1
it "manages noting interactivity periods", sinon.test () ->
d = new Document()
expect(d._interactive_plot).to.be.null
expect(d._interactive_timestamp).to.be.null
expect(d.interactive_duration()).to.equal -1
stub = sinon.stub(Date, 'now')
stub.onCall(0).returns(10);
stub.onCall(1).returns(12);
stub.onCall(2).returns(15);
stub.onCall(3).returns(18);
m1 = new SomeModel()
m2 = new AnotherModel()
d.interactive_start(m1) # first stub value 10
expect(d._interactive_plot.id).to.equal m1.id
expect(d._interactive_timestamp).to.be.equal 10
expect(d.interactive_duration()).to.be.equal 2 # second stub value 12
d.interactive_start(m2) # third stub value 15
expect(d._interactive_plot.id).to.equal m1.id
expect(d._interactive_timestamp).to.be.equal 15
expect(d.interactive_duration()).to.be.equal 3 # second stub value 18
d.interactive_stop(m1)
expect(d._interactive_plot).to.be.null
expect(d._interactive_timestamp).to.be.null
expect(d.interactive_duration()).to.equal -1
it "has working set_title", ->
d = new Document()
expect(d.title()).to.equal "Bokeh Application"
d.set_title("Foo")
expect(d.title()).to.equal "Foo"
it "tracks all_models", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModel()
m2 = new AnotherModel()
m.child = m2
expect(m.child).to.equal m2
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 2
m.child = null
expect(Object.keys(d._all_models).length).to.equal 1
m.child = m2
expect(Object.keys(d._all_models).length).to.equal 2
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "tracks all_models with list property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModelWithChildren()
m2 = new AnotherModel()
m.children = [m2]
expect(m.children).to.deep.equal [ m2 ]
# check that we get the right all_models on initial add_root
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 2
# check that removing children list drops the models beneath it
m.children = []
expect(Object.keys(d._all_models).length).to.equal 1
# check that adding children back re-adds the models
m.children = [m2]
expect(Object.keys(d._all_models).length).to.equal 2
# check that removing root removes the models
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "tracks all_models with list property where list elements have a child", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
m = new SomeModelWithChildren()
m3 = new AnotherModel()
m2 = new SomeModel({ child: m3 })
m.children = [m2]
expect(m.children).to.deep.equal [ m2 ]
# check that we get the right all_models on initial add_root
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(Object.keys(d._all_models).length).to.equal 3
# check that removing children list drops the models beneath it
m.children = []
expect(Object.keys(d._all_models).length).to.equal 1
# check that adding children back re-adds the models
m.children = [m2]
expect(Object.keys(d._all_models).length).to.equal 3
# check that removing root removes the models
d.remove_root(m)
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
it "lets us get_model_by_id", ->
d = new Document()
m = new SomeModel()
m2 = new AnotherModel()
m.child = m2
d.add_root(m)
expect(d.get_model_by_id(m.id)).to.equal(m)
expect(d.get_model_by_id(m2.id)).to.equal(m2)
expect(d.get_model_by_id("invalidid")).to.equal(null)
it "lets us get_model_by_name", ->
d = new Document()
m = new SomeModel({ name : "PI:NAME:<NAME>END_PI" })
m2 = new AnotherModel({ name : "bar" })
m.child = m2
d.add_root(m)
expect(d.get_model_by_name(m.name)).to.equal(m)
expect(d.get_model_by_name(m2.name)).to.equal(m2)
expect(d.get_model_by_name("invalidid")).to.equal(null)
it "lets us get_model_by_name after changing name", ->
d = new Document()
m = new SomeModel({ name : "PI:NAME:<NAME>END_PI" })
d.add_root(m)
expect(d.get_model_by_name("foo")).to.equal(m)
expect(d.get_model_by_name("bar")).to.equal(null)
m.name = "bar"
expect(d.get_model_by_name("foo")).to.equal(null)
expect(d.get_model_by_name("bar")).to.equal(m)
it "throws on get_model_by_name with duplicate name", ->
d = new Document()
m = new SomeModel({ name : "PI:NAME:<NAME>END_PI" })
m2 = new AnotherModel({ name : "PI:NAME:<NAME>END_PI" })
d.add_root(m)
d.add_root(m2)
got_error = false
try
d.get_model_by_name('foo')
catch e
got_error = true
expect(e.message).to.include('Multiple models')
expect(got_error).to.equal(true)
it "can have all_models with multiple references", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModel()
root2 = new SomeModel()
child1 = new AnotherModel()
root1.child = child1
root2.child = child1
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.child = null
expect(size(d._all_models)).to.equal 3
root2.child = null
expect(size(d._all_models)).to.equal 2
root1.child = child1
expect(size(d._all_models)).to.equal 3
root2.child = child1
expect(size(d._all_models)).to.equal 3
d.remove_root(root1)
expect(size(d._all_models)).to.equal 2
d.remove_root(root2)
expect(size(d._all_models)).to.equal 0
it "can have all_models with cycles", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModel()
root2 = new SomeModel()
child1 = new SomeModel()
root1.child = child1
root2.child = child1
child1.child = root1
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.child = null
expect(size(d._all_models)).to.equal 3
root2.child = null
expect(size(d._all_models)).to.equal 2
root1.child = child1
expect(size(d._all_models)).to.equal 3
it "can have all_models with cycles through lists", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
root1 = new SomeModelWithChildren()
root2 = new SomeModelWithChildren()
child1 = new SomeModelWithChildren()
root1.children = [child1]
root2.children = [child1]
child1.children = [root1]
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(size(d._all_models)).to.equal 3
root1.children = []
expect(size(d._all_models)).to.equal 3
root2.children = []
expect(size(d._all_models)).to.equal 2
root1.children = [child1]
expect(size(d._all_models)).to.equal 3
it "can notify on changes", ->
d = new Document()
expect(d.roots().length).to.equal 0
m = new AnotherModel()
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(m.bar).to.equal 1
events = []
curdoc_from_listener = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m.bar = 42
expect(events.length).to.equal 1
expect(events[0]).is.instanceof ModelChangedEvent
expect(events[0].document).to.equal d
expect(events[0].model).to.equal m
expect(events[0].attr).to.equal 'bar'
expect(events[0].old).to.equal 1
expect(events[0].new_).to.equal 42
it "can remove notification changes", ->
d = new Document()
expect(d.roots().length).to.equal 0
m = new AnotherModel()
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(m.bar).to.equal 1
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m.bar = 42
expect(events.length).to.equal 1
expect(events[0].new_).to.equal 42
d.remove_on_change(listener)
m.bar = 43
expect(events.length).to.equal 1
it "should notify on roots change", ->
d = new Document()
expect(d.roots().length).to.equal 0
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
m = new AnotherModel({bar:1})
d.add_root(m)
expect(d.roots().length).to.equal 1
expect(events.length).to.equal 1
expect(events[0]).is.instanceof RootAddedEvent
expect(events[0].model).to.equal m
m2 = new AnotherModel({bar:2})
d.add_root(m2)
expect(d.roots().length).to.equal 2
expect(events.length).to.equal 2
expect(events[1]).is.instanceof RootAddedEvent
expect(events[1].model).to.equal m2
d.remove_root(m)
expect(d.roots().length).to.equal 1
expect(events.length).to.equal 3
expect(events[2]).is.instanceof RootRemovedEvent
expect(events[2].model).to.equal m
d.remove_root(m2)
expect(d.roots().length).to.equal 0
expect(events.length).to.equal 4
expect(events[3]).is.instanceof RootRemovedEvent
expect(events[3].model).to.equal m2
it "should notify on title change", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
events = []
listener = (event) ->
events.push(event)
d.on_change(listener)
d.set_title('Foo')
expect(d.title()).to.equal 'Foo'
expect(events.length).to.equal 1
expect(events[0]).is.instanceof TitleChangedEvent
expect(events[0].document).to.equal d
expect(events[0].title).to.equal 'Foo'
it "can clear", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
d.clear()
expect(d.roots().length).to.equal 0
expect(size(d._all_models)).to.equal 0
# does not reset title
expect(d.title()).to.equal 'Foo'
it "throws on destructive move of itself", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
try
d.destructively_move(d)
catch e
got_error = true
expect(e.message).to.include('Attempted to overwrite a document with itself')
expect(got_error).to.equal(true)
it "can destructively move", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(d.title()).to.equal DEFAULT_TITLE
d.add_root(new AnotherModel())
d.add_root(new AnotherModel())
d.set_title('Foo')
expect(d.roots().length).to.equal 2
expect(d.title()).to.equal 'Foo'
d2 = new Document()
expect(d2.roots().length).to.equal 0
expect(d2.title()).to.equal DEFAULT_TITLE
d2.add_root(new SomeModel())
d2.set_title('Bar')
expect(d2.roots().length).to.equal 1
expect(d2.title()).to.equal 'Bar'
d2.destructively_move(d)
expect(d.roots().length).to.equal 1
expect(d.roots()[0].foo).to.equal 2
expect(d.title()).to.equal 'Bar'
expect(d2.roots().length).to.equal 0
it "checks for versions matching", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
d.add_root(root1)
expect(d.roots().length).to.equal 1
d.set_title("Foo")
old_log_level = logging.logger.level.name
logging.set_log_level("warn")
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = "#{js_version}"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "0.0.1"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}rc123"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}dev123"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal "[bokeh] JS/Python version mismatch\n[bokeh] Library versions: JS (#{js_version}) / Python (#{parsed["version"]})\n"
parsed['version'] = "#{js_version}-foo"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "#{js_version}rc123-foo"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
parsed['version'] = "#{js_version}dev123-bar"
out = stderrTrap -> Document.from_json_string(JSON.stringify(parsed))
expect(out).to.be.equal ""
# need to reset old log level
logging.set_log_level(old_log_level)
it "can serialize with one model in it", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
d.add_root(root1)
expect(d.roots().length).to.equal 1
d.set_title("Foo")
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
expect(copy.roots().length).to.equal 1
expect(copy.roots()[0]).to.be.an.instanceof(SomeModel)
expect(copy.title()).to.equal "Foo"
it "can serialize excluding defaults", ->
d = new Document()
expect(d.roots().length).to.equal 0
root1 = new SomeModel()
root1.name = 'bar'
d.add_root(root1)
expect(d.roots().length).to.equal 1
json = d.to_json_string(include_defaults=false)
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
expect(copy.roots().length).to.equal 1
expect(copy.roots()[0]).to.be.an.instanceof(SomeModel)
expect(copy.roots()[0].name).to.be.equal 'bar'
# be sure defaults were NOT included
attrs = parsed['roots']['references'][0]['attributes']
expect('tags' of attrs).to.be.equal false
expect('foo' of attrs).to.be.equal false
expect('child' of attrs).to.be.equal false
# this should be included, non-default
expect('name' of attrs).to.be.equal true
# double-check different results if we do include_defaults
parsed_with_defaults = JSON.parse(d.to_json_string(include_defaults=true))
attrs = parsed_with_defaults['roots']['references'][0]['attributes']
#expect('tags' of attrs).to.be.equal true
expect('foo' of attrs).to.be.equal true
expect('child' of attrs).to.be.equal true
expect('name' of attrs).to.be.equal true
# TODO copy the following tests from test_document.py here
# TODO(havocp) test_serialization_more_models
it "can patch an integer property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
root2 = new SomeModel({ foo: 43 })
child1 = new SomeModel({ foo: 44 })
root1.setv({ child: child1 })
root2.setv({ child: child1 })
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
event1 = new ModelChangedEvent(d, root1, 'foo', root1.foo, 57)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.foo).to.equal 57
event2 = new ModelChangedEvent(d, child1, 'foo', child1.foo, 67)
patch2 = d.create_json_patch_string([event2])
d.apply_json_patch(JSON.parse(patch2))
expect(child1.foo).to.equal 67
it "can patch a reference property", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
root2 = new SomeModel({ foo: 43 })
child1 = new SomeModel({ foo: 44 })
child2 = new SomeModel({ foo: 45 })
child3 = new SomeModel({ foo: 46, child: child2})
root1.setv({ child: child1 })
root2.setv({ child: child1 })
d.add_root(root1)
d.add_root(root2)
expect(d.roots().length).to.equal 2
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.not.have.property(child2.id)
expect(d._all_models).to.not.have.property(child3.id)
event1 = new ModelChangedEvent(d, root1, 'child', root1.child, child3)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.child.id).to.equal child3.id
expect(root1.child.child.id).to.equal child2.id
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.have.property(child2.id)
expect(d._all_models).to.have.property(child3.id)
# put it back how it was before
event2 = new ModelChangedEvent(d, root1, 'child', child1.child, child1)
patch2 = d.create_json_patch_string([event2])
d.apply_json_patch(JSON.parse(patch2))
expect(root1.child.id).to.equal child1.id
expect(root1.child.child).to.be.equal null
expect(d._all_models).to.have.property(child1.id)
expect(d._all_models).to.not.have.property(child2.id)
expect(d._all_models).to.not.have.property(child3.id)
it "can patch two properties at once", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
child1 = new SomeModel({ foo: 43 })
root1.setv({ child: child1 })
d.add_root(root1)
expect(d.roots().length).to.equal 1
child2 = new SomeModel({ foo: 44 })
event1 = new ModelChangedEvent(d, root1, 'foo', root1.foo, 57)
event2 = new ModelChangedEvent(d, root1, 'child', root1.child, child2)
patch1 = d.create_json_patch_string([event1, event2])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.foo).to.equal 57
expect(root1.child.foo).to.be.equal 44
it "sets proper document on models added during patching", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new SomeModel({ foo: 42 })
child1 = new SomeModel({ foo: 44 })
d.add_root(root1)
expect(d.roots().length).to.equal 1
# can't create copy of doc here like other test. Testing explicitly that
# doc attach happens when *not* creating a new document (i.e only patching)
# Testing only for/against null .document is not the strongest test but it
# should suffice.
expect(root1.document.roots().length).equal 1
expect(root1.child).to.equal null
event1 = new ModelChangedEvent(d, root1, 'child', root1.child, child1)
patch1 = d.create_json_patch_string([event1])
d.apply_json_patch(JSON.parse(patch1))
expect(root1.document.roots().length).equal 1
expect(root1.child.document.roots().length).equal 1
it "sets proper document on models added during construction", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
root1.foo = 3
root1.child = null
d.add_root(root1)
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
root1_copy = copy.get_model_by_id(root1.id)
expect(root1.foo).to.equal 3
expect(root1.child).to.equal null
# when unpacking the copy, initialize() was supposed to overwrite
# what we unpacked.
expect(root1_copy.foo).to.equal 4
expect(root1_copy.child).to.be.an.instanceof(AnotherModel)
expect(root1_copy.document).to.equal copy
expect(root1_copy.child.document).to.equal copy
it "computes patch for models added during construction", ->
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
root1.foo = 3
root1.child = null
d.add_root(root1)
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
patch = Document._compute_patch_since_json(JSON.parse(json), copy)
expect(patch.events.length).to.equal 2
expect(root1.foo).to.equal 3
expect(root1.child).to.equal null
d.apply_json_patch(patch)
expect(root1.foo).to.equal 4
expect(root1.child).to.be.an.instanceof(AnotherModel)
it "computes complicated patch for models added during construction", ->
# this test simulates how from_json has to compute changes
# to send back to the server, when the client side makes
# changes while constructing the parsed document.
d = new Document()
expect(d.roots().length).to.equal 0
expect(Object.keys(d._all_models).length).to.equal 0
root1 = new ComplicatedModelWithConstructTimeChanges()
# change it so it doesn't match what initialize() does
serialized_values = {
'name' : 'foo',
'tags' : ['bar'],
'list_prop' : [new AnotherModel({ 'bar' : 42 })],
'dict_prop' : { foo: new AnotherModel({ 'bar' : 43 }) },
'obj_prop' : new ModelWithConstructTimeChanges(),
'dict_of_list_prop' : { foo: [new AnotherModel({ 'bar' : 44 })] }
}
root1.setv(serialized_values)
d.add_root(root1)
# in computing this, we will construct a
# ComplicatedModelWithConstructTimeChanges which will set
# stuff in initialize(), overwriting serialized_values above.
json = d.to_json_string()
parsed = JSON.parse(json)
parsed['version'] = js_version
copy = Document.from_json_string(JSON.stringify(parsed))
patch = Document._compute_patch_since_json(JSON.parse(json), copy)
# document should have the values we set above
for own key, value of serialized_values
expect(root1.getv(key)).to.deep.equal value
expect(root1.list_prop[0].bar).to.equal 42
expect(root1.dict_prop['foo'].bar).to.equal 43
expect(patch.events.length).to.equal 4
# but when we apply the patch, initialize() should override
# what we had in the json only for the four things that
# ComplicatedModelWithConstructTimeChanges changes (not name
# and tags)
d.apply_json_patch(patch)
expect(root1.name).to.equal 'foo'
expect(root1.tags).to.deep.equal ['bar']
expect(root1.list_prop.length).to.equal 1
expect(root1.list_prop[0].bar).to.equal 1
expect(Object.keys(root1.dict_prop).length).to.equal 1
expect(root1.dict_prop['foo'].bar).to.equal 1
expect(root1.obj_prop).to.be.an.instanceof(ModelWithConstructTimeChanges)
expect(root1.obj_prop.child).to.be.an.instanceof(AnotherModel)
expect(Object.keys(root1.dict_of_list_prop).length).to.equal 1
expect(values(root1.dict_of_list_prop)[0].length).to.equal 1
|
[
{
"context": "CSS Quo Module\n\n@namespace Quo\n@class css\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\n",
"end": 76,
"score": 0.9998495578765869,
"start": 55,
"tag": "NAME",
"value": "Javier Jimenez Villar"
},
{
"context": "ce Quo\n@class ... | source/quo.css.coffee | lguzzon/QuoJS | 558 | ###
CSS Quo Module
@namespace Quo
@class css
@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
VENDORS = [ "-webkit-", "-moz-", "-ms-", "-o-", "" ]
###
Add class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.addClass = (values) ->
@each ->
@classList.add value for value in _arrayOf values
###
Remove stylesheet class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.removeClass = (values) ->
@each ->
@classList.remove value for value in _arrayOf values
###
Toggle stylesheet class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.toggleClass = (values) ->
@each ->
@classList.toggle value for value in _arrayOf values
###
Test if a stylesheet class is in the giben instance element
@method hasClass
@param {string} Name of stylesheet class
###
$$.fn.hasClass = (name) ->
@length > 0 and @[0].classList.contains name
###
List a object with all classes in a given instance element
@method listClass
@param {string} Name of stylesheet class
###
$$.fn.listClass = ->
@[0].classList if @length > 0
###
Set/Get a stylesheet property in a given instance element
@method style
@param {string} Name of property
@param {string} [OPTIONAL] Value for property
###
$$.fn.style = $$.fn.css = (property, value) ->
if value?
@each -> @style[property] = value
else
el = @[0]
el.style[property] or _computedStyle(el, property)
###
Set/Get a stylesheet vendor-prefix property in a given instance element
@method vendor
@param {string} Name of property
@param {string} Value for property
###
$$.fn.vendor = (property, value) ->
@style("#{prefix}#{property}", value) for prefix in VENDORS
# ---------------------------------------------------------------------------
# Private Methods
# ---------------------------------------------------------------------------
_computedStyle = (element, property) ->
document.defaultView.getComputedStyle(element, "")[property]
_arrayOf = (values) ->
values = [values] unless Array.isArray(values)
values
| 141859 | ###
CSS Quo Module
@namespace Quo
@class css
@author <NAME> <<EMAIL>> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
VENDORS = [ "-webkit-", "-moz-", "-ms-", "-o-", "" ]
###
Add class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.addClass = (values) ->
@each ->
@classList.add value for value in _arrayOf values
###
Remove stylesheet class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.removeClass = (values) ->
@each ->
@classList.remove value for value in _arrayOf values
###
Toggle stylesheet class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.toggleClass = (values) ->
@each ->
@classList.toggle value for value in _arrayOf values
###
Test if a stylesheet class is in the giben instance element
@method hasClass
@param {string} Name of stylesheet class
###
$$.fn.hasClass = (name) ->
@length > 0 and @[0].classList.contains name
###
List a object with all classes in a given instance element
@method listClass
@param {string} Name of stylesheet class
###
$$.fn.listClass = ->
@[0].classList if @length > 0
###
Set/Get a stylesheet property in a given instance element
@method style
@param {string} Name of property
@param {string} [OPTIONAL] Value for property
###
$$.fn.style = $$.fn.css = (property, value) ->
if value?
@each -> @style[property] = value
else
el = @[0]
el.style[property] or _computedStyle(el, property)
###
Set/Get a stylesheet vendor-prefix property in a given instance element
@method vendor
@param {string} Name of property
@param {string} Value for property
###
$$.fn.vendor = (property, value) ->
@style("#{prefix}#{property}", value) for prefix in VENDORS
# ---------------------------------------------------------------------------
# Private Methods
# ---------------------------------------------------------------------------
_computedStyle = (element, property) ->
document.defaultView.getComputedStyle(element, "")[property]
_arrayOf = (values) ->
values = [values] unless Array.isArray(values)
values
| true | ###
CSS Quo Module
@namespace Quo
@class css
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
VENDORS = [ "-webkit-", "-moz-", "-ms-", "-o-", "" ]
###
Add class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.addClass = (values) ->
@each ->
@classList.add value for value in _arrayOf values
###
Remove stylesheet class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.removeClass = (values) ->
@each ->
@classList.remove value for value in _arrayOf values
###
Toggle stylesheet class to a given instance element
@method addClass
@param {string} Name of stylesheet class
###
$$.fn.toggleClass = (values) ->
@each ->
@classList.toggle value for value in _arrayOf values
###
Test if a stylesheet class is in the giben instance element
@method hasClass
@param {string} Name of stylesheet class
###
$$.fn.hasClass = (name) ->
@length > 0 and @[0].classList.contains name
###
List a object with all classes in a given instance element
@method listClass
@param {string} Name of stylesheet class
###
$$.fn.listClass = ->
@[0].classList if @length > 0
###
Set/Get a stylesheet property in a given instance element
@method style
@param {string} Name of property
@param {string} [OPTIONAL] Value for property
###
$$.fn.style = $$.fn.css = (property, value) ->
if value?
@each -> @style[property] = value
else
el = @[0]
el.style[property] or _computedStyle(el, property)
###
Set/Get a stylesheet vendor-prefix property in a given instance element
@method vendor
@param {string} Name of property
@param {string} Value for property
###
$$.fn.vendor = (property, value) ->
@style("#{prefix}#{property}", value) for prefix in VENDORS
# ---------------------------------------------------------------------------
# Private Methods
# ---------------------------------------------------------------------------
_computedStyle = (element, property) ->
document.defaultView.getComputedStyle(element, "")[property]
_arrayOf = (values) ->
values = [values] unless Array.isArray(values)
values
|
[
{
"context": "ateService\n\n beforeEach (done) ->\n @redisKey = UUID.v1()\n meshbluConfig =\n server: 'localhost'\n ",
"end": 517,
"score": 0.8661410808563232,
"start": 510,
"tag": "KEY",
"value": "UUID.v1"
},
{
"context": "0000'\n uuid: 'governator-uuid'\n toke... | test/integration/create-cancellation-spec.coffee | octoblu/governator-service | 0 | request = require 'request'
shmock = require 'shmock'
RedisNs = require '@octoblu/redis-ns'
redis = require 'ioredis'
enableDestroy = require 'server-destroy'
UUID = require 'uuid'
Server = require '../../server'
describe 'Create Cancellation', ->
beforeEach ->
@meshbluServer = shmock 30000
enableDestroy @meshbluServer
beforeEach ->
@deployStateService = shmock 0xbabe
enableDestroy @deployStateService
beforeEach (done) ->
@redisKey = UUID.v1()
meshbluConfig =
server: 'localhost'
port: '30000'
uuid: 'governator-uuid'
token: 'governator-token'
@client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true
@sut = new Server {
meshbluConfig: meshbluConfig
port: 20000
disableLogging: true
deployDelay: 0
redisUri: 'redis://localhost:6379'
namespace: @redisKey
maxConnections: 2,
requiredClusters: ['minor']
cluster: 'super'
deployStateUri: "http://hi:hello@localhost:#{0xbabe}"
}
@sut.run done
afterEach ->
@sut.destroy()
@meshbluServer.destroy()
@deployStateService.destroy()
describe 'POST /cancellations', ->
describe 'when called with valid auth', ->
describe 'when called with an existing deploy', ->
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
deployStateAuth = new Buffer('hi:hello').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
@notifyDeployState = @deployStateService
.put '/deployments/octoblu/a-deploy/v1/cluster/super/failed'
.set 'Authorization', "Basic #{deployStateAuth}"
.reply 204
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: 'governator-token'}
json: {the: 'stuff i posted', etcdDir: '/dir/a-deploy', dockerUrl: 'octoblu/a-deploy:v1' }
request.post options, (error, @response, @body) =>
return done error if error?
done()
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should have set a ttl', (done) ->
keyName = 'governator:/dir/a-deploy:octoblu/a-deploy:v1'
@client.ttl keyName, (error, ttl) =>
return done error if error?
expect(ttl).to.be.greaterThan 0
done()
it 'should set the cancellation metadata', (done) ->
@client.hexists 'governator:/dir/a-deploy:octoblu/a-deploy:v1', 'cancellation', (error, exists) =>
return done error if error?
expect(exists).to.equal 1
done()
it 'should notify the deploy state service', ->
@notifyDeployState.done()
describe 'when called with invalid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 403
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'wrong-token'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
describe 'when called the wrong valid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 200, uuid: 'wrong-uuid'
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'wrong-token'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
| 136460 | request = require 'request'
shmock = require 'shmock'
RedisNs = require '@octoblu/redis-ns'
redis = require 'ioredis'
enableDestroy = require 'server-destroy'
UUID = require 'uuid'
Server = require '../../server'
describe 'Create Cancellation', ->
beforeEach ->
@meshbluServer = shmock 30000
enableDestroy @meshbluServer
beforeEach ->
@deployStateService = shmock 0xbabe
enableDestroy @deployStateService
beforeEach (done) ->
@redisKey = <KEY>()
meshbluConfig =
server: 'localhost'
port: '30000'
uuid: 'governator-uuid'
token: '<PASSWORD>ator-token'
@client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true
@sut = new Server {
meshbluConfig: meshbluConfig
port: 20000
disableLogging: true
deployDelay: 0
redisUri: 'redis://localhost:6379'
namespace: @redisKey
maxConnections: 2,
requiredClusters: ['minor']
cluster: 'super'
deployStateUri: "http://hi:hello@localhost:#{0xbabe}"
}
@sut.run done
afterEach ->
@sut.destroy()
@meshbluServer.destroy()
@deployStateService.destroy()
describe 'POST /cancellations', ->
describe 'when called with valid auth', ->
describe 'when called with an existing deploy', ->
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
deployStateAuth = new Buffer('hi:hello').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
@notifyDeployState = @deployStateService
.put '/deployments/octoblu/a-deploy/v1/cluster/super/failed'
.set 'Authorization', "Basic #{deployStateAuth}"
.reply 204
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: '<PASSWORD>'}
json: {the: 'stuff i posted', etcdDir: '/dir/a-deploy', dockerUrl: 'octoblu/a-deploy:v1' }
request.post options, (error, @response, @body) =>
return done error if error?
done()
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should have set a ttl', (done) ->
keyName = '<KEY>'
@client.ttl keyName, (error, ttl) =>
return done error if error?
expect(ttl).to.be.greaterThan 0
done()
it 'should set the cancellation metadata', (done) ->
@client.hexists 'governator:/dir/a-deploy:octoblu/a-deploy:v1', 'cancellation', (error, exists) =>
return done error if error?
expect(exists).to.equal 1
done()
it 'should notify the deploy state service', ->
@notifyDeployState.done()
describe 'when called with invalid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 403
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: '<PASSWORD>'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
describe 'when called the wrong valid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 200, uuid: 'wrong-uuid'
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: '<PASSWORD>'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
| true | request = require 'request'
shmock = require 'shmock'
RedisNs = require '@octoblu/redis-ns'
redis = require 'ioredis'
enableDestroy = require 'server-destroy'
UUID = require 'uuid'
Server = require '../../server'
describe 'Create Cancellation', ->
beforeEach ->
@meshbluServer = shmock 30000
enableDestroy @meshbluServer
beforeEach ->
@deployStateService = shmock 0xbabe
enableDestroy @deployStateService
beforeEach (done) ->
@redisKey = PI:KEY:<KEY>END_PI()
meshbluConfig =
server: 'localhost'
port: '30000'
uuid: 'governator-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PIator-token'
@client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true
@sut = new Server {
meshbluConfig: meshbluConfig
port: 20000
disableLogging: true
deployDelay: 0
redisUri: 'redis://localhost:6379'
namespace: @redisKey
maxConnections: 2,
requiredClusters: ['minor']
cluster: 'super'
deployStateUri: "http://hi:hello@localhost:#{0xbabe}"
}
@sut.run done
afterEach ->
@sut.destroy()
@meshbluServer.destroy()
@deployStateService.destroy()
describe 'POST /cancellations', ->
describe 'when called with valid auth', ->
describe 'when called with an existing deploy', ->
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
deployStateAuth = new Buffer('hi:hello').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
@notifyDeployState = @deployStateService
.put '/deployments/octoblu/a-deploy/v1/cluster/super/failed'
.set 'Authorization', "Basic #{deployStateAuth}"
.reply 204
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
json: {the: 'stuff i posted', etcdDir: '/dir/a-deploy', dockerUrl: 'octoblu/a-deploy:v1' }
request.post options, (error, @response, @body) =>
return done error if error?
done()
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should have set a ttl', (done) ->
keyName = 'PI:KEY:<KEY>END_PI'
@client.ttl keyName, (error, ttl) =>
return done error if error?
expect(ttl).to.be.greaterThan 0
done()
it 'should set the cancellation metadata', (done) ->
@client.hexists 'governator:/dir/a-deploy:octoblu/a-deploy:v1', 'cancellation', (error, exists) =>
return done error if error?
expect(exists).to.equal 1
done()
it 'should notify the deploy state service', ->
@notifyDeployState.done()
describe 'when called with invalid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 403
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
describe 'when called the wrong valid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 200, uuid: 'wrong-uuid'
options =
uri: '/cancellations'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998549222946167,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/widgets/button.coffee | git-j/hallo | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallobutton',
button: null
isChecked: false
options:
uuid: ''
label: null
icon: null
editable: null
command: null
queryState: true
cssClass: null
_create: ->
# By default the icon is icon-command, but this doesn't
# always match with <http://fortawesome.github.com/Font-Awesome/#base-icons>
#@options.icon ?= "icon-#{@options.label.toLowerCase()}"
@options.text = false
@options.icons = { "primary": "ui-icon-#{@options.command}-p" }
id = "#{@options.uuid}-#{@options.label}"
@button = @_createButton id, @options.command, @options.label, @options.icon
@element.append @button
@button.button {"icons": @options.icons,"text": false}
@button.addClass @options.cssClass if @options.cssClass
@button.addClass 'btn-large' if @options.editable.options.touchScreen
@button.data 'hallo-command', @options.command
hoverclass = 'ui-state-hover'
@button.bind 'mouseenter', (event) =>
if @isEnabled()
@button.addClass hoverclass
@button.bind 'mouseleave', (event) =>
@button.removeClass hoverclass
_init: ->
@button = @_prepareButton() unless @button
@element.append @button
queryState = (event) =>
# console.log(@options.command,document.queryCommandState(@options.command))
return unless @options.command
return unless ( (event.keyCode >= 33 && event.keyCode <= 40) || event.type == 'mouseup' || event.type == 'hallomodified')
if ( rangy.getSelection().anchorNode == null )
# console.log('empty anchorNode',rangy.getSelection().anchorNode )
return;
try
# HACK for qt-webkit
state = false
if ( @options.command == 'subscript' || @options.command == 'superscript' )
# broken command state for sub/sup
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
parent = range.startContainer.parentNode
if parent.nodeName == 'SUB' && @options.command == 'subscript'
state = true
if parent.nodeName == 'SUP' && @options.command == 'superscript'
state = true
@checked state
else if ( @options.command.indexOf('justify') == 0 )
# broken justify
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
node = range.startContainer
while ( node )
break if ( node.contentEditable == 'true' )
if ( typeof node.attributes == 'object' && node.attributes != null)
for attribute in node.attributes
if attribute.nodeName == 'style' && attribute.nodeValue.indexOf('text-align') >= 0
style = attribute.nodeValue
style = style.replace(/.*text-align:([^;]*).*/,'$1').trim()
state = true if ( @options.command.toLowerCase() == 'justify' + style )
break
break if state
node = node.parentNode
@checked state
else
@checked document.queryCommandState @options.command
catch e
console.error(e)
return
if typeof @options.command_function == 'function'
@button.bind 'click', @options.command_function
#command_function = () =>
# range = rangy.getSelection().getRangeAt(0)
# console.log(range)
# if ( range.collapsed )
# console.log('TODO: select entire text node')
# range.selectNode(range.startContainer)
# rangy.getSelection().addRange(range)
# widget.execute(format, false, null)
else if typeof @options.command == 'string'
@button.bind 'click', (event) =>
jQuery('.misspelled').remove()
# HACK for qt-webkit
if ( @options.command == 'subscript' || @options.command == 'superscript' )
range = rangy.getSelection().getRangeAt(0)
node = jQuery(range.startContainer)
state = false
if node.closest('SUB').length && @options.command == 'subscript'
state = true
if node.closest('SUP').length && @options.command == 'superscript'
state = true
if ( !state )
@options.editable.execute @options.command
else
@options.editable.execute 'removeformat'
else
@options.editable.execute @options.command
queryState
return false
return unless @options.queryState
editableElement = @options.editable.element
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'halloenabled', =>
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'hallodisabled', =>
editableElement.unbind 'keyup paste change mouseup hallomodified', queryState
enable: ->
# @button.removeAttr 'disabled'
@button.removeClass('disabled')
disable: ->
# @button.attr 'disabled', 'true'
@button.addClass('disabled')
isEnabled: ->
# return @button.attr('disabled') != 'true'
return @button.hasClass('disabled') != 'true'
refresh: ->
if @isChecked
@button.addClass 'ui-state-active'
else
@button.removeClass 'ui-state-active'
checked: (checked) ->
@isChecked = checked
@refresh()
_createButton: (id, command, label, icon) ->
button_str = "<button for=\"#{id}\""
button_str+= " class=\"#{command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " title=\"#{label}\""
button_str+= " rel=\"#{command}\""
button_str+= "></button>"
buttonEl = jQuery button_str
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
# could we switch this somehow?
# jQuery "<button for=\"#{id}\" class=\"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only #{command}_button\" title=\"#{label}\"><span class=\"ui-button-text\"><i class=\"#{icon}\"></i></span></button>"
jQuery.widget 'IKS.hallobuttonset',
buttons: null
_create: ->
@element.addClass 'ui-buttonset'
_init: ->
@refresh()
refresh: ->
rtl = @element.css('direction') == 'rtl'
@buttons = @element.find '.ui-button'
@buttons.hallobutton 'refresh'
@buttons.removeClass 'ui-corner-all ui-corner-left ui-corner-right'
@buttons.filter(':first').addClass if rtl then 'ui-corner-right' else 'ui-corner-left'
@buttons.filter(':last').addClass if rtl then 'ui-corner-left' else 'ui-corner-right'
)(jQuery) | 196376 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallobutton',
button: null
isChecked: false
options:
uuid: ''
label: null
icon: null
editable: null
command: null
queryState: true
cssClass: null
_create: ->
# By default the icon is icon-command, but this doesn't
# always match with <http://fortawesome.github.com/Font-Awesome/#base-icons>
#@options.icon ?= "icon-#{@options.label.toLowerCase()}"
@options.text = false
@options.icons = { "primary": "ui-icon-#{@options.command}-p" }
id = "#{@options.uuid}-#{@options.label}"
@button = @_createButton id, @options.command, @options.label, @options.icon
@element.append @button
@button.button {"icons": @options.icons,"text": false}
@button.addClass @options.cssClass if @options.cssClass
@button.addClass 'btn-large' if @options.editable.options.touchScreen
@button.data 'hallo-command', @options.command
hoverclass = 'ui-state-hover'
@button.bind 'mouseenter', (event) =>
if @isEnabled()
@button.addClass hoverclass
@button.bind 'mouseleave', (event) =>
@button.removeClass hoverclass
_init: ->
@button = @_prepareButton() unless @button
@element.append @button
queryState = (event) =>
# console.log(@options.command,document.queryCommandState(@options.command))
return unless @options.command
return unless ( (event.keyCode >= 33 && event.keyCode <= 40) || event.type == 'mouseup' || event.type == 'hallomodified')
if ( rangy.getSelection().anchorNode == null )
# console.log('empty anchorNode',rangy.getSelection().anchorNode )
return;
try
# HACK for qt-webkit
state = false
if ( @options.command == 'subscript' || @options.command == 'superscript' )
# broken command state for sub/sup
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
parent = range.startContainer.parentNode
if parent.nodeName == 'SUB' && @options.command == 'subscript'
state = true
if parent.nodeName == 'SUP' && @options.command == 'superscript'
state = true
@checked state
else if ( @options.command.indexOf('justify') == 0 )
# broken justify
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
node = range.startContainer
while ( node )
break if ( node.contentEditable == 'true' )
if ( typeof node.attributes == 'object' && node.attributes != null)
for attribute in node.attributes
if attribute.nodeName == 'style' && attribute.nodeValue.indexOf('text-align') >= 0
style = attribute.nodeValue
style = style.replace(/.*text-align:([^;]*).*/,'$1').trim()
state = true if ( @options.command.toLowerCase() == 'justify' + style )
break
break if state
node = node.parentNode
@checked state
else
@checked document.queryCommandState @options.command
catch e
console.error(e)
return
if typeof @options.command_function == 'function'
@button.bind 'click', @options.command_function
#command_function = () =>
# range = rangy.getSelection().getRangeAt(0)
# console.log(range)
# if ( range.collapsed )
# console.log('TODO: select entire text node')
# range.selectNode(range.startContainer)
# rangy.getSelection().addRange(range)
# widget.execute(format, false, null)
else if typeof @options.command == 'string'
@button.bind 'click', (event) =>
jQuery('.misspelled').remove()
# HACK for qt-webkit
if ( @options.command == 'subscript' || @options.command == 'superscript' )
range = rangy.getSelection().getRangeAt(0)
node = jQuery(range.startContainer)
state = false
if node.closest('SUB').length && @options.command == 'subscript'
state = true
if node.closest('SUP').length && @options.command == 'superscript'
state = true
if ( !state )
@options.editable.execute @options.command
else
@options.editable.execute 'removeformat'
else
@options.editable.execute @options.command
queryState
return false
return unless @options.queryState
editableElement = @options.editable.element
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'halloenabled', =>
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'hallodisabled', =>
editableElement.unbind 'keyup paste change mouseup hallomodified', queryState
enable: ->
# @button.removeAttr 'disabled'
@button.removeClass('disabled')
disable: ->
# @button.attr 'disabled', 'true'
@button.addClass('disabled')
isEnabled: ->
# return @button.attr('disabled') != 'true'
return @button.hasClass('disabled') != 'true'
refresh: ->
if @isChecked
@button.addClass 'ui-state-active'
else
@button.removeClass 'ui-state-active'
checked: (checked) ->
@isChecked = checked
@refresh()
_createButton: (id, command, label, icon) ->
button_str = "<button for=\"#{id}\""
button_str+= " class=\"#{command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " title=\"#{label}\""
button_str+= " rel=\"#{command}\""
button_str+= "></button>"
buttonEl = jQuery button_str
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
# could we switch this somehow?
# jQuery "<button for=\"#{id}\" class=\"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only #{command}_button\" title=\"#{label}\"><span class=\"ui-button-text\"><i class=\"#{icon}\"></i></span></button>"
jQuery.widget 'IKS.hallobuttonset',
buttons: null
_create: ->
@element.addClass 'ui-buttonset'
_init: ->
@refresh()
refresh: ->
rtl = @element.css('direction') == 'rtl'
@buttons = @element.find '.ui-button'
@buttons.hallobutton 'refresh'
@buttons.removeClass 'ui-corner-all ui-corner-left ui-corner-right'
@buttons.filter(':first').addClass if rtl then 'ui-corner-right' else 'ui-corner-left'
@buttons.filter(':last').addClass if rtl then 'ui-corner-left' else 'ui-corner-right'
)(jQuery) | true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallobutton',
button: null
isChecked: false
options:
uuid: ''
label: null
icon: null
editable: null
command: null
queryState: true
cssClass: null
_create: ->
# By default the icon is icon-command, but this doesn't
# always match with <http://fortawesome.github.com/Font-Awesome/#base-icons>
#@options.icon ?= "icon-#{@options.label.toLowerCase()}"
@options.text = false
@options.icons = { "primary": "ui-icon-#{@options.command}-p" }
id = "#{@options.uuid}-#{@options.label}"
@button = @_createButton id, @options.command, @options.label, @options.icon
@element.append @button
@button.button {"icons": @options.icons,"text": false}
@button.addClass @options.cssClass if @options.cssClass
@button.addClass 'btn-large' if @options.editable.options.touchScreen
@button.data 'hallo-command', @options.command
hoverclass = 'ui-state-hover'
@button.bind 'mouseenter', (event) =>
if @isEnabled()
@button.addClass hoverclass
@button.bind 'mouseleave', (event) =>
@button.removeClass hoverclass
_init: ->
@button = @_prepareButton() unless @button
@element.append @button
queryState = (event) =>
# console.log(@options.command,document.queryCommandState(@options.command))
return unless @options.command
return unless ( (event.keyCode >= 33 && event.keyCode <= 40) || event.type == 'mouseup' || event.type == 'hallomodified')
if ( rangy.getSelection().anchorNode == null )
# console.log('empty anchorNode',rangy.getSelection().anchorNode )
return;
try
# HACK for qt-webkit
state = false
if ( @options.command == 'subscript' || @options.command == 'superscript' )
# broken command state for sub/sup
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
parent = range.startContainer.parentNode
if parent.nodeName == 'SUB' && @options.command == 'subscript'
state = true
if parent.nodeName == 'SUP' && @options.command == 'superscript'
state = true
@checked state
else if ( @options.command.indexOf('justify') == 0 )
# broken justify
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
node = range.startContainer
while ( node )
break if ( node.contentEditable == 'true' )
if ( typeof node.attributes == 'object' && node.attributes != null)
for attribute in node.attributes
if attribute.nodeName == 'style' && attribute.nodeValue.indexOf('text-align') >= 0
style = attribute.nodeValue
style = style.replace(/.*text-align:([^;]*).*/,'$1').trim()
state = true if ( @options.command.toLowerCase() == 'justify' + style )
break
break if state
node = node.parentNode
@checked state
else
@checked document.queryCommandState @options.command
catch e
console.error(e)
return
if typeof @options.command_function == 'function'
@button.bind 'click', @options.command_function
#command_function = () =>
# range = rangy.getSelection().getRangeAt(0)
# console.log(range)
# if ( range.collapsed )
# console.log('TODO: select entire text node')
# range.selectNode(range.startContainer)
# rangy.getSelection().addRange(range)
# widget.execute(format, false, null)
else if typeof @options.command == 'string'
@button.bind 'click', (event) =>
jQuery('.misspelled').remove()
# HACK for qt-webkit
if ( @options.command == 'subscript' || @options.command == 'superscript' )
range = rangy.getSelection().getRangeAt(0)
node = jQuery(range.startContainer)
state = false
if node.closest('SUB').length && @options.command == 'subscript'
state = true
if node.closest('SUP').length && @options.command == 'superscript'
state = true
if ( !state )
@options.editable.execute @options.command
else
@options.editable.execute 'removeformat'
else
@options.editable.execute @options.command
queryState
return false
return unless @options.queryState
editableElement = @options.editable.element
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'halloenabled', =>
editableElement.bind 'keyup paste change mouseup hallomodified', queryState
editableElement.bind 'hallodisabled', =>
editableElement.unbind 'keyup paste change mouseup hallomodified', queryState
enable: ->
# @button.removeAttr 'disabled'
@button.removeClass('disabled')
disable: ->
# @button.attr 'disabled', 'true'
@button.addClass('disabled')
isEnabled: ->
# return @button.attr('disabled') != 'true'
return @button.hasClass('disabled') != 'true'
refresh: ->
if @isChecked
@button.addClass 'ui-state-active'
else
@button.removeClass 'ui-state-active'
checked: (checked) ->
@isChecked = checked
@refresh()
_createButton: (id, command, label, icon) ->
button_str = "<button for=\"#{id}\""
button_str+= " class=\"#{command}_button ui-button ui-widget ui-state-default ui-corner-all\""
button_str+= " title=\"#{label}\""
button_str+= " rel=\"#{command}\""
button_str+= "></button>"
buttonEl = jQuery button_str
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.addClass 'btn-large' if @options.editable.options.touchScreen
button = buttonEl.button { "icons": { "primary": "ui-icon-#{@options.command}-p" }, "text": false }
button.addClass @options.cssClass if @options.cssClass
button
# could we switch this somehow?
# jQuery "<button for=\"#{id}\" class=\"ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only #{command}_button\" title=\"#{label}\"><span class=\"ui-button-text\"><i class=\"#{icon}\"></i></span></button>"
jQuery.widget 'IKS.hallobuttonset',
buttons: null
_create: ->
@element.addClass 'ui-buttonset'
_init: ->
@refresh()
refresh: ->
rtl = @element.css('direction') == 'rtl'
@buttons = @element.find '.ui-button'
@buttons.hallobutton 'refresh'
@buttons.removeClass 'ui-corner-all ui-corner-left ui-corner-right'
@buttons.filter(':first').addClass if rtl then 'ui-corner-right' else 'ui-corner-left'
@buttons.filter(':last').addClass if rtl then 'ui-corner-left' else 'ui-corner-right'
)(jQuery) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.